@component-hook/pdf-canvas 1.5.0 → 1.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/react/assets/pdfjs.worker-QHzJtIzr.js +11 -0
- package/dist/react/pdf-canvas.es.d.ts +0 -10622
- package/dist/react/pdf-canvas.es.js +1487 -1686
- package/dist/react/pdf-canvas.umd.js +33 -38
- package/dist/vue/assets/pdfjs.worker-QHzJtIzr.js +11 -0
- package/dist/vue/pdf-canvas.es.d.ts +0 -10622
- package/dist/vue/pdf-canvas.es.js +153 -175
- package/dist/vue/pdf-canvas.umd.js +14 -14
- package/package.json +5 -5
- package/dist/react/assets/pdfjs.worker-635tbwI0.js +0 -11
- package/dist/vue/assets/pdfjs.worker-635tbwI0.js +0 -11
|
@@ -1,39 +1,39 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("react")):typeof define==`function`&&define.amd?define([`exports`,`react`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pdf-canvas`]={},e.React))})(this,function(e,t){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var n=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),r=`data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='20'%20cy='20'%20r='10.75'%20stroke='currentColor'%20stroke-width='2.5'/%3e%3cpath%20d='M16%2024L23.7782%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3cpath%20d='M24%2024L16.2218%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3c/svg%3e`,i={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:`black`,cornerStrokeColor:`black`,cornerSize:6,selectionBackgroundColor:`rgba(245, 245, 245, 0.8)`},a={top:100,left:50,fontFamily:`helvetica`,borderColor:`black`,cornerStrokeColor:`black`,scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:`rgba(245, 245, 245, 0.8)`},o={borderColor:`black`,cornerStrokeColor:`black`,cornerSize:8,selectionBackgroundColor:`rgba(245, 245, 245, 0.8)`},s={stroke:`#000`,hoverStroke:`#B7EC5D`,src:r},c=[`borderColor`,`cornerStrokeColor`,`cornerSize`,`_cornerSize`,`selectionBackgroundColor`],l=Object.defineProperty,u=(e,t)=>{let n={};for(var r in e)l(n,r,{get:e[r],enumerable:!0});return t||l(n,Symbol.toStringTag,{value:`Module`}),n};function d(e){return d=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},d(e)}function f(e){var t=function(e,t){if(d(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(d(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}(e,`string`);return d(t)==`symbol`?t:t+``}function p(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var m=class{constructor(){p(this,`browserShadowBlurConstant`,1),p(this,`DPI`,96),p(this,`devicePixelRatio`,typeof window<`u`?window.devicePixelRatio:1),p(this,`perfLimitSizeTotal`,2097152),p(this,`maxCacheSideLimit`,4096),p(this,`minCacheSideLimit`,256),p(this,`disableStyleCopyPaste`,!1),p(this,`enableGLFiltering`,!0),p(this,`textureSize`,4096),p(this,`forceGLPutImageData`,!1),p(this,`cachesBoundsOfCurve`,!1),p(this,`fontPaths`,{}),p(this,`NUM_FRACTION_DIGITS`,4)}},h=new class extends m{constructor(e){super(),this.configure(e)}configure(e={}){Object.assign(this,e)}addFonts(e={}){this.fontPaths={...this.fontPaths,...e}}removeFonts(e=[]){e.forEach(e=>{delete this.fontPaths[e]})}clearFonts(){this.fontPaths={}}restoreDefaults(e){let t=new m,n=e?.reduce((e,n)=>(e[n]=t[n],e),{})||t;this.configure(n)}},g=(e,...t)=>console[e](`fabric`,...t),_=class extends Error{constructor(e,t){super(`fabric: ${e}`,t)}},v=class extends _{constructor(e){super(`${e} 'options.signal' is in 'aborted' state`)}},y=class{},b=class extends y{testPrecision(e,t){let n=`precision ${t} float;\nvoid main(){}`,r=e.createShader(e.FRAGMENT_SHADER);return!!r&&(e.shaderSource(r,n),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS))}queryWebGL(e){let t=e.getContext(`webgl`);t&&(this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.GLPrecision=[`highp`,`mediump`,`lowp`].find(e=>this.testPrecision(t,e)),t.getExtension(`WEBGL_lose_context`).loseContext(),g(`log`,`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(e){return!!this.maxTextureSize&&this.maxTextureSize>=e}},x={},S,C=()=>S||={document,window,isTouchSupported:`ontouchstart`in window||`ontouchstart`in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new b,dispose(){},copyPasteData:x},w=()=>C().document,T=()=>C().window,E=()=>Math.max(h.devicePixelRatio??T().devicePixelRatio,1),D=new class{constructor(){p(this,`boundsOfCurveCache`,{}),this.charWidthsCache=new Map}getFontCache({fontFamily:e,fontStyle:t,fontWeight:n}){e=e.toLowerCase();let r=this.charWidthsCache;r.has(e)||r.set(e,new Map);let i=r.get(e),a=`${t.toLowerCase()}_${(n+``).toLowerCase()}`;return i.has(a)||i.set(a,new Map),i.get(a)}clearFontCache(e){e?this.charWidthsCache.delete((e||``).toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(e){let{perfLimitSizeTotal:t}=h,n=Math.sqrt(t*e);return[Math.floor(n),Math.floor(t/n)]}},O=`7.4.0`;function k(){}var A=Math.PI/2,j=Math.PI/4,M=2*Math.PI,ee=Math.PI/180,N=Object.freeze([1,0,0,1,0,0]),P=`center`,F=`left`,I=`bottom`,te=`right`,ne=`none`,re=/\r?\n/,ie=`moving`,ae=`scaling`,oe=`rotating`,se=`rotate`,ce=`skewing`,le=`resizing`,ue=`modifyPoly`,de=`changed`,fe=`scale`,pe=`scaleX`,me=`scaleY`,he=`skewX`,ge=`skewY`,_e=`fill`,ve=`stroke`,ye=`modified`,be=`normal`,xe=`json`,L=new class{constructor(){this[xe]=new Map,this.svg=new Map}has(e){return this[xe].has(e)}getClass(e){let t=this[xe].get(e);if(!t)throw new _(`No class registered for ${e}`);return t}setClass(e,t){t?this[xe].set(t,e):(this[xe].set(e.type,e),this[xe].set(e.type.toLowerCase(),e))}getSVGClass(e){return this.svg.get(e)}setSVGClass(e,t){this.svg.set(t??e.type.toLowerCase(),e)}},Se=new class extends Array{remove(e){let t=this.indexOf(e);t>-1&&this.splice(t,1)}cancelAll(){let e=this.splice(0);return e.forEach(e=>e.abort()),e}cancelByCanvas(e){if(!e)return[];let t=this.filter(t=>t.target===e||typeof t.target==`object`&&t.target?.canvas===e);return t.forEach(e=>e.abort()),t}cancelByTarget(e){if(!e)return[];let t=this.filter(t=>t.target===e);return t.forEach(e=>e.abort()),t}},Ce=class{constructor(){p(this,`__eventListeners`,{})}on(e,t){if(this.__eventListeners||={},typeof e==`object`)return Object.entries(e).forEach(([e,t])=>{this.on(e,t)}),()=>this.off(e);if(t){let n=e;return this.__eventListeners[n]||(this.__eventListeners[n]=[]),this.__eventListeners[n].push(t),()=>this.off(n,t)}return()=>!1}once(e,t){if(typeof e==`object`){let t=[];return Object.entries(e).forEach(([e,n])=>{t.push(this.once(e,n))}),()=>t.forEach(e=>e())}if(t){let n=this.on(e,function(...e){t.call(this,...e),n()});return n}return()=>!1}_removeEventListener(e,t){if(this.__eventListeners[e])if(t){let n=this.__eventListeners[e],r=n.indexOf(t);r>-1&&n.splice(r,1)}else this.__eventListeners[e]=[]}off(e,t){if(this.__eventListeners)if(e===void 0)for(let e in this.__eventListeners)this._removeEventListener(e);else typeof e==`object`?Object.entries(e).forEach(([e,t])=>{this._removeEventListener(e,t)}):this._removeEventListener(e,t)}fire(e,t){if(!this.__eventListeners)return;let n=this.__eventListeners[e]?.concat();if(n)for(let e=0;e<n.length;e++)n[e].call(this,t||{})}},we=(e,t)=>{let n=e.indexOf(t);return n!==-1&&e.splice(n,1),e},Te=e=>{if(e===0)return 1;switch(Math.abs(e)/A){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},Ee=e=>{if(e===0)return 0;let t=e/A,n=Math.sign(e);switch(t){case 1:return n;case 2:return 0;case 3:return-n}return Math.sin(e)},R=class e{constructor(e=0,t=0){typeof e==`object`?(this.x=e.x,this.y=e.y):(this.x=e,this.y=t)}add(t){return new e(this.x+t.x,this.y+t.y)}addEquals(e){return this.x+=e.x,this.y+=e.y,this}scalarAdd(t){return new e(this.x+t,this.y+t)}scalarAddEquals(e){return this.x+=e,this.y+=e,this}subtract(t){return new e(this.x-t.x,this.y-t.y)}subtractEquals(e){return this.x-=e.x,this.y-=e.y,this}scalarSubtract(t){return new e(this.x-t,this.y-t)}scalarSubtractEquals(e){return this.x-=e,this.y-=e,this}multiply(t){return new e(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new e(this.x*t,this.y*t)}scalarMultiplyEquals(e){return this.x*=e,this.y*=e,this}divide(t){return new e(this.x/t.x,this.y/t.y)}scalarDivide(t){return new e(this.x/t,this.y/t)}scalarDivideEquals(e){return this.x/=e,this.y/=e,this}eq(e){return this.x===e.x&&this.y===e.y}lt(e){return this.x<e.x&&this.y<e.y}lte(e){return this.x<=e.x&&this.y<=e.y}gt(e){return this.x>e.x&&this.y>e.y}gte(e){return this.x>=e.x&&this.y>=e.y}lerp(t,n=.5){return n=Math.max(Math.min(1,n),0),new e(this.x+(t.x-this.x)*n,this.y+(t.y-this.y)*n)}distanceFrom(e){let t=this.x-e.x,n=this.y-e.y;return Math.sqrt(t*t+n*n)}midPointFrom(e){return this.lerp(e)}min(t){return new e(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new e(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return`${this.x},${this.y}`}setXY(e,t){return this.x=e,this.y=t,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setFromPoint(e){return this.x=e.x,this.y=e.y,this}swap(e){let t=this.x,n=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=n}clone(){return new e(this.x,this.y)}rotate(t,n=De){let r=Ee(t),i=Te(t),a=this.subtract(n);return new e(a.x*i-a.y*r,a.x*r+a.y*i).add(n)}transform(t,n=!1){return new e(t[0]*this.x+t[2]*this.y+(n?0:t[4]),t[1]*this.x+t[3]*this.y+(n?0:t[5]))}},De=new R(0,0),Oe=e=>!!e&&Array.isArray(e._objects);function ke(e){class t extends e{constructor(...e){super(...e),p(this,`_objects`,[])}_onObjectAdded(e){}_onObjectRemoved(e){}_onStackOrderChanged(e){}add(...e){let t=this._objects.push(...e);return e.forEach(e=>this._onObjectAdded(e)),t}insertAt(e,...t){return this._objects.splice(e,0,...t),t.forEach(e=>this._onObjectAdded(e)),this._objects.length}remove(...e){let t=this._objects,n=[];return e.forEach(e=>{let r=t.indexOf(e);r!==-1&&(t.splice(r,1),n.push(e),this._onObjectRemoved(e))}),n}forEachObject(e){this.getObjects().forEach((t,n,r)=>e(t,n,r))}getObjects(...e){return e.length===0?[...this._objects]:this._objects.filter(t=>t.isType(...e))}item(e){return this._objects[e]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(e,n){return!!this._objects.includes(e)||!!n&&this._objects.some(n=>n instanceof t&&n.contains(e,!0))}complexity(){return this._objects.reduce((e,t)=>e+=t.complexity?t.complexity():0,0)}sendObjectToBack(e){return!(!e||e===this._objects[0])&&(we(this._objects,e),this._objects.unshift(e),this._onStackOrderChanged(e),!0)}bringObjectToFront(e){return!(!e||e===this._objects[this._objects.length-1])&&(we(this._objects,e),this._objects.push(e),this._onStackOrderChanged(e),!0)}sendObjectBackwards(e,t){if(!e)return!1;let n=this._objects.indexOf(e);if(n!==0){let r=this.findNewLowerIndex(e,n,t);return we(this._objects,e),this._objects.splice(r,0,e),this._onStackOrderChanged(e),!0}return!1}bringObjectForward(e,t){if(!e)return!1;let n=this._objects.indexOf(e);if(n!==this._objects.length-1){let r=this.findNewUpperIndex(e,n,t);return we(this._objects,e),this._objects.splice(r,0,e),this._onStackOrderChanged(e),!0}return!1}moveObjectTo(e,t){return e!==this._objects[t]&&(we(this._objects,e),this._objects.splice(t,0,e),this._onStackOrderChanged(e),!0)}findNewLowerIndex(e,t,n){let r;if(n){r=t;for(let n=t-1;n>=0;--n)if(e.isOverlapping(this._objects[n])){r=n;break}}else r=t-1;return r}findNewUpperIndex(e,t,n){let r;if(n){r=t;for(let n=t+1;n<this._objects.length;++n)if(e.isOverlapping(this._objects[n])){r=n;break}}else r=t+1;return r}collectObjects({left:e,top:t,width:n,height:r},{includeIntersecting:i=!0}={}){let a=[],o=new R(e,t),s=o.add(new R(n,r));for(let e=this._objects.length-1;e>=0;e--){let t=this._objects[e];t.selectable&&t.visible&&(i&&t.intersectsWithRect(o,s)||t.isContainedWithinRect(o,s)||i&&t.containsPoint(o)||i&&t.containsPoint(s))&&a.push(t)}return a}}return t}var Ae=class extends Ce{_setOptions(e={}){for(let t in e)this.set(t,e[t])}_setObject(e){for(let t in e)this._set(t,e[t])}set(e,t){return typeof e==`object`?this._setObject(e):this._set(e,t),this}_set(e,t){this[e]=t}toggle(e){let t=this.get(e);return typeof t==`boolean`&&this.set(e,!t),this}get(e){return this[e]}};function je(e){return T().requestAnimationFrame(e)}function Me(e){return T().cancelAnimationFrame(e)}var Ne=0,Pe=()=>Ne++,Fe=()=>{let e=w().createElement(`canvas`);if(!e||e.getContext===void 0)throw new _("Failed to create `canvas` element");return e},Ie=()=>w().createElement(`img`),Le=e=>{var t;let n=Re(e);return(t=n.getContext(`2d`))==null||t.drawImage(e,0,0),n},Re=e=>{let t=Fe();return t.width=e.width,t.height=e.height,t},ze=(e,t,n)=>e.toDataURL(`image/${t}`,n),Be=(e,t,n)=>new Promise((r,i)=>{e.toBlob(r,`image/${t}`,n)}),z=e=>e*ee,Ve=e=>e/ee,He=e=>e.every((e,t)=>e===N[t]),Ue=(e,t,n)=>new R(e).transform(t,n),We=e=>{let t=1/(e[0]*e[3]-e[1]*e[2]),n=[t*e[3],-t*e[1],-t*e[2],t*e[0],0,0],{x:r,y:i}=new R(e[4],e[5]).transform(n,!0);return n[4]=-r,n[5]=-i,n},B=(e,t,n)=>[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],n?0:e[0]*t[4]+e[2]*t[5]+e[4],n?0:e[1]*t[4]+e[3]*t[5]+e[5]],Ge=(e,t)=>e.reduceRight((e,n)=>n&&e?B(n,e,t):n||e,void 0)||N.concat(),Ke=([e,t])=>Math.atan2(t,e),qe=([e,t])=>Math.sqrt(e*e+t*t),Je=([,,e,t])=>Math.sqrt(e*e+t*t),Ye=e=>{let t=Ke(e),n=e[0]**2+e[1]**2,r=Math.sqrt(n),i=(e[0]*e[3]-e[2]*e[1])/r,a=Math.atan2(e[0]*e[2]+e[1]*e[3],n);return{angle:Ve(t),scaleX:r,scaleY:i,skewX:Ve(a),skewY:0,translateX:e[4]||0,translateY:e[5]||0}},Xe=(e,t=0)=>[1,0,0,1,e,t];function Ze({angle:e=0}={},{x:t=0,y:n=0}={}){let r=z(e),i=Te(r),a=Ee(r);return[i,a,-a,i,t?t-(i*t-a*n):0,n?n-(a*t+i*n):0]}var Qe=(e,t=e)=>[e,0,0,t,0,0],$e=e=>Math.tan(z(e)),et=e=>[1,0,$e(e),1,0,0],tt=e=>[1,$e(e),0,1,0,0],nt=({scaleX:e=1,scaleY:t=1,flipX:n=!1,flipY:r=!1,skewX:i=0,skewY:a=0})=>{let o=Qe(n?-e:e,r?-t:t);return i&&(o=B(o,et(i),!0)),a&&(o=B(o,tt(a),!0)),o},rt=e=>{let{translateX:t=0,translateY:n=0,angle:r=0}=e,i=Xe(t,n);r&&(i=B(i,Ze({angle:r})));let a=nt(e);return He(a)||(i=B(i,a)),i},it=(e,{signal:t,crossOrigin:n=null}={})=>new Promise(function(r,i){if(t&&t.aborted)return i(new v(`loadImage`));let a=Ie(),o;t&&(o=function(e){a.src=``,i(e)},t.addEventListener(`abort`,o,{once:!0}));let s=function(){a.onload=a.onerror=null,o&&t?.removeEventListener(`abort`,o),r(a)};e?(a.onload=s,a.onerror=function(){o&&t?.removeEventListener(`abort`,o),i(new _(`Error loading ${a.src}`))},n&&(a.crossOrigin=n),a.src=e):s()}),at=(e,{signal:t,reviver:n=k}={})=>new Promise((r,i)=>{let a=[];t&&t.addEventListener(`abort`,i,{once:!0}),Promise.allSettled(e.map(e=>L.getClass(e.type).fromObject(e,{signal:t}))).then(async t=>{for(let[r,i]of t.entries())if(i.status===`fulfilled`&&(await n(e[r],i.value),a.push(i.value)),i.status===`rejected`){let t=await n(e[r],void 0,i.reason);t&&a.push(t)}r(a)}).catch(e=>{a.forEach(e=>{e.dispose&&e.dispose()}),i(e)}).finally(()=>{t&&t.removeEventListener(`abort`,i)})}),ot=(e,{signal:t}={})=>new Promise((n,r)=>{let i=[];t&&t.addEventListener(`abort`,r,{once:!0});let a=Object.values(e).map(e=>e&&e.type&&L.has(e.type)?at([e],{signal:t}).then(([e])=>(i.push(e),e)):e),o=Object.keys(e);Promise.all(a).then(e=>e.reduce((e,t,n)=>(e[o[n]]=t,e),{})).then(n).catch(e=>{i.forEach(e=>{e.dispose&&e.dispose()}),r(e)}).finally(()=>{t&&t.removeEventListener(`abort`,r)})}),st=(e,t=[])=>t.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{}),ct=(e,t)=>Object.keys(e).reduce((n,r)=>(t(e[r],r,e)&&(n[r]=e[r]),n),{}),V=(e,t)=>parseFloat(Number(e).toFixed(t)),lt=e=>`matrix(`+e.map(e=>V(e,h.NUM_FRACTION_DIGITS)).join(` `)+`)`,ut=e=>!!e&&e.toLive!==void 0,dt=e=>!!e&&typeof e.toObject==`function`,ft=e=>!!e&&e.offsetX!==void 0&&`source`in e,pt=e=>!!e&&`multiSelectionStacking`in e;function mt(e){let t=e&&ht(e),n=0,r=0;if(!e||!t)return{left:n,top:r};let i=e,a=t.documentElement,o=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(n=o.scrollLeft||a.scrollLeft||0,r=o.scrollTop||a.scrollTop||0):(n+=i.scrollLeft||0,r+=i.scrollTop||0),i.nodeType!==1||i.style.position!==`fixed`););return{left:n,top:r}}var ht=e=>e.ownerDocument||null,gt=e=>e.ownerDocument?.defaultView||null,_t=(e,t,{width:n,height:r},i=1)=>{e.width=n,e.height=r,i>1&&(e.setAttribute(`width`,(n*i).toString()),e.setAttribute(`height`,(r*i).toString()),t.scale(i,i))},vt=(e,{width:t,height:n})=>{t&&(e.style.width=typeof t==`number`?`${t}px`:t),n&&(e.style.height=typeof n==`number`?`${n}px`:n)};function yt(e){return e.onselectstart!==void 0&&(e.onselectstart=()=>!1),e.style.userSelect=ne,e}var bt=class{constructor(e){p(this,`_originalCanvasStyle`,void 0),p(this,`lower`,void 0);let t=this.createLowerCanvas(e);this.lower={el:t,ctx:t.getContext(`2d`)}}createLowerCanvas(e){let t=(n=e)&&n.getContext!==void 0?e:e&&w().getElementById(e)||Fe();var n;if(t.hasAttribute(`data-fabric`))throw new _(`Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?`);return this._originalCanvasStyle=t.style.cssText,t.setAttribute(`data-fabric`,`main`),t.classList.add(`lower-canvas`),t}cleanupDOM({width:e,height:t}){let{el:n}=this.lower;n.classList.remove(`lower-canvas`),n.removeAttribute(`data-fabric`),n.setAttribute(`width`,`${e}`),n.setAttribute(`height`,`${t}`),n.style.cssText=this._originalCanvasStyle||``,this._originalCanvasStyle=void 0}setDimensions(e,t){let{el:n,ctx:r}=this.lower;_t(n,r,e,t)}setCSSDimensions(e){vt(this.lower.el,e)}calcOffset(){return function(e){let t=e&&ht(e),n={left:0,top:0};if(!t)return n;let r=gt(e)?.getComputedStyle(e,null)||{};n.left+=parseInt(r.borderLeftWidth,10)||0,n.top+=parseInt(r.borderTopWidth,10)||0,n.left+=parseInt(r.paddingLeft,10)||0,n.top+=parseInt(r.paddingTop,10)||0;let i={left:0,top:0},a=t.documentElement;e.getBoundingClientRect!==void 0&&(i=e.getBoundingClientRect());let o=mt(e);return{left:i.left+o.left-(a.clientLeft||0)+n.left,top:i.top+o.top-(a.clientTop||0)+n.top}}(this.lower.el)}dispose(){C().dispose(this.lower.el),delete this.lower}},xt={backgroundVpt:!0,backgroundColor:``,overlayVpt:!0,overlayColor:``,includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...N],patternQuality:`best`},St=u({capitalize:()=>Ct,escapeXml:()=>H,graphemeSplit:()=>Tt}),Ct=(e,t=!1)=>`${e.charAt(0).toUpperCase()}${t?e.slice(1):e.slice(1).toLowerCase()}`,H=e=>e.toString().replace(/&/g,`&`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/</g,`<`).replace(/>/g,`>`),wt,Tt=e=>{if(wt||wt||(wt=`Intl`in T()&&`Segmenter`in Intl&&new Intl.Segmenter(void 0,{granularity:`grapheme`})),wt){let t=wt.segment(e);return Array.from(t).map(({segment:e})=>e)}return Et(e)},Et=e=>{let t=[];for(let n,r=0;r<e.length;r++)!1!==(n=Dt(e,r))&&t.push(n);return t},Dt=(e,t)=>{let n=e.charCodeAt(t);if(isNaN(n))return``;if(n<55296||n>57343)return e.charAt(t);if(55296<=n&&n<=56319){if(e.length<=t+1)throw`High surrogate without following low surrogate`;let n=e.charCodeAt(t+1);if(56320>n||n>57343)throw`High surrogate without following low surrogate`;return e.charAt(t)+e.charAt(t+1)}if(t===0)throw`Low surrogate without preceding high surrogate`;let r=e.charCodeAt(t-1);if(55296>r||r>56319)throw`Low surrogate without preceding high surrogate`;return!1},Ot=class e extends ke(Ae){get lowerCanvasEl(){return this.elements.lower?.el}get contextContainer(){return this.elements.lower?.ctx}static getDefaults(){return e.ownDefaults}constructor(e,t={}){super(),Object.assign(this,this.constructor.getDefaults()),this.set(t),this.initElements(e),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(e){this.elements=new bt(e)}add(...e){let t=super.add(...e);return e.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(e,...t){let n=super.insertAt(e,...t);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(...e){let t=super.remove(...e);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(e){e.canvas&&e.canvas!==this&&(g(`warn`,`Canvas is trying to add an object that belongs to a different canvas.
|
|
2
|
-
Resulting to default behavior: removing object from previous canvas and adding to new canvas`),e.canvas.remove(e)),e._set(`canvas`,this),e.setCoords(),this.fire(`object:added`,{target:e}),e.fire(`added`,{target:this})}_onObjectRemoved(e){e._set(`canvas`,void 0),this.fire(`object:removed`,{target:e}),e.fire(`removed`,{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?E():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(e,{cssOnly:t=!1,backstoreOnly:n=!1}={}){if(!t){let t={width:this.width,height:this.height,...e};this.elements.setDimensions(t,this.getRetinaScaling()),this.hasLostContext=!0,this.width=t.width,this.height=t.height}n||this.elements.setCSSDimensions(e),this.calcOffset()}setDimensions(e,t){this._setDimensionsImpl(e,t),t&&t.cssOnly||this.requestRenderAll()}getZoom(){return qe(this.viewportTransform)}setViewportTransform(e){this.viewportTransform=e,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(e,t){let n=e,r=[...this.viewportTransform],i=Ue(e,We(r));r[0]=t,r[3]=t;let a=Ue(i,r);r[4]+=n.x-a.x,r[5]+=n.y-a.y,this.setViewportTransform(r)}setZoom(e){this.zoomToPoint(new R(0,0),e)}absolutePan(e){let t=[...this.viewportTransform];return t[4]=-e.x,t[5]=-e.y,this.setViewportTransform(t)}relativePan(e){return this.absolutePan(new R(-e.x-this.viewportTransform[4],-e.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(e){e.clearRect(0,0,this.width,this.height)}getContext(){return this.elements.lower.ctx}clear(){this.remove(...this.getObjects()),this.backgroundImage=void 0,this.overlayImage=void 0,this.backgroundColor=``,this.overlayColor=``,this.clearContext(this.getContext()),this.fire(`canvas:cleared`),this.renderOnAddRemove&&this.requestRenderAll()}renderAll(){this.cancelRequestedRender(),this.destroyed||this.renderCanvas(this.getContext(),this._objects)}renderAndReset(){this.nextRenderHandle=0,this.renderAll()}requestRenderAll(){this.nextRenderHandle||this.disposed||this.destroyed||(this.nextRenderHandle=je(()=>this.renderAndReset()))}calcViewportBoundaries(){let e=this.width,t=this.height,n=We(this.viewportTransform),r=Ue({x:0,y:0},n),i=Ue({x:e,y:t},n),a=r.min(i),o=r.max(i);return this.vptCoords={tl:a,tr:new R(o.x,a.y),bl:new R(a.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&=(Me(this.nextRenderHandle),0)}drawControls(e){}renderCanvas(e,t){if(this.destroyed)return;let n=this.viewportTransform,r=this.clipPath;this.calcViewportBoundaries(),this.clearContext(e),e.imageSmoothingEnabled=this.imageSmoothingEnabled,e.patternQuality=this.patternQuality,this.fire(`before:render`,{ctx:e}),this._renderBackground(e),e.save(),e.transform(n[0],n[1],n[2],n[3],n[4],n[5]),this._renderObjects(e,t),e.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(e),r&&(r._set(`canvas`,this),r.shouldCache(),r._transformDone=!0,r.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(e,r)),this._renderOverlay(e),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(e),this.fire(`after:render`,{ctx:e}),this.__cleanupTask&&=(this.__cleanupTask(),void 0)}drawClipPathOnCanvas(e,t){let n=this.viewportTransform;e.save(),e.transform(...n),e.globalCompositeOperation=`destination-in`,t.transform(e),e.scale(1/t.zoomX,1/t.zoomY),e.drawImage(t._cacheCanvas,-t.cacheTranslationX,-t.cacheTranslationY),e.restore()}_renderObjects(e,t){for(let n=0,r=t.length;n<r;++n)t[n]&&t[n].render(e)}_renderBackgroundOrOverlay(e,t){let n=this[`${t}Color`],r=this[`${t}Image`],i=this.viewportTransform,a=this[`${t}Vpt`];if(!n&&!r)return;let o=ut(n);if(n){if(e.save(),e.beginPath(),e.moveTo(0,0),e.lineTo(this.width,0),e.lineTo(this.width,this.height),e.lineTo(0,this.height),e.closePath(),e.fillStyle=o?n.toLive(e):n,a&&e.transform(...i),o){e.transform(1,0,0,1,n.offsetX||0,n.offsetY||0);let t=n.gradientTransform||n.patternTransform;t&&e.transform(...t)}e.fill(),e.restore()}if(r){e.save();let{skipOffscreen:t}=this;this.skipOffscreen=a,a&&e.transform(...i),r.render(e),this.skipOffscreen=t,e.restore()}}_renderBackground(e){this._renderBackgroundOrOverlay(e,`background`)}_renderOverlay(e){this._renderBackgroundOrOverlay(e,`overlay`)}getCenterPoint(){return new R(this.width/2,this.height/2)}centerObjectH(e){return this._centerObject(e,new R(this.getCenterPoint().x,e.getCenterPoint().y))}centerObjectV(e){return this._centerObject(e,new R(e.getCenterPoint().x,this.getCenterPoint().y))}centerObject(e){return this._centerObject(e,this.getCenterPoint())}viewportCenterObject(e){return this._centerObject(e,this.getVpCenter())}viewportCenterObjectH(e){return this._centerObject(e,new R(this.getVpCenter().x,e.getCenterPoint().y))}viewportCenterObjectV(e){return this._centerObject(e,new R(e.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Ue(this.getCenterPoint(),We(this.viewportTransform))}_centerObject(e,t){e.setXY(t,P,P),e.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(e){return this.toDatalessObject(e)}toObject(e){return this._toObjectMethod(`toObject`,e)}toJSON(){return this.toObject()}toDatalessObject(e){return this._toObjectMethod(`toDatalessObject`,e)}_toObjectMethod(e,t){let n=this.clipPath,r=n&&!n.excludeFromExport?this._toObject(n,e,t):null;return{version:O,...st(this,t),objects:this._objects.filter(e=>!e.excludeFromExport).map(n=>this._toObject(n,e,t)),...this.__serializeBgOverlay(e,t),...r?{clipPath:r}:null}}_toObject(e,t,n){let r;this.includeDefaultValues||(r=e.includeDefaultValues,e.includeDefaultValues=!1);let i=e[t](n);return this.includeDefaultValues||(e.includeDefaultValues=!!r),i}__serializeBgOverlay(e,t){let n={},r=this.backgroundImage,i=this.overlayImage,a=this.backgroundColor,o=this.overlayColor;return ut(a)?a.excludeFromExport||(n.background=a.toObject(t)):a&&(n.background=a),ut(o)?o.excludeFromExport||(n.overlay=o.toObject(t)):o&&(n.overlay=o),r&&!r.excludeFromExport&&(n.backgroundImage=this._toObject(r,e,t)),i&&!i.excludeFromExport&&(n.overlayImage=this._toObject(i,e,t)),n}toSVG(e={},t){e.reviver=t;let n=[];return
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require("react"),require("react/jsx-runtime")):typeof define==`function`&&define.amd?define([`exports`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e[`pdf-canvas`]={},e.React,e.react_jsx_runtime))})(this,function(e,t,n){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});var r=`data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='20'%20cy='20'%20r='10.75'%20stroke='currentColor'%20stroke-width='2.5'/%3e%3cpath%20d='M16%2024L23.7782%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3cpath%20d='M24%2024L16.2218%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3c/svg%3e`,i={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:`black`,cornerStrokeColor:`black`,cornerSize:6,selectionBackgroundColor:`rgba(245, 245, 245, 0.8)`},a={top:100,left:50,fontFamily:`helvetica`,borderColor:`black`,cornerStrokeColor:`black`,scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:`rgba(245, 245, 245, 0.8)`},o={borderColor:`black`,cornerStrokeColor:`black`,cornerSize:8,selectionBackgroundColor:`rgba(245, 245, 245, 0.8)`},s={stroke:`#000`,hoverStroke:`#B7EC5D`,src:r},c=[`borderColor`,`cornerStrokeColor`,`cornerSize`,`_cornerSize`,`selectionBackgroundColor`],l=Object.defineProperty,u=(e,t)=>{let n={};for(var r in e)l(n,r,{get:e[r],enumerable:!0});return t||l(n,Symbol.toStringTag,{value:`Module`}),n};function d(e){return d=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},d(e)}function f(e){var t=function(e,t){if(d(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(d(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}(e,`string`);return d(t)==`symbol`?t:t+``}function p(e,t,n){return(t=f(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var m=class{constructor(){p(this,`browserShadowBlurConstant`,1),p(this,`DPI`,96),p(this,`devicePixelRatio`,typeof window<`u`?window.devicePixelRatio:1),p(this,`perfLimitSizeTotal`,2097152),p(this,`maxCacheSideLimit`,4096),p(this,`minCacheSideLimit`,256),p(this,`disableStyleCopyPaste`,!1),p(this,`enableGLFiltering`,!0),p(this,`textureSize`,4096),p(this,`forceGLPutImageData`,!1),p(this,`cachesBoundsOfCurve`,!1),p(this,`fontPaths`,{}),p(this,`NUM_FRACTION_DIGITS`,4)}},h=new class extends m{constructor(e){super(),this.configure(e)}configure(e={}){Object.assign(this,e)}addFonts(e={}){this.fontPaths={...this.fontPaths,...e}}removeFonts(e=[]){e.forEach(e=>{delete this.fontPaths[e]})}clearFonts(){this.fontPaths={}}restoreDefaults(e){let t=new m,n=e?.reduce((e,n)=>(e[n]=t[n],e),{})||t;this.configure(n)}},g=(e,...t)=>console[e](`fabric`,...t),_=class extends Error{constructor(e,t){super(`fabric: ${e}`,t)}},v=class extends _{constructor(e){super(`${e} 'options.signal' is in 'aborted' state`)}},y=class{},b=class extends y{testPrecision(e,t){let n=`precision ${t} float;\nvoid main(){}`,r=e.createShader(e.FRAGMENT_SHADER);return!!r&&(e.shaderSource(r,n),e.compileShader(r),!!e.getShaderParameter(r,e.COMPILE_STATUS))}queryWebGL(e){let t=e.getContext(`webgl`);t&&(this.maxTextureSize=t.getParameter(t.MAX_TEXTURE_SIZE),this.GLPrecision=[`highp`,`mediump`,`lowp`].find(e=>this.testPrecision(t,e)),t.getExtension(`WEBGL_lose_context`).loseContext(),g(`log`,`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(e){return!!this.maxTextureSize&&this.maxTextureSize>=e}},x={},S,C=()=>S||={document,window,isTouchSupported:`ontouchstart`in window||`ontouchstart`in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new b,dispose(){},copyPasteData:x},w=()=>C().document,T=()=>C().window,E=()=>Math.max(h.devicePixelRatio??T().devicePixelRatio,1),D=new class{constructor(){p(this,`boundsOfCurveCache`,{}),this.charWidthsCache=new Map}getFontCache({fontFamily:e,fontStyle:t,fontWeight:n}){e=e.toLowerCase();let r=this.charWidthsCache;r.has(e)||r.set(e,new Map);let i=r.get(e),a=`${t.toLowerCase()}_${(n+``).toLowerCase()}`;return i.has(a)||i.set(a,new Map),i.get(a)}clearFontCache(e){e?this.charWidthsCache.delete((e||``).toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(e){let{perfLimitSizeTotal:t}=h,n=Math.sqrt(t*e);return[Math.floor(n),Math.floor(t/n)]}},O=`7.4.0`;function k(){}var A=Math.PI/2,j=Math.PI/4,M=2*Math.PI,ee=Math.PI/180,N=Object.freeze([1,0,0,1,0,0]),P=`center`,F=`left`,I=`bottom`,te=`right`,ne=`none`,re=/\r?\n/,ie=`moving`,ae=`scaling`,oe=`rotating`,se=`rotate`,ce=`skewing`,le=`resizing`,ue=`modifyPoly`,de=`changed`,fe=`scale`,pe=`scaleX`,me=`scaleY`,he=`skewX`,ge=`skewY`,_e=`fill`,ve=`stroke`,ye=`modified`,be=`normal`,xe=`json`,L=new class{constructor(){this[xe]=new Map,this.svg=new Map}has(e){return this[xe].has(e)}getClass(e){let t=this[xe].get(e);if(!t)throw new _(`No class registered for ${e}`);return t}setClass(e,t){t?this[xe].set(t,e):(this[xe].set(e.type,e),this[xe].set(e.type.toLowerCase(),e))}getSVGClass(e){return this.svg.get(e)}setSVGClass(e,t){this.svg.set(t??e.type.toLowerCase(),e)}},Se=new class extends Array{remove(e){let t=this.indexOf(e);t>-1&&this.splice(t,1)}cancelAll(){let e=this.splice(0);return e.forEach(e=>e.abort()),e}cancelByCanvas(e){if(!e)return[];let t=this.filter(t=>t.target===e||typeof t.target==`object`&&t.target?.canvas===e);return t.forEach(e=>e.abort()),t}cancelByTarget(e){if(!e)return[];let t=this.filter(t=>t.target===e);return t.forEach(e=>e.abort()),t}},Ce=class{constructor(){p(this,`__eventListeners`,{})}on(e,t){if(this.__eventListeners||={},typeof e==`object`)return Object.entries(e).forEach(([e,t])=>{this.on(e,t)}),()=>this.off(e);if(t){let n=e;return this.__eventListeners[n]||(this.__eventListeners[n]=[]),this.__eventListeners[n].push(t),()=>this.off(n,t)}return()=>!1}once(e,t){if(typeof e==`object`){let t=[];return Object.entries(e).forEach(([e,n])=>{t.push(this.once(e,n))}),()=>t.forEach(e=>e())}if(t){let n=this.on(e,function(...e){t.call(this,...e),n()});return n}return()=>!1}_removeEventListener(e,t){if(this.__eventListeners[e]){if(t){let n=this.__eventListeners[e],r=n.indexOf(t);r>-1&&n.splice(r,1)}else this.__eventListeners[e]=[]}}off(e,t){if(this.__eventListeners){if(e===void 0)for(let e in this.__eventListeners)this._removeEventListener(e);else typeof e==`object`?Object.entries(e).forEach(([e,t])=>{this._removeEventListener(e,t)}):this._removeEventListener(e,t)}}fire(e,t){if(!this.__eventListeners)return;let n=this.__eventListeners[e]?.concat();if(n)for(let e=0;e<n.length;e++)n[e].call(this,t||{})}},we=(e,t)=>{let n=e.indexOf(t);return n!==-1&&e.splice(n,1),e},Te=e=>{if(e===0)return 1;switch(Math.abs(e)/A){case 1:case 3:return 0;case 2:return-1}return Math.cos(e)},Ee=e=>{if(e===0)return 0;let t=e/A,n=Math.sign(e);switch(t){case 1:return n;case 2:return 0;case 3:return-n}return Math.sin(e)},R=class e{constructor(e=0,t=0){typeof e==`object`?(this.x=e.x,this.y=e.y):(this.x=e,this.y=t)}add(t){return new e(this.x+t.x,this.y+t.y)}addEquals(e){return this.x+=e.x,this.y+=e.y,this}scalarAdd(t){return new e(this.x+t,this.y+t)}scalarAddEquals(e){return this.x+=e,this.y+=e,this}subtract(t){return new e(this.x-t.x,this.y-t.y)}subtractEquals(e){return this.x-=e.x,this.y-=e.y,this}scalarSubtract(t){return new e(this.x-t,this.y-t)}scalarSubtractEquals(e){return this.x-=e,this.y-=e,this}multiply(t){return new e(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new e(this.x*t,this.y*t)}scalarMultiplyEquals(e){return this.x*=e,this.y*=e,this}divide(t){return new e(this.x/t.x,this.y/t.y)}scalarDivide(t){return new e(this.x/t,this.y/t)}scalarDivideEquals(e){return this.x/=e,this.y/=e,this}eq(e){return this.x===e.x&&this.y===e.y}lt(e){return this.x<e.x&&this.y<e.y}lte(e){return this.x<=e.x&&this.y<=e.y}gt(e){return this.x>e.x&&this.y>e.y}gte(e){return this.x>=e.x&&this.y>=e.y}lerp(t,n=.5){return n=Math.max(Math.min(1,n),0),new e(this.x+(t.x-this.x)*n,this.y+(t.y-this.y)*n)}distanceFrom(e){let t=this.x-e.x,n=this.y-e.y;return Math.sqrt(t*t+n*n)}midPointFrom(e){return this.lerp(e)}min(t){return new e(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new e(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return`${this.x},${this.y}`}setXY(e,t){return this.x=e,this.y=t,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setFromPoint(e){return this.x=e.x,this.y=e.y,this}swap(e){let t=this.x,n=this.y;this.x=e.x,this.y=e.y,e.x=t,e.y=n}clone(){return new e(this.x,this.y)}rotate(t,n=De){let r=Ee(t),i=Te(t),a=this.subtract(n);return new e(a.x*i-a.y*r,a.x*r+a.y*i).add(n)}transform(t,n=!1){return new e(t[0]*this.x+t[2]*this.y+(n?0:t[4]),t[1]*this.x+t[3]*this.y+(n?0:t[5]))}},De=new R(0,0),Oe=e=>!!e&&Array.isArray(e._objects);function ke(e){class t extends e{constructor(...e){super(...e),p(this,`_objects`,[])}_onObjectAdded(e){}_onObjectRemoved(e){}_onStackOrderChanged(e){}add(...e){let t=this._objects.push(...e);return e.forEach(e=>this._onObjectAdded(e)),t}insertAt(e,...t){return this._objects.splice(e,0,...t),t.forEach(e=>this._onObjectAdded(e)),this._objects.length}remove(...e){let t=this._objects,n=[];return e.forEach(e=>{let r=t.indexOf(e);r!==-1&&(t.splice(r,1),n.push(e),this._onObjectRemoved(e))}),n}forEachObject(e){this.getObjects().forEach((t,n,r)=>e(t,n,r))}getObjects(...e){return e.length===0?[...this._objects]:this._objects.filter(t=>t.isType(...e))}item(e){return this._objects[e]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(e,n){return!!this._objects.includes(e)||!!n&&this._objects.some(n=>n instanceof t&&n.contains(e,!0))}complexity(){return this._objects.reduce((e,t)=>e+=t.complexity?t.complexity():0,0)}sendObjectToBack(e){return!(!e||e===this._objects[0])&&(we(this._objects,e),this._objects.unshift(e),this._onStackOrderChanged(e),!0)}bringObjectToFront(e){return!(!e||e===this._objects[this._objects.length-1])&&(we(this._objects,e),this._objects.push(e),this._onStackOrderChanged(e),!0)}sendObjectBackwards(e,t){if(!e)return!1;let n=this._objects.indexOf(e);if(n!==0){let r=this.findNewLowerIndex(e,n,t);return we(this._objects,e),this._objects.splice(r,0,e),this._onStackOrderChanged(e),!0}return!1}bringObjectForward(e,t){if(!e)return!1;let n=this._objects.indexOf(e);if(n!==this._objects.length-1){let r=this.findNewUpperIndex(e,n,t);return we(this._objects,e),this._objects.splice(r,0,e),this._onStackOrderChanged(e),!0}return!1}moveObjectTo(e,t){return e!==this._objects[t]&&(we(this._objects,e),this._objects.splice(t,0,e),this._onStackOrderChanged(e),!0)}findNewLowerIndex(e,t,n){let r;if(n){r=t;for(let n=t-1;n>=0;--n)if(e.isOverlapping(this._objects[n])){r=n;break}}else r=t-1;return r}findNewUpperIndex(e,t,n){let r;if(n){r=t;for(let n=t+1;n<this._objects.length;++n)if(e.isOverlapping(this._objects[n])){r=n;break}}else r=t+1;return r}collectObjects({left:e,top:t,width:n,height:r},{includeIntersecting:i=!0}={}){let a=[],o=new R(e,t),s=o.add(new R(n,r));for(let e=this._objects.length-1;e>=0;e--){let t=this._objects[e];t.selectable&&t.visible&&(i&&t.intersectsWithRect(o,s)||t.isContainedWithinRect(o,s)||i&&t.containsPoint(o)||i&&t.containsPoint(s))&&a.push(t)}return a}}return t}var Ae=class extends Ce{_setOptions(e={}){for(let t in e)this.set(t,e[t])}_setObject(e){for(let t in e)this._set(t,e[t])}set(e,t){return typeof e==`object`?this._setObject(e):this._set(e,t),this}_set(e,t){this[e]=t}toggle(e){let t=this.get(e);return typeof t==`boolean`&&this.set(e,!t),this}get(e){return this[e]}};function je(e){return T().requestAnimationFrame(e)}function Me(e){return T().cancelAnimationFrame(e)}var Ne=0,Pe=()=>Ne++,Fe=()=>{let e=w().createElement(`canvas`);if(!e||e.getContext===void 0)throw new _("Failed to create `canvas` element");return e},Ie=()=>w().createElement(`img`),Le=e=>{var t;let n=Re(e);return(t=n.getContext(`2d`))==null||t.drawImage(e,0,0),n},Re=e=>{let t=Fe();return t.width=e.width,t.height=e.height,t},ze=(e,t,n)=>e.toDataURL(`image/${t}`,n),Be=(e,t,n)=>new Promise((r,i)=>{e.toBlob(r,`image/${t}`,n)}),z=e=>e*ee,Ve=e=>e/ee,He=e=>e.every((e,t)=>e===N[t]),Ue=(e,t,n)=>new R(e).transform(t,n),We=e=>{let t=1/(e[0]*e[3]-e[1]*e[2]),n=[t*e[3],-t*e[1],-t*e[2],t*e[0],0,0],{x:r,y:i}=new R(e[4],e[5]).transform(n,!0);return n[4]=-r,n[5]=-i,n},B=(e,t,n)=>[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],n?0:e[0]*t[4]+e[2]*t[5]+e[4],n?0:e[1]*t[4]+e[3]*t[5]+e[5]],Ge=(e,t)=>e.reduceRight((e,n)=>n&&e?B(n,e,t):n||e,void 0)||N.concat(),Ke=([e,t])=>Math.atan2(t,e),qe=([e,t])=>Math.sqrt(e*e+t*t),Je=([,,e,t])=>Math.sqrt(e*e+t*t),Ye=e=>{let t=Ke(e),n=e[0]**2+e[1]**2,r=Math.sqrt(n),i=(e[0]*e[3]-e[2]*e[1])/r,a=Math.atan2(e[0]*e[2]+e[1]*e[3],n);return{angle:Ve(t),scaleX:r,scaleY:i,skewX:Ve(a),skewY:0,translateX:e[4]||0,translateY:e[5]||0}},Xe=(e,t=0)=>[1,0,0,1,e,t];function Ze({angle:e=0}={},{x:t=0,y:n=0}={}){let r=z(e),i=Te(r),a=Ee(r);return[i,a,-a,i,t?t-(i*t-a*n):0,n?n-(a*t+i*n):0]}var Qe=(e,t=e)=>[e,0,0,t,0,0],$e=e=>Math.tan(z(e)),et=e=>[1,0,$e(e),1,0,0],tt=e=>[1,$e(e),0,1,0,0],nt=({scaleX:e=1,scaleY:t=1,flipX:n=!1,flipY:r=!1,skewX:i=0,skewY:a=0})=>{let o=Qe(n?-e:e,r?-t:t);return i&&(o=B(o,et(i),!0)),a&&(o=B(o,tt(a),!0)),o},rt=e=>{let{translateX:t=0,translateY:n=0,angle:r=0}=e,i=Xe(t,n);r&&(i=B(i,Ze({angle:r})));let a=nt(e);return He(a)||(i=B(i,a)),i},it=(e,{signal:t,crossOrigin:n=null}={})=>new Promise(function(r,i){if(t&&t.aborted)return i(new v(`loadImage`));let a=Ie(),o;t&&(o=function(e){a.src=``,i(e)},t.addEventListener(`abort`,o,{once:!0}));let s=function(){a.onload=a.onerror=null,o&&t?.removeEventListener(`abort`,o),r(a)};e?(a.onload=s,a.onerror=function(){o&&t?.removeEventListener(`abort`,o),i(new _(`Error loading ${a.src}`))},n&&(a.crossOrigin=n),a.src=e):s()}),at=(e,{signal:t,reviver:n=k}={})=>new Promise((r,i)=>{let a=[];t&&t.addEventListener(`abort`,i,{once:!0}),Promise.allSettled(e.map(e=>L.getClass(e.type).fromObject(e,{signal:t}))).then(async t=>{for(let[r,i]of t.entries())if(i.status===`fulfilled`&&(await n(e[r],i.value),a.push(i.value)),i.status===`rejected`){let t=await n(e[r],void 0,i.reason);t&&a.push(t)}r(a)}).catch(e=>{a.forEach(e=>{e.dispose&&e.dispose()}),i(e)}).finally(()=>{t&&t.removeEventListener(`abort`,i)})}),ot=(e,{signal:t}={})=>new Promise((n,r)=>{let i=[];t&&t.addEventListener(`abort`,r,{once:!0});let a=Object.values(e).map(e=>e&&e.type&&L.has(e.type)?at([e],{signal:t}).then(([e])=>(i.push(e),e)):e),o=Object.keys(e);Promise.all(a).then(e=>e.reduce((e,t,n)=>(e[o[n]]=t,e),{})).then(n).catch(e=>{i.forEach(e=>{e.dispose&&e.dispose()}),r(e)}).finally(()=>{t&&t.removeEventListener(`abort`,r)})}),st=(e,t=[])=>t.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{}),ct=(e,t)=>Object.keys(e).reduce((n,r)=>(t(e[r],r,e)&&(n[r]=e[r]),n),{}),V=(e,t)=>parseFloat(Number(e).toFixed(t)),lt=e=>`matrix(`+e.map(e=>V(e,h.NUM_FRACTION_DIGITS)).join(` `)+`)`,ut=e=>!!e&&e.toLive!==void 0,dt=e=>!!e&&typeof e.toObject==`function`,ft=e=>!!e&&e.offsetX!==void 0&&`source`in e,pt=e=>!!e&&`multiSelectionStacking`in e;function mt(e){let t=e&&ht(e),n=0,r=0;if(!e||!t)return{left:n,top:r};let i=e,a=t.documentElement,o=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(n=o.scrollLeft||a.scrollLeft||0,r=o.scrollTop||a.scrollTop||0):(n+=i.scrollLeft||0,r+=i.scrollTop||0),i.nodeType!==1||i.style.position!==`fixed`););return{left:n,top:r}}var ht=e=>e.ownerDocument||null,gt=e=>e.ownerDocument?.defaultView||null,_t=(e,t,{width:n,height:r},i=1)=>{e.width=n,e.height=r,i>1&&(e.setAttribute(`width`,(n*i).toString()),e.setAttribute(`height`,(r*i).toString()),t.scale(i,i))},vt=(e,{width:t,height:n})=>{t&&(e.style.width=typeof t==`number`?`${t}px`:t),n&&(e.style.height=typeof n==`number`?`${n}px`:n)};function yt(e){return e.onselectstart!==void 0&&(e.onselectstart=()=>!1),e.style.userSelect=ne,e}var bt=class{constructor(e){p(this,`_originalCanvasStyle`,void 0),p(this,`lower`,void 0);let t=this.createLowerCanvas(e);this.lower={el:t,ctx:t.getContext(`2d`)}}createLowerCanvas(e){let t=(n=e)&&n.getContext!==void 0?e:e&&w().getElementById(e)||Fe();var n;if(t.hasAttribute(`data-fabric`))throw new _(`Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?`);return this._originalCanvasStyle=t.style.cssText,t.setAttribute(`data-fabric`,`main`),t.classList.add(`lower-canvas`),t}cleanupDOM({width:e,height:t}){let{el:n}=this.lower;n.classList.remove(`lower-canvas`),n.removeAttribute(`data-fabric`),n.setAttribute(`width`,`${e}`),n.setAttribute(`height`,`${t}`),n.style.cssText=this._originalCanvasStyle||``,this._originalCanvasStyle=void 0}setDimensions(e,t){let{el:n,ctx:r}=this.lower;_t(n,r,e,t)}setCSSDimensions(e){vt(this.lower.el,e)}calcOffset(){return function(e){let t=e&&ht(e),n={left:0,top:0};if(!t)return n;let r=gt(e)?.getComputedStyle(e,null)||{};n.left+=parseInt(r.borderLeftWidth,10)||0,n.top+=parseInt(r.borderTopWidth,10)||0,n.left+=parseInt(r.paddingLeft,10)||0,n.top+=parseInt(r.paddingTop,10)||0;let i={left:0,top:0},a=t.documentElement;e.getBoundingClientRect!==void 0&&(i=e.getBoundingClientRect());let o=mt(e);return{left:i.left+o.left-(a.clientLeft||0)+n.left,top:i.top+o.top-(a.clientTop||0)+n.top}}(this.lower.el)}dispose(){C().dispose(this.lower.el),delete this.lower}},xt={backgroundVpt:!0,backgroundColor:``,overlayVpt:!0,overlayColor:``,includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...N],patternQuality:`best`},St=u({capitalize:()=>Ct,escapeXml:()=>H,graphemeSplit:()=>Tt}),Ct=(e,t=!1)=>`${e.charAt(0).toUpperCase()}${t?e.slice(1):e.slice(1).toLowerCase()}`,H=e=>e.toString().replace(/&/g,`&`).replace(/"/g,`"`).replace(/'/g,`'`).replace(/</g,`<`).replace(/>/g,`>`),wt,Tt=e=>{if(wt||wt||(wt=`Intl`in T()&&`Segmenter`in Intl&&new Intl.Segmenter(void 0,{granularity:`grapheme`})),wt){let t=wt.segment(e);return Array.from(t).map(({segment:e})=>e)}return Et(e)},Et=e=>{let t=[];for(let n,r=0;r<e.length;r++)!1!==(n=Dt(e,r))&&t.push(n);return t},Dt=(e,t)=>{let n=e.charCodeAt(t);if(isNaN(n))return``;if(n<55296||n>57343)return e.charAt(t);if(55296<=n&&n<=56319){if(e.length<=t+1)throw`High surrogate without following low surrogate`;let n=e.charCodeAt(t+1);if(56320>n||n>57343)throw`High surrogate without following low surrogate`;return e.charAt(t)+e.charAt(t+1)}if(t===0)throw`Low surrogate without preceding high surrogate`;let r=e.charCodeAt(t-1);if(55296>r||r>56319)throw`Low surrogate without preceding high surrogate`;return!1},Ot=class e extends ke(Ae){get lowerCanvasEl(){return this.elements.lower?.el}get contextContainer(){return this.elements.lower?.ctx}static getDefaults(){return e.ownDefaults}constructor(e,t={}){super(),Object.assign(this,this.constructor.getDefaults()),this.set(t),this.initElements(e),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(e){this.elements=new bt(e)}add(...e){let t=super.add(...e);return e.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(e,...t){let n=super.insertAt(e,...t);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(...e){let t=super.remove(...e);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(e){e.canvas&&e.canvas!==this&&(g(`warn`,`Canvas is trying to add an object that belongs to a different canvas.
|
|
2
|
+
Resulting to default behavior: removing object from previous canvas and adding to new canvas`),e.canvas.remove(e)),e._set(`canvas`,this),e.setCoords(),this.fire(`object:added`,{target:e}),e.fire(`added`,{target:this})}_onObjectRemoved(e){e._set(`canvas`,void 0),this.fire(`object:removed`,{target:e}),e.fire(`removed`,{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?E():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(e,{cssOnly:t=!1,backstoreOnly:n=!1}={}){if(!t){let t={width:this.width,height:this.height,...e};this.elements.setDimensions(t,this.getRetinaScaling()),this.hasLostContext=!0,this.width=t.width,this.height=t.height}n||this.elements.setCSSDimensions(e),this.calcOffset()}setDimensions(e,t){this._setDimensionsImpl(e,t),t&&t.cssOnly||this.requestRenderAll()}getZoom(){return qe(this.viewportTransform)}setViewportTransform(e){this.viewportTransform=e,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(e,t){let n=e,r=[...this.viewportTransform],i=Ue(e,We(r));r[0]=t,r[3]=t;let a=Ue(i,r);r[4]+=n.x-a.x,r[5]+=n.y-a.y,this.setViewportTransform(r)}setZoom(e){this.zoomToPoint(new R(0,0),e)}absolutePan(e){let t=[...this.viewportTransform];return t[4]=-e.x,t[5]=-e.y,this.setViewportTransform(t)}relativePan(e){return this.absolutePan(new R(-e.x-this.viewportTransform[4],-e.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(e){e.clearRect(0,0,this.width,this.height)}getContext(){return this.elements.lower.ctx}clear(){this.remove(...this.getObjects()),this.backgroundImage=void 0,this.overlayImage=void 0,this.backgroundColor=``,this.overlayColor=``,this.clearContext(this.getContext()),this.fire(`canvas:cleared`),this.renderOnAddRemove&&this.requestRenderAll()}renderAll(){this.cancelRequestedRender(),this.destroyed||this.renderCanvas(this.getContext(),this._objects)}renderAndReset(){this.nextRenderHandle=0,this.renderAll()}requestRenderAll(){this.nextRenderHandle||this.disposed||this.destroyed||(this.nextRenderHandle=je(()=>this.renderAndReset()))}calcViewportBoundaries(){let e=this.width,t=this.height,n=We(this.viewportTransform),r=Ue({x:0,y:0},n),i=Ue({x:e,y:t},n),a=r.min(i),o=r.max(i);return this.vptCoords={tl:a,tr:new R(o.x,a.y),bl:new R(a.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&=(Me(this.nextRenderHandle),0)}drawControls(e){}renderCanvas(e,t){if(this.destroyed)return;let n=this.viewportTransform,r=this.clipPath;this.calcViewportBoundaries(),this.clearContext(e),e.imageSmoothingEnabled=this.imageSmoothingEnabled,e.patternQuality=this.patternQuality,this.fire(`before:render`,{ctx:e}),this._renderBackground(e),e.save(),e.transform(n[0],n[1],n[2],n[3],n[4],n[5]),this._renderObjects(e,t),e.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(e),r&&(r._set(`canvas`,this),r.shouldCache(),r._transformDone=!0,r.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(e,r)),this._renderOverlay(e),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(e),this.fire(`after:render`,{ctx:e}),this.__cleanupTask&&=(this.__cleanupTask(),void 0)}drawClipPathOnCanvas(e,t){let n=this.viewportTransform;e.save(),e.transform(...n),e.globalCompositeOperation=`destination-in`,t.transform(e),e.scale(1/t.zoomX,1/t.zoomY),e.drawImage(t._cacheCanvas,-t.cacheTranslationX,-t.cacheTranslationY),e.restore()}_renderObjects(e,t){for(let n=0,r=t.length;n<r;++n)t[n]&&t[n].render(e)}_renderBackgroundOrOverlay(e,t){let n=this[`${t}Color`],r=this[`${t}Image`],i=this.viewportTransform,a=this[`${t}Vpt`];if(!n&&!r)return;let o=ut(n);if(n){if(e.save(),e.beginPath(),e.moveTo(0,0),e.lineTo(this.width,0),e.lineTo(this.width,this.height),e.lineTo(0,this.height),e.closePath(),e.fillStyle=o?n.toLive(e):n,a&&e.transform(...i),o){e.transform(1,0,0,1,n.offsetX||0,n.offsetY||0);let t=n.gradientTransform||n.patternTransform;t&&e.transform(...t)}e.fill(),e.restore()}if(r){e.save();let{skipOffscreen:t}=this;this.skipOffscreen=a,a&&e.transform(...i),r.render(e),this.skipOffscreen=t,e.restore()}}_renderBackground(e){this._renderBackgroundOrOverlay(e,`background`)}_renderOverlay(e){this._renderBackgroundOrOverlay(e,`overlay`)}getCenterPoint(){return new R(this.width/2,this.height/2)}centerObjectH(e){return this._centerObject(e,new R(this.getCenterPoint().x,e.getCenterPoint().y))}centerObjectV(e){return this._centerObject(e,new R(e.getCenterPoint().x,this.getCenterPoint().y))}centerObject(e){return this._centerObject(e,this.getCenterPoint())}viewportCenterObject(e){return this._centerObject(e,this.getVpCenter())}viewportCenterObjectH(e){return this._centerObject(e,new R(this.getVpCenter().x,e.getCenterPoint().y))}viewportCenterObjectV(e){return this._centerObject(e,new R(e.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Ue(this.getCenterPoint(),We(this.viewportTransform))}_centerObject(e,t){e.setXY(t,P,P),e.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(e){return this.toDatalessObject(e)}toObject(e){return this._toObjectMethod(`toObject`,e)}toJSON(){return this.toObject()}toDatalessObject(e){return this._toObjectMethod(`toDatalessObject`,e)}_toObjectMethod(e,t){let n=this.clipPath,r=n&&!n.excludeFromExport?this._toObject(n,e,t):null;return{version:O,...st(this,t),objects:this._objects.filter(e=>!e.excludeFromExport).map(n=>this._toObject(n,e,t)),...this.__serializeBgOverlay(e,t),...r?{clipPath:r}:null}}_toObject(e,t,n){let r;this.includeDefaultValues||(r=e.includeDefaultValues,e.includeDefaultValues=!1);let i=e[t](n);return this.includeDefaultValues||(e.includeDefaultValues=!!r),i}__serializeBgOverlay(e,t){let n={},r=this.backgroundImage,i=this.overlayImage,a=this.backgroundColor,o=this.overlayColor;return ut(a)?a.excludeFromExport||(n.background=a.toObject(t)):a&&(n.background=a),ut(o)?o.excludeFromExport||(n.overlay=o.toObject(t)):o&&(n.overlay=o),r&&!r.excludeFromExport&&(n.backgroundImage=this._toObject(r,e,t)),i&&!i.excludeFromExport&&(n.overlayImage=this._toObject(i,e,t)),n}toSVG(e={},t){e.reviver=t;let n=[];return this._setSVGPreamble(n,e),this._setSVGHeader(n,e),this.clipPath&&n.push(`<g clip-path="url(#${H(this.clipPath.clipPathId??``)})" >\n`),this._setSVGBgOverlayColor(n,`background`),this._setSVGBgOverlayImage(n,`backgroundImage`,t),this._setSVGObjects(n,t),this.clipPath&&n.push(`</g>
|
|
3
3
|
`),this._setSVGBgOverlayColor(n,`overlay`),this._setSVGBgOverlayImage(n,`overlayImage`,t),n.push(`</svg>`),n.join(``)}_setSVGPreamble(e,t){t.suppressPreamble||e.push(`<?xml version="1.0" encoding="`,t.encoding||`UTF-8`,`" standalone="no" ?>
|
|
4
4
|
`,`<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" `,`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
|
5
5
|
`)}_setSVGHeader(e,t){let n=t.width||`${this.width}`,r=t.height||`${this.height}`,i=h.NUM_FRACTION_DIGITS,a=t.viewBox,o;if(a)o=`viewBox="${a.x} ${a.y} ${a.width} ${a.height}" `;else if(this.svgViewportTransformation){let e=this.viewportTransform;o=`viewBox="${V(-e[4]/e[0],i)} ${V(-e[5]/e[3],i)} ${V(this.width/e[0],i)} ${V(this.height/e[3],i)}" `}else o=`viewBox="0 0 ${this.width} ${this.height}" `;e.push(`<svg `,`xmlns="http://www.w3.org/2000/svg" `,`xmlns:xlink="http://www.w3.org/1999/xlink" `,`version="1.1" `,`width="`,n,`" `,`height="`,r,`" `,o,`xml:space="preserve">
|
|
6
6
|
`,`<desc>Created with Fabric.js `,O,`</desc>
|
|
7
7
|
`,`<defs>
|
|
8
8
|
`,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(t),`</defs>
|
|
9
|
-
`)}createSVGClipPathMarkup(e){let t=this.clipPath;return t?(t.clipPathId=`CLIPPATH_${Pe()}`,`<clipPath id="${t.clipPathId}" >\n${t.toClipPathSVG(e.reviver)}</clipPath>\n`):``}createSVGRefElementsMarkup(){return[`background`,`overlay`].map(e=>{let t=this[`${e}Color`];if(ut(t)){let n=this[`${e}Vpt`],r=this.viewportTransform,i={isType:()=>!1,width:this.width/(n?r[0]:1),height:this.height/(n?r[3]:1)};return t.toSVG(i,{additionalTransform:n?lt(r):``})}}).join(``)}createSVGFontFacesMarkup(){let e=[],t={},n=h.fontPaths;this._objects.forEach(function t(n){e.push(n),Oe(n)&&n._objects.forEach(t)}),e.forEach(e=>{if(!(r=e)||typeof r._renderText!=`function`)return;var r;let{styles:i,fontFamily:a}=e;!t[a]&&n[a]&&(t[a]=!0,i&&Object.values(i).forEach(e=>{Object.values(e).forEach(({fontFamily:e=``})=>{!t[e]&&n[e]&&(t[e]=!0)})}))});let r=Object.keys(t).map(e=>`\t\t@font-face {\n\t\t\tfont-family: '${e}';\n\t\t\tsrc: url('${n[e]}');\n\t\t}\n`).join(``);return r?`\t<style type="text/css"><![CDATA[\n${r}]]></style>\n`:``}_setSVGObjects(e,t){this.forEachObject(n=>{n.excludeFromExport||this._setSVGObject(e,n,t)})}_setSVGObject(e,t,n){e.push(t.toSVG(n))}_setSVGBgOverlayImage(e,t,n){let r=this[t];r&&!r.excludeFromExport&&r.toSVG&&e.push(r.toSVG(n))}_setSVGBgOverlayColor(e,t){let n=this[`${t}Color`];if(n)if(ut(n)){let r=n.repeat||``,i=this.width,a=this.height,o=this[`${t}Vpt`]?lt(We(this.viewportTransform)):``;e.push(`<rect transform="${o} translate(${i/2},${a/2})" x="${n.offsetX-i/2}" y="${n.offsetY-a/2}" width="${r!==`repeat-y`&&r!==`no-repeat`||!ft(n)?i:n.source.width}" height="${r!==`repeat-x`&&r!==`no-repeat`||!ft(n)?a:n.source.height}" fill="url(#SVGID_${n.id})"></rect>\n`)}else e.push(`<rect x="0" y="0" width="100%" height="100%" `,`fill="`,n,`"`,`></rect>
|
|
10
|
-
`)}loadFromJSON(e,t,{signal:n}={}){if(!e)return Promise.reject(new _("`json` is undefined"));let{objects:r=[],...i}=typeof e==`string`?JSON.parse(e):e,{backgroundImage:a,background:o,overlayImage:s,overlay:c,clipPath:l}=i,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([at(r,{reviver:t,signal:n}),ot({backgroundImage:a,backgroundColor:o,overlayImage:s,overlayColor:c,clipPath:l},{signal:n})]).then(([e,t])=>(this.clear(),this.add(...e),this.set(i),this.set(t),this.renderOnAddRemove=u,this))}clone(e){let t=this.toObject(e);return this.cloneWithoutData().loadFromJSON(t)}cloneWithoutData(){let e=Re(this);return new this.constructor(e)}toDataURL(e={}){let{format:t=`png`,quality:n=1,multiplier:r=1,enableRetinaScaling:i=!1}=e,a=r*(i?this.getRetinaScaling():1);return ze(this.toCanvasElement(a,e),t,n)}toBlob(e={}){let{format:t=`png`,quality:n=1,multiplier:r=1,enableRetinaScaling:i=!1}=e,a=r*(i?this.getRetinaScaling():1);return Be(this.toCanvasElement(a,e),t,n)}toCanvasElement(e=1,{width:t,height:n,left:r,top:i,filter:a}={}){let o=(t||this.width)*e,s=(n||this.height)*e,c=this.getZoom(),l=this.width,u=this.height,d=this.skipControlsDrawing,f=c*e,p=this.viewportTransform,m=[f,0,0,f,(p[4]-(r||0))*e,(p[5]-(i||0))*e],h=this.enableRetinaScaling,g=Re({width:o,height:s}),_=a?this._objects.filter(e=>a(e)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=s,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(g.getContext(`2d`),_),this.viewportTransform=p,this.width=l,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=h,this.skipControlsDrawing=d,g}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Se.cancelByCanvas(this),this.disposed=!0,new Promise((e,t)=>{let n=()=>{this.destroy(),e(!0)};n.kill=t,this.__cleanupTask&&this.__cleanupTask.kill(`aborted`),this.destroyed?e(!1):this.nextRenderHandle?this.__cleanupTask=n:n()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(e=>e.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return`#<Canvas (${this.complexity()}): { objects: ${this._objects.length} }>`}};p(Ot,`ownDefaults`,xt);var kt=[`touchstart`,`touchmove`,`touchend`],At=e=>{let t=mt(e.target),n=function(e){let t=e.changedTouches;return t&&t[0]?t[0]:e}(e);return new R(n.clientX+t.left,n.clientY+t.top)},jt=e=>kt.includes(e.type)||e.pointerType===`touch`,Mt=e=>{e.preventDefault(),e.stopPropagation()},Nt=e=>{let t=0,n=0,r=0,i=0;for(let a=0,o=e.length;a<o;a++){let{x:o,y:s}=e[a];(o>r||!a)&&(r=o),(o<t||!a)&&(t=o),(s>i||!a)&&(i=s),(s<n||!a)&&(n=s)}return{left:t,top:n,width:r-t,height:i-n}},Pt=(e,t)=>{It(e,B(We(t),e.calcOwnMatrix()))},Ft=(e,t)=>It(e,B(t,e.calcOwnMatrix())),It=(e,t)=>{let{translateX:n,translateY:r,scaleX:i,scaleY:a,...o}=Ye(t),s=new R(n,r);e.flipX=!1,e.flipY=!1,Object.assign(e,o),e.set({scaleX:i,scaleY:a}),e.setPositionByOrigin(s,P,P)},Lt=e=>{e.scaleX=1,e.scaleY=1,e.skewX=0,e.skewY=0,e.flipX=!1,e.flipY=!1,e.rotate(0)},Rt=e=>({scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,angle:e.angle,left:e.left,flipX:e.flipX,flipY:e.flipY,top:e.top}),zt=(e,t,n)=>{let r=e/2,i=t/2,a=Nt([new R(-r,-i),new R(r,-i),new R(-r,i),new R(r,i)].map(e=>e.transform(n)));return new R(a.width,a.height)},Bt=(e=N,t=N)=>B(We(t),e),Vt=(e,t=N,n=N)=>e.transform(Bt(t,n)),Ht=(e,t=N,n=N)=>e.transform(Bt(t,n),!0),Ut=(e,t,n)=>{let r=Bt(t,n);return It(e,B(r,e.calcOwnMatrix())),r},Wt={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Gt=e=>typeof e==`string`?Wt[e]:e-.5,Kt=new R(1,0),qt=new R,Jt=(e,t)=>e.rotate(t),Yt=(e,t)=>new R(t).subtract(e),Xt=e=>e.distanceFrom(qt),Zt=(e,t)=>Math.atan2(tn(e,t),nn(e,t)),Qt=e=>Zt(Kt,e),$t=e=>e.eq(qt)?e:e.scalarDivide(Xt(e)),en=(e,t=!0)=>$t(new R(-e.y,e.x).scalarMultiply(t?1:-1)),tn=(e,t)=>e.x*t.y-e.y*t.x,nn=(e,t)=>e.x*t.x+e.y*t.y,rn=(e,t,n)=>{if(e.eq(t)||e.eq(n))return!0;let r=tn(t,n),i=tn(t,e),a=tn(n,e);return r>=0?i>=0&&a<=0:!(i<=0&&a>=0)},an=`not-allowed`;function on(e){return Gt(e.originX)===Gt(`center`)&&Gt(e.originY)===Gt(`center`)}function sn(e){return .5-Gt(e)}var cn=(e,t)=>e[t],ln=(e,t,n,r)=>({e,transform:t,pointer:new R(n,r)});function un(e,t,n){let r=n,i=Qt(Yt(Vt(e.getCenterPoint(),e.canvas.viewportTransform,void 0),r))+M;return Math.round(i%M/j)}function dn({target:e,corner:t},n,r,i,a){let o=e.controls[t],s=e.canvas?.getZoom()||1,c=e.padding/s,l=function(e,t,n,r){let i=e.getRelativeCenterPoint(),a=n!==void 0&&r!==void 0?e.translateToGivenOrigin(i,P,P,n,r):new R(e.left,e.top);return(e.angle?t.rotate(-z(e.angle),i):t).subtract(a)}(e,new R(i,a),n,r);return l.x>=c&&(l.x-=c),l.x<=-c&&(l.x+=c),l.y>=c&&(l.y-=c),l.y<=c&&(l.y+=c),l.x-=o.offsetX,l.y-=o.offsetY,l}var fn=new RegExp(String.raw`[\0-\x1F\x7F;<>\\]|\/\*|\*\/|url\s*\(|expression\s*\(|(?:java|vb)script\s*:|data\s*:|@import\b`,`iu`),pn=e=>typeof e==`string`&&e.trim().length>0&&!fn.test(e),mn=(e,t=``)=>{let n=Number(e);return Number.isFinite(n)?`${n}`:t},hn=(e,t=``)=>typeof e==`string`&&pn(e)?e:t,gn=e=>e.replace(/\s+/g,` `),_n={aliceblue:`#F0F8FF`,antiquewhite:`#FAEBD7`,aqua:`#0FF`,aquamarine:`#7FFFD4`,azure:`#F0FFFF`,beige:`#F5F5DC`,bisque:`#FFE4C4`,black:`#000`,blanchedalmond:`#FFEBCD`,blue:`#00F`,blueviolet:`#8A2BE2`,brown:`#A52A2A`,burlywood:`#DEB887`,cadetblue:`#5F9EA0`,chartreuse:`#7FFF00`,chocolate:`#D2691E`,coral:`#FF7F50`,cornflowerblue:`#6495ED`,cornsilk:`#FFF8DC`,crimson:`#DC143C`,cyan:`#0FF`,darkblue:`#00008B`,darkcyan:`#008B8B`,darkgoldenrod:`#B8860B`,darkgray:`#A9A9A9`,darkgrey:`#A9A9A9`,darkgreen:`#006400`,darkkhaki:`#BDB76B`,darkmagenta:`#8B008B`,darkolivegreen:`#556B2F`,darkorange:`#FF8C00`,darkorchid:`#9932CC`,darkred:`#8B0000`,darksalmon:`#E9967A`,darkseagreen:`#8FBC8F`,darkslateblue:`#483D8B`,darkslategray:`#2F4F4F`,darkslategrey:`#2F4F4F`,darkturquoise:`#00CED1`,darkviolet:`#9400D3`,deeppink:`#FF1493`,deepskyblue:`#00BFFF`,dimgray:`#696969`,dimgrey:`#696969`,dodgerblue:`#1E90FF`,firebrick:`#B22222`,floralwhite:`#FFFAF0`,forestgreen:`#228B22`,fuchsia:`#F0F`,gainsboro:`#DCDCDC`,ghostwhite:`#F8F8FF`,gold:`#FFD700`,goldenrod:`#DAA520`,gray:`#808080`,grey:`#808080`,green:`#008000`,greenyellow:`#ADFF2F`,honeydew:`#F0FFF0`,hotpink:`#FF69B4`,indianred:`#CD5C5C`,indigo:`#4B0082`,ivory:`#FFFFF0`,khaki:`#F0E68C`,lavender:`#E6E6FA`,lavenderblush:`#FFF0F5`,lawngreen:`#7CFC00`,lemonchiffon:`#FFFACD`,lightblue:`#ADD8E6`,lightcoral:`#F08080`,lightcyan:`#E0FFFF`,lightgoldenrodyellow:`#FAFAD2`,lightgray:`#D3D3D3`,lightgrey:`#D3D3D3`,lightgreen:`#90EE90`,lightpink:`#FFB6C1`,lightsalmon:`#FFA07A`,lightseagreen:`#20B2AA`,lightskyblue:`#87CEFA`,lightslategray:`#789`,lightslategrey:`#789`,lightsteelblue:`#B0C4DE`,lightyellow:`#FFFFE0`,lime:`#0F0`,limegreen:`#32CD32`,linen:`#FAF0E6`,magenta:`#F0F`,maroon:`#800000`,mediumaquamarine:`#66CDAA`,mediumblue:`#0000CD`,mediumorchid:`#BA55D3`,mediumpurple:`#9370DB`,mediumseagreen:`#3CB371`,mediumslateblue:`#7B68EE`,mediumspringgreen:`#00FA9A`,mediumturquoise:`#48D1CC`,mediumvioletred:`#C71585`,midnightblue:`#191970`,mintcream:`#F5FFFA`,mistyrose:`#FFE4E1`,moccasin:`#FFE4B5`,navajowhite:`#FFDEAD`,navy:`#000080`,oldlace:`#FDF5E6`,olive:`#808000`,olivedrab:`#6B8E23`,orange:`#FFA500`,orangered:`#FF4500`,orchid:`#DA70D6`,palegoldenrod:`#EEE8AA`,palegreen:`#98FB98`,paleturquoise:`#AFEEEE`,palevioletred:`#DB7093`,papayawhip:`#FFEFD5`,peachpuff:`#FFDAB9`,peru:`#CD853F`,pink:`#FFC0CB`,plum:`#DDA0DD`,powderblue:`#B0E0E6`,purple:`#800080`,rebeccapurple:`#639`,red:`#F00`,rosybrown:`#BC8F8F`,royalblue:`#4169E1`,saddlebrown:`#8B4513`,salmon:`#FA8072`,sandybrown:`#F4A460`,seagreen:`#2E8B57`,seashell:`#FFF5EE`,sienna:`#A0522D`,silver:`#C0C0C0`,skyblue:`#87CEEB`,slateblue:`#6A5ACD`,slategray:`#708090`,slategrey:`#708090`,snow:`#FFFAFA`,springgreen:`#00FF7F`,steelblue:`#4682B4`,tan:`#D2B48C`,teal:`#008080`,thistle:`#D8BFD8`,tomato:`#FF6347`,turquoise:`#40E0D0`,violet:`#EE82EE`,wheat:`#F5DEB3`,white:`#FFF`,whitesmoke:`#F5F5F5`,yellow:`#FF0`,yellowgreen:`#9ACD32`},vn=(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e),yn=(e,t,n,r)=>{e/=255,t/=255,n/=255;let i=Math.max(e,t,n),a=Math.min(e,t,n),o,s,c=(i+a)/2;if(i===a)o=s=0;else{let r=i-a;switch(s=c>.5?r/(2-i-a):r/(i+a),i){case e:o=(t-n)/r+(t<n?6:0);break;case t:o=(n-e)/r+2;break;case n:o=(e-t)/r+4}o/=6}return[Math.round(360*o),Math.round(100*s),Math.round(100*c),r]},bn=(e=`1`)=>parseFloat(e)/(e.endsWith(`%`)?100:1),xn=e=>Math.min(Math.round(e),255).toString(16).toUpperCase().padStart(2,`0`),Sn=([e,t,n,r=1])=>{let i=Math.round(.3*e+.59*t+.11*n);return[i,i,i,r]},Cn=class e{constructor(t){if(p(this,`isUnrecognised`,!1),t)if(t instanceof e)this.setSource([...t._source]);else if(Array.isArray(t)){let[e,n,r,i=1]=t;this.setSource([e,n,r,i])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in _n&&(t=_n[t]),t===`transparent`?[255,255,255,0]:e.sourceFromHex(t)||e.sourceFromRgb(t)||e.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(e){this._source=e}toRgb(){let[e,t,n]=this.getSource();return`rgb(${e},${t},${n})`}toRgba(){return`rgba(${this.getSource().join(`,`)})`}toHsl(){let[e,t,n]=yn(...this.getSource());return`hsl(${e},${t}%,${n}%)`}toHsla(){let[e,t,n,r]=yn(...this.getSource());return`hsla(${e},${t}%,${n}%,${r})`}toHex(){return this.toHexa().slice(0,6)}toHexa(){let[e,t,n,r]=this.getSource();return`${xn(e)}${xn(t)}${xn(n)}${xn(Math.round(255*r))}`}getAlpha(){return this.getSource()[3]}setAlpha(e){return this._source[3]=e,this}toGrayscale(){return this.setSource(Sn(this.getSource())),this}toBlackWhite(e){let[t,,,n]=Sn(this.getSource()),r=t<(e||127)?0:255;return this.setSource([r,r,r,n]),this}overlayWith(t){t instanceof e||(t=new e(t));let n=this.getSource(),r=t.getSource(),[i,a,o]=n.map((e,t)=>Math.round(.5*e+.5*r[t]));return this.setSource([i,a,o,n[3]]),this}static fromRgb(t){return e.fromRgba(t)}static fromRgba(t){return new e(e.sourceFromRgb(t))}static sourceFromRgb(e){let t=gn(e).match(/^rgba?\(\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d{0,3}(?:\.\d+)?%?)\s?)?\)$/i);if(t){let[e,n,r]=t.slice(1,4).map(e=>{let t=parseFloat(e);return e.endsWith(`%`)?Math.round(2.55*t):t});return[e,n,r,bn(t[4])]}}static fromHsl(t){return e.fromHsla(t)}static fromHsla(t){return new e(e.sourceFromHsl(t))}static sourceFromHsl(t){let n=gn(t).match(/^hsla?\(\s?([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d*(?:\.\d+)?%?)\s?)?\)$/i);if(!n)return;let r=(e.parseAngletoDegrees(n[1])%360+360)%360/360,i=parseFloat(n[2])/100,a=parseFloat(n[3])/100,o,s,c;if(i===0)o=s=c=a;else{let e=a<=.5?a*(i+1):a+i-a*i,t=2*a-e;o=vn(t,e,r+1/3),s=vn(t,e,r),c=vn(t,e,r-1/3)}return[Math.round(255*o),Math.round(255*s),Math.round(255*c),bn(n[4])]}static fromHex(t){return new e(e.sourceFromHex(t))}static sourceFromHex(e){if(e.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){let t=e.slice(e.indexOf(`#`)+1),n;n=t.length<=4?t.split(``).map(e=>e+e):t.match(/.{2}/g);let[r,i,a,o=255]=n.map(e=>parseInt(e,16));return[r,i,a,o/255]}}static parseAngletoDegrees(e){let t=e.toLowerCase(),n=parseFloat(t);return t.includes(`rad`)?Ve(n):t.includes(`turn`)?360*n:n}},wn=e=>{let t=[`instantiated_by_use`,`style`,`id`,`class`];switch(e){case`linearGradient`:return t.concat([`x1`,`y1`,`x2`,`y2`,`gradientUnits`,`gradientTransform`]);case`radialGradient`:return t.concat([`gradientUnits`,`gradientTransform`,`cx`,`cy`,`r`,`fx`,`fy`,`fr`]);case`stop`:return t.concat([`offset`,`stop-color`,`stop-opacity`])}return t},Tn=(e,t=16)=>{let n=/\D{0,2}$/.exec(e),r=parseFloat(e),i=h.DPI;switch(n?.[0]){case`mm`:return r*i/25.4;case`cm`:return r*i/2.54;case`in`:return r*i;case`pt`:return r*i/72;case`pc`:return r*i/72*12;case`em`:return r*t;default:return r}},En=e=>{let[t,n]=e.trim().split(` `),[r,i]=(a=t)&&a!==`none`?[a.slice(1,4),a.slice(5,8)]:a===`none`?[a,a]:[`Mid`,`Mid`];var a;return{meetOrSlice:n||`meet`,alignX:r,alignY:i}},Dn=(e,t,n=!0)=>{let r,i;if(t)if(t.toLive)r=`url(#SVGID_${H(t.id)})`;else{let e=String(t);if(pn(e)){let t=new Cn(e),n=t.getAlpha();r=t.toRgb(),n!==1&&(i=n.toString())}else r=new Cn(`black`).toRgb()}else r=`none`;return n?`${e}: ${r}; ${i?`${e}-opacity: ${i}; `:``}`:`${e}="${r}" ${i?`${e}-opacity="${i}" `:``}`},On=class{getSvgStyles(e){let t=this.fillRule==null?`nonzero`:hn(this.fillRule),n=this.strokeWidth==null?`0`:mn(this.strokeWidth),r=this.strokeDashArray==null?ne:this.strokeDashArray.every(e=>Number.isFinite(Number(e)))?this.strokeDashArray.join(` `):``,i=this.strokeDashOffset==null?`0`:mn(this.strokeDashOffset),a=this.strokeLineCap==null?`butt`:hn(this.strokeLineCap),o=this.strokeLineJoin==null?`miter`:hn(this.strokeLineJoin),s=this.strokeMiterLimit==null?`4`:mn(this.strokeMiterLimit),c=this.opacity==null?`1`:mn(this.opacity),l=this.visible?``:` visibility: hidden;`,u=e?``:this.getSvgFilter(),d=Dn(_e,this.fill);return[Dn(ve,this.stroke),n?`stroke-width: ${n}; `:``,r?`stroke-dasharray: ${r}; `:``,a?`stroke-linecap: ${a}; `:``,i?`stroke-dashoffset: ${i}; `:``,o?`stroke-linejoin: ${o}; `:``,s?`stroke-miterlimit: ${s}; `:``,d,t?`fill-rule: ${t}; `:``,c?`opacity: ${c};`:``,u,l].map(e=>H(e)).join(``)}getSvgFilter(){return this.shadow?`filter: url(#SVGID_${H(this.shadow.id)});`:``}getSvgCommons(){return[this.id?`id="${H(String(this.id))}" `:``,this.clipPath?`clip-path="url(#${H(this.clipPath.clipPathId)})" `:``].join(``)}getSvgTransform(e,t=``){return`transform="${lt(e?this.calcTransformMatrix():this.calcOwnMatrix())}${t}" `}_toSVG(e){return[``]}toSVG(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})}toClipPathSVG(e){return` `+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})}_createBaseClipPathSVGMarkup(e,{reviver:t,additionalTransform:n=``}={}){let r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(``),i=e.indexOf(`COMMON_PARTS`);return e[i]=r,t?t(e.join(``)):e.join(``)}_createBaseSVGMarkup(e,{noStyle:t,reviver:n,withShadow:r,additionalTransform:i}={}){let a=t?``:`style="${this.getSvgStyles()}" `,o=r?`style="${this.getSvgFilter()}" `:``,s=this.clipPath,c=this.strokeUniform?`vector-effect="non-scaling-stroke" `:``,l=s&&s.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,p=[],m=e.indexOf(`COMMON_PARTS`),h;return s&&(s.clipPathId=`CLIPPATH_${Pe()}`,h=`<clipPath id="${s.clipPathId}" >\n${s.toClipPathSVG(n)}</clipPath>\n`),l&&p.push(`<g `,o,this.getSvgCommons(),` >
|
|
9
|
+
`)}createSVGClipPathMarkup(e){let t=this.clipPath;return t?(t.clipPathId=`CLIPPATH_${Pe()}`,`<clipPath id="${t.clipPathId}" >\n${t.toClipPathSVG(e.reviver)}</clipPath>\n`):``}createSVGRefElementsMarkup(){return[`background`,`overlay`].map(e=>{let t=this[`${e}Color`];if(ut(t)){let n=this[`${e}Vpt`],r=this.viewportTransform,i={isType:()=>!1,width:this.width/(n?r[0]:1),height:this.height/(n?r[3]:1)};return t.toSVG(i,{additionalTransform:n?lt(r):``})}}).join(``)}createSVGFontFacesMarkup(){let e=[],t={},n=h.fontPaths;this._objects.forEach(function t(n){e.push(n),Oe(n)&&n._objects.forEach(t)}),e.forEach(e=>{if(!(r=e)||typeof r._renderText!=`function`)return;var r;let{styles:i,fontFamily:a}=e;!t[a]&&n[a]&&(t[a]=!0,i&&Object.values(i).forEach(e=>{Object.values(e).forEach(({fontFamily:e=``})=>{!t[e]&&n[e]&&(t[e]=!0)})}))});let r=Object.keys(t).map(e=>`\t\t@font-face {\n\t\t\tfont-family: '${e}';\n\t\t\tsrc: url('${n[e]}');\n\t\t}\n`).join(``);return r?`\t<style type="text/css"><![CDATA[\n${r}]]></style>\n`:``}_setSVGObjects(e,t){this.forEachObject(n=>{n.excludeFromExport||this._setSVGObject(e,n,t)})}_setSVGObject(e,t,n){e.push(t.toSVG(n))}_setSVGBgOverlayImage(e,t,n){let r=this[t];r&&!r.excludeFromExport&&r.toSVG&&e.push(r.toSVG(n))}_setSVGBgOverlayColor(e,t){let n=this[`${t}Color`];if(n){if(ut(n)){let r=n.repeat||``,i=this.width,a=this.height,o=this[`${t}Vpt`]?lt(We(this.viewportTransform)):``;e.push(`<rect transform="${o} translate(${i/2},${a/2})" x="${n.offsetX-i/2}" y="${n.offsetY-a/2}" width="${r!==`repeat-y`&&r!==`no-repeat`||!ft(n)?i:n.source.width}" height="${r!==`repeat-x`&&r!==`no-repeat`||!ft(n)?a:n.source.height}" fill="url(#SVGID_${n.id})"></rect>\n`)}else e.push(`<rect x="0" y="0" width="100%" height="100%" `,`fill="`,n,`"`,`></rect>
|
|
10
|
+
`)}}loadFromJSON(e,t,{signal:n}={}){if(!e)return Promise.reject(new _("`json` is undefined"));let{objects:r=[],...i}=typeof e==`string`?JSON.parse(e):e,{backgroundImage:a,background:o,overlayImage:s,overlay:c,clipPath:l}=i,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([at(r,{reviver:t,signal:n}),ot({backgroundImage:a,backgroundColor:o,overlayImage:s,overlayColor:c,clipPath:l},{signal:n})]).then(([e,t])=>(this.clear(),this.add(...e),this.set(i),this.set(t),this.renderOnAddRemove=u,this))}clone(e){let t=this.toObject(e);return this.cloneWithoutData().loadFromJSON(t)}cloneWithoutData(){let e=Re(this);return new this.constructor(e)}toDataURL(e={}){let{format:t=`png`,quality:n=1,multiplier:r=1,enableRetinaScaling:i=!1}=e,a=r*(i?this.getRetinaScaling():1);return ze(this.toCanvasElement(a,e),t,n)}toBlob(e={}){let{format:t=`png`,quality:n=1,multiplier:r=1,enableRetinaScaling:i=!1}=e,a=r*(i?this.getRetinaScaling():1);return Be(this.toCanvasElement(a,e),t,n)}toCanvasElement(e=1,{width:t,height:n,left:r,top:i,filter:a}={}){let o=(t||this.width)*e,s=(n||this.height)*e,c=this.getZoom(),l=this.width,u=this.height,d=this.skipControlsDrawing,f=c*e,p=this.viewportTransform,m=[f,0,0,f,(p[4]-(r||0))*e,(p[5]-(i||0))*e],h=this.enableRetinaScaling,g=Re({width:o,height:s}),_=a?this._objects.filter(e=>a(e)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=s,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(g.getContext(`2d`),_),this.viewportTransform=p,this.width=l,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=h,this.skipControlsDrawing=d,g}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Se.cancelByCanvas(this),this.disposed=!0,new Promise((e,t)=>{let n=()=>{this.destroy(),e(!0)};n.kill=t,this.__cleanupTask&&this.__cleanupTask.kill(`aborted`),this.destroyed?e(!1):this.nextRenderHandle?this.__cleanupTask=n:n()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(e=>e.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return`#<Canvas (${this.complexity()}): { objects: ${this._objects.length} }>`}};p(Ot,`ownDefaults`,xt);var kt=[`touchstart`,`touchmove`,`touchend`],At=e=>{let t=mt(e.target),n=function(e){let t=e.changedTouches;return t&&t[0]?t[0]:e}(e);return new R(n.clientX+t.left,n.clientY+t.top)},jt=e=>kt.includes(e.type)||e.pointerType===`touch`,Mt=e=>{e.preventDefault(),e.stopPropagation()},Nt=e=>{let t=0,n=0,r=0,i=0;for(let a=0,o=e.length;a<o;a++){let{x:o,y:s}=e[a];(o>r||!a)&&(r=o),(o<t||!a)&&(t=o),(s>i||!a)&&(i=s),(s<n||!a)&&(n=s)}return{left:t,top:n,width:r-t,height:i-n}},Pt=(e,t)=>{It(e,B(We(t),e.calcOwnMatrix()))},Ft=(e,t)=>It(e,B(t,e.calcOwnMatrix())),It=(e,t)=>{let{translateX:n,translateY:r,scaleX:i,scaleY:a,...o}=Ye(t),s=new R(n,r);e.flipX=!1,e.flipY=!1,Object.assign(e,o),e.set({scaleX:i,scaleY:a}),e.setPositionByOrigin(s,P,P)},Lt=e=>{e.scaleX=1,e.scaleY=1,e.skewX=0,e.skewY=0,e.flipX=!1,e.flipY=!1,e.rotate(0)},Rt=e=>({scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,angle:e.angle,left:e.left,flipX:e.flipX,flipY:e.flipY,top:e.top}),zt=(e,t,n)=>{let r=e/2,i=t/2,a=Nt([new R(-r,-i),new R(r,-i),new R(-r,i),new R(r,i)].map(e=>e.transform(n)));return new R(a.width,a.height)},Bt=(e=N,t=N)=>B(We(t),e),Vt=(e,t=N,n=N)=>e.transform(Bt(t,n)),Ht=(e,t=N,n=N)=>e.transform(Bt(t,n),!0),Ut=(e,t,n)=>{let r=Bt(t,n);return It(e,B(r,e.calcOwnMatrix())),r},Wt={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Gt=e=>typeof e==`string`?Wt[e]:e-.5,Kt=new R(1,0),qt=new R,Jt=(e,t)=>e.rotate(t),Yt=(e,t)=>new R(t).subtract(e),Xt=e=>e.distanceFrom(qt),Zt=(e,t)=>Math.atan2(tn(e,t),nn(e,t)),Qt=e=>Zt(Kt,e),$t=e=>e.eq(qt)?e:e.scalarDivide(Xt(e)),en=(e,t=!0)=>$t(new R(-e.y,e.x).scalarMultiply(t?1:-1)),tn=(e,t)=>e.x*t.y-e.y*t.x,nn=(e,t)=>e.x*t.x+e.y*t.y,rn=(e,t,n)=>{if(e.eq(t)||e.eq(n))return!0;let r=tn(t,n),i=tn(t,e),a=tn(n,e);return r>=0?i>=0&&a<=0:!(i<=0&&a>=0)},an=`not-allowed`;function on(e){return Gt(e.originX)===Gt(`center`)&&Gt(e.originY)===Gt(`center`)}function sn(e){return .5-Gt(e)}var cn=(e,t)=>e[t],ln=(e,t,n,r)=>({e,transform:t,pointer:new R(n,r)});function un(e,t,n){let r=n,i=Qt(Yt(Vt(e.getCenterPoint(),e.canvas.viewportTransform,void 0),r))+M;return Math.round(i%M/j)}function dn({target:e,corner:t},n,r,i,a){let o=e.controls[t],s=e.canvas?.getZoom()||1,c=e.padding/s,l=function(e,t,n,r){let i=e.getRelativeCenterPoint(),a=n!==void 0&&r!==void 0?e.translateToGivenOrigin(i,P,P,n,r):new R(e.left,e.top);return(e.angle?t.rotate(-z(e.angle),i):t).subtract(a)}(e,new R(i,a),n,r);return l.x>=c&&(l.x-=c),l.x<=-c&&(l.x+=c),l.y>=c&&(l.y-=c),l.y<=c&&(l.y+=c),l.x-=o.offsetX,l.y-=o.offsetY,l}var fn=new RegExp(String.raw`[\0-\x1F\x7F;<>\\]|\/\*|\*\/|url\s*\(|expression\s*\(|(?:java|vb)script\s*:|data\s*:|@import\b`,`iu`),pn=e=>typeof e==`string`&&e.trim().length>0&&!fn.test(e),mn=(e,t=``)=>{let n=Number(e);return Number.isFinite(n)?`${n}`:t},hn=(e,t=``)=>typeof e==`string`&&pn(e)?e:t,gn=e=>e.replace(/\s+/g,` `),_n={aliceblue:`#F0F8FF`,antiquewhite:`#FAEBD7`,aqua:`#0FF`,aquamarine:`#7FFFD4`,azure:`#F0FFFF`,beige:`#F5F5DC`,bisque:`#FFE4C4`,black:`#000`,blanchedalmond:`#FFEBCD`,blue:`#00F`,blueviolet:`#8A2BE2`,brown:`#A52A2A`,burlywood:`#DEB887`,cadetblue:`#5F9EA0`,chartreuse:`#7FFF00`,chocolate:`#D2691E`,coral:`#FF7F50`,cornflowerblue:`#6495ED`,cornsilk:`#FFF8DC`,crimson:`#DC143C`,cyan:`#0FF`,darkblue:`#00008B`,darkcyan:`#008B8B`,darkgoldenrod:`#B8860B`,darkgray:`#A9A9A9`,darkgrey:`#A9A9A9`,darkgreen:`#006400`,darkkhaki:`#BDB76B`,darkmagenta:`#8B008B`,darkolivegreen:`#556B2F`,darkorange:`#FF8C00`,darkorchid:`#9932CC`,darkred:`#8B0000`,darksalmon:`#E9967A`,darkseagreen:`#8FBC8F`,darkslateblue:`#483D8B`,darkslategray:`#2F4F4F`,darkslategrey:`#2F4F4F`,darkturquoise:`#00CED1`,darkviolet:`#9400D3`,deeppink:`#FF1493`,deepskyblue:`#00BFFF`,dimgray:`#696969`,dimgrey:`#696969`,dodgerblue:`#1E90FF`,firebrick:`#B22222`,floralwhite:`#FFFAF0`,forestgreen:`#228B22`,fuchsia:`#F0F`,gainsboro:`#DCDCDC`,ghostwhite:`#F8F8FF`,gold:`#FFD700`,goldenrod:`#DAA520`,gray:`#808080`,grey:`#808080`,green:`#008000`,greenyellow:`#ADFF2F`,honeydew:`#F0FFF0`,hotpink:`#FF69B4`,indianred:`#CD5C5C`,indigo:`#4B0082`,ivory:`#FFFFF0`,khaki:`#F0E68C`,lavender:`#E6E6FA`,lavenderblush:`#FFF0F5`,lawngreen:`#7CFC00`,lemonchiffon:`#FFFACD`,lightblue:`#ADD8E6`,lightcoral:`#F08080`,lightcyan:`#E0FFFF`,lightgoldenrodyellow:`#FAFAD2`,lightgray:`#D3D3D3`,lightgrey:`#D3D3D3`,lightgreen:`#90EE90`,lightpink:`#FFB6C1`,lightsalmon:`#FFA07A`,lightseagreen:`#20B2AA`,lightskyblue:`#87CEFA`,lightslategray:`#789`,lightslategrey:`#789`,lightsteelblue:`#B0C4DE`,lightyellow:`#FFFFE0`,lime:`#0F0`,limegreen:`#32CD32`,linen:`#FAF0E6`,magenta:`#F0F`,maroon:`#800000`,mediumaquamarine:`#66CDAA`,mediumblue:`#0000CD`,mediumorchid:`#BA55D3`,mediumpurple:`#9370DB`,mediumseagreen:`#3CB371`,mediumslateblue:`#7B68EE`,mediumspringgreen:`#00FA9A`,mediumturquoise:`#48D1CC`,mediumvioletred:`#C71585`,midnightblue:`#191970`,mintcream:`#F5FFFA`,mistyrose:`#FFE4E1`,moccasin:`#FFE4B5`,navajowhite:`#FFDEAD`,navy:`#000080`,oldlace:`#FDF5E6`,olive:`#808000`,olivedrab:`#6B8E23`,orange:`#FFA500`,orangered:`#FF4500`,orchid:`#DA70D6`,palegoldenrod:`#EEE8AA`,palegreen:`#98FB98`,paleturquoise:`#AFEEEE`,palevioletred:`#DB7093`,papayawhip:`#FFEFD5`,peachpuff:`#FFDAB9`,peru:`#CD853F`,pink:`#FFC0CB`,plum:`#DDA0DD`,powderblue:`#B0E0E6`,purple:`#800080`,rebeccapurple:`#639`,red:`#F00`,rosybrown:`#BC8F8F`,royalblue:`#4169E1`,saddlebrown:`#8B4513`,salmon:`#FA8072`,sandybrown:`#F4A460`,seagreen:`#2E8B57`,seashell:`#FFF5EE`,sienna:`#A0522D`,silver:`#C0C0C0`,skyblue:`#87CEEB`,slateblue:`#6A5ACD`,slategray:`#708090`,slategrey:`#708090`,snow:`#FFFAFA`,springgreen:`#00FF7F`,steelblue:`#4682B4`,tan:`#D2B48C`,teal:`#008080`,thistle:`#D8BFD8`,tomato:`#FF6347`,turquoise:`#40E0D0`,violet:`#EE82EE`,wheat:`#F5DEB3`,white:`#FFF`,whitesmoke:`#F5F5F5`,yellow:`#FF0`,yellowgreen:`#9ACD32`},vn=(e,t,n)=>(n<0&&(n+=1),n>1&&--n,n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e),yn=(e,t,n,r)=>{e/=255,t/=255,n/=255;let i=Math.max(e,t,n),a=Math.min(e,t,n),o,s,c=(i+a)/2;if(i===a)o=s=0;else{let r=i-a;switch(s=c>.5?r/(2-i-a):r/(i+a),i){case e:o=(t-n)/r+(t<n?6:0);break;case t:o=(n-e)/r+2;break;case n:o=(e-t)/r+4}o/=6}return[Math.round(360*o),Math.round(100*s),Math.round(100*c),r]},bn=(e=`1`)=>parseFloat(e)/(e.endsWith(`%`)?100:1),xn=e=>Math.min(Math.round(e),255).toString(16).toUpperCase().padStart(2,`0`),Sn=([e,t,n,r=1])=>{let i=Math.round(.3*e+.59*t+.11*n);return[i,i,i,r]},Cn=class e{constructor(t){if(p(this,`isUnrecognised`,!1),t){if(t instanceof e)this.setSource([...t._source]);else if(Array.isArray(t)){let[e,n,r,i=1]=t;this.setSource([e,n,r,i])}else this.setSource(this._tryParsingColor(t))}else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in _n&&(t=_n[t]),t===`transparent`?[255,255,255,0]:e.sourceFromHex(t)||e.sourceFromRgb(t)||e.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(e){this._source=e}toRgb(){let[e,t,n]=this.getSource();return`rgb(${e},${t},${n})`}toRgba(){return`rgba(${this.getSource().join(`,`)})`}toHsl(){let[e,t,n]=yn(...this.getSource());return`hsl(${e},${t}%,${n}%)`}toHsla(){let[e,t,n,r]=yn(...this.getSource());return`hsla(${e},${t}%,${n}%,${r})`}toHex(){return this.toHexa().slice(0,6)}toHexa(){let[e,t,n,r]=this.getSource();return`${xn(e)}${xn(t)}${xn(n)}${xn(Math.round(255*r))}`}getAlpha(){return this.getSource()[3]}setAlpha(e){return this._source[3]=e,this}toGrayscale(){return this.setSource(Sn(this.getSource())),this}toBlackWhite(e){let[t,,,n]=Sn(this.getSource()),r=t<(e||127)?0:255;return this.setSource([r,r,r,n]),this}overlayWith(t){t instanceof e||(t=new e(t));let n=this.getSource(),r=t.getSource(),[i,a,o]=n.map((e,t)=>Math.round(.5*e+.5*r[t]));return this.setSource([i,a,o,n[3]]),this}static fromRgb(t){return e.fromRgba(t)}static fromRgba(t){return new e(e.sourceFromRgb(t))}static sourceFromRgb(e){let t=gn(e).match(/^rgba?\(\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d{0,3}(?:\.\d+)?%?)\s?)?\)$/i);if(t){let[e,n,r]=t.slice(1,4).map(e=>{let t=parseFloat(e);return e.endsWith(`%`)?Math.round(2.55*t):t});return[e,n,r,bn(t[4])]}}static fromHsl(t){return e.fromHsla(t)}static fromHsla(t){return new e(e.sourceFromHsl(t))}static sourceFromHsl(t){let n=gn(t).match(/^hsla?\(\s?([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d*(?:\.\d+)?%?)\s?)?\)$/i);if(!n)return;let r=(e.parseAngletoDegrees(n[1])%360+360)%360/360,i=parseFloat(n[2])/100,a=parseFloat(n[3])/100,o,s,c;if(i===0)o=s=c=a;else{let e=a<=.5?a*(i+1):a+i-a*i,t=2*a-e;o=vn(t,e,r+1/3),s=vn(t,e,r),c=vn(t,e,r-1/3)}return[Math.round(255*o),Math.round(255*s),Math.round(255*c),bn(n[4])]}static fromHex(t){return new e(e.sourceFromHex(t))}static sourceFromHex(e){if(e.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){let t=e.slice(e.indexOf(`#`)+1),n;n=t.length<=4?t.split(``).map(e=>e+e):t.match(/.{2}/g);let[r,i,a,o=255]=n.map(e=>parseInt(e,16));return[r,i,a,o/255]}}static parseAngletoDegrees(e){let t=e.toLowerCase(),n=parseFloat(t);return t.includes(`rad`)?Ve(n):t.includes(`turn`)?360*n:n}},wn=e=>{let t=[`instantiated_by_use`,`style`,`id`,`class`];switch(e){case`linearGradient`:return t.concat([`x1`,`y1`,`x2`,`y2`,`gradientUnits`,`gradientTransform`]);case`radialGradient`:return t.concat([`gradientUnits`,`gradientTransform`,`cx`,`cy`,`r`,`fx`,`fy`,`fr`]);case`stop`:return t.concat([`offset`,`stop-color`,`stop-opacity`])}return t},Tn=(e,t=16)=>{let n=/\D{0,2}$/.exec(e),r=parseFloat(e),i=h.DPI;switch(n?.[0]){case`mm`:return r*i/25.4;case`cm`:return r*i/2.54;case`in`:return r*i;case`pt`:return r*i/72;case`pc`:return r*i/72*12;case`em`:return r*t;default:return r}},En=e=>{let[t,n]=e.trim().split(` `),[r,i]=(a=t)&&a!==`none`?[a.slice(1,4),a.slice(5,8)]:a===`none`?[a,a]:[`Mid`,`Mid`];var a;return{meetOrSlice:n||`meet`,alignX:r,alignY:i}},Dn=(e,t,n=!0)=>{let r,i;if(t){if(t.toLive)r=`url(#SVGID_${H(t.id)})`;else{let e=String(t);if(pn(e)){let t=new Cn(e),n=t.getAlpha();r=t.toRgb(),n!==1&&(i=n.toString())}else r=new Cn(`black`).toRgb()}}else r=`none`;return n?`${e}: ${r}; ${i?`${e}-opacity: ${i}; `:``}`:`${e}="${r}" ${i?`${e}-opacity="${i}" `:``}`},On=class{getSvgStyles(e){let t=this.fillRule==null?`nonzero`:hn(this.fillRule),n=this.strokeWidth==null?`0`:mn(this.strokeWidth),r=this.strokeDashArray==null?ne:this.strokeDashArray.every(e=>Number.isFinite(Number(e)))?this.strokeDashArray.join(` `):``,i=this.strokeDashOffset==null?`0`:mn(this.strokeDashOffset),a=this.strokeLineCap==null?`butt`:hn(this.strokeLineCap),o=this.strokeLineJoin==null?`miter`:hn(this.strokeLineJoin),s=this.strokeMiterLimit==null?`4`:mn(this.strokeMiterLimit),c=this.opacity==null?`1`:mn(this.opacity),l=this.visible?``:` visibility: hidden;`,u=e?``:this.getSvgFilter(),d=Dn(_e,this.fill);return[Dn(ve,this.stroke),n?`stroke-width: ${n}; `:``,r?`stroke-dasharray: ${r}; `:``,a?`stroke-linecap: ${a}; `:``,i?`stroke-dashoffset: ${i}; `:``,o?`stroke-linejoin: ${o}; `:``,s?`stroke-miterlimit: ${s}; `:``,d,t?`fill-rule: ${t}; `:``,c?`opacity: ${c};`:``,u,l].map(e=>H(e)).join(``)}getSvgFilter(){return this.shadow?`filter: url(#SVGID_${H(this.shadow.id)});`:``}getSvgCommons(){return[this.id?`id="${H(String(this.id))}" `:``,this.clipPath?`clip-path="url(#${H(this.clipPath.clipPathId)})" `:``].join(``)}getSvgTransform(e,t=``){return`transform="${lt(e?this.calcTransformMatrix():this.calcOwnMatrix())}${t}" `}_toSVG(e){return[``]}toSVG(e){return this._createBaseSVGMarkup(this._toSVG(e),{reviver:e})}toClipPathSVG(e){return` `+this._createBaseClipPathSVGMarkup(this._toSVG(e),{reviver:e})}_createBaseClipPathSVGMarkup(e,{reviver:t,additionalTransform:n=``}={}){let r=[this.getSvgTransform(!0,n),this.getSvgCommons()].join(``),i=e.indexOf(`COMMON_PARTS`);return e[i]=r,t?t(e.join(``)):e.join(``)}_createBaseSVGMarkup(e,{noStyle:t,reviver:n,withShadow:r,additionalTransform:i}={}){let a=t?``:`style="${this.getSvgStyles()}" `,o=r?`style="${this.getSvgFilter()}" `:``,s=this.clipPath,c=this.strokeUniform?`vector-effect="non-scaling-stroke" `:``,l=s&&s.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,p=[],m=e.indexOf(`COMMON_PARTS`),h;return s&&(s.clipPathId=`CLIPPATH_${Pe()}`,h=`<clipPath id="${s.clipPathId}" >\n${s.toClipPathSVG(n)}</clipPath>\n`),l&&p.push(`<g `,o,this.getSvgCommons(),` >
|
|
11
11
|
`),p.push(`<g `,this.getSvgTransform(!1),l?``:o+this.getSvgCommons(),` >
|
|
12
12
|
`),e[m]=[a,c,t?``:this.addPaintOrder(),` `,i?`transform="${i}" `:``].join(``),ut(d)&&p.push(d.toSVG(this)),ut(u)&&p.push(u.toSVG(this)),f&&p.push(f.toSVG(this)),s&&p.push(h),p.push(e.join(``)),p.push(`</g>
|
|
13
13
|
`),l&&p.push(`</g>
|
|
14
|
-
`),n?n(p.join(``)):p.join(``)}addPaintOrder(){return this.paintFirst===`fill`?``:` paint-order="${H(this.paintFirst)}" `}};function kn(e){return RegExp(`^(`+e.join(`|`)+`)\\b`,`i`)}var An=`textDecorationThickness`,jn=`textDecorationColor`,Mn=[`fontSize`,`fontWeight`,`fontFamily`,`fontStyle`],Nn=[`underline`,`overline`,`linethrough`],Pn=[...Mn,`lineHeight`,`text`,`charSpacing`,`textAlign`,`styles`,`path`,`pathStartOffset`,`pathSide`,`pathAlign`],Fn=[...Pn,...Nn,`textBackgroundColor`,`direction`,An,jn],In=[...Mn,...Nn,ve,`strokeWidth`,_e,`deltaY`,`textBackgroundColor`,An,jn],Ln={_reNewline:re,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:be,fontFamily:`Times New Roman`,underline:!1,overline:!1,linethrough:!1,textAlign:F,fontStyle:be,lineHeight:1.16,textBackgroundColor:``,stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:F,pathAlign:`baseline`,charSpacing:0,deltaY:0,direction:`ltr`,CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[An]:66.667},Rn=`justify`,zn=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,Bn=String.raw`(?:\s*,?\s+|\s*,\s*)`,Vn=`http://www.w3.org/2000/svg`,Hn=RegExp(`(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(`+zn+`(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|`+zn+`))?\\s+(.*)`),Un={cx:F,x:F,r:`radius`,cy:`top`,y:`top`,display:`visible`,visibility:`visible`,transform:`transformMatrix`,"fill-opacity":`fillOpacity`,"fill-rule":`fillRule`,"font-family":`fontFamily`,"font-size":`fontSize`,"font-style":`fontStyle`,"font-weight":`fontWeight`,"letter-spacing":`charSpacing`,"paint-order":`paintFirst`,"stroke-dasharray":`strokeDashArray`,"stroke-dashoffset":`strokeDashOffset`,"stroke-linecap":`strokeLineCap`,"stroke-linejoin":`strokeLineJoin`,"stroke-miterlimit":`strokeMiterLimit`,"stroke-opacity":`strokeOpacity`,"stroke-width":`strokeWidth`,"text-decoration":`textDecoration`,"text-anchor":`textAnchor`,opacity:`opacity`,"clip-path":`clipPath`,"clip-rule":`clipRule`,"vector-effect":`strokeUniform`,"image-rendering":`imageSmoothing`,"text-decoration-thickness":An,"text-decoration-color":jn},Wn=`font-size`,Gn=`clip-path`,Kn=kn([`path`,`circle`,`polygon`,`polyline`,`ellipse`,`rect`,`line`,`image`,`text`]),qn=kn([`symbol`,`image`,`marker`,`pattern`,`view`,`svg`]),Jn=kn([`symbol`,`g`,`a`,`svg`,`clipPath`,`defs`]),Yn=new RegExp(String.raw`^\s*(${zn})${Bn}(${zn})${Bn}(${zn})${Bn}(${zn})\s*$`),Xn=`(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?`,Zn=RegExp(`(?:\\s|^)`+Xn+Xn+`(`+zn+`?(?:px)?)?(?:\\s?|$)(?:$|\\s)`),Qn=class e{constructor(t={}){let n=typeof t==`string`?e.parseShadow(t):t;Object.assign(this,e.ownDefaults,n),this.id=Pe()}static parseShadow(e){let t=e.trim(),[,n=0,r=0,i=0]=(Zn.exec(t)||[]).map(e=>parseFloat(e)||0);return{color:(t.replace(Zn,``)||`rgb(0,0,0)`).trim(),offsetX:n,offsetY:r,blur:i}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join(`px `)}toSVG(e){let t=Jt(new R(this.offsetX,this.offsetY),z(-e.angle)),n=h.NUM_FRACTION_DIGITS,r=new Cn(this.color),i=40,a=40;return e.width&&e.height&&(i=100*V((Math.abs(t.x)+this.blur)/e.width,n)+20,a=100*V((Math.abs(t.y)+this.blur)/e.height,n)+20),e.flipX&&(t.x*=-1),e.flipY&&(t.y*=-1),`<filter id="SVGID_${H(this.id)}" y="-${a}%" height="${100+2*a}%" x="-${i}%" width="${100+2*i}%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="${V(this.blur?this.blur/2:0,n)}"></feGaussianBlur>\n\t<feOffset dx="${V(t.x,n)}" dy="${V(t.y,n)}" result="oBlur" ></feOffset>\n\t<feFlood flood-color="${r.toRgb()}" flood-opacity="${r.getAlpha()}"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n`}toObject(){let t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},n=e.ownDefaults;return this.includeDefaultValues?t:ct(t,(e,t)=>e!==n[t])}static async fromObject(e){return new this(e)}};p(Qn,`ownDefaults`,{color:`rgb(0,0,0)`,blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),p(Qn,`type`,`shadow`),L.setClass(Qn,`shadow`);var $n=(e,t,n)=>Math.max(e,Math.min(t,n)),er=[`top`,F,pe,me,`flipX`,`flipY`,`originX`,`originY`,`angle`,`opacity`,`globalCompositeOperation`,`shadow`,`visible`,he,ge],tr=[_e,ve,`strokeWidth`,`strokeDashArray`,`width`,`height`,`paintFirst`,`strokeUniform`,`strokeLineCap`,`strokeDashOffset`,`strokeLineJoin`,`strokeMiterLimit`,`backgroundColor`,`clipPath`],nr={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:P,originY:P,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:_e,fill:`rgb(0,0,0)`,fillRule:`nonzero`,stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:`butt`,strokeLineJoin:`miter`,strokeMiterLimit:4,globalCompositeOperation:`source-over`,backgroundColor:``,shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},rr=u({defaultEasing:()=>or,easeInBack:()=>Or,easeInBounce:()=>Mr,easeInCirc:()=>Sr,easeInCubic:()=>sr,easeInElastic:()=>Tr,easeInExpo:()=>yr,easeInOutBack:()=>Ar,easeInOutBounce:()=>Nr,easeInOutCirc:()=>wr,easeInOutCubic:()=>lr,easeInOutElastic:()=>Dr,easeInOutExpo:()=>xr,easeInOutQuad:()=>Ir,easeInOutQuart:()=>fr,easeInOutQuint:()=>hr,easeInOutSine:()=>vr,easeInQuad:()=>Pr,easeInQuart:()=>ur,easeInQuint:()=>pr,easeInSine:()=>gr,easeOutBack:()=>kr,easeOutBounce:()=>jr,easeOutCirc:()=>Cr,easeOutCubic:()=>cr,easeOutElastic:()=>Er,easeOutExpo:()=>br,easeOutQuad:()=>Fr,easeOutQuart:()=>dr,easeOutQuint:()=>mr,easeOutSine:()=>_r}),ir=(e,t,n,r)=>(e<Math.abs(t)?(e=t,r=n/4):r=t===0&&e===0?n/M*Math.asin(1):n/M*Math.asin(t/e),{a:e,c:t,p:n,s:r}),ar=(e,t,n,r,i)=>e*2**(10*--r)*Math.sin((r*i-t)*M/n),or=(e,t,n,r)=>-n*Math.cos(e/r*A)+n+t,sr=(e,t,n,r)=>n*(e/r)**3+t,cr=(e,t,n,r)=>n*((e/r-1)**3+1)+t,lr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**3+t:n/2*((e-2)**3+2)+t,ur=(e,t,n,r)=>n*(e/=r)*e**3+t,dr=(e,t,n,r)=>-n*((e=e/r-1)*e**3-1)+t,fr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**4+t:-n/2*((e-=2)*e**3-2)+t,pr=(e,t,n,r)=>n*(e/r)**5+t,mr=(e,t,n,r)=>n*((e/r-1)**5+1)+t,hr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**5+t:n/2*((e-2)**5+2)+t,gr=(e,t,n,r)=>-n*Math.cos(e/r*A)+n+t,_r=(e,t,n,r)=>n*Math.sin(e/r*A)+t,vr=(e,t,n,r)=>-n/2*(Math.cos(Math.PI*e/r)-1)+t,yr=(e,t,n,r)=>e===0?t:n*2**(10*(e/r-1))+t,br=(e,t,n,r)=>e===r?t+n:n*-(2**(-10*e/r)+1)+t,xr=(e,t,n,r)=>e===0?t:e===r?t+n:(e/=r/2)<1?n/2*2**(10*(e-1))+t:n/2*-(2**(-10*(e-1))+2)+t,Sr=(e,t,n,r)=>-n*(Math.sqrt(1-(e/=r)*e)-1)+t,Cr=(e,t,n,r)=>n*Math.sqrt(1-(e=e/r-1)*e)+t,wr=(e,t,n,r)=>(e/=r/2)<1?-n/2*(Math.sqrt(1-e**2)-1)+t:n/2*(Math.sqrt(1-(e-=2)*e)+1)+t,Tr=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r)===1)return t+n;a||=.3*r;let{a:o,s,p:c}=ir(i,n,a,1.70158);return-ar(o,s,c,e,r)+t},Er=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r)===1)return t+n;a||=.3*r;let{a:o,s,p:c,c:l}=ir(i,n,a,1.70158);return o*2**(-10*e)*Math.sin((e*r-s)*M/c)+l+t},Dr=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r/2)==2)return t+n;a||=.3*1.5*r;let{a:o,s,p:c,c:l}=ir(i,n,a,1.70158);return e<1?-.5*ar(o,s,c,e,r)+t:o*2**(-10*--e)*Math.sin((e*r-s)*M/c)*.5+l+t},Or=(e,t,n,r,i=1.70158)=>n*(e/=r)*e*((i+1)*e-i)+t,kr=(e,t,n,r,i=1.70158)=>n*((e=e/r-1)*e*((i+1)*e+i)+1)+t,Ar=(e,t,n,r,i=1.70158)=>(e/=r/2)<1?n/2*(e*e*((1+(i*=1.525))*e-i))+t:n/2*((e-=2)*e*((1+(i*=1.525))*e+i)+2)+t,jr=(e,t,n,r)=>(e/=r)<1/2.75?n*(7.5625*e*e)+t:e<2/2.75?n*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?n*(7.5625*(e-=2.25/2.75)*e+.9375)+t:n*(7.5625*(e-=2.625/2.75)*e+.984375)+t,Mr=(e,t,n,r)=>n-jr(r-e,0,n,r)+t,Nr=(e,t,n,r)=>e<r/2?.5*Mr(2*e,0,n,r)+t:.5*jr(2*e-r,0,n,r)+.5*n+t,Pr=(e,t,n,r)=>n*(e/=r)*e+t,Fr=(e,t,n,r)=>-n*(e/=r)*(e-2)+t,Ir=(e,t,n,r)=>(e/=r/2)<1?n/2*e**2+t:-n/2*(--e*(e-2)-1)+t,Lr=()=>!1,Rr=class{constructor({startValue:e,byValue:t,duration:n=500,delay:r=0,easing:i=or,onStart:a=k,onChange:o=k,onComplete:s=k,abort:c=Lr,target:l}){p(this,`_state`,`pending`),p(this,`durationProgress`,0),p(this,`valueProgress`,0),this.tick=this.tick.bind(this),this.duration=n,this.delay=r,this.easing=i,this._onStart=a,this._onChange=o,this._onComplete=s,this._abort=c,this.target=l,this.startValue=e,this.byValue=t,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state===`aborted`||this._state===`completed`}start(){let e=e=>{this._state===`pending`&&(this.startTime=e||+new Date,this._state=`running`,this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?this.timeout=T().setTimeout(()=>je(e),this.delay):je(e)}tick(e){let t=(e||+new Date)-this.startTime,n=Math.min(t,this.duration);this.durationProgress=n/this.duration;let{value:r,valueProgress:i}=this.calculate(n);this.value=Object.freeze(r),this.valueProgress=i,this._state!==`aborted`&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state=`aborted`,this.unregister()):t>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state=`completed`,this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister(),this.timeout=null):(this._onChange(this.value,this.valueProgress,this.durationProgress),je(this.tick)))}register(){Se.push(this)}unregister(){Se.remove(this)}abort(){this._state=`aborted`,this.unregister(),this.timeout&&T().clearTimeout(this.timeout)}},zr=class extends Rr{constructor({startValue:e=0,endValue:t=100,...n}){super({...n,startValue:e,byValue:t-e})}calculate(e){let t=this.easing(e,this.startValue,this.byValue,this.duration);return{value:t,valueProgress:Math.abs((t-this.startValue)/this.byValue)}}},Br=class extends Rr{constructor({startValue:e=[0],endValue:t=[100],...n}){super({...n,startValue:e,byValue:t.map((t,n)=>t-e[n])})}calculate(e){let t=this.startValue.map((t,n)=>this.easing(e,t,this.byValue[n],this.duration,n));return{value:t,valueProgress:Math.abs((t[0]-this.startValue[0])/this.byValue[0])}}},Vr=(e,t,n,r)=>t+n*(1-Math.cos(e/r*A)),Hr=e=>e&&((t,n,r)=>e(new Cn(t).toRgba(),n,r)),Ur=class extends Rr{constructor({startValue:e,endValue:t,easing:n=Vr,onChange:r,onComplete:i,abort:a,...o}){let s=new Cn(e).getSource(),c=new Cn(t).getSource();super({...o,startValue:s,byValue:c.map((e,t)=>e-s[t]),easing:n,onChange:Hr(r),onComplete:Hr(i),abort:Hr(a)})}calculate(e){let[t,n,r,i]=this.startValue.map((t,n)=>this.easing(e,t,this.byValue[n],this.duration,n)),a=[...[t,n,r].map(Math.round),$n(0,i,1)];return{value:a,valueProgress:a.map((e,t)=>this.byValue[t]===0?0:Math.abs((e-this.startValue[t])/this.byValue[t])).find(e=>e!==0)||0}}};function Wr(e){let t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(e)?new Br(e):new zr(e);return t.start(),t}function Gr(e){let t=new Ur(e);return t.start(),t}var Kr=class e{constructor(e){this.status=e,this.points=[]}includes(e){return this.points.some(t=>t.eq(e))}append(...e){return this.points=this.points.concat(e.filter(e=>!this.includes(e))),this}static isPointContained(e,t,n,r=!1){if(t.eq(n))return e.eq(t);if(t.x===n.x)return e.x===t.x&&(r||e.y>=Math.min(t.y,n.y)&&e.y<=Math.max(t.y,n.y));if(t.y===n.y)return e.y===t.y&&(r||e.x>=Math.min(t.x,n.x)&&e.x<=Math.max(t.x,n.x));{let i=Yt(t,n),a=Yt(t,e).divide(i);return r?Math.abs(a.x)===Math.abs(a.y):a.x===a.y&&a.x>=0&&a.x<=1}}static isPointInPolygon(e,t){let n=new R(e).setX(Math.min(e.x-1,...t.map(e=>e.x))),r=0;for(let i=0;i<t.length;i++){let a=this.intersectSegmentSegment(t[i],t[(i+1)%t.length],e,n);if(a.includes(e))return!0;r+=Number(a.status===`Intersection`)}return r%2==1}static intersectLineLine(t,n,r,i,a=!0,o=!0){let s=n.x-t.x,c=n.y-t.y,l=i.x-r.x,u=i.y-r.y,d=t.x-r.x,f=t.y-r.y,p=l*f-u*d,m=s*f-c*d,h=u*s-l*c;if(h!==0){let n=p/h,r=m/h;return(a||0<=n&&n<=1)&&(o||0<=r&&r<=1)?new e(`Intersection`).append(new R(t.x+n*s,t.y+n*c)):new e}return new e(p===0||m===0?a||o||e.isPointContained(t,r,i)||e.isPointContained(n,r,i)||e.isPointContained(r,t,n)||e.isPointContained(i,t,n)?`Coincident`:void 0:`Parallel`)}static intersectSegmentLine(t,n,r,i){return e.intersectLineLine(t,n,r,i,!1,!0)}static intersectSegmentSegment(t,n,r,i){return e.intersectLineLine(t,n,r,i,!1,!1)}static intersectLinePolygon(t,n,r,i=!0){let a=new e,o=r.length;for(let s,c,l,u=0;u<o;u++){if(s=r[u],c=r[(u+1)%o],l=e.intersectLineLine(t,n,s,c,i,!1),l.status===`Coincident`)return l;a.append(...l.points)}return a.points.length>0&&(a.status=`Intersection`),a}static intersectSegmentPolygon(t,n,r){return e.intersectLinePolygon(t,n,r,!1)}static intersectPolygonPolygon(t,n){let r=new e,i=t.length,a=[];for(let o=0;o<i;o++){let s=t[o],c=t[(o+1)%i],l=e.intersectSegmentPolygon(s,c,n);l.status===`Coincident`?(a.push(l),r.append(s,c)):r.append(...l.points)}return a.length>0&&a.length===t.length?new e(`Coincident`):(r.points.length>0&&(r.status=`Intersection`),r)}static intersectPolygonRectangle(t,n,r){let i=n.min(r),a=n.max(r),o=new R(a.x,i.y),s=new R(i.x,a.y);return e.intersectPolygonPolygon(t,[i,o,a,s])}},qr=class extends Ae{getX(){return this.getXY().x}setX(e){this.setXY(this.getXY().setX(e))}getY(){return this.getXY().y}setY(e){this.setXY(this.getXY().setY(e))}getRelativeX(){return this.left}setRelativeX(e){this.left=e}getRelativeY(){return this.top}setRelativeY(e){this.top=e}getXY(){let e=this.getRelativeXY();return this.group?Ue(e,this.group.calcTransformMatrix()):e}setXY(e,t,n){this.group&&(e=Ue(e,We(this.group.calcTransformMatrix()))),this.setRelativeXY(e,t,n)}getRelativeXY(){return new R(this.left,this.top)}setRelativeXY(e,t=this.originX,n=this.originY){this.setPositionByOrigin(e,t,n)}isStrokeAccountedForInDimensions(){return!1}getCoords(){let{tl:e,tr:t,br:n,bl:r}=this.aCoords||=this.calcACoords(),i=[e,t,n,r];if(this.group){let e=this.group.calcTransformMatrix();return i.map(t=>Ue(t,e))}return i}intersectsWithRect(e,t){return Kr.intersectPolygonRectangle(this.getCoords(),e,t).status===`Intersection`}intersectsWithObject(e){let t=Kr.intersectPolygonPolygon(this.getCoords(),e.getCoords());return t.status===`Intersection`||t.status===`Coincident`||e.isContainedWithinObject(this)||this.isContainedWithinObject(e)}isContainedWithinObject(e){return this.getCoords().every(t=>e.containsPoint(t))}isContainedWithinRect(e,t){let{left:n,top:r,width:i,height:a}=this.getBoundingRect();return n>=e.x&&n+i<=t.x&&r>=e.y&&r+a<=t.y}isOverlapping(e){return this.intersectsWithObject(e)||this.isContainedWithinObject(e)||e.isContainedWithinObject(this)}containsPoint(e){return Kr.isPointInPolygon(e,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;let{tl:e,br:t}=this.canvas.vptCoords;return!!this.getCoords().some(n=>n.x<=t.x&&n.x>=e.x&&n.y<=t.y&&n.y>=e.y)||!!this.intersectsWithRect(e,t)||this.containsPoint(e.midPointFrom(t))}isPartiallyOnScreen(){if(!this.canvas)return!1;let{tl:e,br:t}=this.canvas.vptCoords;return!!this.intersectsWithRect(e,t)||this.getCoords().every(n=>(n.x>=t.x||n.x<=e.x)&&(n.y>=t.y||n.y<=e.y))&&this.containsPoint(e.midPointFrom(t))}getBoundingRect(){return Nt(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(e){this._set(pe,e),this._set(me,e),this.setCoords()}scaleToWidth(e){let t=this.getBoundingRect().width/this.getScaledWidth();return this.scale(e/this.width/t)}scaleToHeight(e){let t=this.getBoundingRect().height/this.getScaledHeight();return this.scale(e/this.height/t)}getCanvasRetinaScaling(){return this.canvas?.getRetinaScaling()||1}getTotalAngle(){return this.group?Ve(Ke(this.calcTransformMatrix())):this.angle}getViewportTransform(){return this.canvas?.viewportTransform||N.concat()}calcACoords(){let e=Ze({angle:this.angle}),{x:t,y:n}=this.getRelativeCenterPoint(),r=B(Xe(t,n),e),i=this._getTransformedDimensions(),a=i.x/2,o=i.y/2;return{tl:Ue({x:-a,y:-o},r),tr:Ue({x:a,y:-o},r),bl:Ue({x:-a,y:o},r),br:Ue({x:a,y:o},r)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(e=!1){let t=[];return!e&&this.group&&(t=this.group.transformMatrixKey(e)),t.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,Gt(this.originX),Gt(this.originY)),t}calcTransformMatrix(e=!1){let t=this.calcOwnMatrix();if(e||!this.group)return t;let n=this.transformMatrixKey(e),r=this.matrixCache;return r&&r.key.every((e,t)=>e===n[t])?r.value:(this.group&&(t=B(this.group.calcTransformMatrix(!1),t)),this.matrixCache={key:n,value:t},t)}calcOwnMatrix(){let e=this.transformMatrixKey(!0),t=this.ownMatrixCache;if(t&&t.key.every((t,n)=>t===e[n]))return t.value;let n=this.getRelativeCenterPoint(),r=rt({angle:this.angle,translateX:n.x,translateY:n.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY});return this.ownMatrixCache={key:e,value:r},r}_getNonTransformedDimensions(){return new R(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(e){let t=this.canvas?.viewportTransform,n=this._getTransformedDimensions(e);return t?n.multiply(new R(qe(t),Je(t))).scalarAdd(2*this.padding):n.scalarAdd(2*this.padding)}_getTransformedDimensions(e={}){let t={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth,...e},n=t.strokeWidth,r=n,i=0;this.strokeUniform&&(r=0,i=n);let a=t.width+r,o=t.height+r,s;return s=t.skewX===0&&t.skewY===0?new R(a*t.scaleX,o*t.scaleY):zt(a,o,nt(t)),s.scalarAdd(i)}translateToGivenOrigin(e,t,n,r,i){let a=e.x,o=e.y,s=Gt(r)-Gt(t),c=Gt(i)-Gt(n);if(s||c){let e=this._getTransformedDimensions();a+=s*e.x,o+=c*e.y}return new R(a,o)}translateToCenterPoint(e,t,n){if(t===`center`&&n===`center`)return e;let r=this.translateToGivenOrigin(e,t,n,P,P);return this.angle?r.rotate(z(this.angle),e):r}translateToOriginPoint(e,t,n){let r=this.translateToGivenOrigin(e,P,P,t,n);return this.angle?r.rotate(z(this.angle),e):r}getCenterPoint(){let e=this.getRelativeCenterPoint();return this.group?Ue(e,this.group.calcTransformMatrix()):e}getRelativeCenterPoint(){return this.translateToCenterPoint(new R(this.left,this.top),this.originX,this.originY)}getPointByOrigin(e,t){return this.getPositionByOrigin(e,t)}getPositionByOrigin(e,t){return this.translateToOriginPoint(this.getRelativeCenterPoint(),e,t)}setPositionByOrigin(e,t,n){let r=this.translateToCenterPoint(e,t,n),i=this.translateToOriginPoint(r,this.originX,this.originY);this.set({left:i.x,top:i.y})}_getLeftTopCoords(){return this.getPositionByOrigin(F,`top`)}positionByLeftTop(e){return this.setPositionByOrigin(e,F,`top`)}},Jr=class e extends qr{static getDefaults(){return e.ownDefaults}get type(){let e=this.constructor.type;return e===`FabricObject`?`object`:e.toLowerCase()}set type(e){g(`warn`,`Setting type has no effect`,e)}constructor(t){super(),p(this,`_cacheContext`,null),Object.assign(this,e.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Fe(),this._cacheContext=this._cacheCanvas.getContext(`2d`),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(e){let t=e.width,n=e.height,r=h.maxCacheSideLimit,i=h.minCacheSideLimit;if(t<=r&&n<=r&&t*n<=h.perfLimitSizeTotal)return t<i&&(e.width=i),n<i&&(e.height=i),e;let a=t/n,[o,s]=D.limitDimsByArea(a),c=$n(i,o,r),l=$n(i,s,r);return t>c&&(e.zoomX/=t/c,e.width=c,e.capped=!0),n>l&&(e.zoomY/=n/l,e.height=l,e.capped=!0),e}_getCacheCanvasDimensions(){let e=this.getTotalObjectScaling(),t=this._getTransformedDimensions({skewX:0,skewY:0}),n=t.x*e.x/this.scaleX,r=t.y*e.y/this.scaleY;return{width:Math.ceil(n+2),height:Math.ceil(r+2),zoomX:e.x,zoomY:e.y,x:n,y:r}}_updateCacheCanvas(){let e=this._cacheCanvas,t=this._cacheContext,{width:n,height:r,zoomX:i,zoomY:a,x:o,y:s}=this._limitCacheSize(this._getCacheCanvasDimensions()),c=n!==e.width||r!==e.height,l=this.zoomX!==i||this.zoomY!==a;if(!e||!t)return!1;if(c||l){n!==e.width||r!==e.height?(e.width=n,e.height=r):(t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,e.width,e.height));let c=o/2,l=s/2;return this.cacheTranslationX=Math.round(e.width/2-c)+c,this.cacheTranslationY=Math.round(e.height/2-l)+l,t.translate(this.cacheTranslationX,this.cacheTranslationY),t.scale(i,a),this.zoomX=i,this.zoomY=a,!0}return!1}setOptions(e={}){this._setOptions(e)}transform(e){let t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,n=this.calcTransformMatrix(!t);e.transform(n[0],n[1],n[2],n[3],n[4],n[5])}getObjectScaling(){if(!this.group)return new R(Math.abs(this.scaleX),Math.abs(this.scaleY));let e=Ye(this.calcTransformMatrix());return new R(Math.abs(e.scaleX),Math.abs(e.scaleY))}getTotalObjectScaling(){let e=this.getObjectScaling();if(this.canvas){let t=this.canvas.getZoom(),n=this.getCanvasRetinaScaling();return e.scalarMultiply(t*n)}return e}getObjectOpacity(){let e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e}_constrainScale(e){return Math.abs(e)<this.minScaleLimit?e<0?-this.minScaleLimit:this.minScaleLimit:e===0?1e-4:e}_set(e,t){e!==`scaleX`&&e!==`scaleY`||(t=this._constrainScale(t)),e===`scaleX`&&t<0?(this.flipX=!this.flipX,t*=-1):e===`scaleY`&&t<0?(this.flipY=!this.flipY,t*=-1):e!==`shadow`||!t||t instanceof Qn||(t=new Qn(t));let n=this[e]!==t;return this[e]=t,n&&this.constructor.cacheProperties.includes(e)&&(this.dirty=!0),this.parent&&(this.dirty||n&&this.constructor.stateProperties.includes(e))&&this.parent._set(`dirty`,!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.drawObject(e,!1,{}),this.dirty=!1),e.restore())}drawSelectionBackground(e){}renderCache(e){if(e||={},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){let{zoomX:t,zoomY:n,cacheTranslationX:r,cacheTranslationY:i}=this,{width:a,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,e.forClipping,{zoomX:t,zoomY:n,cacheTranslationX:r,cacheTranslationY:i,width:a,height:o,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return!!this.stroke&&this.stroke!==`transparent`&&this.strokeWidth!==0}hasFill(){return!!this.fill&&this.fill!==`transparent`}needsItsOwnCache(){return!!(this.paintFirst===`stroke`&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(e,t,n){e.save(),t.inverted?e.globalCompositeOperation=`destination-out`:e.globalCompositeOperation=`destination-in`,e.setTransform(1,0,0,1,0,0),e.drawImage(n,0,0),e.restore()}drawObject(e,t,n){let r=this.fill,i=this.stroke;t?(this.fill=`black`,this.stroke=``,this._setClippingProperties(e)):this._renderBackground(e),this.fire(`before:render`,{ctx:e}),this._render(e),this._drawClipPath(e,this.clipPath,n),this.fill=r,this.stroke=i}createClipPathLayer(e,t){let n=Re(t),r=n.getContext(`2d`);if(r.translate(t.cacheTranslationX,t.cacheTranslationY),r.scale(t.zoomX,t.zoomY),e._cacheCanvas=n,t.parentClipPaths.forEach(e=>{e.transform(r)}),t.parentClipPaths.push(e),e.absolutePositioned){let e=We(this.calcTransformMatrix());r.transform(e[0],e[1],e[2],e[3],e[4],e[5])}return e.transform(r),e.drawObject(r,!0,t),n}_drawClipPath(e,t,n){if(!t)return;t._transformDone=!0;let r=this.createClipPathLayer(t,n);this.drawClipPathOnCache(e,t,r)}drawCacheOnCanvas(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(e=!1){if(this.isNotVisible())return!1;let t=this._cacheCanvas,n=this._cacheContext;return!(!t||!n||e||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(t&&n&&!e&&(n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,t.width,t.height),n.restore()),!0)}_renderBackground(e){if(!this.backgroundColor)return;let t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}_setOpacity(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity}_setStrokeStyles(e,t){let n=t.stroke;n&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,ut(n)?n.gradientUnits===`percentage`||n.gradientTransform||n.patternTransform?this._applyPatternForTransformedGradient(e,n):(e.strokeStyle=n.toLive(e),this._applyPatternGradientTransform(e,n)):e.strokeStyle=t.stroke)}_setFillStyles(e,{fill:t}){t&&(ut(t)?(e.fillStyle=t.toLive(e),this._applyPatternGradientTransform(e,t)):e.fillStyle=t)}_setClippingProperties(e){e.globalAlpha=1,e.strokeStyle=`transparent`,e.fillStyle=`#000000`}_setLineDash(e,t){t&&t.length!==0&&e.setLineDash(t)}_setShadow(e){if(!this.shadow)return;let t=this.shadow,n=this.canvas,r=this.getCanvasRetinaScaling(),[i,,,a]=n?.viewportTransform||N,o=i*r,s=a*r,c=t.nonScaling?new R(1,1):this.getObjectScaling();e.shadowColor=t.color,e.shadowBlur=t.blur*h.browserShadowBlurConstant*(o+s)*(c.x+c.y)/4,e.shadowOffsetX=t.offsetX*o*c.x,e.shadowOffsetY=t.offsetY*s*c.y}_removeShadow(e){this.shadow&&(e.shadowColor=``,e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)}_applyPatternGradientTransform(e,t){if(!ut(t))return{offsetX:0,offsetY:0};let n=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,i=-this.height/2+t.offsetY||0;return t.gradientUnits===`percentage`?e.transform(this.width,0,0,this.height,r,i):e.transform(1,0,0,1,r,i),n&&e.transform(n[0],n[1],n[2],n[3],n[4],n[5]),{offsetX:r,offsetY:i}}_renderPaintInOrder(e){this.paintFirst===`stroke`?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))}_render(e){}_renderFill(e){this.fill&&(e.save(),this._setFillStyles(e,this),this.fillRule===`evenodd`?e.fill(`evenodd`):e.fill(),e.restore())}_renderStroke(e){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform){let t=this.getObjectScaling();e.scale(1/t.x,1/t.y)}this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}}_applyPatternForTransformedGradient(e,t){let n=this._limitCacheSize(this._getCacheCanvasDimensions()),r=this.getCanvasRetinaScaling(),i=n.x/this.scaleX/r,a=n.y/this.scaleY/r,o=Re({width:Math.ceil(i),height:Math.ceil(a)}),s=o.getContext(`2d`);s&&(s.beginPath(),s.moveTo(0,0),s.lineTo(i,0),s.lineTo(i,a),s.lineTo(0,a),s.closePath(),s.translate(i/2,a/2),s.scale(n.zoomX/this.scaleX/r,n.zoomY/this.scaleY/r),this._applyPatternGradientTransform(s,t),s.fillStyle=t.toLive(e),s.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(r*this.scaleX/n.zoomX,r*this.scaleY/n.zoomY),e.strokeStyle=s.createPattern(o,`no-repeat`)??``)}_findCenterFromElement(){return new R(this.left+this.width/2,this.top+this.height/2)}clone(e){let t=this.toObject(e);return this.constructor.fromObject(t)}cloneAsImage(e){let t=this.toCanvasElement(e);return new(L.getClass(`image`))(t)}toCanvasElement(e={}){let t=Rt(this),n=this.group,r=this.shadow,i=Math.abs,a=e.enableRetinaScaling?E():1,o=(e.multiplier||1)*a,s=e.canvasProvider||(e=>new Ot(e,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,e.withoutTransform&&Lt(this),e.withoutShadow&&(this.shadow=null),e.viewportTransform&&Ut(this,this.getViewportTransform()),this.setCoords();let c=Fe(),l=this.getBoundingRect(),u=this.shadow,d=new R;if(u){let e=u.blur,t=u.nonScaling?new R(1,1):this.getObjectScaling();d.x=2*Math.round(i(u.offsetX)+e)*i(t.x),d.y=2*Math.round(i(u.offsetY)+e)*i(t.y)}let f=l.width+d.x,p=l.height+d.y;c.width=Math.ceil(f),c.height=Math.ceil(p);let m=s(c);e.format===`jpeg`&&(m.backgroundColor=`#fff`),this.setPositionByOrigin(new R(m.width/2,m.height/2),P,P);let h=this.canvas;m._objects=[this],this.set(`canvas`,m),this.setCoords();let g=m.toCanvasElement(o||1,e);return this.set(`canvas`,h),this.shadow=r,n&&(this.group=n),this.set(t),this.setCoords(),m._objects=[],m.destroy(),g}toDataURL(e={}){return ze(this.toCanvasElement(e),e.format||`png`,e.quality||1)}toBlob(e={}){return Be(this.toCanvasElement(e),e.format||`png`,e.quality||1)}isType(...e){return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(e){let{centeredRotation:t,originX:n,originY:r}=this;if(t){let{x:e,y:t}=this.getRelativeCenterPoint();this.originX=P,this.originY=P,this.left=e,this.top=t}if(this.set(`angle`,e),t){let{x:e,y:t}=this.getPositionByOrigin(n,r);this.left=e,this.top=t,this.originX=n,this.originY=r}}setOnGroup(){}_setupCompositeOperation(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Se.cancelByTarget(this),this.off(),this._set(`canvas`,void 0),this._cacheCanvas&&C().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(e,t){return Object.entries(e).reduce((e,[n,r])=>(e[n]=this._animate(n,r,t),e),{})}_animate(e,t,n={}){let r=e.split(`.`),i=this.constructor.colorProperties.includes(r[r.length-1]),{abort:a,startValue:o,onChange:s,onComplete:c}=n,l={...n,target:this,startValue:o??r.reduce((e,t)=>e[t],this),endValue:t,abort:a?.bind(this),onChange:(e,t,n)=>{r.reduce((t,n,i)=>(i===r.length-1&&(t[n]=e),t[n]),this),s&&s(e,t,n)},onComplete:(e,t,n)=>{this.setCoords(),c&&c(e,t,n)}};return i?Gr(l):Wr(l)}isDescendantOf(e){let{parent:t,group:n}=this;return t===e||n===e||!!t&&t.isDescendantOf(e)||!!n&&n!==t&&n.isDescendantOf(e)}getAncestors(){let e=[],t=this;do t=t.parent,t&&e.push(t);while(t);return e}findCommonAncestors(e){if(this===e)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};let t=this.getAncestors(),n=e.getAncestors();if(t.length===0&&n.length>0&&this===n[n.length-1])return{fork:[],otherFork:[e,...n.slice(0,n.length-1)],common:[this]};for(let r,i=0;i<t.length;i++){if(r=t[i],r===e)return{fork:[this,...t.slice(0,i)],otherFork:[],common:t.slice(i)};for(let a=0;a<n.length;a++){if(this===n[a])return{fork:[],otherFork:[e,...n.slice(0,a)],common:[this,...t]};if(r===n[a])return{fork:[this,...t.slice(0,i)],otherFork:[e,...n.slice(0,a)],common:t.slice(i)}}}return{fork:[this,...t],otherFork:[e,...n],common:[]}}hasCommonAncestors(e){let t=this.findCommonAncestors(e);return t&&!!t.common.length}isInFrontOf(e){if(this===e)return;let t=this.findCommonAncestors(e);if(t.fork.includes(e))return!0;if(t.otherFork.includes(this))return!1;let n=t.common[0]||this.canvas;if(!n)return;let r=t.fork.pop(),i=t.otherFork.pop(),a=n._objects.indexOf(r),o=n._objects.indexOf(i);return a>-1&&a>o}toObject(t=[]){let n=t.concat(e.customProperties,this.constructor.customProperties||[]),r,i=h.NUM_FRACTION_DIGITS,{clipPath:a,fill:o,stroke:s,shadow:c,strokeDashArray:l,left:u,top:d,originX:f,originY:p,width:m,height:g,strokeWidth:_,strokeLineCap:v,strokeDashOffset:y,strokeLineJoin:b,strokeUniform:x,strokeMiterLimit:S,scaleX:C,scaleY:w,angle:T,flipX:E,flipY:D,opacity:k,visible:A,backgroundColor:j,fillRule:M,paintFirst:ee,globalCompositeOperation:N,skewX:P,skewY:F}=this;a&&!a.excludeFromExport&&(r=a.toObject(n.concat(`inverted`,`absolutePositioned`)));let I=e=>V(e,i),te={...st(this,n),type:this.constructor.type,version:O,originX:f,originY:p,left:I(u),top:I(d),width:I(m),height:I(g),fill:dt(o)?o.toObject():o,stroke:dt(s)?s.toObject():s,strokeWidth:I(_),strokeDashArray:l&&l.concat(),strokeLineCap:v,strokeDashOffset:y,strokeLineJoin:b,strokeUniform:x,strokeMiterLimit:I(S),scaleX:I(C),scaleY:I(w),angle:I(T),flipX:E,flipY:D,opacity:I(k),shadow:c&&c.toObject(),visible:A,backgroundColor:j,fillRule:M,paintFirst:ee,globalCompositeOperation:N,skewX:I(P),skewY:I(F),...r?{clipPath:r}:null};return this.includeDefaultValues?te:this._removeDefaultValues(te)}toDatalessObject(e){return this.toObject(e)}_removeDefaultValues(e){let t=this.constructor.getDefaults(),n=Object.keys(t).length>0?t:Object.getPrototypeOf(this);return ct(e,(e,t)=>{if(t===`left`||t===`top`||t===`type`)return!0;let r=n[t];return e!==r&&!(Array.isArray(e)&&Array.isArray(r)&&e.length===0&&r.length===0)})}toString(){return`#<${this.constructor.type}>`}static _fromObject({type:e,...t},{extraParam:n,...r}={}){return ot(t,r).then(e=>n?(delete e[n],new this(t[n],e)):new this(e))}static fromObject(e,t){return this._fromObject(e,t)}};p(Jr,`stateProperties`,er),p(Jr,`cacheProperties`,tr),p(Jr,`ownDefaults`,nr),p(Jr,`type`,`FabricObject`),p(Jr,`colorProperties`,[_e,ve,`backgroundColor`]),p(Jr,`customProperties`,[]),L.setClass(Jr),L.setClass(Jr,`object`);var Yr=(e,t)=>{var n;let{transform:{target:r}}=t;(n=r.canvas)==null||n.fire(`object:${e}`,{...t,target:r}),r.fire(e,t)},Xr=(e,t,n)=>(r,i,a,o)=>{let s=t(r,i,a,o);return s&&Yr(e,{...ln(r,i,a,o),...n}),s};function Zr(e){return(t,n,r,i)=>{let{target:a,originX:o,originY:s}=n,c=a.getPositionByOrigin(o,s),l=e(t,n,r,i);return a.setPositionByOrigin(c,n.originX,n.originY),l}}var Qr=(e,t,n,r)=>(i,a,o,s)=>{let c=dn(a,a.originX,a.originY,o,s)[n],l=Gt(a[t]);if(l===0||l>0&&c<0||l<0&&c>0){let{target:t}=a,n=t.strokeWidth/(t.strokeUniform?t[r]:1),i=on(a)?2:1,o=t[e],s=Math.abs(c*i/t[r])-n;return t.set(e,Math.max(s,1)),o!==t[e]}return!1},$r=Qr(`width`,`originX`,`x`,`scaleX`),ei=Qr(`height`,`originY`,`y`,`scaleY`),ti=Xr(le,Zr($r)),ni=Xr(le,Zr(ei));function ri(e,t,n,r,i){e.save();let{stroke:a,xSize:o,ySize:s,opName:c}=this.commonRenderProps(e,t,n,i,r),l=o;o>s?e.scale(1,s/o):s>o&&(l=s,e.scale(o/s,1)),e.beginPath(),e.arc(0,0,l/2,0,M,!1),e[c](),a&&e.stroke(),e.restore()}function ii(e,t,n,r,i){e.save();let{stroke:a,xSize:o,ySize:s,opName:c}=this.commonRenderProps(e,t,n,i,r),l=o/2,u=s/2;e[`${c}Rect`](-l,-u,o,s),a&&e.strokeRect(-l,-u,o,s),e.restore()}var ai=class{constructor(e){p(this,`visible`,!0),p(this,`actionName`,fe),p(this,`angle`,0),p(this,`x`,0),p(this,`y`,0),p(this,`offsetX`,0),p(this,`offsetY`,0),p(this,`sizeX`,0),p(this,`sizeY`,0),p(this,`touchSizeX`,0),p(this,`touchSizeY`,0),p(this,`cursorStyle`,`crosshair`),p(this,`withConnection`,!1),Object.assign(this,e)}getTransformAnchorPoint(){return this.transformAnchorPoint??new R(.5-this.x,.5-this.y)}shouldActivate(e,t,n,{tl:r,tr:i,br:a,bl:o}){return t.canvas?.getActiveObject()===t&&t.isControlVisible(e)&&Kr.isPointInPolygon(n,[r,i,a,o])}getActionHandler(e,t,n){return this.actionHandler}getMouseDownHandler(e,t,n){return this.mouseDownHandler}getMouseUpHandler(e,t,n){return this.mouseUpHandler}cursorStyleHandler(e,t,n,r){return t.cursorStyle}getActionName(e,t,n){return t.actionName}getVisibility(e,t){return e._controlsVisibility?.[t]??this.visible}setVisibility(e,t,n){this.visible=e}positionHandler(e,t,n,r){return new R(this.x*e.x+this.offsetX,this.y*e.y+this.offsetY).transform(t)}calcCornerCoords(e,t,n,r,i,a){let o=Ge([Xe(n,r),Ze({angle:e}),Qe((i?this.touchSizeX:this.sizeX)||t,(i?this.touchSizeY:this.sizeY)||t)]);return{tl:new R(-.5,-.5).transform(o),tr:new R(.5,-.5).transform(o),br:new R(.5,.5).transform(o),bl:new R(-.5,.5).transform(o)}}commonRenderProps(e,t,n,r,i={}){let{cornerSize:a,cornerColor:o,transparentCorners:s,cornerStrokeColor:c}=i,l=a||r.cornerSize,u=this.sizeX||l,d=this.sizeY||l,f=s===void 0?r.transparentCorners:s,p=f?ve:_e,m=c||r.cornerStrokeColor,h=!f&&!!m;return e.fillStyle=o||r.cornerColor||``,e.strokeStyle=m||``,e.translate(t,n),e.rotate(z(r.getTotalAngle())),{stroke:h,xSize:u,ySize:d,transparentCorners:f,opName:p}}render(e,t,n,r,i){((r||={}).cornerStyle||i.cornerStyle)===`circle`?ri.call(this,e,t,n,r,i):ii.call(this,e,t,n,r,i)}},oi=(e,t,n)=>n.lockRotation?an:t.cursorStyle,si=Xr(oe,Zr((e,{target:t,ex:n,ey:r,theta:i,originX:a,originY:o},s,c)=>{let l=t.getPositionByOrigin(a,o);if(cn(t,`lockRotation`))return!1;let u=Math.atan2(r-l.y,n-l.x),d=Ve(Math.atan2(c-l.y,s-l.x)-u+i);if(t.snapAngle&&t.snapAngle>0){let e=t.snapAngle,n=t.snapThreshold||e,r=Math.ceil(d/e)*e,i=Math.floor(d/e)*e;Math.abs(d-i)<n?d=i:Math.abs(d-r)<n&&(d=r)}d<0&&(d=360+d),d%=360;let f=t.angle!==d;return t.angle=d,f}));function ci(e,t){let n=t.canvas,r=e[n.uniScaleKey];return n.uniformScaling&&!r||!n.uniformScaling&&r}function li(e,t,n){let r=cn(e,`lockScalingX`),i=cn(e,`lockScalingY`);if(r&&i||!t&&(r||i)&&n||r&&t===`x`||i&&t===`y`)return!0;let{width:a,height:o,strokeWidth:s}=e;return a===0&&s===0&&t!==`y`||o===0&&s===0&&t!==`x`}var ui=[`e`,`se`,`s`,`sw`,`w`,`nw`,`n`,`ne`,`e`],di=(e,t,n,r)=>{let i=ci(e,n);return li(n,t.x!==0&&t.y===0?`x`:t.x===0&&t.y!==0?`y`:``,i)?an:`${ui[un(n,0,r)]}-resize`};function fi(e,t,n,r,i={}){let a=t.target,o=i.by,s=ci(e,a),c,l,u,d,f,p;if(li(a,o,s))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,u=t.scaleY*t.gestureScale;else{if(c=dn(t,t.originX,t.originY,n,r),f=o===`y`?1:Math.sign(c.x||t.signX||1),p=o===`x`?1:Math.sign(c.y||t.signY||1),t.signX||=f,t.signY||=p,cn(a,`lockScalingFlip`)&&(t.signX!==f||t.signY!==p))return!1;if(d=a._getTransformedDimensions(),s&&!o){let e=Math.abs(c.x)+Math.abs(c.y),{original:n}=t,r=e/(Math.abs(d.x*n.scaleX/a.scaleX)+Math.abs(d.y*n.scaleY/a.scaleY));l=n.scaleX*r,u=n.scaleY*r}else l=Math.abs(c.x*a.scaleX/d.x),u=Math.abs(c.y*a.scaleY/d.y);on(t)&&(l*=2,u*=2),t.signX!==f&&o!==`y`&&(t.originX=sn(t.originX),l*=-1,t.signX=f),t.signY!==p&&o!==`x`&&(t.originY=sn(t.originY),u*=-1,t.signY=p)}let m=a.scaleX,h=a.scaleY;return o?(o===`x`&&a.set(`scaleX`,l),o===`y`&&a.set(`scaleY`,u)):(!cn(a,`lockScalingX`)&&a.set(`scaleX`,l),!cn(a,`lockScalingY`)&&a.set(`scaleY`,u)),m!==a.scaleX||h!==a.scaleY}var pi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r))),mi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r,{by:`x`}))),hi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r,{by:`y`}))),gi={x:{counterAxis:`y`,scale:pe,skew:he,lockSkewing:`lockSkewingX`,origin:`originX`,flip:`flipX`},y:{counterAxis:`x`,scale:me,skew:ge,lockSkewing:`lockSkewingY`,origin:`originY`,flip:`flipY`}},_i=[`ns`,`nesw`,`ew`,`nwse`],vi=(e,t,n,r)=>t.x!==0&&cn(n,`lockSkewingY`)||t.y!==0&&cn(n,`lockSkewingX`)?an:`${_i[un(n,0,r)%4]}-resize`;function yi(e,t,n,r,i){let{target:a}=n,{counterAxis:o,origin:s,lockSkewing:c,skew:l,flip:u}=gi[e];if(cn(a,c))return!1;let{origin:d,flip:f}=gi[o],p=Gt(n[d])*(a[f]?-1:1),m=-Math.sign(p)*(a[u]?-1:1),h=-(a[l]===0&&dn(n,`center`,`center`,r,i)[e]>0||a[l]>0?1:-1)*m*.5+.5;return Xr(ce,Zr((t,n,r,i)=>function(e,{target:t,ex:n,ey:r,skewingSide:i,...a},o){let{skew:s}=gi[e],c=o.subtract(new R(n,r)).divide(new R(t.scaleX,t.scaleY))[e],l=t[s],u=a[s],d=Math.tan(z(u)),f=e===`y`?t._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:t._getTransformedDimensions({scaleX:1,scaleY:1}).y,p=2*c*i/Math.max(f,1)+d,m=Ve(Math.atan(p));t.set(s,m);let h=l!==t[s];if(h&&e===`y`){let{skewX:e,scaleX:n}=t,r=t._getTransformedDimensions({skewY:l}),i=t._getTransformedDimensions(),a=e===0?1:r.x/i.x;a!==1&&t.set(`scaleX`,a*n)}return h}(e,n,new R(r,i))))(t,{...n,[s]:h,skewingSide:m},r,i)}var bi=(e,t,n,r)=>yi(`x`,e,t,n,r),xi=(e,t,n,r)=>yi(`y`,e,t,n,r);function Si(e,t){return e[t.canvas.altActionKey]}var Ci=(e,t,n)=>{let r=Si(e,n);return t.x===0?r?he:me:t.y===0?r?ge:pe:``},wi=(e,t,n,r)=>Si(e,n)?vi(0,t,n,r):di(e,t,n,r),Ti=(e,t,n,r)=>Si(e,t.target)?xi(e,t,n,r):mi(e,t,n,r),Ei=(e,t,n,r)=>Si(e,t.target)?bi(e,t,n,r):hi(e,t,n,r),Di=()=>({ml:new ai({x:-.5,y:0,cursorStyleHandler:wi,actionHandler:Ti,getActionName:Ci}),mr:new ai({x:.5,y:0,cursorStyleHandler:wi,actionHandler:Ti,getActionName:Ci}),mb:new ai({x:0,y:.5,cursorStyleHandler:wi,actionHandler:Ei,getActionName:Ci}),mt:new ai({x:0,y:-.5,cursorStyleHandler:wi,actionHandler:Ei,getActionName:Ci}),tl:new ai({x:-.5,y:-.5,cursorStyleHandler:di,actionHandler:pi}),tr:new ai({x:.5,y:-.5,cursorStyleHandler:di,actionHandler:pi}),bl:new ai({x:-.5,y:.5,cursorStyleHandler:di,actionHandler:pi}),br:new ai({x:.5,y:.5,cursorStyleHandler:di,actionHandler:pi}),mtr:new ai({x:0,y:-.5,actionHandler:si,cursorStyleHandler:oi,offsetY:-40,withConnection:!0,actionName:se})}),Oi=()=>({mr:new ai({x:.5,y:0,actionHandler:ti,cursorStyleHandler:wi,actionName:le}),ml:new ai({x:-.5,y:0,actionHandler:ti,cursorStyleHandler:wi,actionName:le})}),ki=()=>({...Di(),...Oi()}),Ai=class e extends Jr{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,this.constructor.createControls(),e.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Di()}}_updateCacheCanvas(){let e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){let t=e._currentTransform,n=t.target,r=t.action;if(this===n&&r&&r.startsWith(`scale`))return!1}return super._updateCacheCanvas()}getActiveControl(){let e=this.__corner;return e?{key:e,control:this.controls[e],coord:this.oCoords[e]}:void 0}findControl(e,t=!1){if(!this.hasControls||!this.canvas)return;this.__corner=void 0;let n=Object.entries(this.oCoords);for(let r=n.length-1;r>=0;r--){let[i,a]=n[r],o=this.controls[i];if(o.shouldActivate(i,this,e,t?a.touchCorner:a.corner))return this.__corner=i,{key:i,control:o,coord:this.oCoords[i]}}}calcOCoords(){let e=this.getViewportTransform(),t=qe(e),n=Je(e),r=this.getCenterPoint(),i=B(B(e,B(Xe(r.x,r.y),Ze({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}))),[1/t,0,0,1/n,0,0]),a=this.group?Ye(this.calcTransformMatrix()):void 0;a&&(a.scaleX=Math.abs(a.scaleX),a.scaleY=Math.abs(a.scaleY));let o=this._calculateCurrentDimensions(a),s={};return this.forEachControl((e,t)=>{let n=e.positionHandler(o,i,this,e);s[t]=Object.assign(n,this._calcCornerCoords(e,n))}),s}_calcCornerCoords(e,t){let n=this.getTotalAngle();return{corner:e.calcCornerCoords(n,this.cornerSize,t.x,t.y,!1,this),touchCorner:e.calcCornerCoords(n,this.touchCornerSize,t.x,t.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(e){for(let t in this.controls)e(this.controls[t],t,this)}drawSelectionBackground(e){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;e.save();let t=this.getRelativeCenterPoint(),n=this._calculateCurrentDimensions(),r=this.getViewportTransform();e.translate(t.x,t.y),e.scale(1/r[0],1/r[3]),e.rotate(z(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore()}strokeBorders(e,t){e.strokeRect(-t.x/2,-t.y/2,t.x,t.y)}_drawBorders(e,t,n={}){let r={hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray,...n};e.save(),e.strokeStyle=r.borderColor,this._setLineDash(e,r.borderDashArray),this.strokeBorders(e,t),r.hasControls&&this.drawControlsConnectingLines(e,t),e.restore()}_renderControls(e,t={}){let{hasBorders:n,hasControls:r}=this,i={hasBorders:n,hasControls:r,...t},a=this.getViewportTransform(),o=i.hasBorders,s=i.hasControls,c=Ye(B(a,this.calcTransformMatrix()));e.save(),e.translate(c.translateX,c.translateY),e.lineWidth=this.borderScaleFactor,this.group===this.parent&&(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180);let l=Ke(a);e.rotate(this.group?z(c.angle):z(this.angle)+l),o&&this.drawBorders(e,c,t),s&&this.drawControls(e,t),e.restore()}drawBorders(e,t,n){let r;if(n&&n.forActiveSelection||this.group){let e=zt(this.width,this.height,nt(t)),n=this.isStrokeAccountedForInDimensions()?De:(this.strokeUniform?new R().scalarAdd(this.canvas?this.canvas.getZoom():1):new R(t.scaleX,t.scaleY)).scalarMultiply(this.strokeWidth);r=e.add(n).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else r=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(e,r,n)}drawControlsConnectingLines(e,t){let n=!1;e.beginPath(),this.forEachControl((r,i)=>{r.withConnection&&r.getVisibility(this,i)&&(n=!0,e.moveTo(r.x*t.x,r.y*t.y),e.lineTo(r.x*t.x+r.offsetX,r.y*t.y+r.offsetY))}),n&&e.stroke()}drawControls(e,t={}){e.save();let n=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:i,cornerColor:a}=this,o={cornerStrokeColor:r,cornerDashArray:i,cornerColor:a,...t};e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=o.cornerColor,this.transparentCorners||(e.strokeStyle=o.cornerStrokeColor),this._setLineDash(e,o.cornerDashArray),this.forEachControl((t,n)=>{if(t.getVisibility(this,n)){let r=this.oCoords[n];t.render(e,r.x,r.y,o,this)}}),e.restore()}isControlVisible(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)}setControlVisible(e,t){this._controlsVisibility||={},this._controlsVisibility[e]=t}setControlsVisibility(e={}){Object.entries(e).forEach(([e,t])=>this.setControlVisible(e,t))}clearContextTop(e){if(!this.canvas)return;let t=this.canvas.contextTop;if(!t)return;let n=this.canvas.viewportTransform;t.save(),t.transform(n[0],n[1],n[2],n[3],n[4],n[5]),this.transform(t);let r=this.width+4,i=this.height+4;return t.clearRect(-r/2,-i/2,r,i),e||t.restore(),t}onDeselect(e){return!1}onSelect(e){return!1}shouldStartDragging(e){return!1}onDragStart(e){return!1}canDrop(e){return!1}renderDragSourceEffect(e){}renderDropTargetEffect(e){}};function ji(e,t){return t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(n=>{n!==`constructor`&&Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)||Object.create(null))})}),e}p(Ai,`ownDefaults`,{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:`rgb(178,204,255)`,cornerStrokeColor:``,cornerStyle:`rect`,cornerDashArray:null,hasControls:!0,borderColor:`rgb(178,204,255)`,borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:``,selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:`down`,hoverCursor:null,moveCursor:null});var Mi=class extends Ai{};ji(Mi,[On]),L.setClass(Mi),L.setClass(Mi,`object`);var Ni=(e,t,n,r)=>{let i=2*(r=Math.round(r))+1,{data:a}=e.getImageData(t-r,n-r,i,i);for(let e=3;e<a.length;e+=4)if(a[e]>0)return!1;return!0},Pi=class{constructor(e){this.options=e,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new R(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new R(1/this.options.scaleX,1/this.options.scaleY):new R(1,1)}createSideVector(e,t){let n=Yt(e,t);return this.options.strokeUniform?n.multiply(this.scale):n}projectOrthogonally(e,t,n){return this.applySkew(e.add(this.calcOrthogonalProjection(e,t,n)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(e){let t=new R(e);return t.y+=t.x*Math.tan(z(this.options.skewY)),t.x+=t.y*Math.tan(z(this.options.skewX)),t}scaleUnitVector(e,t){return e.multiply(this.strokeUniformScalar).scalarMultiply(t)}},Fi=new R,Ii=class e extends Pi{static getOrthogonalRotationFactor(e,t){let n=t?Zt(e,t):Qt(e);return Math.abs(n)<A?-1:1}constructor(e,t,n,r){super(r),p(this,`AB`,void 0),p(this,`AC`,void 0),p(this,`alpha`,void 0),p(this,`bisector`,void 0),this.A=new R(e),this.B=new R(t),this.C=new R(n),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Zt(this.AB,this.AC),this.bisector=$t(Jt(this.AB.eq(Fi)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,n,r=this.strokeProjectionMagnitude){let i=en(this.createSideVector(t,n)),a=e.getOrthogonalRotationFactor(i,this.bisector);return this.scaleUnitVector(i,r*a)}projectBevel(){let e=[];return(this.alpha%M===0?[this.B]:[this.B,this.C]).forEach(t=>{e.push(this.projectOrthogonally(this.A,t)),e.push(this.projectOrthogonally(this.A,t,-this.strokeProjectionMagnitude))}),e}projectMiter(){let e=[],t=Math.abs(this.alpha),n=1/Math.sin(t/2),r=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*n),i=this.options.strokeUniform?Xt(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Xt(r)/this.strokeProjectionMagnitude<=i&&e.push(this.applySkew(this.A.add(r))),e.push(...this.projectBevel()),e}projectRoundNoSkew(t,n){let r=[],i=new R(e.getOrthogonalRotationFactor(this.bisector),e.getOrthogonalRotationFactor(new R(this.bisector.y,this.bisector.x)));return[new R(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new R(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(e=>{rn(e,t,n)&&r.push(this.A.add(e))}),r}projectRoundWithSkew(e,t){let n=[],{skewX:r,skewY:i,scaleX:a,scaleY:o,strokeUniform:s}=this.options,c=new R(Math.tan(z(r)),Math.tan(z(i))),l=this.strokeProjectionMagnitude,u=s?l/o/Math.sqrt(1/o**2+1/a**2*c.y**2):l/Math.sqrt(1+c.y**2),d=new R(Math.sqrt(Math.max(l**2-u**2,0)),u),f=s?l/Math.sqrt(1+c.x**2*(1/o)**2/(1/a+1/a*c.x*c.y)**2):l/Math.sqrt(1+c.x**2/(1+c.x*c.y)**2),p=new R(f,Math.sqrt(Math.max(l**2-f**2,0)));return[p,p.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(e=>this.applySkew(s?e.multiply(this.strokeUniformScalar):e)).forEach(r=>{rn(r,e,t)&&n.push(this.applySkew(this.A).add(r))}),n}projectRound(){let e=[];e.push(...this.projectBevel());let t=this.alpha%M===0,n=this.applySkew(this.A),r=e[t?0:2].subtract(n),i=e[+!!t].subtract(n),a=tn(r,t?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)))>0,o=a?r:i,s=a?i:r;return this.isSkewed()?e.push(...this.projectRoundWithSkew(o,s)):e.push(...this.projectRoundNoSkew(o,s)),e}projectPoints(){switch(this.options.strokeLineJoin){case`miter`:return this.projectMiter();case`round`:return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(e=>({originPoint:this.A,projectedPoint:e,angle:this.alpha,bisector:this.bisector}))}},Li=class extends Pi{constructor(e,t,n){super(n),this.A=new R(e),this.T=new R(t)}calcOrthogonalProjection(e,t,n=this.strokeProjectionMagnitude){let r=this.createSideVector(e,t);return this.scaleUnitVector(en(r),n)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){let e=[];if(!this.isSkewed()&&this.A.eq(this.T)){let t=new R(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);e.push(this.applySkew(this.A.add(t)),this.applySkew(this.A.subtract(t)))}else e.push(...new Ii(this.A,this.T,this.T,this.options).projectRound());return e}projectSquare(){let e=[];if(this.A.eq(this.T)){let t=new R(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);e.push(this.A.add(t),this.A.subtract(t))}else{let t=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),n=this.scaleUnitVector($t(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),r=this.A.add(n);e.push(r.add(t),r.subtract(t))}return e.map(e=>this.applySkew(e))}projectPoints(){switch(this.options.strokeLineCap){case`round`:return this.projectRound();case`square`:return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(e=>({originPoint:this.A,projectedPoint:e}))}},Ri=(e,t,n=!1)=>{let r=[];if(e.length===0)return r;let i=e.reduce((e,t)=>(e[e.length-1].eq(t)||e.push(new R(t)),e),[new R(e[0])]);if(i.length===1)n=!0;else if(!n){let e=i[0],t=((e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n],n,e))return n;return-1})(i,t=>!t.eq(e));i.splice(t+1)}return i.forEach((e,i,a)=>{let o,s;i===0?(s=a[1],o=n?e:a[a.length-1]):i===a.length-1?(o=a[i-1],s=n?e:a[0]):(o=a[i-1],s=a[i+1]),n&&a.length===1?r.push(...new Li(e,e,t).project()):!n||i!==0&&i!==a.length-1?r.push(...new Ii(e,o,s,t).project()):r.push(...new Li(e,i===0?s:o,t).project())}),r},zi=e=>{let t={};return Object.keys(e).forEach(n=>{t[n]={},Object.keys(e[n]).forEach(r=>{t[n][r]={...e[n][r]}})}),t},Bi=(e,t,n=!1)=>e.fill!==t.fill||e.stroke!==t.stroke||e.strokeWidth!==t.strokeWidth||e.fontSize!==t.fontSize||e.fontFamily!==t.fontFamily||e.fontWeight!==t.fontWeight||e.fontStyle!==t.fontStyle||e.textDecorationThickness!==t.textDecorationThickness||e.textDecorationColor!==t.textDecorationColor||e.textBackgroundColor!==t.textBackgroundColor||e.deltaY!==t.deltaY||n&&(e.overline!==t.overline||e.underline!==t.underline||e.linethrough!==t.linethrough),Vi=(e,t)=>{let n=t.split(`
|
|
14
|
+
`),n?n(p.join(``)):p.join(``)}addPaintOrder(){return this.paintFirst===`fill`?``:` paint-order="${H(this.paintFirst)}" `}};function kn(e){return RegExp(`^(`+e.join(`|`)+`)\\b`,`i`)}var An=`textDecorationThickness`,jn=`textDecorationColor`,Mn=[`fontSize`,`fontWeight`,`fontFamily`,`fontStyle`],Nn=[`underline`,`overline`,`linethrough`],Pn=[...Mn,`lineHeight`,`text`,`charSpacing`,`textAlign`,`styles`,`path`,`pathStartOffset`,`pathSide`,`pathAlign`],Fn=[...Pn,...Nn,`textBackgroundColor`,`direction`,An,jn],In=[...Mn,...Nn,ve,`strokeWidth`,_e,`deltaY`,`textBackgroundColor`,An,jn],Ln={_reNewline:re,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:be,fontFamily:`Times New Roman`,underline:!1,overline:!1,linethrough:!1,textAlign:F,fontStyle:be,lineHeight:1.16,textBackgroundColor:``,stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:F,pathAlign:`baseline`,charSpacing:0,deltaY:0,direction:`ltr`,CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[An]:66.667},Rn=`justify`,zn=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,Bn=String.raw`(?:\s*,?\s+|\s*,\s*)`,Vn=`http://www.w3.org/2000/svg`,Hn=RegExp(`(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*(`+zn+`(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|`+zn+`))?\\s+(.*)`),Un={cx:F,x:F,r:`radius`,cy:`top`,y:`top`,display:`visible`,visibility:`visible`,transform:`transformMatrix`,"fill-opacity":`fillOpacity`,"fill-rule":`fillRule`,"font-family":`fontFamily`,"font-size":`fontSize`,"font-style":`fontStyle`,"font-weight":`fontWeight`,"letter-spacing":`charSpacing`,"paint-order":`paintFirst`,"stroke-dasharray":`strokeDashArray`,"stroke-dashoffset":`strokeDashOffset`,"stroke-linecap":`strokeLineCap`,"stroke-linejoin":`strokeLineJoin`,"stroke-miterlimit":`strokeMiterLimit`,"stroke-opacity":`strokeOpacity`,"stroke-width":`strokeWidth`,"text-decoration":`textDecoration`,"text-anchor":`textAnchor`,opacity:`opacity`,"clip-path":`clipPath`,"clip-rule":`clipRule`,"vector-effect":`strokeUniform`,"image-rendering":`imageSmoothing`,"text-decoration-thickness":An,"text-decoration-color":jn},Wn=`font-size`,Gn=`clip-path`,Kn=kn([`path`,`circle`,`polygon`,`polyline`,`ellipse`,`rect`,`line`,`image`,`text`]),qn=kn([`symbol`,`image`,`marker`,`pattern`,`view`,`svg`]),Jn=kn([`symbol`,`g`,`a`,`svg`,`clipPath`,`defs`]),Yn=new RegExp(String.raw`^\s*(${zn})${Bn}(${zn})${Bn}(${zn})${Bn}(${zn})\s*$`),Xn=`(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?`,Zn=RegExp(`(?:\\s|^)`+Xn+Xn+`(`+zn+`?(?:px)?)?(?:\\s?|$)(?:$|\\s)`),Qn=class e{constructor(t={}){let n=typeof t==`string`?e.parseShadow(t):t;Object.assign(this,e.ownDefaults,n),this.id=Pe()}static parseShadow(e){let t=e.trim(),[,n=0,r=0,i=0]=(Zn.exec(t)||[]).map(e=>parseFloat(e)||0);return{color:(t.replace(Zn,``)||`rgb(0,0,0)`).trim(),offsetX:n,offsetY:r,blur:i}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join(`px `)}toSVG(e){let t=Jt(new R(this.offsetX,this.offsetY),z(-e.angle)),n=h.NUM_FRACTION_DIGITS,r=new Cn(this.color),i=40,a=40;return e.width&&e.height&&(i=100*V((Math.abs(t.x)+this.blur)/e.width,n)+20,a=100*V((Math.abs(t.y)+this.blur)/e.height,n)+20),e.flipX&&(t.x*=-1),e.flipY&&(t.y*=-1),`<filter id="SVGID_${H(this.id)}" y="-${a}%" height="${100+2*a}%" x="-${i}%" width="${100+2*i}%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="${V(this.blur?this.blur/2:0,n)}"></feGaussianBlur>\n\t<feOffset dx="${V(t.x,n)}" dy="${V(t.y,n)}" result="oBlur" ></feOffset>\n\t<feFlood flood-color="${r.toRgb()}" flood-opacity="${r.getAlpha()}"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n`}toObject(){let t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},n=e.ownDefaults;return this.includeDefaultValues?t:ct(t,(e,t)=>e!==n[t])}static async fromObject(e){return new this(e)}};p(Qn,`ownDefaults`,{color:`rgb(0,0,0)`,blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),p(Qn,`type`,`shadow`),L.setClass(Qn,`shadow`);var $n=(e,t,n)=>Math.max(e,Math.min(t,n)),er=[`top`,F,pe,me,`flipX`,`flipY`,`originX`,`originY`,`angle`,`opacity`,`globalCompositeOperation`,`shadow`,`visible`,he,ge],tr=[_e,ve,`strokeWidth`,`strokeDashArray`,`width`,`height`,`paintFirst`,`strokeUniform`,`strokeLineCap`,`strokeDashOffset`,`strokeLineJoin`,`strokeMiterLimit`,`backgroundColor`,`clipPath`],nr={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:P,originY:P,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:_e,fill:`rgb(0,0,0)`,fillRule:`nonzero`,stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:`butt`,strokeLineJoin:`miter`,strokeMiterLimit:4,globalCompositeOperation:`source-over`,backgroundColor:``,shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},rr=u({defaultEasing:()=>or,easeInBack:()=>Or,easeInBounce:()=>Mr,easeInCirc:()=>Sr,easeInCubic:()=>sr,easeInElastic:()=>Tr,easeInExpo:()=>yr,easeInOutBack:()=>Ar,easeInOutBounce:()=>Nr,easeInOutCirc:()=>wr,easeInOutCubic:()=>lr,easeInOutElastic:()=>Dr,easeInOutExpo:()=>xr,easeInOutQuad:()=>Ir,easeInOutQuart:()=>fr,easeInOutQuint:()=>hr,easeInOutSine:()=>vr,easeInQuad:()=>Pr,easeInQuart:()=>ur,easeInQuint:()=>pr,easeInSine:()=>gr,easeOutBack:()=>kr,easeOutBounce:()=>jr,easeOutCirc:()=>Cr,easeOutCubic:()=>cr,easeOutElastic:()=>Er,easeOutExpo:()=>br,easeOutQuad:()=>Fr,easeOutQuart:()=>dr,easeOutQuint:()=>mr,easeOutSine:()=>_r}),ir=(e,t,n,r)=>(e<Math.abs(t)?(e=t,r=n/4):r=t===0&&e===0?n/M*Math.asin(1):n/M*Math.asin(t/e),{a:e,c:t,p:n,s:r}),ar=(e,t,n,r,i)=>e*2**(10*--r)*Math.sin((r*i-t)*M/n),or=(e,t,n,r)=>-n*Math.cos(e/r*A)+n+t,sr=(e,t,n,r)=>n*(e/r)**3+t,cr=(e,t,n,r)=>n*((e/r-1)**3+1)+t,lr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**3+t:n/2*((e-2)**3+2)+t,ur=(e,t,n,r)=>n*(e/=r)*e**3+t,dr=(e,t,n,r)=>-n*((e=e/r-1)*e**3-1)+t,fr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**4+t:-n/2*((e-=2)*e**3-2)+t,pr=(e,t,n,r)=>n*(e/r)**5+t,mr=(e,t,n,r)=>n*((e/r-1)**5+1)+t,hr=(e,t,n,r)=>(e/=r/2)<1?n/2*e**5+t:n/2*((e-2)**5+2)+t,gr=(e,t,n,r)=>-n*Math.cos(e/r*A)+n+t,_r=(e,t,n,r)=>n*Math.sin(e/r*A)+t,vr=(e,t,n,r)=>-n/2*(Math.cos(Math.PI*e/r)-1)+t,yr=(e,t,n,r)=>e===0?t:n*2**(10*(e/r-1))+t,br=(e,t,n,r)=>e===r?t+n:n*-(2**(-10*e/r)+1)+t,xr=(e,t,n,r)=>e===0?t:e===r?t+n:(e/=r/2)<1?n/2*2**(10*(e-1))+t:n/2*-(2**(-10*(e-1))+2)+t,Sr=(e,t,n,r)=>-n*(Math.sqrt(1-(e/=r)*e)-1)+t,Cr=(e,t,n,r)=>n*Math.sqrt(1-(e=e/r-1)*e)+t,wr=(e,t,n,r)=>(e/=r/2)<1?-n/2*(Math.sqrt(1-e**2)-1)+t:n/2*(Math.sqrt(1-(e-=2)*e)+1)+t,Tr=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r)===1)return t+n;a||=.3*r;let{a:o,s,p:c}=ir(i,n,a,1.70158);return-ar(o,s,c,e,r)+t},Er=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r)===1)return t+n;a||=.3*r;let{a:o,s,p:c,c:l}=ir(i,n,a,1.70158);return o*2**(-10*e)*Math.sin((e*r-s)*M/c)+l+t},Dr=(e,t,n,r)=>{let i=n,a=0;if(e===0)return t;if((e/=r/2)==2)return t+n;a||=.3*1.5*r;let{a:o,s,p:c,c:l}=ir(i,n,a,1.70158);return e<1?-.5*ar(o,s,c,e,r)+t:o*2**(-10*--e)*Math.sin((e*r-s)*M/c)*.5+l+t},Or=(e,t,n,r,i=1.70158)=>n*(e/=r)*e*((i+1)*e-i)+t,kr=(e,t,n,r,i=1.70158)=>n*((e=e/r-1)*e*((i+1)*e+i)+1)+t,Ar=(e,t,n,r,i=1.70158)=>(e/=r/2)<1?n/2*(e*e*((1+(i*=1.525))*e-i))+t:n/2*((e-=2)*e*((1+(i*=1.525))*e+i)+2)+t,jr=(e,t,n,r)=>(e/=r)<1/2.75?n*(7.5625*e*e)+t:e<2/2.75?n*(7.5625*(e-=1.5/2.75)*e+.75)+t:e<2.5/2.75?n*(7.5625*(e-=2.25/2.75)*e+.9375)+t:n*(7.5625*(e-=2.625/2.75)*e+.984375)+t,Mr=(e,t,n,r)=>n-jr(r-e,0,n,r)+t,Nr=(e,t,n,r)=>e<r/2?.5*Mr(2*e,0,n,r)+t:.5*jr(2*e-r,0,n,r)+.5*n+t,Pr=(e,t,n,r)=>n*(e/=r)*e+t,Fr=(e,t,n,r)=>-n*(e/=r)*(e-2)+t,Ir=(e,t,n,r)=>(e/=r/2)<1?n/2*e**2+t:-n/2*(--e*(e-2)-1)+t,Lr=()=>!1,Rr=class{constructor({startValue:e,byValue:t,duration:n=500,delay:r=0,easing:i=or,onStart:a=k,onChange:o=k,onComplete:s=k,abort:c=Lr,target:l}){p(this,`_state`,`pending`),p(this,`durationProgress`,0),p(this,`valueProgress`,0),this.tick=this.tick.bind(this),this.duration=n,this.delay=r,this.easing=i,this._onStart=a,this._onChange=o,this._onComplete=s,this._abort=c,this.target=l,this.startValue=e,this.byValue=t,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state===`aborted`||this._state===`completed`}start(){let e=e=>{this._state===`pending`&&(this.startTime=e||+new Date,this._state=`running`,this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?this.timeout=T().setTimeout(()=>je(e),this.delay):je(e)}tick(e){let t=(e||+new Date)-this.startTime,n=Math.min(t,this.duration);this.durationProgress=n/this.duration;let{value:r,valueProgress:i}=this.calculate(n);this.value=Object.freeze(r),this.valueProgress=i,this._state!==`aborted`&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state=`aborted`,this.unregister()):t>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state=`completed`,this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister(),this.timeout=null):(this._onChange(this.value,this.valueProgress,this.durationProgress),je(this.tick)))}register(){Se.push(this)}unregister(){Se.remove(this)}abort(){this._state=`aborted`,this.unregister(),this.timeout&&T().clearTimeout(this.timeout)}},zr=class extends Rr{constructor({startValue:e=0,endValue:t=100,...n}){super({...n,startValue:e,byValue:t-e})}calculate(e){let t=this.easing(e,this.startValue,this.byValue,this.duration);return{value:t,valueProgress:Math.abs((t-this.startValue)/this.byValue)}}},Br=class extends Rr{constructor({startValue:e=[0],endValue:t=[100],...n}){super({...n,startValue:e,byValue:t.map((t,n)=>t-e[n])})}calculate(e){let t=this.startValue.map((t,n)=>this.easing(e,t,this.byValue[n],this.duration,n));return{value:t,valueProgress:Math.abs((t[0]-this.startValue[0])/this.byValue[0])}}},Vr=(e,t,n,r)=>t+n*(1-Math.cos(e/r*A)),Hr=e=>e&&((t,n,r)=>e(new Cn(t).toRgba(),n,r)),Ur=class extends Rr{constructor({startValue:e,endValue:t,easing:n=Vr,onChange:r,onComplete:i,abort:a,...o}){let s=new Cn(e).getSource(),c=new Cn(t).getSource();super({...o,startValue:s,byValue:c.map((e,t)=>e-s[t]),easing:n,onChange:Hr(r),onComplete:Hr(i),abort:Hr(a)})}calculate(e){let[t,n,r,i]=this.startValue.map((t,n)=>this.easing(e,t,this.byValue[n],this.duration,n)),a=[...[t,n,r].map(Math.round),$n(0,i,1)];return{value:a,valueProgress:a.map((e,t)=>this.byValue[t]===0?0:Math.abs((e-this.startValue[t])/this.byValue[t])).find(e=>e!==0)||0}}};function Wr(e){let t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(e)?new Br(e):new zr(e);return t.start(),t}function Gr(e){let t=new Ur(e);return t.start(),t}var Kr=class e{constructor(e){this.status=e,this.points=[]}includes(e){return this.points.some(t=>t.eq(e))}append(...e){return this.points=this.points.concat(e.filter(e=>!this.includes(e))),this}static isPointContained(e,t,n,r=!1){if(t.eq(n))return e.eq(t);if(t.x===n.x)return e.x===t.x&&(r||e.y>=Math.min(t.y,n.y)&&e.y<=Math.max(t.y,n.y));if(t.y===n.y)return e.y===t.y&&(r||e.x>=Math.min(t.x,n.x)&&e.x<=Math.max(t.x,n.x));{let i=Yt(t,n),a=Yt(t,e).divide(i);return r?Math.abs(a.x)===Math.abs(a.y):a.x===a.y&&a.x>=0&&a.x<=1}}static isPointInPolygon(e,t){let n=new R(e).setX(Math.min(e.x-1,...t.map(e=>e.x))),r=0;for(let i=0;i<t.length;i++){let a=this.intersectSegmentSegment(t[i],t[(i+1)%t.length],e,n);if(a.includes(e))return!0;r+=Number(a.status===`Intersection`)}return r%2==1}static intersectLineLine(t,n,r,i,a=!0,o=!0){let s=n.x-t.x,c=n.y-t.y,l=i.x-r.x,u=i.y-r.y,d=t.x-r.x,f=t.y-r.y,p=l*f-u*d,m=s*f-c*d,h=u*s-l*c;if(h!==0){let n=p/h,r=m/h;return(a||0<=n&&n<=1)&&(o||0<=r&&r<=1)?new e(`Intersection`).append(new R(t.x+n*s,t.y+n*c)):new e}return new e(p===0||m===0?a||o||e.isPointContained(t,r,i)||e.isPointContained(n,r,i)||e.isPointContained(r,t,n)||e.isPointContained(i,t,n)?`Coincident`:void 0:`Parallel`)}static intersectSegmentLine(t,n,r,i){return e.intersectLineLine(t,n,r,i,!1,!0)}static intersectSegmentSegment(t,n,r,i){return e.intersectLineLine(t,n,r,i,!1,!1)}static intersectLinePolygon(t,n,r,i=!0){let a=new e,o=r.length;for(let s,c,l,u=0;u<o;u++){if(s=r[u],c=r[(u+1)%o],l=e.intersectLineLine(t,n,s,c,i,!1),l.status===`Coincident`)return l;a.append(...l.points)}return a.points.length>0&&(a.status=`Intersection`),a}static intersectSegmentPolygon(t,n,r){return e.intersectLinePolygon(t,n,r,!1)}static intersectPolygonPolygon(t,n){let r=new e,i=t.length,a=[];for(let o=0;o<i;o++){let s=t[o],c=t[(o+1)%i],l=e.intersectSegmentPolygon(s,c,n);l.status===`Coincident`?(a.push(l),r.append(s,c)):r.append(...l.points)}return a.length>0&&a.length===t.length?new e(`Coincident`):(r.points.length>0&&(r.status=`Intersection`),r)}static intersectPolygonRectangle(t,n,r){let i=n.min(r),a=n.max(r),o=new R(a.x,i.y),s=new R(i.x,a.y);return e.intersectPolygonPolygon(t,[i,o,a,s])}},qr=class extends Ae{getX(){return this.getXY().x}setX(e){this.setXY(this.getXY().setX(e))}getY(){return this.getXY().y}setY(e){this.setXY(this.getXY().setY(e))}getRelativeX(){return this.left}setRelativeX(e){this.left=e}getRelativeY(){return this.top}setRelativeY(e){this.top=e}getXY(){let e=this.getRelativeXY();return this.group?Ue(e,this.group.calcTransformMatrix()):e}setXY(e,t,n){this.group&&(e=Ue(e,We(this.group.calcTransformMatrix()))),this.setRelativeXY(e,t,n)}getRelativeXY(){return new R(this.left,this.top)}setRelativeXY(e,t=this.originX,n=this.originY){this.setPositionByOrigin(e,t,n)}isStrokeAccountedForInDimensions(){return!1}getCoords(){let{tl:e,tr:t,br:n,bl:r}=this.aCoords||=this.calcACoords(),i=[e,t,n,r];if(this.group){let e=this.group.calcTransformMatrix();return i.map(t=>Ue(t,e))}return i}intersectsWithRect(e,t){return Kr.intersectPolygonRectangle(this.getCoords(),e,t).status===`Intersection`}intersectsWithObject(e){let t=Kr.intersectPolygonPolygon(this.getCoords(),e.getCoords());return t.status===`Intersection`||t.status===`Coincident`||e.isContainedWithinObject(this)||this.isContainedWithinObject(e)}isContainedWithinObject(e){return this.getCoords().every(t=>e.containsPoint(t))}isContainedWithinRect(e,t){let{left:n,top:r,width:i,height:a}=this.getBoundingRect();return n>=e.x&&n+i<=t.x&&r>=e.y&&r+a<=t.y}isOverlapping(e){return this.intersectsWithObject(e)||this.isContainedWithinObject(e)||e.isContainedWithinObject(this)}containsPoint(e){return Kr.isPointInPolygon(e,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;let{tl:e,br:t}=this.canvas.vptCoords;return!!this.getCoords().some(n=>n.x<=t.x&&n.x>=e.x&&n.y<=t.y&&n.y>=e.y)||!!this.intersectsWithRect(e,t)||this.containsPoint(e.midPointFrom(t))}isPartiallyOnScreen(){if(!this.canvas)return!1;let{tl:e,br:t}=this.canvas.vptCoords;return!!this.intersectsWithRect(e,t)||this.getCoords().every(n=>(n.x>=t.x||n.x<=e.x)&&(n.y>=t.y||n.y<=e.y))&&this.containsPoint(e.midPointFrom(t))}getBoundingRect(){return Nt(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(e){this._set(pe,e),this._set(me,e),this.setCoords()}scaleToWidth(e){let t=this.getBoundingRect().width/this.getScaledWidth();return this.scale(e/this.width/t)}scaleToHeight(e){let t=this.getBoundingRect().height/this.getScaledHeight();return this.scale(e/this.height/t)}getCanvasRetinaScaling(){return this.canvas?.getRetinaScaling()||1}getTotalAngle(){return this.group?Ve(Ke(this.calcTransformMatrix())):this.angle}getViewportTransform(){return this.canvas?.viewportTransform||N.concat()}calcACoords(){let e=Ze({angle:this.angle}),{x:t,y:n}=this.getRelativeCenterPoint(),r=B(Xe(t,n),e),i=this._getTransformedDimensions(),a=i.x/2,o=i.y/2;return{tl:Ue({x:-a,y:-o},r),tr:Ue({x:a,y:-o},r),bl:Ue({x:-a,y:o},r),br:Ue({x:a,y:o},r)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(e=!1){let t=[];return!e&&this.group&&(t=this.group.transformMatrixKey(e)),t.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,Gt(this.originX),Gt(this.originY)),t}calcTransformMatrix(e=!1){let t=this.calcOwnMatrix();if(e||!this.group)return t;let n=this.transformMatrixKey(e),r=this.matrixCache;return r&&r.key.every((e,t)=>e===n[t])?r.value:(this.group&&(t=B(this.group.calcTransformMatrix(!1),t)),this.matrixCache={key:n,value:t},t)}calcOwnMatrix(){let e=this.transformMatrixKey(!0),t=this.ownMatrixCache;if(t&&t.key.every((t,n)=>t===e[n]))return t.value;let n=this.getRelativeCenterPoint(),r=rt({angle:this.angle,translateX:n.x,translateY:n.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY});return this.ownMatrixCache={key:e,value:r},r}_getNonTransformedDimensions(){return new R(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(e){let t=this.canvas?.viewportTransform,n=this._getTransformedDimensions(e);return t?n.multiply(new R(qe(t),Je(t))).scalarAdd(2*this.padding):n.scalarAdd(2*this.padding)}_getTransformedDimensions(e={}){let t={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth,...e},n=t.strokeWidth,r=n,i=0;this.strokeUniform&&(r=0,i=n);let a=t.width+r,o=t.height+r,s;return s=t.skewX===0&&t.skewY===0?new R(a*t.scaleX,o*t.scaleY):zt(a,o,nt(t)),s.scalarAdd(i)}translateToGivenOrigin(e,t,n,r,i){let a=e.x,o=e.y,s=Gt(r)-Gt(t),c=Gt(i)-Gt(n);if(s||c){let e=this._getTransformedDimensions();a+=s*e.x,o+=c*e.y}return new R(a,o)}translateToCenterPoint(e,t,n){if(t===`center`&&n===`center`)return e;let r=this.translateToGivenOrigin(e,t,n,P,P);return this.angle?r.rotate(z(this.angle),e):r}translateToOriginPoint(e,t,n){let r=this.translateToGivenOrigin(e,P,P,t,n);return this.angle?r.rotate(z(this.angle),e):r}getCenterPoint(){let e=this.getRelativeCenterPoint();return this.group?Ue(e,this.group.calcTransformMatrix()):e}getRelativeCenterPoint(){return this.translateToCenterPoint(new R(this.left,this.top),this.originX,this.originY)}getPointByOrigin(e,t){return this.getPositionByOrigin(e,t)}getPositionByOrigin(e,t){return this.translateToOriginPoint(this.getRelativeCenterPoint(),e,t)}setPositionByOrigin(e,t,n){let r=this.translateToCenterPoint(e,t,n),i=this.translateToOriginPoint(r,this.originX,this.originY);this.set({left:i.x,top:i.y})}_getLeftTopCoords(){return this.getPositionByOrigin(F,`top`)}positionByLeftTop(e){return this.setPositionByOrigin(e,F,`top`)}},Jr=class e extends qr{static getDefaults(){return e.ownDefaults}get type(){let e=this.constructor.type;return e===`FabricObject`?`object`:e.toLowerCase()}set type(e){g(`warn`,`Setting type has no effect`,e)}constructor(t){super(),p(this,`_cacheContext`,null),Object.assign(this,e.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Fe(),this._cacheContext=this._cacheCanvas.getContext(`2d`),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(e){let t=e.width,n=e.height,r=h.maxCacheSideLimit,i=h.minCacheSideLimit;if(t<=r&&n<=r&&t*n<=h.perfLimitSizeTotal)return t<i&&(e.width=i),n<i&&(e.height=i),e;let a=t/n,[o,s]=D.limitDimsByArea(a),c=$n(i,o,r),l=$n(i,s,r);return t>c&&(e.zoomX/=t/c,e.width=c,e.capped=!0),n>l&&(e.zoomY/=n/l,e.height=l,e.capped=!0),e}_getCacheCanvasDimensions(){let e=this.getTotalObjectScaling(),t=this._getTransformedDimensions({skewX:0,skewY:0}),n=t.x*e.x/this.scaleX,r=t.y*e.y/this.scaleY;return{width:Math.ceil(n+2),height:Math.ceil(r+2),zoomX:e.x,zoomY:e.y,x:n,y:r}}_updateCacheCanvas(){let e=this._cacheCanvas,t=this._cacheContext,{width:n,height:r,zoomX:i,zoomY:a,x:o,y:s}=this._limitCacheSize(this._getCacheCanvasDimensions()),c=n!==e.width||r!==e.height,l=this.zoomX!==i||this.zoomY!==a;if(!e||!t)return!1;if(c||l){n!==e.width||r!==e.height?(e.width=n,e.height=r):(t.setTransform(1,0,0,1,0,0),t.clearRect(0,0,e.width,e.height));let c=o/2,l=s/2;return this.cacheTranslationX=Math.round(e.width/2-c)+c,this.cacheTranslationY=Math.round(e.height/2-l)+l,t.translate(this.cacheTranslationX,this.cacheTranslationY),t.scale(i,a),this.zoomX=i,this.zoomY=a,!0}return!1}setOptions(e={}){this._setOptions(e)}transform(e){let t=this.group&&!this.group._transformDone||this.group&&this.canvas&&e===this.canvas.contextTop,n=this.calcTransformMatrix(!t);e.transform(n[0],n[1],n[2],n[3],n[4],n[5])}getObjectScaling(){if(!this.group)return new R(Math.abs(this.scaleX),Math.abs(this.scaleY));let e=Ye(this.calcTransformMatrix());return new R(Math.abs(e.scaleX),Math.abs(e.scaleY))}getTotalObjectScaling(){let e=this.getObjectScaling();if(this.canvas){let t=this.canvas.getZoom(),n=this.getCanvasRetinaScaling();return e.scalarMultiply(t*n)}return e}getObjectOpacity(){let e=this.opacity;return this.group&&(e*=this.group.getObjectOpacity()),e}_constrainScale(e){return Math.abs(e)<this.minScaleLimit?e<0?-this.minScaleLimit:this.minScaleLimit:e===0?1e-4:e}_set(e,t){e!==`scaleX`&&e!==`scaleY`||(t=this._constrainScale(t)),e===`scaleX`&&t<0?(this.flipX=!this.flipX,t*=-1):e===`scaleY`&&t<0?(this.flipY=!this.flipY,t*=-1):e!==`shadow`||!t||t instanceof Qn||(t=new Qn(t));let n=this[e]!==t;return this[e]=t,n&&this.constructor.cacheProperties.includes(e)&&(this.dirty=!0),this.parent&&(this.dirty||n&&this.constructor.stateProperties.includes(e))&&this.parent._set(`dirty`,!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(e){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(e.save(),this._setupCompositeOperation(e),this.drawSelectionBackground(e),this.transform(e),this._setOpacity(e),this._setShadow(e),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(e)):(this._removeCacheCanvas(),this.drawObject(e,!1,{}),this.dirty=!1),e.restore())}drawSelectionBackground(e){}renderCache(e){if(e||={},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){let{zoomX:t,zoomY:n,cacheTranslationX:r,cacheTranslationY:i}=this,{width:a,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,e.forClipping,{zoomX:t,zoomY:n,cacheTranslationX:r,cacheTranslationY:i,width:a,height:o,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return!!this.stroke&&this.stroke!==`transparent`&&this.strokeWidth!==0}hasFill(){return!!this.fill&&this.fill!==`transparent`}needsItsOwnCache(){return!!(this.paintFirst===`stroke`&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(e,t,n){e.save(),e.globalCompositeOperation=t.inverted?`destination-out`:`destination-in`,e.setTransform(1,0,0,1,0,0),e.drawImage(n,0,0),e.restore()}drawObject(e,t,n){let r=this.fill,i=this.stroke;t?(this.fill=`black`,this.stroke=``,this._setClippingProperties(e)):this._renderBackground(e),this.fire(`before:render`,{ctx:e}),this._render(e),this._drawClipPath(e,this.clipPath,n),this.fill=r,this.stroke=i}createClipPathLayer(e,t){let n=Re(t),r=n.getContext(`2d`);if(r.translate(t.cacheTranslationX,t.cacheTranslationY),r.scale(t.zoomX,t.zoomY),e._cacheCanvas=n,t.parentClipPaths.forEach(e=>{e.transform(r)}),t.parentClipPaths.push(e),e.absolutePositioned){let e=We(this.calcTransformMatrix());r.transform(e[0],e[1],e[2],e[3],e[4],e[5])}return e.transform(r),e.drawObject(r,!0,t),n}_drawClipPath(e,t,n){if(!t)return;t._transformDone=!0;let r=this.createClipPathLayer(t,n);this.drawClipPathOnCache(e,t,r)}drawCacheOnCanvas(e){e.scale(1/this.zoomX,1/this.zoomY),e.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(e=!1){if(this.isNotVisible())return!1;let t=this._cacheCanvas,n=this._cacheContext;return!(!t||!n||e||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(t&&n&&!e&&(n.save(),n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,t.width,t.height),n.restore()),!0)}_renderBackground(e){if(!this.backgroundColor)return;let t=this._getNonTransformedDimensions();e.fillStyle=this.backgroundColor,e.fillRect(-t.x/2,-t.y/2,t.x,t.y),this._removeShadow(e)}_setOpacity(e){this.group&&!this.group._transformDone?e.globalAlpha=this.getObjectOpacity():e.globalAlpha*=this.opacity}_setStrokeStyles(e,t){let n=t.stroke;n&&(e.lineWidth=t.strokeWidth,e.lineCap=t.strokeLineCap,e.lineDashOffset=t.strokeDashOffset,e.lineJoin=t.strokeLineJoin,e.miterLimit=t.strokeMiterLimit,ut(n)?n.gradientUnits===`percentage`||n.gradientTransform||n.patternTransform?this._applyPatternForTransformedGradient(e,n):(e.strokeStyle=n.toLive(e),this._applyPatternGradientTransform(e,n)):e.strokeStyle=t.stroke)}_setFillStyles(e,{fill:t}){t&&(ut(t)?(e.fillStyle=t.toLive(e),this._applyPatternGradientTransform(e,t)):e.fillStyle=t)}_setClippingProperties(e){e.globalAlpha=1,e.strokeStyle=`transparent`,e.fillStyle=`#000000`}_setLineDash(e,t){t&&t.length!==0&&e.setLineDash(t)}_setShadow(e){if(!this.shadow)return;let t=this.shadow,n=this.canvas,r=this.getCanvasRetinaScaling(),[i,,,a]=n?.viewportTransform||N,o=i*r,s=a*r,c=t.nonScaling?new R(1,1):this.getObjectScaling();e.shadowColor=t.color,e.shadowBlur=t.blur*h.browserShadowBlurConstant*(o+s)*(c.x+c.y)/4,e.shadowOffsetX=t.offsetX*o*c.x,e.shadowOffsetY=t.offsetY*s*c.y}_removeShadow(e){this.shadow&&(e.shadowColor=``,e.shadowBlur=e.shadowOffsetX=e.shadowOffsetY=0)}_applyPatternGradientTransform(e,t){if(!ut(t))return{offsetX:0,offsetY:0};let n=t.gradientTransform||t.patternTransform,r=-this.width/2+t.offsetX||0,i=-this.height/2+t.offsetY||0;return t.gradientUnits===`percentage`?e.transform(this.width,0,0,this.height,r,i):e.transform(1,0,0,1,r,i),n&&e.transform(n[0],n[1],n[2],n[3],n[4],n[5]),{offsetX:r,offsetY:i}}_renderPaintInOrder(e){this.paintFirst===`stroke`?(this._renderStroke(e),this._renderFill(e)):(this._renderFill(e),this._renderStroke(e))}_render(e){}_renderFill(e){this.fill&&(e.save(),this._setFillStyles(e,this),this.fillRule===`evenodd`?e.fill(`evenodd`):e.fill(),e.restore())}_renderStroke(e){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this.strokeUniform){let t=this.getObjectScaling();e.scale(1/t.x,1/t.y)}this._setLineDash(e,this.strokeDashArray),this._setStrokeStyles(e,this),e.stroke(),e.restore()}}_applyPatternForTransformedGradient(e,t){let n=this._limitCacheSize(this._getCacheCanvasDimensions()),r=this.getCanvasRetinaScaling(),i=n.x/this.scaleX/r,a=n.y/this.scaleY/r,o=Re({width:Math.ceil(i),height:Math.ceil(a)}),s=o.getContext(`2d`);s&&(s.beginPath(),s.moveTo(0,0),s.lineTo(i,0),s.lineTo(i,a),s.lineTo(0,a),s.closePath(),s.translate(i/2,a/2),s.scale(n.zoomX/this.scaleX/r,n.zoomY/this.scaleY/r),this._applyPatternGradientTransform(s,t),s.fillStyle=t.toLive(e),s.fill(),e.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),e.scale(r*this.scaleX/n.zoomX,r*this.scaleY/n.zoomY),e.strokeStyle=s.createPattern(o,`no-repeat`)??``)}_findCenterFromElement(){return new R(this.left+this.width/2,this.top+this.height/2)}clone(e){let t=this.toObject(e);return this.constructor.fromObject(t)}cloneAsImage(e){let t=this.toCanvasElement(e);return new(L.getClass(`image`))(t)}toCanvasElement(e={}){let t=Rt(this),n=this.group,r=this.shadow,i=Math.abs,a=e.enableRetinaScaling?E():1,o=(e.multiplier||1)*a,s=e.canvasProvider||(e=>new Ot(e,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,e.withoutTransform&&Lt(this),e.withoutShadow&&(this.shadow=null),e.viewportTransform&&Ut(this,this.getViewportTransform()),this.setCoords();let c=Fe(),l=this.getBoundingRect(),u=this.shadow,d=new R;if(u){let e=u.blur,t=u.nonScaling?new R(1,1):this.getObjectScaling();d.x=2*Math.round(i(u.offsetX)+e)*i(t.x),d.y=2*Math.round(i(u.offsetY)+e)*i(t.y)}let f=l.width+d.x,p=l.height+d.y;c.width=Math.ceil(f),c.height=Math.ceil(p);let m=s(c);e.format===`jpeg`&&(m.backgroundColor=`#fff`),this.setPositionByOrigin(new R(m.width/2,m.height/2),P,P);let h=this.canvas;m._objects=[this],this.set(`canvas`,m),this.setCoords();let g=m.toCanvasElement(o||1,e);return this.set(`canvas`,h),this.shadow=r,n&&(this.group=n),this.set(t),this.setCoords(),m._objects=[],m.destroy(),g}toDataURL(e={}){return ze(this.toCanvasElement(e),e.format||`png`,e.quality||1)}toBlob(e={}){return Be(this.toCanvasElement(e),e.format||`png`,e.quality||1)}isType(...e){return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(e){let{centeredRotation:t,originX:n,originY:r}=this;if(t){let{x:e,y:t}=this.getRelativeCenterPoint();this.originX=P,this.originY=P,this.left=e,this.top=t}if(this.set(`angle`,e),t){let{x:e,y:t}=this.getPositionByOrigin(n,r);this.left=e,this.top=t,this.originX=n,this.originY=r}}setOnGroup(){}_setupCompositeOperation(e){this.globalCompositeOperation&&(e.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Se.cancelByTarget(this),this.off(),this._set(`canvas`,void 0),this._cacheCanvas&&C().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(e,t){return Object.entries(e).reduce((e,[n,r])=>(e[n]=this._animate(n,r,t),e),{})}_animate(e,t,n={}){let r=e.split(`.`),i=this.constructor.colorProperties.includes(r[r.length-1]),{abort:a,startValue:o,onChange:s,onComplete:c}=n,l={...n,target:this,startValue:o??r.reduce((e,t)=>e[t],this),endValue:t,abort:a?.bind(this),onChange:(e,t,n)=>{r.reduce((t,n,i)=>(i===r.length-1&&(t[n]=e),t[n]),this),s&&s(e,t,n)},onComplete:(e,t,n)=>{this.setCoords(),c&&c(e,t,n)}};return i?Gr(l):Wr(l)}isDescendantOf(e){let{parent:t,group:n}=this;return t===e||n===e||!!t&&t.isDescendantOf(e)||!!n&&n!==t&&n.isDescendantOf(e)}getAncestors(){let e=[],t=this;do t=t.parent,t&&e.push(t);while(t);return e}findCommonAncestors(e){if(this===e)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};let t=this.getAncestors(),n=e.getAncestors();if(t.length===0&&n.length>0&&this===n[n.length-1])return{fork:[],otherFork:[e,...n.slice(0,n.length-1)],common:[this]};for(let r,i=0;i<t.length;i++){if(r=t[i],r===e)return{fork:[this,...t.slice(0,i)],otherFork:[],common:t.slice(i)};for(let a=0;a<n.length;a++){if(this===n[a])return{fork:[],otherFork:[e,...n.slice(0,a)],common:[this,...t]};if(r===n[a])return{fork:[this,...t.slice(0,i)],otherFork:[e,...n.slice(0,a)],common:t.slice(i)}}}return{fork:[this,...t],otherFork:[e,...n],common:[]}}hasCommonAncestors(e){let t=this.findCommonAncestors(e);return t&&!!t.common.length}isInFrontOf(e){if(this===e)return;let t=this.findCommonAncestors(e);if(t.fork.includes(e))return!0;if(t.otherFork.includes(this))return!1;let n=t.common[0]||this.canvas;if(!n)return;let r=t.fork.pop(),i=t.otherFork.pop(),a=n._objects.indexOf(r),o=n._objects.indexOf(i);return a>-1&&a>o}toObject(t=[]){let n=t.concat(e.customProperties,this.constructor.customProperties||[]),r,i=h.NUM_FRACTION_DIGITS,{clipPath:a,fill:o,stroke:s,shadow:c,strokeDashArray:l,left:u,top:d,originX:f,originY:p,width:m,height:g,strokeWidth:_,strokeLineCap:v,strokeDashOffset:y,strokeLineJoin:b,strokeUniform:x,strokeMiterLimit:S,scaleX:C,scaleY:w,angle:T,flipX:E,flipY:D,opacity:k,visible:A,backgroundColor:j,fillRule:M,paintFirst:ee,globalCompositeOperation:N,skewX:P,skewY:F}=this;a&&!a.excludeFromExport&&(r=a.toObject(n.concat(`inverted`,`absolutePositioned`)));let I=e=>V(e,i),te={...st(this,n),type:this.constructor.type,version:O,originX:f,originY:p,left:I(u),top:I(d),width:I(m),height:I(g),fill:dt(o)?o.toObject():o,stroke:dt(s)?s.toObject():s,strokeWidth:I(_),strokeDashArray:l&&l.concat(),strokeLineCap:v,strokeDashOffset:y,strokeLineJoin:b,strokeUniform:x,strokeMiterLimit:I(S),scaleX:I(C),scaleY:I(w),angle:I(T),flipX:E,flipY:D,opacity:I(k),shadow:c&&c.toObject(),visible:A,backgroundColor:j,fillRule:M,paintFirst:ee,globalCompositeOperation:N,skewX:I(P),skewY:I(F),...r?{clipPath:r}:null};return this.includeDefaultValues?te:this._removeDefaultValues(te)}toDatalessObject(e){return this.toObject(e)}_removeDefaultValues(e){let t=this.constructor.getDefaults(),n=Object.keys(t).length>0?t:Object.getPrototypeOf(this);return ct(e,(e,t)=>{if(t===`left`||t===`top`||t===`type`)return!0;let r=n[t];return e!==r&&!(Array.isArray(e)&&Array.isArray(r)&&e.length===0&&r.length===0)})}toString(){return`#<${this.constructor.type}>`}static _fromObject({type:e,...t},{extraParam:n,...r}={}){return ot(t,r).then(e=>n?(delete e[n],new this(t[n],e)):new this(e))}static fromObject(e,t){return this._fromObject(e,t)}};p(Jr,`stateProperties`,er),p(Jr,`cacheProperties`,tr),p(Jr,`ownDefaults`,nr),p(Jr,`type`,`FabricObject`),p(Jr,`colorProperties`,[_e,ve,`backgroundColor`]),p(Jr,`customProperties`,[]),L.setClass(Jr),L.setClass(Jr,`object`);var Yr=(e,t)=>{var n;let{transform:{target:r}}=t;(n=r.canvas)==null||n.fire(`object:${e}`,{...t,target:r}),r.fire(e,t)},Xr=(e,t,n)=>(r,i,a,o)=>{let s=t(r,i,a,o);return s&&Yr(e,{...ln(r,i,a,o),...n}),s};function Zr(e){return(t,n,r,i)=>{let{target:a,originX:o,originY:s}=n,c=a.getPositionByOrigin(o,s),l=e(t,n,r,i);return a.setPositionByOrigin(c,n.originX,n.originY),l}}var Qr=(e,t,n,r)=>(i,a,o,s)=>{let c=dn(a,a.originX,a.originY,o,s)[n],l=Gt(a[t]);if(l===0||l>0&&c<0||l<0&&c>0){let{target:t}=a,n=t.strokeWidth/(t.strokeUniform?t[r]:1),i=on(a)?2:1,o=t[e],s=Math.abs(c*i/t[r])-n;return t.set(e,Math.max(s,1)),o!==t[e]}return!1},$r=Qr(`width`,`originX`,`x`,`scaleX`),ei=Qr(`height`,`originY`,`y`,`scaleY`),ti=Xr(le,Zr($r)),ni=Xr(le,Zr(ei));function ri(e,t,n,r,i){e.save();let{stroke:a,xSize:o,ySize:s,opName:c}=this.commonRenderProps(e,t,n,i,r),l=o;o>s?e.scale(1,s/o):s>o&&(l=s,e.scale(o/s,1)),e.beginPath(),e.arc(0,0,l/2,0,M,!1),e[c](),a&&e.stroke(),e.restore()}function ii(e,t,n,r,i){e.save();let{stroke:a,xSize:o,ySize:s,opName:c}=this.commonRenderProps(e,t,n,i,r),l=o/2,u=s/2;e[`${c}Rect`](-l,-u,o,s),a&&e.strokeRect(-l,-u,o,s),e.restore()}var ai=class{constructor(e){p(this,`visible`,!0),p(this,`actionName`,fe),p(this,`angle`,0),p(this,`x`,0),p(this,`y`,0),p(this,`offsetX`,0),p(this,`offsetY`,0),p(this,`sizeX`,0),p(this,`sizeY`,0),p(this,`touchSizeX`,0),p(this,`touchSizeY`,0),p(this,`cursorStyle`,`crosshair`),p(this,`withConnection`,!1),Object.assign(this,e)}getTransformAnchorPoint(){return this.transformAnchorPoint??new R(.5-this.x,.5-this.y)}shouldActivate(e,t,n,{tl:r,tr:i,br:a,bl:o}){return t.canvas?.getActiveObject()===t&&t.isControlVisible(e)&&Kr.isPointInPolygon(n,[r,i,a,o])}getActionHandler(e,t,n){return this.actionHandler}getMouseDownHandler(e,t,n){return this.mouseDownHandler}getMouseUpHandler(e,t,n){return this.mouseUpHandler}cursorStyleHandler(e,t,n,r){return t.cursorStyle}getActionName(e,t,n){return t.actionName}getVisibility(e,t){return e._controlsVisibility?.[t]??this.visible}setVisibility(e,t,n){this.visible=e}positionHandler(e,t,n,r){return new R(this.x*e.x+this.offsetX,this.y*e.y+this.offsetY).transform(t)}calcCornerCoords(e,t,n,r,i,a){let o=Ge([Xe(n,r),Ze({angle:e}),Qe((i?this.touchSizeX:this.sizeX)||t,(i?this.touchSizeY:this.sizeY)||t)]);return{tl:new R(-.5,-.5).transform(o),tr:new R(.5,-.5).transform(o),br:new R(.5,.5).transform(o),bl:new R(-.5,.5).transform(o)}}commonRenderProps(e,t,n,r,i={}){let{cornerSize:a,cornerColor:o,transparentCorners:s,cornerStrokeColor:c}=i,l=a||r.cornerSize,u=this.sizeX||l,d=this.sizeY||l,f=s===void 0?r.transparentCorners:s,p=f?ve:_e,m=c||r.cornerStrokeColor,h=!f&&!!m;return e.fillStyle=o||r.cornerColor||``,e.strokeStyle=m||``,e.translate(t,n),e.rotate(z(r.getTotalAngle())),{stroke:h,xSize:u,ySize:d,transparentCorners:f,opName:p}}render(e,t,n,r,i){((r||={}).cornerStyle||i.cornerStyle)===`circle`?ri.call(this,e,t,n,r,i):ii.call(this,e,t,n,r,i)}},oi=(e,t,n)=>n.lockRotation?an:t.cursorStyle,si=Xr(oe,Zr((e,{target:t,ex:n,ey:r,theta:i,originX:a,originY:o},s,c)=>{let l=t.getPositionByOrigin(a,o);if(cn(t,`lockRotation`))return!1;let u=Math.atan2(r-l.y,n-l.x),d=Ve(Math.atan2(c-l.y,s-l.x)-u+i);if(t.snapAngle&&t.snapAngle>0){let e=t.snapAngle,n=t.snapThreshold||e,r=Math.ceil(d/e)*e,i=Math.floor(d/e)*e;Math.abs(d-i)<n?d=i:Math.abs(d-r)<n&&(d=r)}d<0&&(d=360+d),d%=360;let f=t.angle!==d;return t.angle=d,f}));function ci(e,t){let n=t.canvas,r=e[n.uniScaleKey];return n.uniformScaling&&!r||!n.uniformScaling&&r}function li(e,t,n){let r=cn(e,`lockScalingX`),i=cn(e,`lockScalingY`);if(r&&i||!t&&(r||i)&&n||r&&t===`x`||i&&t===`y`)return!0;let{width:a,height:o,strokeWidth:s}=e;return a===0&&s===0&&t!==`y`||o===0&&s===0&&t!==`x`}var ui=[`e`,`se`,`s`,`sw`,`w`,`nw`,`n`,`ne`,`e`],di=(e,t,n,r)=>{let i=ci(e,n);return li(n,t.x!==0&&t.y===0?`x`:t.x===0&&t.y!==0?`y`:``,i)?an:`${ui[un(n,0,r)]}-resize`};function fi(e,t,n,r,i={}){let a=t.target,o=i.by,s=ci(e,a),c,l,u,d,f,p;if(li(a,o,s))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,u=t.scaleY*t.gestureScale;else{if(c=dn(t,t.originX,t.originY,n,r),f=o===`y`?1:Math.sign(c.x||t.signX||1),p=o===`x`?1:Math.sign(c.y||t.signY||1),t.signX||=f,t.signY||=p,cn(a,`lockScalingFlip`)&&(t.signX!==f||t.signY!==p))return!1;if(d=a._getTransformedDimensions(),s&&!o){let e=Math.abs(c.x)+Math.abs(c.y),{original:n}=t,r=e/(Math.abs(d.x*n.scaleX/a.scaleX)+Math.abs(d.y*n.scaleY/a.scaleY));l=n.scaleX*r,u=n.scaleY*r}else l=Math.abs(c.x*a.scaleX/d.x),u=Math.abs(c.y*a.scaleY/d.y);on(t)&&(l*=2,u*=2),t.signX!==f&&o!==`y`&&(t.originX=sn(t.originX),l*=-1,t.signX=f),t.signY!==p&&o!==`x`&&(t.originY=sn(t.originY),u*=-1,t.signY=p)}let m=a.scaleX,h=a.scaleY;return o?(o===`x`&&a.set(`scaleX`,l),o===`y`&&a.set(`scaleY`,u)):(!cn(a,`lockScalingX`)&&a.set(`scaleX`,l),!cn(a,`lockScalingY`)&&a.set(`scaleY`,u)),m!==a.scaleX||h!==a.scaleY}var pi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r))),mi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r,{by:`x`}))),hi=Xr(ae,Zr((e,t,n,r)=>fi(e,t,n,r,{by:`y`}))),gi={x:{counterAxis:`y`,scale:pe,skew:he,lockSkewing:`lockSkewingX`,origin:`originX`,flip:`flipX`},y:{counterAxis:`x`,scale:me,skew:ge,lockSkewing:`lockSkewingY`,origin:`originY`,flip:`flipY`}},_i=[`ns`,`nesw`,`ew`,`nwse`],vi=(e,t,n,r)=>t.x!==0&&cn(n,`lockSkewingY`)||t.y!==0&&cn(n,`lockSkewingX`)?an:`${_i[un(n,0,r)%4]}-resize`;function yi(e,t,n,r,i){let{target:a}=n,{counterAxis:o,origin:s,lockSkewing:c,skew:l,flip:u}=gi[e];if(cn(a,c))return!1;let{origin:d,flip:f}=gi[o],p=Gt(n[d])*(a[f]?-1:1),m=-Math.sign(p)*(a[u]?-1:1),h=-(a[l]===0&&dn(n,`center`,`center`,r,i)[e]>0||a[l]>0?1:-1)*m*.5+.5;return Xr(ce,Zr((t,n,r,i)=>function(e,{target:t,ex:n,ey:r,skewingSide:i,...a},o){let{skew:s}=gi[e],c=o.subtract(new R(n,r)).divide(new R(t.scaleX,t.scaleY))[e],l=t[s],u=a[s],d=Math.tan(z(u)),f=e===`y`?t._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:t._getTransformedDimensions({scaleX:1,scaleY:1}).y,p=2*c*i/Math.max(f,1)+d,m=Ve(Math.atan(p));t.set(s,m);let h=l!==t[s];if(h&&e===`y`){let{skewX:e,scaleX:n}=t,r=t._getTransformedDimensions({skewY:l}),i=t._getTransformedDimensions(),a=e===0?1:r.x/i.x;a!==1&&t.set(`scaleX`,a*n)}return h}(e,n,new R(r,i))))(t,{...n,[s]:h,skewingSide:m},r,i)}var bi=(e,t,n,r)=>yi(`x`,e,t,n,r),xi=(e,t,n,r)=>yi(`y`,e,t,n,r);function Si(e,t){return e[t.canvas.altActionKey]}var Ci=(e,t,n)=>{let r=Si(e,n);return t.x===0?r?he:me:t.y===0?r?ge:pe:``},wi=(e,t,n,r)=>Si(e,n)?vi(0,t,n,r):di(e,t,n,r),Ti=(e,t,n,r)=>Si(e,t.target)?xi(e,t,n,r):mi(e,t,n,r),Ei=(e,t,n,r)=>Si(e,t.target)?bi(e,t,n,r):hi(e,t,n,r),Di=()=>({ml:new ai({x:-.5,y:0,cursorStyleHandler:wi,actionHandler:Ti,getActionName:Ci}),mr:new ai({x:.5,y:0,cursorStyleHandler:wi,actionHandler:Ti,getActionName:Ci}),mb:new ai({x:0,y:.5,cursorStyleHandler:wi,actionHandler:Ei,getActionName:Ci}),mt:new ai({x:0,y:-.5,cursorStyleHandler:wi,actionHandler:Ei,getActionName:Ci}),tl:new ai({x:-.5,y:-.5,cursorStyleHandler:di,actionHandler:pi}),tr:new ai({x:.5,y:-.5,cursorStyleHandler:di,actionHandler:pi}),bl:new ai({x:-.5,y:.5,cursorStyleHandler:di,actionHandler:pi}),br:new ai({x:.5,y:.5,cursorStyleHandler:di,actionHandler:pi}),mtr:new ai({x:0,y:-.5,actionHandler:si,cursorStyleHandler:oi,offsetY:-40,withConnection:!0,actionName:se})}),Oi=()=>({mr:new ai({x:.5,y:0,actionHandler:ti,cursorStyleHandler:wi,actionName:le}),ml:new ai({x:-.5,y:0,actionHandler:ti,cursorStyleHandler:wi,actionName:le})}),ki=()=>({...Di(),...Oi()}),Ai=class e extends Jr{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,this.constructor.createControls(),e.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Di()}}_updateCacheCanvas(){let e=this.canvas;if(this.noScaleCache&&e&&e._currentTransform){let t=e._currentTransform,n=t.target,r=t.action;if(this===n&&r&&r.startsWith(`scale`))return!1}return super._updateCacheCanvas()}getActiveControl(){let e=this.__corner;return e?{key:e,control:this.controls[e],coord:this.oCoords[e]}:void 0}findControl(e,t=!1){if(!this.hasControls||!this.canvas)return;this.__corner=void 0;let n=Object.entries(this.oCoords);for(let r=n.length-1;r>=0;r--){let[i,a]=n[r],o=this.controls[i];if(o.shouldActivate(i,this,e,t?a.touchCorner:a.corner))return this.__corner=i,{key:i,control:o,coord:this.oCoords[i]}}}calcOCoords(){let e=this.getViewportTransform(),t=qe(e),n=Je(e),r=this.getCenterPoint(),i=B(B(e,B(Xe(r.x,r.y),Ze({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}))),[1/t,0,0,1/n,0,0]),a=this.group?Ye(this.calcTransformMatrix()):void 0;a&&(a.scaleX=Math.abs(a.scaleX),a.scaleY=Math.abs(a.scaleY));let o=this._calculateCurrentDimensions(a),s={};return this.forEachControl((e,t)=>{let n=e.positionHandler(o,i,this,e);s[t]=Object.assign(n,this._calcCornerCoords(e,n))}),s}_calcCornerCoords(e,t){let n=this.getTotalAngle();return{corner:e.calcCornerCoords(n,this.cornerSize,t.x,t.y,!1,this),touchCorner:e.calcCornerCoords(n,this.touchCornerSize,t.x,t.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(e){for(let t in this.controls)e(this.controls[t],t,this)}drawSelectionBackground(e){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;e.save();let t=this.getRelativeCenterPoint(),n=this._calculateCurrentDimensions(),r=this.getViewportTransform();e.translate(t.x,t.y),e.scale(1/r[0],1/r[3]),e.rotate(z(this.angle)),e.fillStyle=this.selectionBackgroundColor,e.fillRect(-n.x/2,-n.y/2,n.x,n.y),e.restore()}strokeBorders(e,t){e.strokeRect(-t.x/2,-t.y/2,t.x,t.y)}_drawBorders(e,t,n={}){let r={hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray,...n};e.save(),e.strokeStyle=r.borderColor,this._setLineDash(e,r.borderDashArray),this.strokeBorders(e,t),r.hasControls&&this.drawControlsConnectingLines(e,t),e.restore()}_renderControls(e,t={}){let{hasBorders:n,hasControls:r}=this,i={hasBorders:n,hasControls:r,...t},a=this.getViewportTransform(),o=i.hasBorders,s=i.hasControls,c=Ye(B(a,this.calcTransformMatrix()));e.save(),e.translate(c.translateX,c.translateY),e.lineWidth=this.borderScaleFactor,this.group===this.parent&&(e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180);let l=Ke(a);e.rotate(this.group?z(c.angle):z(this.angle)+l),o&&this.drawBorders(e,c,t),s&&this.drawControls(e,t),e.restore()}drawBorders(e,t,n){let r;if(n&&n.forActiveSelection||this.group){let e=zt(this.width,this.height,nt(t)),n=this.isStrokeAccountedForInDimensions()?De:(this.strokeUniform?new R().scalarAdd(this.canvas?this.canvas.getZoom():1):new R(t.scaleX,t.scaleY)).scalarMultiply(this.strokeWidth);r=e.add(n).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else r=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(e,r,n)}drawControlsConnectingLines(e,t){let n=!1;e.beginPath(),this.forEachControl((r,i)=>{r.withConnection&&r.getVisibility(this,i)&&(n=!0,e.moveTo(r.x*t.x,r.y*t.y),e.lineTo(r.x*t.x+r.offsetX,r.y*t.y+r.offsetY))}),n&&e.stroke()}drawControls(e,t={}){e.save();let n=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:i,cornerColor:a}=this,o={cornerStrokeColor:r,cornerDashArray:i,cornerColor:a,...t};e.setTransform(n,0,0,n,0,0),e.strokeStyle=e.fillStyle=o.cornerColor,this.transparentCorners||(e.strokeStyle=o.cornerStrokeColor),this._setLineDash(e,o.cornerDashArray),this.forEachControl((t,n)=>{if(t.getVisibility(this,n)){let r=this.oCoords[n];t.render(e,r.x,r.y,o,this)}}),e.restore()}isControlVisible(e){return this.controls[e]&&this.controls[e].getVisibility(this,e)}setControlVisible(e,t){this._controlsVisibility||={},this._controlsVisibility[e]=t}setControlsVisibility(e={}){Object.entries(e).forEach(([e,t])=>this.setControlVisible(e,t))}clearContextTop(e){if(!this.canvas)return;let t=this.canvas.contextTop;if(!t)return;let n=this.canvas.viewportTransform;t.save(),t.transform(n[0],n[1],n[2],n[3],n[4],n[5]),this.transform(t);let r=this.width+4,i=this.height+4;return t.clearRect(-r/2,-i/2,r,i),e||t.restore(),t}onDeselect(e){return!1}onSelect(e){return!1}shouldStartDragging(e){return!1}onDragStart(e){return!1}canDrop(e){return!1}renderDragSourceEffect(e){}renderDropTargetEffect(e){}};function ji(e,t){return t.forEach(t=>{Object.getOwnPropertyNames(t.prototype).forEach(n=>{n!==`constructor`&&Object.defineProperty(e.prototype,n,Object.getOwnPropertyDescriptor(t.prototype,n)||Object.create(null))})}),e}p(Ai,`ownDefaults`,{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:`rgb(178,204,255)`,cornerStrokeColor:``,cornerStyle:`rect`,cornerDashArray:null,hasControls:!0,borderColor:`rgb(178,204,255)`,borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:``,selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:`down`,hoverCursor:null,moveCursor:null});var Mi=class extends Ai{};ji(Mi,[On]),L.setClass(Mi),L.setClass(Mi,`object`);var Ni=(e,t,n,r)=>{let i=2*(r=Math.round(r))+1,{data:a}=e.getImageData(t-r,n-r,i,i);for(let e=3;e<a.length;e+=4)if(a[e]>0)return!1;return!0},Pi=class{constructor(e){this.options=e,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new R(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new R(1/this.options.scaleX,1/this.options.scaleY):new R(1,1)}createSideVector(e,t){let n=Yt(e,t);return this.options.strokeUniform?n.multiply(this.scale):n}projectOrthogonally(e,t,n){return this.applySkew(e.add(this.calcOrthogonalProjection(e,t,n)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(e){let t=new R(e);return t.y+=t.x*Math.tan(z(this.options.skewY)),t.x+=t.y*Math.tan(z(this.options.skewX)),t}scaleUnitVector(e,t){return e.multiply(this.strokeUniformScalar).scalarMultiply(t)}},Fi=new R,Ii=class e extends Pi{static getOrthogonalRotationFactor(e,t){let n=t?Zt(e,t):Qt(e);return Math.abs(n)<A?-1:1}constructor(e,t,n,r){super(r),p(this,`AB`,void 0),p(this,`AC`,void 0),p(this,`alpha`,void 0),p(this,`bisector`,void 0),this.A=new R(e),this.B=new R(t),this.C=new R(n),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Zt(this.AB,this.AC),this.bisector=$t(Jt(this.AB.eq(Fi)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,n,r=this.strokeProjectionMagnitude){let i=en(this.createSideVector(t,n)),a=e.getOrthogonalRotationFactor(i,this.bisector);return this.scaleUnitVector(i,r*a)}projectBevel(){let e=[];return(this.alpha%M===0?[this.B]:[this.B,this.C]).forEach(t=>{e.push(this.projectOrthogonally(this.A,t)),e.push(this.projectOrthogonally(this.A,t,-this.strokeProjectionMagnitude))}),e}projectMiter(){let e=[],t=Math.abs(this.alpha),n=1/Math.sin(t/2),r=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*n),i=this.options.strokeUniform?Xt(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Xt(r)/this.strokeProjectionMagnitude<=i&&e.push(this.applySkew(this.A.add(r))),e.push(...this.projectBevel()),e}projectRoundNoSkew(t,n){let r=[],i=new R(e.getOrthogonalRotationFactor(this.bisector),e.getOrthogonalRotationFactor(new R(this.bisector.y,this.bisector.x)));return[new R(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new R(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(e=>{rn(e,t,n)&&r.push(this.A.add(e))}),r}projectRoundWithSkew(e,t){let n=[],{skewX:r,skewY:i,scaleX:a,scaleY:o,strokeUniform:s}=this.options,c=new R(Math.tan(z(r)),Math.tan(z(i))),l=this.strokeProjectionMagnitude,u=s?l/o/Math.sqrt(1/o**2+1/a**2*c.y**2):l/Math.sqrt(1+c.y**2),d=new R(Math.sqrt(Math.max(l**2-u**2,0)),u),f=s?l/Math.sqrt(1+c.x**2*(1/o)**2/(1/a+1/a*c.x*c.y)**2):l/Math.sqrt(1+c.x**2/(1+c.x*c.y)**2),p=new R(f,Math.sqrt(Math.max(l**2-f**2,0)));return[p,p.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(e=>this.applySkew(s?e.multiply(this.strokeUniformScalar):e)).forEach(r=>{rn(r,e,t)&&n.push(this.applySkew(this.A).add(r))}),n}projectRound(){let e=[];e.push(...this.projectBevel());let t=this.alpha%M===0,n=this.applySkew(this.A),r=e[t?0:2].subtract(n),i=e[+!!t].subtract(n),a=tn(r,t?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)))>0,o=a?r:i,s=a?i:r;return this.isSkewed()?e.push(...this.projectRoundWithSkew(o,s)):e.push(...this.projectRoundNoSkew(o,s)),e}projectPoints(){switch(this.options.strokeLineJoin){case`miter`:return this.projectMiter();case`round`:return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(e=>({originPoint:this.A,projectedPoint:e,angle:this.alpha,bisector:this.bisector}))}},Li=class extends Pi{constructor(e,t,n){super(n),this.A=new R(e),this.T=new R(t)}calcOrthogonalProjection(e,t,n=this.strokeProjectionMagnitude){let r=this.createSideVector(e,t);return this.scaleUnitVector(en(r),n)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){let e=[];if(!this.isSkewed()&&this.A.eq(this.T)){let t=new R(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);e.push(this.applySkew(this.A.add(t)),this.applySkew(this.A.subtract(t)))}else e.push(...new Ii(this.A,this.T,this.T,this.options).projectRound());return e}projectSquare(){let e=[];if(this.A.eq(this.T)){let t=new R(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);e.push(this.A.add(t),this.A.subtract(t))}else{let t=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),n=this.scaleUnitVector($t(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),r=this.A.add(n);e.push(r.add(t),r.subtract(t))}return e.map(e=>this.applySkew(e))}projectPoints(){switch(this.options.strokeLineCap){case`round`:return this.projectRound();case`square`:return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(e=>({originPoint:this.A,projectedPoint:e}))}},Ri=(e,t,n=!1)=>{let r=[];if(e.length===0)return r;let i=e.reduce((e,t)=>(e[e.length-1].eq(t)||e.push(new R(t)),e),[new R(e[0])]);if(i.length===1)n=!0;else if(!n){let e=i[0],t=((e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n],n,e))return n;return-1})(i,t=>!t.eq(e));i.splice(t+1)}return i.forEach((e,i,a)=>{let o,s;i===0?(s=a[1],o=n?e:a[a.length-1]):i===a.length-1?(o=a[i-1],s=n?e:a[0]):(o=a[i-1],s=a[i+1]),n&&a.length===1?r.push(...new Li(e,e,t).project()):!n||i!==0&&i!==a.length-1?r.push(...new Ii(e,o,s,t).project()):r.push(...new Li(e,i===0?s:o,t).project())}),r},zi=e=>{let t={};return Object.keys(e).forEach(n=>{t[n]={},Object.keys(e[n]).forEach(r=>{t[n][r]={...e[n][r]}})}),t},Bi=(e,t,n=!1)=>e.fill!==t.fill||e.stroke!==t.stroke||e.strokeWidth!==t.strokeWidth||e.fontSize!==t.fontSize||e.fontFamily!==t.fontFamily||e.fontWeight!==t.fontWeight||e.fontStyle!==t.fontStyle||e.textDecorationThickness!==t.textDecorationThickness||e.textDecorationColor!==t.textDecorationColor||e.textBackgroundColor!==t.textBackgroundColor||e.deltaY!==t.deltaY||n&&(e.overline!==t.overline||e.underline!==t.underline||e.linethrough!==t.linethrough),Vi=(e,t)=>{let n=t.split(`
|
|
15
15
|
`),r=[],i=-1,a={};e=zi(e);for(let t=0;t<n.length;t++){let o=Tt(n[t]);if(e[t])for(let n=0;n<o.length;n++){i++;let o=e[t][n];o&&Object.keys(o).length>0&&(Bi(a,o,!0)?r.push({start:i,end:i+1,style:o}):r[r.length-1].end++),a=o||{}}else i+=o.length,a={}}return r},Hi=(e,t)=>{if(!Array.isArray(e))return zi(e);let n=t.split(re),r={},i=-1,a=0;for(let t=0;t<n.length;t++){let o=Tt(n[t]);for(let n=0;n<o.length;n++)i++,e[a]&&e[a].start<=i&&i<e[a].end&&(r[t]=r[t]||{},r[t][n]={...e[a].style},i===e[a].end-1&&a++)}return r},Ui=[`display`,`transform`,_e,`fill-opacity`,`fill-rule`,`opacity`,ve,`stroke-dasharray`,`stroke-linecap`,`stroke-dashoffset`,`stroke-linejoin`,`stroke-miterlimit`,`stroke-opacity`,`stroke-width`,`id`,`paint-order`,`vector-effect`,`instantiated_by_use`,`clip-path`];function Wi(e,t){let n=e.nodeName,r=e.getAttribute(`class`),i=e.getAttribute(`id`),a=`(?![a-zA-Z\\-]+)`,o;if(o=RegExp(`^`+n,`i`),t=t.replace(o,``),i&&t.length&&(o=RegExp(`#`+i+a,`i`),t=t.replace(o,``)),r&&t.length){let e=r.split(` `);for(let n=e.length;n--;)o=RegExp(`\\.`+e[n]+a,`i`),t=t.replace(o,``)}return t.length===0}function Gi(e,t){let n=!0,r=Wi(e,t.pop());return r&&t.length&&(n=function(e,t){let n,r=!0;for(;e.parentElement&&e.parentElement.nodeType===1&&t.length;)r&&(n=t.pop()),r=Wi(e=e.parentElement,n);return t.length===0}(e,t)),r&&n&&t.length===0}function Ki(e,t={}){let n={};for(let r in t)Gi(e,r.split(` `))&&(n={...n,...t[r]});return n}var qi=e=>Un[e]??e,Ji=RegExp(`(${zn})`,`gi`),Yi=`(${zn})`,Xi=String.raw`(skewX)\(${Yi}\)`,Zi=String.raw`(skewY)\(${Yi}\)`,Qi=String.raw`(rotate)\(${Yi}(?: ${Yi} ${Yi})?\)`,$i=String.raw`(scale)\(${Yi}(?: ${Yi})?\)`,ea=String.raw`(translate)\(${Yi}(?: ${Yi})?\)`,ta=`(?:${String.raw`(matrix)\(${Yi} ${Yi} ${Yi} ${Yi} ${Yi} ${Yi}\)`}|${ea}|${Qi}|${$i}|${Xi}|${Zi})`,na=`(?:${ta}*)`,ra=String.raw`^\s*(?:${na}?)\s*$`,ia=new RegExp(ra),aa=new RegExp(ta),oa=new RegExp(ta,`g`);function sa(e){let t=[];if(!(e=(e=>gn(e.replace(Ji,` $1 `).replace(/,/gi,` `)))(e).replace(/\s*([()])\s*/gi,`$1`))||e&&!ia.test(e))return[...N];for(let n of e.matchAll(oa)){let e=aa.exec(n[0]);if(!e)continue;let r=N,[,i,...a]=e.filter(e=>!!e),[o,s,c,l,u,d]=a.map(e=>parseFloat(e));switch(i){case`translate`:r=Xe(o,s);break;case se:r=Ze({angle:o},{x:s,y:c});break;case fe:r=Qe(o,s);break;case he:r=et(o);break;case ge:r=tt(o);break;case`matrix`:r=[o,s,c,l,u,d]}t.push(r)}return Ge(t)}function ca(e,t,n,r){let i=Array.isArray(t),a,o=t;if(e!==`fill`&&e!==`stroke`||t!==`none`){if(e===`strokeUniform`)return t===`non-scaling-stroke`;if(e===`strokeDashArray`)o=t===`none`?null:t.replace(/,/g,` `).split(/\s+/).map(parseFloat);else if(e===`transformMatrix`)o=n&&n.transformMatrix?B(n.transformMatrix,sa(t)):sa(t);else if(e===`visible`)o=t!==`none`&&t!==`hidden`,n&&!1===n.visible&&(o=!1);else if(e===`opacity`)o=parseFloat(t),n&&n.opacity!==void 0&&(o*=n.opacity);else if(e===`textAnchor`)o=t===`start`?F:t===`end`?te:P;else if(e===`charSpacing`||e===`textDecorationThickness`)a=Tn(t,r)/r*1e3;else if(e===`paintFirst`){let e=t.indexOf(_e),n=t.indexOf(ve);o=_e,(e>-1&&n>-1&&n<e||e===-1&&n>-1)&&(o=ve)}else{if(e===`href`||e===`xlink:href`||e===`font`||e===`id`)return t;if(e===`imageSmoothing`)return t===`optimizeQuality`;a=i?t.map(Tn):Tn(t,r)}}else o=``;return!i&&isNaN(a)?o:a}function la(e,t){e.replace(/;\s*$/,``).split(`;`).forEach(e=>{if(!e)return;let[n,r]=e.split(`:`);t[n.trim().toLowerCase()]=r.trim()})}function ua(e){let t={},n=e.getAttribute(`style`);return n&&(typeof n==`string`?la(n,t):function(e,t){Object.entries(e).forEach(([e,n])=>{n!==void 0&&(t[e.toLowerCase()]=n)})}(n,t)),t}var da={stroke:`strokeOpacity`,fill:`fillOpacity`};function fa(e,t,n){if(!e)return{};let r,i={},a=16;e.parentNode&&Jn.test(e.parentNode.nodeName)&&(i=fa(e.parentElement,t,n),i.fontSize&&(r=a=Tn(i.fontSize)));let o={...t.reduce((t,n)=>{let r=e.getAttribute(n);return r&&(t[n]=r),t},{}),...Ki(e,n),...ua(e)};o[`clip-path`]&&e.setAttribute(Gn,o[Gn]),o[`font-size`]&&(r=Tn(o[Wn],a),o[Wn]=`${r}`);let s={};for(let e in o){let t=qi(e);s[t]=ca(t,o[e],i,r)}s&&s.font&&function(e,t){let n=e.match(Hn);if(!n)return;let r=n[1],i=n[3],a=n[4],o=n[5],s=n[6];r&&(t.fontStyle=r),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),a&&(t.fontSize=Tn(a)),s&&(t.fontFamily=s),o&&(t.lineHeight=o===`normal`?1:o)}(s.font,s);let c={...i,...s};return Jn.test(e.nodeName)?c:function(e){let t=Mi.getDefaults();return Object.entries(da).forEach(([n,r])=>{if(e[r]===void 0||e[n]===``)return;if(e[n]===void 0){if(!t[n])return;e[n]=t[n]}if(e[n].indexOf(`url(`)===0)return;let i=new Cn(e[n]);e[n]=i.setAlpha(V(i.getAlpha()*e[r],2)).toRgba()}),e}(c)}var pa=[`rx`,`ry`],ma=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){let{rx:e,ry:t}=this;e&&!t?this.ry=e:t&&!e&&(this.rx=t)}_render(e){let{width:t,height:n}=this,r=-t/2,i=-n/2,a=this.rx?Math.min(this.rx,t/2):0,o=this.ry?Math.min(this.ry,n/2):0,s=a!==0||o!==0;e.beginPath(),e.moveTo(r+a,i),e.lineTo(r+t-a,i),s&&e.bezierCurveTo(r+t-.4477152502*a,i,r+t,i+.4477152502*o,r+t,i+o),e.lineTo(r+t,i+n-o),s&&e.bezierCurveTo(r+t,i+n-.4477152502*o,r+t-.4477152502*a,i+n,r+t-a,i+n),e.lineTo(r+a,i+n),s&&e.bezierCurveTo(r+.4477152502*a,i+n,r,i+n-.4477152502*o,r,i+n-o),e.lineTo(r,i+o),s&&e.bezierCurveTo(r,i+.4477152502*o,r+.4477152502*a,i,r+a,i),e.closePath(),this._renderPaintInOrder(e)}toObject(e=[]){return super.toObject([...pa,...e])}_toSVG(){let{width:e,height:t,rx:n,ry:r}=this;return[`<rect `,`COMMON_PARTS`,`x="${-e/2}" y="${-t/2}" rx="${H(n)}" ry="${H(r)}" width="${H(e)}" height="${H(t)}" />\n`]}static async fromElement(e,t,n){let{left:r=0,top:i=0,width:a=0,height:o=0,visible:s=!0,...c}=fa(e,this.ATTRIBUTE_NAMES,n);return new this({...t,...c,left:r,top:i,width:a,height:o,visible:!!(s&&a&&o)})}};p(ma,`type`,`Rect`),p(ma,`cacheProperties`,[...tr,...pa]),p(ma,`ownDefaults`,{rx:0,ry:0}),p(ma,`ATTRIBUTE_NAMES`,[...Ui,`x`,`y`,`rx`,`ry`,`width`,`height`]),L.setClass(ma),L.setSVGClass(ma);var ha=`initialization`,ga=`added`,_a=(e,t)=>{let{strokeUniform:n,strokeWidth:r,width:i,height:a,group:o}=t,s=o&&o!==e?Bt(o.calcTransformMatrix(),e.calcTransformMatrix()):null,c=s?t.getRelativeCenterPoint().transform(s):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),u=n&&l?Ht(new R(r,r),void 0,e.calcTransformMatrix()):De,d=!n&&l?r:0,f=zt(i+d,a+d,Ge([s,t.calcOwnMatrix()],!0)).add(u).scalarDivide(2);return[c.subtract(f),c.add(f)]},va=class{calcLayoutResult(e,t){if(this.shouldPerformLayout(e))return this.calcBoundingBox(t,e)}shouldPerformLayout({type:e,prevStrategy:t,strategy:n}){return e===`initialization`||e===`imperative`||!!t&&n!==t}shouldLayoutClipPath({type:e,target:{clipPath:t}}){return e!==`initialization`&&t&&!t.absolutePositioned}getInitialSize(e,t){return t.size}calcBoundingBox(e,t){let{type:n,target:r}=t;if(n===`imperative`&&t.overrides)return t.overrides;if(e.length===0)return;let{left:i,top:a,width:o,height:s}=Nt(e.map(e=>_a(r,e)).reduce((e,t)=>e.concat(t),[])),c=new R(o,s),l=new R(i,a).add(c.scalarDivide(2));if(n===`initialization`){let e=this.getInitialSize(t,{size:c,center:l});return{center:l,relativeCorrection:new R(0,0),size:e}}return{center:l.transform(r.calcOwnMatrix()),size:c}}};p(va,`type`,`strategy`);var ya=class extends va{shouldPerformLayout(e){return!0}};p(ya,`type`,`fit-content`),L.setClass(ya);var ba=`layoutManager`,xa=class{constructor(e=new ya){p(this,`strategy`,void 0),this.strategy=e,this._subscriptions=new Map}performLayout(e){let t={bubbles:!0,strategy:this.strategy,...e,prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}};this.onBeforeLayout(t);let n=this.getLayoutResult(t);n&&this.commitLayout(t,n),this.onAfterLayout(t,n),this._prevLayoutStrategy=t.strategy}attachHandlers(e,t){let{target:n}=t;return[ye,ie,le,oe,ae,ce,de,ue,`modifyPath`].map(t=>e.on(t,e=>this.performLayout(t===`modified`?{type:`object_modified`,trigger:t,e,target:n}:{type:`object_modifying`,trigger:t,e,target:n})))}subscribe(e,t){this.unsubscribe(e,t);let n=this.attachHandlers(e,t);this._subscriptions.set(e,n)}unsubscribe(e,t){(this._subscriptions.get(e)||[]).forEach(e=>e()),this._subscriptions.delete(e)}unsubscribeTargets(e){e.targets.forEach(t=>this.unsubscribe(t,e))}subscribeTargets(e){e.targets.forEach(t=>this.subscribe(t,e))}onBeforeLayout(e){let{target:t,type:n}=e,{canvas:r}=t;if(n===`initialization`||n===`added`?this.subscribeTargets(e):n===`removed`&&this.unsubscribeTargets(e),t.fire(`layout:before`,{context:e}),r&&r.fire(`object:layout:before`,{target:t,context:e}),n===`imperative`&&e.deep){let{strategy:n,...r}=e;t.forEachObject(e=>e.layoutManager&&e.layoutManager.performLayout({...r,bubbles:!1,target:e}))}}getLayoutResult(e){let{target:t,strategy:n,type:r}=e,i=n.calcLayoutResult(e,t.getObjects());if(!i)return;let a=r===`initialization`?new R:t.getRelativeCenterPoint(),{center:o,correction:s=new R,relativeCorrection:c=new R}=i;return{result:i,prevCenter:a,nextCenter:o,offset:a.subtract(o).add(s).transform(r===`initialization`?N:We(t.calcOwnMatrix()),!0).add(c)}}commitLayout(e,t){let{target:n}=e,{result:{size:r},nextCenter:i}=t;n.set({width:r.x,height:r.y}),this.layoutObjects(e,t),e.type===`initialization`?n.set({left:e.x??i.x+r.x*Gt(n.originX),top:e.y??i.y+r.y*Gt(n.originY)}):(n.setPositionByOrigin(i,P,P),n.setCoords(),n.set(`dirty`,!0))}layoutObjects(e,t){let{target:n}=e;n.forEachObject(r=>{r.group===n&&this.layoutObject(e,t,r)}),e.strategy.shouldLayoutClipPath(e)&&this.layoutObject(e,t,n.clipPath)}layoutObject(e,{offset:t},n){n.set({left:n.left+t.x,top:n.top+t.y})}onAfterLayout(e,t){let{target:n,strategy:r,bubbles:i,prevStrategy:a,...o}=e,{canvas:s}=n;n.fire(`layout:after`,{context:e,result:t}),s&&s.fire(`object:layout:after`,{context:e,result:t,target:n});let c=n.parent;i&&c!=null&&c.layoutManager&&((o.path||=[]).push(n),c.layoutManager.performLayout({...o,target:c})),n.set(`dirty`,!0)}dispose(){let{_subscriptions:e}=this;e.forEach(e=>e.forEach(e=>e())),e.clear()}toObject(){return{type:ba,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}};L.setClass(xa,ba);var Sa=class extends xa{performLayout(){}},Ca=class e extends ke(Mi){static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t=[],n={}){super(),p(this,`_activeObjects`,[]),p(this,`__objectSelectionTracker`,void 0),p(this,`__objectSelectionDisposer`,void 0),Object.assign(this,e.ownDefaults),this.setOptions(n),this.groupInit(t,n)}groupInit(e,t){this._objects=[...e],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(e=>{this.enterGroup(e,!1)}),this.layoutManager=t.layoutManager??new xa,this.layoutManager.performLayout({type:ha,target:this,targets:[...e],x:t.left,y:t.top})}canEnterGroup(e){return e===this||this.isDescendantOf(e)?(g(`error`,`Group: circular object trees are not supported, this call has no effect`),!1):this._objects.indexOf(e)===-1||(g(`error`,`Group: duplicate objects are not supported inside group, this call has no effect`),!1)}_filterObjectsBeforeEnteringGroup(e){return e.filter((e,t,n)=>this.canEnterGroup(e)&&n.indexOf(e)===t)}add(...e){let t=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...t);return this._onAfterObjectsChange(ga,t),n}insertAt(e,...t){let n=this._filterObjectsBeforeEnteringGroup(t),r=super.insertAt(e,...n);return this._onAfterObjectsChange(ga,n),r}remove(...e){let t=super.remove(...e);return this._onAfterObjectsChange(`removed`,t),t}_onObjectAdded(e){this.enterGroup(e,!0),this.fire(`object:added`,{target:e}),e.fire(`added`,{target:this})}_onObjectRemoved(e,t){this.exitGroup(e,t),this.fire(`object:removed`,{target:e}),e.fire(`removed`,{target:this})}_onAfterObjectsChange(e,t){this.layoutManager.performLayout({type:e,targets:t,target:this})}_onStackOrderChanged(){this._set(`dirty`,!0)}_set(e,t){let n=this[e];return super._set(e,t),e===`canvas`&&n!==t&&(this._objects||[]).forEach(n=>{n._set(e,t)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(e,{target:t}){let n=this._activeObjects;if(e)n.push(t),this._set(`dirty`,!0);else if(n.length>0){let e=n.indexOf(t);e>-1&&(n.splice(e,1),this._set(`dirty`,!0))}}_watchObject(e,t){e&&this._watchObject(!1,t),e?(t.on(`selected`,this.__objectSelectionTracker),t.on(`deselected`,this.__objectSelectionDisposer)):(t.off(`selected`,this.__objectSelectionTracker),t.off(`deselected`,this.__objectSelectionDisposer))}enterGroup(e,t){e.group&&e.group.remove(e),e._set(`parent`,this),this._enterGroup(e,t)}_enterGroup(e,t){t&&It(e,B(We(this.calcTransformMatrix()),e.calcTransformMatrix())),this._shouldSetNestedCoords()&&e.setCoords(),e._set(`group`,this),e._set(`canvas`,this.canvas),this._watchObject(!0,e);let n=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();n&&(n===e||e.isDescendantOf(n))&&this._activeObjects.push(e)}exitGroup(e,t){this._exitGroup(e,t),e._set(`parent`,void 0),e._set(`canvas`,void 0)}_exitGroup(e,t){e._set(`group`,void 0),t||(It(e,B(this.calcTransformMatrix(),e.calcTransformMatrix())),e.setCoords()),this._watchObject(!1,e);let n=this._activeObjects.length>0?this._activeObjects.indexOf(e):-1;n>-1&&this._activeObjects.splice(n,1)}shouldCache(){let e=Mi.prototype.shouldCache.call(this);if(e){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return e}willDrawShadow(){if(super.willDrawShadow())return!0;for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(e,t,n){this._renderBackground(e);for(let t=0;t<this._objects.length;t++){var r;let n=this._objects[t];(r=this.canvas)!=null&&r.preserveObjectStacking&&n.group!==this?(e.save(),e.transform(...We(this.calcTransformMatrix())),n.render(e),e.restore()):n.group===this&&n.render(e)}this._drawClipPath(e,this.clipPath,n)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(e=>e.setCoords())}triggerLayout(e={}){this.layoutManager.performLayout({target:this,type:`imperative`,...e})}render(e){this._transformDone=!0,super.render(e),this._transformDone=!1}__serializeObjects(e,t){let n=this.includeDefaultValues;return this._objects.filter(function(e){return!e.excludeFromExport}).map(function(r){let i=r.includeDefaultValues;r.includeDefaultValues=n;let a=r[e||`toObject`](t);return r.includeDefaultValues=i,a})}toObject(e=[]){let t=this.layoutManager.toObject();return{...super.toObject([`subTargetCheck`,`interactive`,...e]),...t.strategy!==`fit-content`||this.includeDefaultValues?{layoutManager:t}:{},objects:this.__serializeObjects(`toObject`,e)}}toString(){return`#<Group: (${this.complexity()})>`}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(e=>{this._watchObject(!1,e),e.dispose()}),super.dispose()}_createSVGBgRect(e){if(!this.backgroundColor)return``;let t=ma.prototype._toSVG.call(this),n=t.indexOf(`COMMON_PARTS`);t[n]=`for="group" `;let r=t.join(``);return e?e(r):r}_toSVG(e){let t=[`<g `,`COMMON_PARTS`,` >
|
|
16
16
|
`],n=this._createSVGBgRect(e);n&&t.push(` `,n);for(let n=0;n<this._objects.length;n++)t.push(` `,this._objects[n].toSVG(e));return t.push(`</g>
|
|
17
|
-
`),t}getSvgStyles(){let e=this.opacity!==void 0&&this.opacity!==1?`opacity: ${H(this.opacity)};`:``,t=this.visible?``:` visibility: hidden;`;return[e,this.getSvgFilter(),t].join(``)}toClipPathSVG(e){let t=[],n=this._createSVGBgRect(e);n&&t.push(` `,n);for(let n=0;n<this._objects.length;n++)t.push(` `,this._objects[n].toClipPathSVG(e));return this._createBaseClipPathSVGMarkup(t,{reviver:e})}static fromObject({type:e,objects:t=[],layoutManager:n,...r},i){return Promise.all([at(t,i),ot(r,i)]).then(([e,t])=>{let i=new this(e,{...r,...t,layoutManager:new Sa});return i.layoutManager=n?new(L.getClass(n.type))(new(L.getClass(n.strategy))):new xa,i.layoutManager.subscribeTargets({type:ha,target:i,targets:i.getObjects()}),i.setCoords(),i})}};p(Ca,`type`,`Group`),p(Ca,`ownDefaults`,{strokeWidth:0,subTargetCheck:!1,interactive:!1}),L.setClass(Ca);var wa=(e,t)=>e&&e.length===1?e[0]:new Ca(e,t),Ta=(e,t)=>Math.min(t.width/e.width,t.height/e.height),Ea=(e,t)=>Math.max(t.width/e.width,t.height/e.height),Da=`\\s*,?\\s*`,Oa=`${Da}(${zn})`,ka=`${Oa}${Oa}${Oa}${Da}([01])${Da}([01])${Oa}${Oa}`,Aa={m:`l`,M:`L`},ja=(e,t,n,r,i,a,o,s,c,l,u)=>{let d=Te(e),f=Ee(e),p=Te(t),m=Ee(t),h=n*i*p-r*a*m+o,g=r*i*p+n*a*m+s;return[`C`,l+c*(-n*i*f-r*a*d),u+c*(-r*i*f+n*a*d),h+c*(n*i*m+r*a*p),g+c*(r*i*m-n*a*p),h,g]},Ma=(e,t,n,r)=>{let i=Math.atan2(t,e),a=Math.atan2(r,n);return a>=i?a-i:2*Math.PI-(i-a)};function Na(e,t,n,r,i,a,o,s){let c;if(h.cachesBoundsOfCurve&&(c=[...arguments].join(),D.boundsOfCurveCache[c]))return D.boundsOfCurveCache[c];let l=Math.sqrt,u=Math.abs,d=[],f=[[0,0],[0,0]],p=6*e-12*n+6*i,m=-3*e+9*n-9*i+3*o,g=3*n-3*e;for(let e=0;e<2;++e){if(e>0&&(p=6*t-12*r+6*a,m=-3*t+9*r-9*a+3*s,g=3*r-3*t),u(m)<1e-12){if(u(p)<1e-12)continue;let e=-g/p;0<e&&e<1&&d.push(e);continue}let n=p*p-4*g*m;if(n<0)continue;let i=l(n),o=(-p+i)/(2*m);0<o&&o<1&&d.push(o);let c=(-p-i)/(2*m);0<c&&c<1&&d.push(c)}let _=d.length,v=_,y=La(e,t,n,r,i,a,o,s);for(;_--;){let{x:e,y:t}=y(d[_]);f[0][_]=e,f[1][_]=t}f[0][v]=e,f[1][v]=t,f[0][v+1]=o,f[1][v+1]=s;let b=[new R(Math.min(...f[0]),Math.min(...f[1])),new R(Math.max(...f[0]),Math.max(...f[1]))];return h.cachesBoundsOfCurve&&(D.boundsOfCurveCache[c]=b),b}var Pa=(e,t,[n,r,i,a,o,s,c,l])=>{let u=((e,t,n,r,i,a,o)=>{if(n===0||r===0)return[];let s=0,c=0,l=0,u=Math.PI,d=o*ee,f=Ee(d),p=Te(d),m=.5*(-p*e-f*t),h=.5*(-p*t+f*e),g=n**2,_=r**2,v=h**2,y=m**2,b=g*_-g*v-_*y,x=Math.abs(n),S=Math.abs(r);if(b<0){let e=Math.sqrt(1-b/(g*_));x*=e,S*=e}else l=(i===a?-1:1)*Math.sqrt(b/(g*v+_*y));let C=l*x*h/S,w=-l*S*m/x,T=p*C-f*w+.5*e,E=f*C+p*w+.5*t,D=Ma(1,0,(m-C)/x,(h-w)/S),O=Ma((m-C)/x,(h-w)/S,(-m-C)/x,(-h-w)/S);a===0&&O>0?O-=2*u:a===1&&O<0&&(O+=2*u);let k=Math.ceil(Math.abs(O/u*2)),A=[],j=O/k,M=8/3*Math.sin(j/4)*Math.sin(j/4)/Math.sin(j/2),N=D+j;for(let e=0;e<k;e++)A[e]=ja(D,N,p,f,x,S,T,E,M,s,c),s=A[e][5],c=A[e][6],D=N,N+=j;return A})(c-e,l-t,r,i,o,s,a);for(let n=0,r=u.length;n<r;n++)u[n][1]+=e,u[n][2]+=t,u[n][3]+=e,u[n][4]+=t,u[n][5]+=e,u[n][6]+=t;return u},Fa=e=>{let t=0,n=0,r=0,i=0,a=[],o,s=0,c=0;for(let l of e){let e=[...l],u;switch(e[0]){case`l`:e[1]+=t,e[2]+=n;case`L`:t=e[1],n=e[2],u=[`L`,t,n];break;case`h`:e[1]+=t;case`H`:t=e[1],u=[`L`,t,n];break;case`v`:e[1]+=n;case`V`:n=e[1],u=[`L`,t,n];break;case`m`:e[1]+=t,e[2]+=n;case`M`:t=e[1],n=e[2],r=e[1],i=e[2],u=[`M`,t,n];break;case`c`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n,e[5]+=t,e[6]+=n;case`C`:s=e[3],c=e[4],t=e[5],n=e[6],u=[`C`,e[1],e[2],s,c,t,n];break;case`s`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n;case`S`:o===`C`?(s=2*t-s,c=2*n-c):(s=t,c=n),t=e[3],n=e[4],u=[`C`,s,c,e[1],e[2],t,n],s=u[3],c=u[4];break;case`q`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n;case`Q`:s=e[1],c=e[2],t=e[3],n=e[4],u=[`Q`,s,c,t,n];break;case`t`:e[1]+=t,e[2]+=n;case`T`:o===`Q`?(s=2*t-s,c=2*n-c):(s=t,c=n),t=e[1],n=e[2],u=[`Q`,s,c,t,n];break;case`a`:e[6]+=t,e[7]+=n;case`A`:Pa(t,n,e).forEach(e=>a.push(e)),t=e[6],n=e[7];break;case`z`:case`Z`:t=r,n=i,u=[`Z`]}u?(a.push(u),o=u[0]):o=``}return a},Ia=(e,t,n,r)=>Math.sqrt((n-e)**2+(r-t)**2),La=(e,t,n,r,i,a,o,s)=>c=>{let l=c**3,u=(e=>3*e**2*(1-e))(c),d=(e=>3*e*(1-e)**2)(c),f=(e=>(1-e)**3)(c);return new R(o*l+i*u+n*d+e*f,s*l+a*u+r*d+t*f)},Ra=e=>e**2,za=e=>2*e*(1-e),Ba=e=>(1-e)**2,Va=(e,t,n,r,i,a,o,s)=>c=>{let l=Ra(c),u=za(c),d=Ba(c),f=3*(d*(n-e)+u*(i-n)+l*(o-i)),p=3*(d*(r-t)+u*(a-r)+l*(s-a));return Math.atan2(p,f)},Ha=(e,t,n,r,i,a)=>o=>{let s=Ra(o),c=za(o),l=Ba(o);return new R(i*s+n*c+e*l,a*s+r*c+t*l)},Ua=(e,t,n,r,i,a)=>o=>{let s=1-o,c=2*(s*(n-e)+o*(i-n)),l=2*(s*(r-t)+o*(a-r));return Math.atan2(l,c)},Wa=(e,t,n)=>{let r=new R(t,n),i=0;for(let t=1;t<=100;t+=1){let n=e(t/100);i+=Ia(r.x,r.y,n.x,n.y),r=n}return i},Ga=(e,t)=>{let n,r=0,i=0,a={x:e.x,y:e.y},o={...a},s=.01,c=0,l=e.iterator,u=e.angleFinder;for(;i<t&&s>1e-4;)o=l(r),c=r,n=Ia(a.x,a.y,o.x,o.y),n+i>t?(r-=s,s/=2):(a=o,r+=s,i+=n);return{...o,angle:u(c)}},Ka=e=>{let t,n,r=0,i=0,a=0,o=0,s=0,c=[];for(let l of e){let e={x:i,y:a,command:l[0],length:0};switch(l[0]){case`M`:n=e,n.x=o=i=l[1],n.y=s=a=l[2];break;case`L`:n=e,n.length=Ia(i,a,l[1],l[2]),i=l[1],a=l[2];break;case`C`:t=La(i,a,l[1],l[2],l[3],l[4],l[5],l[6]),n=e,n.iterator=t,n.angleFinder=Va(i,a,l[1],l[2],l[3],l[4],l[5],l[6]),n.length=Wa(t,i,a),i=l[5],a=l[6];break;case`Q`:t=Ha(i,a,l[1],l[2],l[3],l[4]),n=e,n.iterator=t,n.angleFinder=Ua(i,a,l[1],l[2],l[3],l[4]),n.length=Wa(t,i,a),i=l[3],a=l[4];break;case`Z`:n=e,n.destX=o,n.destY=s,n.length=Ia(i,a,o,s),i=o,a=s}r+=n.length,c.push(n)}return c.push({length:r,x:i,y:a}),c},qa=(e,t,n=Ka(e))=>{let r=0;for(;t-n[r].length>0&&r<n.length-2;)t-=n[r].length,r++;let i=n[r],a=t/i.length,o=e[r];switch(i.command){case`M`:return{x:i.x,y:i.y,angle:0};case`Z`:return{...new R(i.x,i.y).lerp(new R(i.destX,i.destY),a),angle:Math.atan2(i.destY-i.y,i.destX-i.x)};case`L`:return{...new R(i.x,i.y).lerp(new R(o[1],o[2]),a),angle:Math.atan2(o[2]-i.y,o[1]-i.x)};case`C`:case`Q`:return Ga(i,t)}},Ja=RegExp(`[mzlhvcsqta][^mzlhvcsqta]*`,`gi`),Ya=new RegExp(ka,`g`),Xa=new RegExp(zn,`gi`),Za={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Qa=e=>{let t=[],n=e.match(Ja)??[];for(let e of n){let n=e[0];if(n===`z`||n===`Z`){t.push([n]);continue}let r=Za[n.toLowerCase()],i=[];if(n===`a`||n===`A`){let t;for(Ya.lastIndex=0;t=Ya.exec(e);)i.push(...t.slice(1))}else i=e.match(Xa)||[];for(let e=0;e<i.length;e+=r){let a=Array(r),o=Aa[n];a[0]=e>0&&o?o:n;for(let t=0;t<r;t++)a[t+1]=parseFloat(i[e+t]);t.push(a)}}return t},$a=(e,t=0)=>{let n=new R(e[0]),r=new R(e[1]),i=1,a=0,o=[],s=e.length,c=s>2,l;for(c&&(i=e[2].x<r.x?-1:e[2].x===r.x?0:1,a=e[2].y<r.y?-1:e[2].y===r.y?0:1),o.push([`M`,n.x-i*t,n.y-a*t]),l=1;l<s;l++){if(!n.eq(r)){let e=n.midPointFrom(r);o.push([`Q`,n.x,n.y,e.x,e.y])}n=e[l],l+1<e.length&&(r=e[l+1])}return c&&(i=n.x>e[l-2].x?1:n.x===e[l-2].x?0:-1,a=n.y>e[l-2].y?1:n.y===e[l-2].y?0:-1),o.push([`L`,n.x+i*t,n.y+a*t]),o},eo=(e,t,n)=>(n&&(t=B(t,[1,0,0,1,-n.x,-n.y])),e.map(e=>{let n=[...e];for(let r=1;r<e.length-1;r+=2){let{x:i,y:a}=Ue({x:e[r],y:e[r+1]},t);n[r]=i,n[r+1]=a}return n})),to=(e,t)=>{let n=2*Math.PI/e,r=-A;e%2==0&&(r+=n/2);let i=Array(e+1);for(let a=0;a<e;a++){let e=a*n+r,{x:o,y:s}=new R(Te(e),Ee(e)).scalarMultiply(t);i[a]=[a===0?`M`:`L`,o,s]}return i[e]=[`Z`],i},no=(e,t)=>e.map(e=>e.map((e,n)=>n===0||t===void 0?e:V(e,t)).join(` `)).join(` `),ro=(e,t)=>{let n=e,r=t;n.inverted&&!r.inverted&&(n=t,r=e),Ut(r,r.group?.calcTransformMatrix(),n.calcTransformMatrix());let i=n.inverted&&r.inverted;return i&&(n.inverted=r.inverted=!1),new Ca([n],{clipPath:r,inverted:i})},io=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,ao=(e,t)=>{let n=e._findCenterFromElement();e.transformMatrix&&((e=>{if(e.transformMatrix){let{scaleX:t,scaleY:n,angle:r,skewX:i}=Ye(e.transformMatrix);e.flipX=!1,e.flipY=!1,e.set(pe,t),e.set(me,n),e.angle=r,e.skewX=i,e.skewY=0}})(e),n=n.transform(e.transformMatrix)),delete e.transformMatrix,t&&(e.scaleX*=t.scaleX,e.scaleY*=t.scaleY,e.cropX=t.cropX,e.cropY=t.cropY,n.x+=t.offsetLeft,n.y+=t.offsetTop,e.width=t.width,e.height=t.height),e.setPositionByOrigin(n,P,P)},oo=u({addTransformToObject:()=>Ft,animate:()=>Wr,animateColor:()=>Gr,applyTransformToObject:()=>It,calcAngleBetweenVectors:()=>Zt,calcDimensionsMatrix:()=>nt,calcPlaneChangeMatrix:()=>Bt,calcVectorRotation:()=>Qt,cancelAnimFrame:()=>Me,capValue:()=>$n,composeMatrix:()=>rt,copyCanvasElement:()=>Le,cos:()=>Te,createCanvasElement:()=>Fe,createImage:()=>Ie,createRotateMatrix:()=>Ze,createScaleMatrix:()=>Qe,createSkewXMatrix:()=>et,createSkewYMatrix:()=>tt,createTranslateMatrix:()=>Xe,createVector:()=>Yt,crossProduct:()=>tn,degreesToRadians:()=>z,dotProduct:()=>nn,ease:()=>rr,enlivenObjectEnlivables:()=>ot,enlivenObjects:()=>at,findScaleToCover:()=>Ea,findScaleToFit:()=>Ta,getBoundsOfCurve:()=>Na,getOrthonormalVector:()=>en,getPathSegmentsInfo:()=>Ka,getPointOnPath:()=>qa,getPointer:()=>At,getRandomInt:()=>io,getRegularPolygonPath:()=>to,getSmoothPathFromPoints:()=>$a,getSvgAttributes:()=>wn,getUnitVector:()=>$t,groupSVGElements:()=>wa,hasStyleChanged:()=>Bi,invertTransform:()=>We,isBetweenVectors:()=>rn,isIdentityMatrix:()=>He,isTouchEvent:()=>jt,isTransparent:()=>Ni,joinPath:()=>no,loadImage:()=>it,magnitude:()=>Xt,makeBoundingBoxFromPoints:()=>Nt,makePathSimpler:()=>Fa,matrixToSVG:()=>lt,mergeClipPaths:()=>ro,multiplyTransformMatrices:()=>B,multiplyTransformMatrixArray:()=>Ge,parsePath:()=>Qa,parsePreserveAspectRatioAttribute:()=>En,parseUnit:()=>Tn,pick:()=>st,projectStrokeOnPoints:()=>Ri,qrDecompose:()=>Ye,radiansToDegrees:()=>Ve,removeFromArray:()=>we,removeTransformFromObject:()=>Pt,removeTransformMatrixForSvgParsing:()=>ao,requestAnimFrame:()=>je,resetObjectTransform:()=>Lt,rotateVector:()=>Jt,saveObjectTransform:()=>Rt,sendObjectToPlane:()=>Ut,sendPointToPlane:()=>Vt,sendVectorToPlane:()=>Ht,sin:()=>Ee,sizeAfterTransform:()=>zt,string:()=>St,stylesFromArray:()=>Hi,stylesToArray:()=>Vi,toBlob:()=>Be,toDataURL:()=>ze,toFixed:()=>V,transformPath:()=>eo,transformPoint:()=>Ue});function so(e,t){let n=e.style;n&&Object.entries(t).forEach(([e,t])=>n.setProperty(e,t))}var co=class extends bt{constructor(e,{allowTouchScrolling:t=!1,containerClass:n=``}={}){super(e),p(this,`upper`,void 0),p(this,`container`,void 0);let{el:r}=this.lower,i=this.createUpperCanvas();this.upper={el:i,ctx:i.getContext(`2d`)},this.applyCanvasStyle(r,{allowTouchScrolling:t}),this.applyCanvasStyle(i,{allowTouchScrolling:t,styles:{position:`absolute`,left:`0`,top:`0`}});let a=this.createContainerElement();a.classList.add(n),r.parentNode&&r.parentNode.replaceChild(a,r),a.append(r,i),this.container=a}createUpperCanvas(){let{el:e}=this.lower,t=Fe();return t.className=e.className,t.classList.remove(`lower-canvas`),t.classList.add(`upper-canvas`),t.setAttribute(`data-fabric`,`top`),t.style.cssText=e.style.cssText,t.setAttribute(`draggable`,`true`),t}createContainerElement(){let e=w().createElement(`div`);return e.setAttribute(`data-fabric`,`wrapper`),so(e,{position:`relative`}),yt(e),e}applyCanvasStyle(e,t){let{styles:n,allowTouchScrolling:r}=t;so(e,{...n,"touch-action":r?`manipulation`:ne}),yt(e)}setDimensions(e,t){super.setDimensions(e,t);let{el:n,ctx:r}=this.upper;_t(n,r,e,t)}setCSSDimensions(e){super.setCSSDimensions(e),vt(this.upper.el,e),vt(this.container,e)}cleanupDOM(e){let t=this.container,{el:n}=this.lower,{el:r}=this.upper;super.cleanupDOM(e),t.removeChild(r),t.removeChild(n),t.parentNode&&t.parentNode.replaceChild(n,t)}dispose(){super.dispose(),C().dispose(this.upper.el),delete this.upper,delete this.container}},lo=(e,t,n,r)=>{let{target:i,offsetX:a,offsetY:o}=t,s=n-a,c=r-o,l=!cn(i,`lockMovementX`)&&i.left!==s,u=!cn(i,`lockMovementY`)&&i.top!==c;return l&&i.set(`left`,s),u&&i.set(`top`,c),(l||u)&&Yr(ie,ln(e,t,n,r)),l||u},uo=ue,fo=e=>function(t,n,r){let{points:i,pathOffset:a}=r;return new R(i[e]).subtract(a).transform(B(r.getViewportTransform(),r.calcTransformMatrix()))},po=(e,t,n,r)=>{let{target:i,pointIndex:a}=t,o=i,s=Vt(new R(n,r),void 0,o.calcOwnMatrix());return o.points[a]=s.add(o.pathOffset),o.setDimensions(),o.set(`dirty`,!0),!0},mo=(e,t)=>function(n,r,i,a){let o=r.target,s=new R(o.points[(e>0?e:o.points.length)-1]),c=s.subtract(o.pathOffset).transform(o.calcOwnMatrix()),l=t(n,{...r,pointIndex:e},i,a),u=s.subtract(o.pathOffset).transform(o.calcOwnMatrix()).subtract(c);return o.left-=u.x,o.top-=u.y,l},ho=e=>Xr(uo,mo(e,po));function go(e,t={}){let n={};for(let r=0;r<(typeof e==`number`?e:e.points.length);r++)n[`p${r}`]=new ai({actionName:uo,positionHandler:fo(r),actionHandler:ho(r),...t});return n}var _o=(e,t,n)=>{let{path:r,pathOffset:i}=e,a=r[t];return new R(a[n]-i.x,a[n+1]-i.y).transform(B(e.getViewportTransform(),e.calcTransformMatrix()))};function vo(e,t,n){let{commandIndex:r,pointIndex:i}=this;return _o(n,r,i)}function yo(e,t,n,r){let{target:i}=t,{commandIndex:a,pointIndex:o}=this,s=((e,t,n,r,i)=>{let{path:a,pathOffset:o}=e,s=a[(r>0?r:a.length)-1],c=new R(s[i],s[i+1]),l=c.subtract(o).transform(e.calcOwnMatrix()),u=Vt(new R(t,n),void 0,e.calcOwnMatrix());a[r][i]=u.x+o.x,a[r][i+1]=u.y+o.y,e.setDimensions();let d=c.subtract(e.pathOffset).transform(e.calcOwnMatrix()).subtract(l);return e.left-=d.x,e.top-=d.y,e.set(`dirty`,!0),!0})(i,n,r,a,o);return s&&Yr(this.actionName,{...ln(e,t,n,r),commandIndex:a,pointIndex:o}),s}var bo=class extends ai{constructor(e){super(e)}render(e,t,n,r,i){let a={...r,cornerColor:this.controlFill,cornerStrokeColor:this.controlStroke,transparentCorners:!this.controlFill};super.render(e,t,n,a,i)}},xo=class extends bo{constructor(e){super(e)}render(e,t,n,r,i){let{path:a}=i,{commandIndex:o,pointIndex:s,connectToCommandIndex:c,connectToPointIndex:l}=this;e.save(),e.strokeStyle=this.controlStroke,this.connectionDashArray&&e.setLineDash(this.connectionDashArray);let[u]=a[o],d=_o(i,c,l);if(u===`Q`){let r=_o(i,o,s+2);e.moveTo(r.x,r.y),e.lineTo(t,n)}else e.moveTo(t,n);e.lineTo(d.x,d.y),e.stroke(),e.restore(),super.render(e,t,n,r,i)}},So=(e,t,n,r,i,a)=>new(n?xo:bo)({commandIndex:e,pointIndex:t,actionName:`modifyPath`,positionHandler:vo,actionHandler:yo,connectToCommandIndex:i,connectToPointIndex:a,...r,...n?r.controlPointStyle:r.pointStyle});function Co(e,t={}){let n={},r=`M`;return e.path.forEach((e,i)=>{let a=e[0];switch(a!==`Z`&&(n[`c_${i}_${a}`]=So(i,e.length-2,!1,t)),a){case`C`:n[`c_${i}_C_CP_1`]=So(i,1,!0,t,i-1,(e=>e===`C`?5:e===`Q`?3:1)(r)),n[`c_${i}_C_CP_2`]=So(i,3,!0,t,i,5);break;case`Q`:n[`c_${i}_Q_CP_1`]=So(i,1,!0,t,i,3)}r=a}),n}u({changeHeight:()=>ni,changeObjectHeight:()=>ei,changeObjectWidth:()=>$r,changeWidth:()=>ti,createObjectDefaultControls:()=>Di,createPathControls:()=>Co,createPolyActionHandler:()=>ho,createPolyControls:()=>go,createPolyPositionHandler:()=>fo,createResizeControls:()=>Oi,createTextboxDefaultControls:()=>ki,dragHandler:()=>lo,factoryPolyActionHandler:()=>mo,getLocalPoint:()=>dn,polyActionHandler:()=>po,renderCircleControl:()=>ri,renderSquareControl:()=>ii,rotationStyleHandler:()=>oi,rotationWithSnapping:()=>si,scaleCursorStyleHandler:()=>di,scaleOrSkewActionName:()=>Ci,scaleSkewCursorStyleHandler:()=>wi,scalingEqually:()=>pi,scalingX:()=>mi,scalingXOrSkewingY:()=>Ti,scalingY:()=>hi,scalingYOrSkewingX:()=>Ei,skewCursorStyleHandler:()=>vi,skewHandlerX:()=>bi,skewHandlerY:()=>xi,wrapWithFireEvent:()=>Xr,wrapWithFixedAnchor:()=>Zr});var wo=class e extends Ot{constructor(...e){super(...e),p(this,`_hoveredTargets`,[]),p(this,`_currentTransform`,null),p(this,`_groupSelector`,null),p(this,`contextTopDirty`,!1)}static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}get upperCanvasEl(){return this.elements.upper?.el}get contextTop(){return this.elements.upper?.ctx}get wrapperEl(){return this.elements.container}initElements(e){this.elements=new co(e,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(e){this._objectsToRender=void 0,super._onObjectAdded(e)}_onObjectRemoved(e){this._objectsToRender=void 0,e===this._activeObject&&(this.fire(`before:selection:cleared`,{deselected:[e]}),this._discardActiveObject(),this.fire(`selection:cleared`,{deselected:[e]}),e.fire(`deselected`,{target:e})),e===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(e)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){let e=this._activeObject;return!this.preserveObjectStacking&&e?this._objects.filter(t=>!t.group&&t!==e).concat(e):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&=(this.renderTopLayer(this.contextTop),!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()}renderTop(){let e=this.contextTop;this.clearContext(e),this.renderTopLayer(e),this.fire(`after:render`,{ctx:e})}setTargetFindTolerance(e){e=Math.round(e),this.targetFindTolerance=e;let t=this.getRetinaScaling(),n=Math.ceil((2*e+1)*t);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=n,this.pixelFindContext.scale(t,t)}isTargetTransparent(e,t,n){let r=this.targetFindTolerance,i=this.pixelFindContext;this.clearContext(i),i.save(),i.translate(-t+r,-n+r),i.transform(...this.viewportTransform);let a=e.selectionBackgroundColor;e.selectionBackgroundColor=``,e.render(i),e.selectionBackgroundColor=a,i.restore();let o=Math.round(r*this.getRetinaScaling());return Ni(i,o,o,o)}_isSelectionKeyPressed(e){let t=this.selectionKey;return!!t&&(Array.isArray(t)?!!t.find(t=>!!t&&!0===e[t]):e[t])}_shouldClearSelection(e,t){let n=this.getActiveObjects(),r=this._activeObject;return!!(!t||t&&r&&n.length>1&&n.indexOf(t)===-1&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t)}_shouldCenterTransform(e,t,n){if(!e)return;let r;return t===`scale`||t===`scaleX`||t===`scaleY`||t===`resizing`?r=this.centeredScaling||e.centeredScaling:t===`rotate`&&(r=this.centeredRotation||e.centeredRotation),r?!n:n}_getOriginFromCorner(e,t){let n=t?e.controls[t].getTransformAnchorPoint():{x:e.originX,y:e.originY};return t?([`ml`,`tl`,`bl`].includes(t)?n.x=te:[`mr`,`tr`,`br`].includes(t)&&(n.x=F),[`tl`,`mt`,`tr`].includes(t)?n.y=I:[`bl`,`mb`,`br`].includes(t)&&(n.y=`top`),n):n}_setupCurrentTransform(e,t,n){let r=t.group?Vt(this.getScenePoint(e),void 0,t.group.calcTransformMatrix()):this.getScenePoint(e),{key:i=``,control:a}=t.getActiveControl()||{},o=n&&a?a.getActionHandler(e,t,a)?.bind(a):lo,s=((e,t,n,r)=>{if(!t||!e)return`drag`;let i=r.controls[t];return i.getActionName(n,i,r)})(n,i,e,t),c=e[this.centeredKey],l=this._shouldCenterTransform(t,s,c)?{x:P,y:P}:this._getOriginFromCorner(t,i),{scaleX:u,scaleY:d,skewX:f,skewY:p,left:m,top:h,angle:g,width:_,height:v,cropX:y,cropY:b}=t,x={target:t,action:s,actionHandler:o,actionPerformed:!1,corner:i,scaleX:u,scaleY:d,skewX:f,skewY:p,offsetX:r.x-m,offsetY:r.y-h,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:z(g),width:_,height:v,shiftKey:e.shiftKey,altKey:c,original:{...Rt(t),originX:l.x,originY:l.y,cropX:y,cropY:b}};this._currentTransform=x,this.fire(`before:transform`,{e,transform:x})}setCursor(e){this.upperCanvasEl.style.cursor=e}_drawSelection(e){let{x:t,y:n,deltaX:r,deltaY:i}=this._groupSelector,a=new R(t,n).transform(this.viewportTransform),o=new R(t+r,n+i).transform(this.viewportTransform),s=this.selectionLineWidth/2,c=Math.min(a.x,o.x),l=Math.min(a.y,o.y),u=Math.max(a.x,o.x),d=Math.max(a.y,o.y);this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(c,l,u-c,d-l)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,c+=s,l+=s,u-=s,d-=s,Mi.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(c,l,u-c,d-l))}findTarget(e){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};let t=this.getScenePoint(e),n=this._activeObject,r=this.getActiveObjects(),i=this.searchPossibleTargets(this._objects,t),{subTargets:a,container:o,target:s}=i,c={...i,currentSubTargets:a,currentContainer:o,currentTarget:s};if(!n)return c;let l={...this.searchPossibleTargets([n],t),currentSubTargets:a,currentContainer:o,currentTarget:s};return n.findControl(this.getViewportPoint(e),jt(e))?{...l,target:n}:l.target&&(r.length>1||!this.preserveObjectStacking||this.preserveObjectStacking&&e[this.altSelectionKey])?l:c}_pointIsInObjectSelectionArea(e,t){let n=e.getCoords(),r=this.getZoom(),i=e.padding/r;if(i){let[e,t,r,a]=n,o=Math.atan2(t.y-e.y,t.x-e.x),s=Te(o)*i,c=Ee(o)*i,l=s+c,u=s-c;n=[new R(e.x-u,e.y-l),new R(t.x+l,t.y-u),new R(r.x+u,r.y+l),new R(a.x-l,a.y+u)]}return Kr.isPointInPolygon(t,n)}_checkTarget(e,t){if(e&&e.visible&&e.evented&&this._pointIsInObjectSelectionArea(e,t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;{let n=t.transform(this.viewportTransform);if(!this.isTargetTransparent(e,n.x,n.y))return!0}}return!1}_searchPossibleTargets(e,t,n){let r=e.length;for(;r--;){let i=e[r];if(this._checkTarget(i,t)){if(Oe(i)&&i.subTargetCheck){let{target:e}=this._searchPossibleTargets(i._objects,t,n);e&&n.push(e)}return{target:i,subTargets:n}}}return{subTargets:[]}}searchPossibleTargets(e,t){let n=this._searchPossibleTargets(e,t,[]);n.container=n.target;let{container:r,subTargets:i}=n;if(r&&Oe(r)&&r.interactive&&i[0]){for(let e=i.length-1;e>0;e--){let t=i[e];if(!Oe(t)||!t.interactive)return n.target=t,n}return n.target=i[0],n}return n}getViewportPoint(e){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(e,!0)}getScenePoint(e){return this._scenePoint?this._scenePoint:this._getPointerImpl(e)}_getPointerImpl(e,t=!1){let n=this.upperCanvasEl,r=n.getBoundingClientRect(),i=At(e),a=r.width||0,o=r.height||0;a&&o||(`top`in r&&`bottom`in r&&(o=Math.abs(r.top-r.bottom)),`right`in r&&`left`in r&&(a=Math.abs(r.right-r.left))),this.calcOffset(),i.x-=this._offset.left,i.y-=this._offset.top,t||(i=Vt(i,void 0,this.viewportTransform));let s=this.getRetinaScaling();s!==1&&(i.x/=s,i.y/=s);let c=a===0||o===0?new R(1,1):new R(n.width/a,n.height/o);return i.multiply(c)}_setDimensionsImpl(e,t){this._resetTransformEventData(),super._setDimensionsImpl(e,t),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Fe(),this.pixelFindContext=this.pixelFindCanvasEl.getContext(`2d`,{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){let e=this._activeObject;return pt(e)?e.getObjects():e?[e]:[]}_fireSelectionEvents(e,t){let n=!1,r=!1,i=this.getActiveObjects(),a=[],o=[];e.forEach(e=>{i.includes(e)||(n=!0,e.fire(`deselected`,{e:t,target:e}),o.push(e))}),i.forEach(r=>{e.includes(r)||(n=!0,r.fire(`selected`,{e:t,target:r}),a.push(r))}),e.length>0&&i.length>0?(r=!0,n&&this.fire(`selection:updated`,{e:t,selected:a,deselected:o})):i.length>0?(r=!0,this.fire(`selection:created`,{e:t,selected:a})):e.length>0&&(r=!0,this.fire(`selection:cleared`,{e:t,deselected:o})),r&&(this._objectsToRender=void 0)}setActiveObject(e,t){let n=this.getActiveObjects(),r=this._setActiveObject(e,t);return this._fireSelectionEvents(n,t),r}_setActiveObject(e,t){let n=this._activeObject;return n!==e&&!(!this._discardActiveObject(t,e)&&this._activeObject)&&!e.onSelect({e:t})&&(this._activeObject=e,pt(e)&&n!==e&&e.set(`canvas`,this),e.setCoords(),!0)}_discardActiveObject(e,t){let n=this._activeObject;return!!n&&!n.onDeselect({e,object:t})&&(this._currentTransform&&this._currentTransform.target===n&&this.endCurrentTransform(e),pt(n)&&n===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(e){let t=this.getActiveObjects(),n=this.getActiveObject();t.length&&this.fire(`before:selection:cleared`,{e,deselected:[n]});let r=this._discardActiveObject(e);return this._fireSelectionEvents(t,e),r}endCurrentTransform(e){let t=this._currentTransform;this._finalizeCurrentTransform(e),t&&t.target&&(t.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(e){let t=this._currentTransform,n=t.target,r={e,target:n,transform:t,action:t.action};n._scaling&&=!1,n.setCoords(),t.actionPerformed&&(this.fire(`object:modified`,r),n.fire(ye,r))}setViewportTransform(e){super.setViewportTransform(e);let t=this._activeObject;t&&t.setCoords()}destroy(){let e=this._activeObject;pt(e)&&(e.removeAll(),e.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(e){let t=this._activeObject;t&&t._renderControls(e)}_toObject(e,t,n){let r=this._realizeGroupTransformOnObject(e),i=super._toObject(e,t,n);return e.set(r),i}_realizeGroupTransformOnObject(e){let{group:t}=e;if(t&&pt(t)&&this._activeObject===t){let n=st(e,[`angle`,`flipX`,`flipY`,F,pe,me,he,ge,`top`]);return Ft(e,t.calcOwnMatrix()),n}return{}}_setSVGObject(e,t,n){let r=this._realizeGroupTransformOnObject(t);super._setSVGObject(e,t,n),t.set(r)}};p(wo,`ownDefaults`,{uniformScaling:!0,uniScaleKey:`shiftKey`,centeredScaling:!1,centeredRotation:!1,centeredKey:`altKey`,altActionKey:`shiftKey`,selection:!0,selectionKey:`shiftKey`,selectionColor:`rgba(100, 100, 255, 0.3)`,selectionDashArray:[],selectionBorderColor:`rgba(255, 255, 255, 0.3)`,selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:`move`,moveCursor:`move`,defaultCursor:`default`,freeDrawingCursor:`crosshair`,notAllowedCursor:`not-allowed`,perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!0,fireRightClick:!0,fireMiddleClick:!0,enablePointerEvents:!1,containerClass:`canvas-container`,preserveObjectStacking:!0});var To=class{constructor(e){p(this,`targets`,[]),p(this,`__disposer`,void 0);let t=()=>{let{hiddenTextarea:t}=e.getActiveObject()||{};t&&t.focus()},n=e.upperCanvasEl;n.addEventListener(`click`,t),this.__disposer=()=>n.removeEventListener(`click`,t)}exitTextEditing(){this.target=void 0,this.targets.forEach(e=>{e.isEditing&&e.exitEditing()})}add(e){this.targets.push(e)}remove(e){this.unregister(e),we(this.targets,e)}register(e){this.target=e}unregister(e){e===this.target&&(this.target=void 0)}onMouseMove(e){var t;(t=this.target)!=null&&t.isEditing&&this.target.updateSelectionOnMouseMove(e)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}},Eo={passive:!1},Do=(e,t)=>({viewportPoint:e.getViewportPoint(t),scenePoint:e.getScenePoint(t)}),Oo=(e,...t)=>e.addEventListener(...t),ko=(e,...t)=>e.removeEventListener(...t),Ao={mouse:{in:`over`,out:`out`,targetIn:`mouseover`,targetOut:`mouseout`,canvasIn:`mouse:over`,canvasOut:`mouse:out`},drag:{in:`enter`,out:`leave`,targetIn:`dragenter`,targetOut:`dragleave`,canvasIn:`drag:enter`,canvasOut:`drag:leave`}},jo=class extends wo{constructor(e,t={}){super(e,t),p(this,`_isClick`,void 0),p(this,`textEditingManager`,new To(this)),[`_onMouseDown`,`_onTouchStart`,`_onMouseMove`,`_onMouseUp`,`_onTouchEnd`,`_onResize`,`_onMouseWheel`,`_onMouseOut`,`_onMouseEnter`,`_onContextMenu`,`_onClick`,`_onDragStart`,`_onDragEnd`,`_onDragProgress`,`_onDragOver`,`_onDragEnter`,`_onDragLeave`,`_onDrop`].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(Oo)}_getEventPrefix(){return this.enablePointerEvents?`pointer`:`mouse`}addOrRemove(e,t=!1){let n=this.upperCanvasEl,r=this._getEventPrefix();e(gt(n),`resize`,this._onResize),e(n,r+`down`,this._onMouseDown),e(n,`${r}move`,this._onMouseMove,Eo),e(n,`${r}out`,this._onMouseOut),e(n,`${r}enter`,this._onMouseEnter),e(n,`wheel`,this._onMouseWheel,{passive:!1}),e(n,`contextmenu`,this._onContextMenu),t||(e(n,`click`,this._onClick),e(n,`dblclick`,this._onClick)),e(n,`dragstart`,this._onDragStart),e(n,`dragend`,this._onDragEnd),e(n,`dragover`,this._onDragOver),e(n,`dragenter`,this._onDragEnter),e(n,`dragleave`,this._onDragLeave),e(n,`drop`,this._onDrop),this.enablePointerEvents||e(n,`touchstart`,this._onTouchStart,Eo)}removeListeners(){this.addOrRemove(ko);let e=this._getEventPrefix(),t=ht(this.upperCanvasEl);ko(t,`${e}up`,this._onMouseUp),ko(t,`touchend`,this._onTouchEnd,Eo),ko(t,`${e}move`,this._onMouseMove,Eo),ko(t,`touchmove`,this._onMouseMove,Eo),clearTimeout(this._willAddMouseDown)}_onMouseWheel(e){this._cacheTransformEventData(e),this._handleEvent(e,`wheel`),this._resetTransformEventData()}_onMouseOut(e){let t=this._hoveredTarget,n={e,...Do(this,e)};this.fire(`mouse:out`,{...n,target:t}),this._hoveredTarget=void 0,t&&t.fire(`mouseout`,{...n}),this._hoveredTargets.forEach(e=>{this.fire(`mouse:out`,{...n,target:e}),e&&e.fire(`mouseout`,{...n})}),this._hoveredTargets=[]}_onMouseEnter(e){let{target:t}=this.findTarget(e);this._currentTransform||t||(this.fire(`mouse:over`,{e,...Do(this,e)}),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(e){this._isClick=!1;let t=this.getActiveObject();if(t&&t.onDragStart(e)){this._dragSource=t;let n={e,target:t};this.fire(`dragstart`,n),t.fire(`dragstart`,n),Oo(this.upperCanvasEl,`drag`,this._onDragProgress);return}Mt(e)}_renderDragEffects(e,t,n){let r=!1,i=this._dropTarget;i&&i!==t&&i!==n&&(i.clearContextTop(),r=!0),t?.clearContextTop(),n!==t&&n?.clearContextTop();let a=this.contextTop;a.save(),a.transform(...this.viewportTransform),t&&(a.save(),t.transform(a),t.renderDragSourceEffect(e),a.restore(),r=!0),n&&(a.save(),n.transform(a),n.renderDropTargetEffect(e),a.restore(),r=!0),a.restore(),r&&(this.contextTopDirty=!0)}_onDragEnd(e){let{currentSubTargets:t}=this.findTarget(e),n=!!e.dataTransfer&&e.dataTransfer.dropEffect!==`none`,r=n?this._activeObject:void 0,i={e,target:this._dragSource,subTargets:t,dragSource:this._dragSource,didDrop:n,dropTarget:r};ko(this.upperCanvasEl,`drag`,this._onDragProgress),this.fire(`dragend`,i),this._dragSource&&this._dragSource.fire(`dragend`,i),delete this._dragSource,this._onMouseUp(e)}_onDragProgress(e){let t={e,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire(`drag`,t),this._dragSource&&this._dragSource.fire(`drag`,t)}_onDragOver(e){let t=`dragover`,{currentContainer:n,currentSubTargets:r}=this.findTarget(e),i=this._dragSource,a={e,target:n,subTargets:r,dragSource:i,canDrop:!1,dropTarget:void 0},o;this.fire(t,a),this._fireEnterLeaveEvents(e,n,a),n&&(n.canDrop(e)&&(o=n),n.fire(t,a));for(let n=0;n<r.length;n++){let i=r[n];i.canDrop(e)&&(o=i),i.fire(t,a)}this._renderDragEffects(e,i,o),this._dropTarget=o}_onDragEnter(e){let{currentContainer:t,currentSubTargets:n}=this.findTarget(e),r={e,target:t,subTargets:n,dragSource:this._dragSource};this.fire(`dragenter`,r),this._fireEnterLeaveEvents(e,t,r)}_onDragLeave(e){let{currentSubTargets:t}=this.findTarget(e),n={e,target:this._draggedoverTarget,subTargets:t,dragSource:this._dragSource};this.fire(`dragleave`,n),this._fireEnterLeaveEvents(e,void 0,n),this._renderDragEffects(e,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(e){let{currentContainer:t,currentSubTargets:n}=this.findTarget(e),r=this._basicEventHandler(`drop:before`,{e,target:t,subTargets:n,dragSource:this._dragSource,...Do(this,e)});r.didDrop=!1,r.dropTarget=void 0,this._basicEventHandler(`drop`,r),this.fire(`drop:after`,r)}_onContextMenu(e){let{target:t,subTargets:n}=this.findTarget(e),r=this._basicEventHandler(`contextmenu:before`,{e,target:t,subTargets:n});return this.stopContextMenu&&Mt(e),this._basicEventHandler(`contextmenu`,r),!1}_onClick(e){let t=e.detail;t>3||t<2||(this._cacheTransformEventData(e),t==2&&e.type===`dblclick`&&this._handleEvent(e,`dblclick`),t==3&&this._handleEvent(e,`tripleclick`),this._resetTransformEventData())}fireEventFromPointerEvent(e,t,n,r={}){this._cacheTransformEventData(e);let{target:i,subTargets:a}=this.findTarget(e),o={e,target:i,subTargets:a,...Do(this,e),transform:this._currentTransform,...r};this.fire(t,o),i&&i.fire(n,o);for(let e=0;e<a.length;e++)a[e]!==i&&a[e].fire(n,o);this._resetTransformEventData()}getPointerId(e){let t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1}_isMainEvent(e){return!0===e.isPrimary||!1!==e.isPrimary&&(e.type===`touchend`&&e.touches.length===0||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(e){this._cacheTransformEventData(e);let t=!this.allowTouchScrolling,n=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(e)),this.__onMouseDown(e);let{target:r}=this.findTarget(e);(this.isDrawingMode||n&&r===n)&&(t=!0),t&&e.preventDefault();let i=this.upperCanvasEl,a=this._getEventPrefix(),o=ht(i);Oo(o,`touchend`,this._onTouchEnd,Eo),t&&Oo(o,`touchmove`,this._onMouseMove,Eo),ko(i,`${a}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(e){this._cacheTransformEventData(e),this.__onMouseDown(e);let t=this.upperCanvasEl,n=this._getEventPrefix();ko(t,`${n}move`,this._onMouseMove,Eo);let r=ht(t);Oo(r,`${n}up`,this._onMouseUp),Oo(r,`${n}move`,this._onMouseMove,Eo),this._resetTransformEventData()}_onTouchEnd(e){if(e.touches.length>0)return;this._cacheTransformEventData(e),this.__onMouseUp(e),this._resetTransformEventData(),delete this.mainTouchId;let t=this._getEventPrefix(),n=ht(this.upperCanvasEl);ko(n,`touchend`,this._onTouchEnd,Eo),ko(n,`touchmove`,this._onMouseMove,Eo),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{Oo(this.upperCanvasEl,`${t}down`,this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(e){this._cacheTransformEventData(e),this.__onMouseUp(e);let t=this.upperCanvasEl,n=this._getEventPrefix();if(this._isMainEvent(e)){let e=ht(this.upperCanvasEl);ko(e,`${n}up`,this._onMouseUp),ko(e,`${n}move`,this._onMouseMove,Eo),Oo(t,`${n}move`,this._onMouseMove,Eo)}this._resetTransformEventData()}_onMouseMove(e){this._cacheTransformEventData(e);let t=this.getActiveObject();!this.allowTouchScrolling&&(!t||!t.shouldStartDragging(e))&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e),this._resetTransformEventData()}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(e){let t=this.getActiveObject();return!!t!=!!e||t&&e&&t!==e}__onMouseUp(e){var t;this._handleEvent(e,`up:before`);let n=this._currentTransform,r=this._isClick,{target:i}=this.findTarget(e),{button:a}=e;if(a)return void((this.fireMiddleClick&&a===1||this.fireRightClick&&a===2)&&this._handleEvent(e,`up`));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(e);if(!this._isMainEvent(e))return;let o,s,c=!1;if(n&&(this._finalizeCurrentTransform(e),c=n.actionPerformed),!r){let t=i===this._activeObject;this.handleSelection(e),c||=this._shouldRender(i)||!t&&i===this._activeObject}if(i){let{key:t,control:r}=i.findControl(this.getViewportPoint(e),jt(e))||{};if(s=t,i.selectable&&i!==this._activeObject&&i.activeOn===`up`)this.setActiveObject(i,e),c=!0;else if(r){let t=r.getMouseUpHandler(e,i,r);t&&(o=this.getScenePoint(e),t.call(r,e,n,o.x,o.y))}i.isMoving=!1}if(n&&(n.target!==i||n.corner!==s)){let t=n.target&&n.target.controls[n.corner],r=t&&t.getMouseUpHandler(e,n.target,t);o||=this.getScenePoint(e),r&&r.call(t,e,n,o.x,o.y)}this._setCursorFromEvent(e,i),this._handleEvent(e,`up`),this._groupSelector=null,this._currentTransform=null,i&&(i.__corner=void 0),c?this.requestRenderAll():r||(t=this._activeObject)!=null&&t.isEditing||this.renderTop()}_basicEventHandler(e,t){let{target:n,subTargets:r=[]}=t;this.fire(e,t),n&&n.fire(e,t);for(let i=0;i<r.length;i++)r[i]!==n&&r[i].fire(e,t);return t}_handleEvent(e,t,n){let{target:r,subTargets:i}=this.findTarget(e),a={e,target:r,subTargets:i,...Do(this,e),transform:this._currentTransform,...t===`down:before`||t===`down`?n:{}};t!==`up:before`&&t!==`up`||(a.isClick=this._isClick),this.fire(`mouse:${t}`,a),r&&r.fire(`mouse${t}`,a);for(let e=0;e<i.length;e++)i[e]!==r&&i[e].fire(`mouse${t}`,a)}_onMouseDownInDrawingMode(e){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(e),this.requestRenderAll());let t=this.getScenePoint(e);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(t,{e,pointer:t}),this._handleEvent(e,`down`,{alreadySelected:!1})}_onMouseMoveInDrawingMode(e){if(this._isCurrentlyDrawing){let t=this.getScenePoint(e);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(t,{e,pointer:t})}this.setCursor(this.freeDrawingCursor),this._handleEvent(e,`move`)}_onMouseUpInDrawingMode(e){let t=this.getScenePoint(e);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e,pointer:t}):this._isCurrentlyDrawing=!1,this._handleEvent(e,`up`)}__onMouseDown(e){this._isClick=!0,this._handleEvent(e,`down:before`);let{target:t}=this.findTarget(e),n=!!t&&t===this._activeObject,{button:r}=e;if(r)return void((this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(e,`down`,{alreadySelected:n}));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(e);if(!this._isMainEvent(e)||this._currentTransform)return;let i=this._shouldRender(t),a=!1;if(this.handleMultiSelection(e,t)?(t=this._activeObject,a=!0,i=!0):this._shouldClearSelection(e,t)&&this.discardActiveObject(e),this.selection&&(!t||!t.selectable&&!t.isEditing&&t!==this._activeObject)){let t=this.getScenePoint(e);this._groupSelector={x:t.x,y:t.y,deltaY:0,deltaX:0}}if(n=!!t&&t===this._activeObject,t){t.selectable&&t.activeOn===`down`&&this.setActiveObject(t,e);let r=t.findControl(this.getViewportPoint(e),jt(e));if(t===this._activeObject&&(r||!a)){this._setupCurrentTransform(e,t,n);let i=r?r.control:void 0,a=this.getScenePoint(e),o=i&&i.getMouseDownHandler(e,t,i);o&&o.call(i,e,this._currentTransform,a.x,a.y)}}i&&(this._objectsToRender=void 0),this._handleEvent(e,`down`,{alreadySelected:n}),i&&this.requestRenderAll()}_resetTransformEventData(){this._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(e){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(e),this._scenePoint=Vt(this._viewportPoint,void 0,this.viewportTransform),this._targetInfo=this.findTarget(e),this._currentTransform&&(this._targetInfo.target=this._currentTransform.target)}__onMouseMove(e){if(this._isClick=!1,this._handleEvent(e,`move:before`),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(e);if(!this._isMainEvent(e))return;let t=this._groupSelector;if(t){let n=this.getScenePoint(e);t.deltaX=n.x-t.x,t.deltaY=n.y-t.y,this.renderTop()}else if(this._currentTransform)this._transformObject(e);else{let{target:t}=this.findTarget(e);this._setCursorFromEvent(e,t),this._fireOverOutEvents(e,t)}this.textEditingManager.onMouseMove(e),this._handleEvent(e,`move`)}_fireOverOutEvents(e,t){let{_hoveredTarget:n,_hoveredTargets:r}=this,{subTargets:i,currentTarget:a}=this.findTarget(e),o=Math.max(r.length,i.length);this.fireSyntheticInOutEvents(`mouse`,{e,target:t,oldTarget:n,actualTarget:a,oldActualTarget:this._hoveredActualTarget,fireCanvas:!0});for(let a=0;a<o;a++)i[a]===t||r[a]&&r[a]===n||this.fireSyntheticInOutEvents(`mouse`,{e,target:i[a],oldTarget:r[a]});this._hoveredActualTarget=a,this._hoveredTarget=t,this._hoveredTargets=i}_fireEnterLeaveEvents(e,t,n){let r=this._draggedoverTarget,i=this._hoveredTargets,{subTargets:a}=this.findTarget(e),o=Math.max(i.length,a.length);this.fireSyntheticInOutEvents(`drag`,{...n,target:t,oldTarget:r,fireCanvas:!0});for(let e=0;e<o;e++)this.fireSyntheticInOutEvents(`drag`,{...n,target:a[e],oldTarget:i[e]});this._draggedoverTarget=t}fireSyntheticInOutEvents(e,{target:t,oldTarget:n,actualTarget:r,oldActualTarget:i,fireCanvas:a,e:o,...s}){let{targetIn:c,targetOut:l,canvasIn:u,canvasOut:d}=Ao[e],f=n!==t,p=i!==r,m=t&&f,h=r&&p,g=n&&f,_=i&&p,v={...s,e:o,...Do(this,o)},y={...v,target:n,nextTarget:t,actualTarget:i,nextActualTarget:r};(g||_)&&a&&this.fire(d,y),g&&n.fire(l,y),_&&n!==i&&i.fire(l,y);let b={...v,target:t,previousTarget:n,actualTarget:r,previousActualTarget:i};(m||h)&&a&&this.fire(u,b),m&&t.fire(c,b),h&&r!==t&&r.fire(c,b)}_transformObject(e){let t=this.getScenePoint(e),n=this._currentTransform,r=n.target,i=r.group?Vt(t,void 0,r.group.calcTransformMatrix()):t;n.shiftKey=e.shiftKey,n.altKey=!!this.centeredKey&&e[this.centeredKey],this._performTransformAction(e,n,i),n.actionPerformed&&this.requestRenderAll()}_performTransformAction(e,t,n){let{action:r,actionHandler:i,target:a}=t,o=!!i&&i(e,t,n.x,n.y);o&&a.setCoords(),r===`drag`&&o&&(t.target.isMoving=!0,this.setCursor(t.target.moveCursor||this.moveCursor)),t.actionPerformed=t.actionPerformed||o}_setCursorFromEvent(e,t){if(!t)return void this.setCursor(this.defaultCursor);let n=t.hoverCursor||this.hoverCursor,r=pt(this._activeObject)?this._activeObject:null,i=(!r||t.group!==r)&&t.findControl(this.getViewportPoint(e));if(i){let{control:n,coord:r}=i;this.setCursor(n.cursorStyleHandler(e,n,t,r))}else{if(t.subTargetCheck){let{subTargets:t}=this.findTarget(e);t.concat().reverse().forEach(e=>{n=e.hoverCursor||n})}this.setCursor(n)}}handleMultiSelection(e,t){let n=this._activeObject,r=pt(n);if(n&&this._isSelectionKeyPressed(e)&&this.selection&&t&&t.selectable&&(n!==t||r)&&(r||!t.isDescendantOf(n)&&!n.isDescendantOf(t))&&!t.onSelect({e})&&!n.getActiveControl()){if(r){let r=n.getObjects(),i=[];if(t===n){let n=this.getScenePoint(e),a=this.searchPossibleTargets(r,n);if(a.target?(t=a.target,i=a.subTargets):(a=this.searchPossibleTargets(this._objects,n),t=a.target,i=a.subTargets),!t||!t.selectable)return!1}t.group===n?(n.remove(t),this._hoveredTarget=t,this._hoveredTargets=i,n.size()===1&&this._setActiveObject(n.item(0),e)):(n.multiSelectAdd(t),this._hoveredTarget=n,this._hoveredTargets=i),this._fireSelectionEvents(r,e)}else{n.isEditing&&n.exitEditing();let r=new(L.getClass(`ActiveSelection`))([],{canvas:this});r.multiSelectAdd(n,t),this._hoveredTarget=r,this._setActiveObject(r,e),this._fireSelectionEvents([n],e)}return!0}return!1}handleSelection(e){if(!this.selection||!this._groupSelector)return!1;let{x:t,y:n,deltaX:r,deltaY:i}=this._groupSelector,a=new R(t,n),o=a.add(new R(r,i)),s=a.min(o),c=a.max(o).subtract(s),l=this.collectObjects({left:s.x,top:s.y,width:c.x,height:c.y},{includeIntersecting:!this.selectionFullyContained}),u=a.eq(o)?l[0]?[l[0]]:[]:l.length>1?l.filter(t=>!t.onSelect({e})).reverse():l;if(u.length===1)this.setActiveObject(u[0],e);else if(u.length>1){let t=L.getClass(`ActiveSelection`);this.setActiveObject(new t(u,{canvas:this}),e)}return this._groupSelector=null,!0}toCanvasElement(e=1,t){let{upper:n}=this.elements;n.ctx=void 0;let r=super.toCanvasElement(e,t);return n.ctx=n.el.getContext(`2d`),r}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}},Mo={x1:0,y1:0,x2:0,y2:0},No={...Mo,r1:0,r2:0},Po=(e,t)=>isNaN(e)&&typeof t==`number`?t:e;function Fo(e){return e&&/%$/.test(e)&&Number.isFinite(parseFloat(e))}function Io(e,t){return $n(0,Po(typeof e==`number`?e:typeof e==`string`?parseFloat(e)/(Fo(e)?100:1):NaN,t),1)}var Lo=/\s*;\s*/,Ro=/\s*:\s*/;function zo(e,t){let n,r,i=e.getAttribute(`style`);if(i){let e=i.split(Lo);e[e.length-1]===``&&e.pop();for(let t=e.length;t--;){let[i,a]=e[t].split(Ro).map(e=>e.trim());i===`stop-color`?n=a:i===`stop-opacity`&&(r=a)}}n=n||e.getAttribute(`stop-color`)||`rgb(0,0,0)`,r=Po(parseFloat(r||e.getAttribute(`stop-opacity`)||``),1);let a=new Cn(n);return a.setAlpha(a.getAlpha()*r*t),{offset:Io(e.getAttribute(`offset`),0),color:a.toRgba()}}function Bo(e,t){let n=[],r=e.getElementsByTagName(`stop`),i=Io(t,1);for(let e=r.length;e--;)n.push(zo(r[e],i));return n}function Vo(e){return e.nodeName===`linearGradient`||e.nodeName===`LINEARGRADIENT`?`linear`:`radial`}function Ho(e){return e.getAttribute(`gradientUnits`)===`userSpaceOnUse`?`pixels`:`percentage`}function Uo(e,t){return e.getAttribute(t)}function Wo(e,t){return function(e,{width:t,height:n,gradientUnits:r}){let i;return Object.entries(e).reduce((e,[a,o])=>{if(o===`Infinity`)i=1;else if(o===`-Infinity`)i=0;else{let e=typeof o==`string`;i=e?parseFloat(o):o,e&&Fo(o)&&(i*=.01,r===`pixels`&&(a!==`x1`&&a!==`x2`&&a!==`r2`||(i*=t),a!==`y1`&&a!==`y2`||(i*=n)))}return e[a]=i,e},{})}(Vo(e)===`linear`?function(e){return{x1:Uo(e,`x1`)||0,y1:Uo(e,`y1`)||0,x2:Uo(e,`x2`)||`100%`,y2:Uo(e,`y2`)||0}}(e):function(e){return{x1:Uo(e,`fx`)||Uo(e,`cx`)||`50%`,y1:Uo(e,`fy`)||Uo(e,`cy`)||`50%`,r1:0,x2:Uo(e,`cx`)||`50%`,y2:Uo(e,`cy`)||`50%`,r2:Uo(e,`r`)||`50%`}}(e),{...t,gradientUnits:Ho(e)})}var Go=class{constructor(e){let{type:t=`linear`,gradientUnits:n=`pixels`,coords:r={},colorStops:i=[],offsetX:a=0,offsetY:o=0,gradientTransform:s,id:c}=e||{};Object.assign(this,{type:t,gradientUnits:n,coords:{...t===`radial`?No:Mo,...r},colorStops:i,offsetX:a,offsetY:o,gradientTransform:s,id:c?`${c}_${Pe()}`:Pe()})}addColorStop(e){for(let t in e)this.colorStops.push({offset:parseFloat(t),color:e[t]});return this}toObject(e){return{...st(this,e),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map(e=>({...e})),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0}}toSVG(e,{additionalTransform:t}={}){let n=[],r=this.gradientTransform?this.gradientTransform.concat():N.concat(),i=this.gradientUnits===`pixels`?`userSpaceOnUse`:`objectBoundingBox`,a=this.colorStops.map(e=>({...e})).sort((e,t)=>e.offset-t.offset),o=-this.offsetX,s=-this.offsetY;var c;i===`objectBoundingBox`?(o/=e.width,s/=e.height):(o+=e.width/2,s+=e.height/2),(c=e)&&typeof c._renderPathCommands==`function`&&this.gradientUnits!==`percentage`&&(o-=e.pathOffset.x,s-=e.pathOffset.y),r[4]-=o,r[5]-=s;let l=[`id="SVGID_${H(String(this.id))}"`,`gradientUnits="${i}"`,`gradientTransform="${t?t+` `:``}${lt(r)}"`,``].join(` `),u=e=>parseFloat(String(e));if(this.type===`linear`){let{x1:e,y1:t,x2:r,y2:i}=this.coords,a=u(e),o=u(t),s=u(r),c=u(i);n.push(`<linearGradient `,l,` x1="`,a,`" y1="`,o,`" x2="`,s,`" y2="`,c,`">
|
|
17
|
+
`),t}getSvgStyles(){let e=this.opacity!==void 0&&this.opacity!==1?`opacity: ${H(this.opacity)};`:``,t=this.visible?``:` visibility: hidden;`;return[e,this.getSvgFilter(),t].join(``)}toClipPathSVG(e){let t=[],n=this._createSVGBgRect(e);n&&t.push(` `,n);for(let n=0;n<this._objects.length;n++)t.push(` `,this._objects[n].toClipPathSVG(e));return this._createBaseClipPathSVGMarkup(t,{reviver:e})}static fromObject({type:e,objects:t=[],layoutManager:n,...r},i){return Promise.all([at(t,i),ot(r,i)]).then(([e,t])=>{let i=new this(e,{...r,...t,layoutManager:new Sa});return i.layoutManager=n?new(L.getClass(n.type))(new(L.getClass(n.strategy))):new xa,i.layoutManager.subscribeTargets({type:ha,target:i,targets:i.getObjects()}),i.setCoords(),i})}};p(Ca,`type`,`Group`),p(Ca,`ownDefaults`,{strokeWidth:0,subTargetCheck:!1,interactive:!1}),L.setClass(Ca);var wa=(e,t)=>e&&e.length===1?e[0]:new Ca(e,t),Ta=(e,t)=>Math.min(t.width/e.width,t.height/e.height),Ea=(e,t)=>Math.max(t.width/e.width,t.height/e.height),Da=`\\s*,?\\s*`,Oa=`${Da}(${zn})`,ka=`${Oa}${Oa}${Oa}${Da}([01])${Da}([01])${Oa}${Oa}`,Aa={m:`l`,M:`L`},ja=(e,t,n,r,i,a,o,s,c,l,u)=>{let d=Te(e),f=Ee(e),p=Te(t),m=Ee(t),h=n*i*p-r*a*m+o,g=r*i*p+n*a*m+s;return[`C`,l+c*(-n*i*f-r*a*d),u+c*(-r*i*f+n*a*d),h+c*(n*i*m+r*a*p),g+c*(r*i*m-n*a*p),h,g]},Ma=(e,t,n,r)=>{let i=Math.atan2(t,e),a=Math.atan2(r,n);return a>=i?a-i:2*Math.PI-(i-a)};function Na(e,t,n,r,i,a,o,s){let c;if(h.cachesBoundsOfCurve&&(c=[...arguments].join(),D.boundsOfCurveCache[c]))return D.boundsOfCurveCache[c];let l=Math.sqrt,u=Math.abs,d=[],f=[[0,0],[0,0]],p=6*e-12*n+6*i,m=-3*e+9*n-9*i+3*o,g=3*n-3*e;for(let e=0;e<2;++e){if(e>0&&(p=6*t-12*r+6*a,m=-3*t+9*r-9*a+3*s,g=3*r-3*t),u(m)<1e-12){if(u(p)<1e-12)continue;let e=-g/p;0<e&&e<1&&d.push(e);continue}let n=p*p-4*g*m;if(n<0)continue;let i=l(n),o=(-p+i)/(2*m);0<o&&o<1&&d.push(o);let c=(-p-i)/(2*m);0<c&&c<1&&d.push(c)}let _=d.length,v=_,y=La(e,t,n,r,i,a,o,s);for(;_--;){let{x:e,y:t}=y(d[_]);f[0][_]=e,f[1][_]=t}f[0][v]=e,f[1][v]=t,f[0][v+1]=o,f[1][v+1]=s;let b=[new R(Math.min(...f[0]),Math.min(...f[1])),new R(Math.max(...f[0]),Math.max(...f[1]))];return h.cachesBoundsOfCurve&&(D.boundsOfCurveCache[c]=b),b}var Pa=(e,t,[n,r,i,a,o,s,c,l])=>{let u=((e,t,n,r,i,a,o)=>{if(n===0||r===0)return[];let s=0,c=0,l=0,u=Math.PI,d=o*ee,f=Ee(d),p=Te(d),m=.5*(-p*e-f*t),h=.5*(-p*t+f*e),g=n**2,_=r**2,v=h**2,y=m**2,b=g*_-g*v-_*y,x=Math.abs(n),S=Math.abs(r);if(b<0){let e=Math.sqrt(1-b/(g*_));x*=e,S*=e}else l=(i===a?-1:1)*Math.sqrt(b/(g*v+_*y));let C=l*x*h/S,w=-l*S*m/x,T=p*C-f*w+.5*e,E=f*C+p*w+.5*t,D=Ma(1,0,(m-C)/x,(h-w)/S),O=Ma((m-C)/x,(h-w)/S,(-m-C)/x,(-h-w)/S);a===0&&O>0?O-=2*u:a===1&&O<0&&(O+=2*u);let k=Math.ceil(Math.abs(O/u*2)),A=[],j=O/k,M=8/3*Math.sin(j/4)*Math.sin(j/4)/Math.sin(j/2),N=D+j;for(let e=0;e<k;e++)A[e]=ja(D,N,p,f,x,S,T,E,M,s,c),s=A[e][5],c=A[e][6],D=N,N+=j;return A})(c-e,l-t,r,i,o,s,a);for(let n=0,r=u.length;n<r;n++)u[n][1]+=e,u[n][2]+=t,u[n][3]+=e,u[n][4]+=t,u[n][5]+=e,u[n][6]+=t;return u},Fa=e=>{let t=0,n=0,r=0,i=0,a=[],o,s=0,c=0;for(let l of e){let e=[...l],u;switch(e[0]){case`l`:e[1]+=t,e[2]+=n;case`L`:t=e[1],n=e[2],u=[`L`,t,n];break;case`h`:e[1]+=t;case`H`:t=e[1],u=[`L`,t,n];break;case`v`:e[1]+=n;case`V`:n=e[1],u=[`L`,t,n];break;case`m`:e[1]+=t,e[2]+=n;case`M`:t=e[1],n=e[2],r=e[1],i=e[2],u=[`M`,t,n];break;case`c`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n,e[5]+=t,e[6]+=n;case`C`:s=e[3],c=e[4],t=e[5],n=e[6],u=[`C`,e[1],e[2],s,c,t,n];break;case`s`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n;case`S`:o===`C`?(s=2*t-s,c=2*n-c):(s=t,c=n),t=e[3],n=e[4],u=[`C`,s,c,e[1],e[2],t,n],s=u[3],c=u[4];break;case`q`:e[1]+=t,e[2]+=n,e[3]+=t,e[4]+=n;case`Q`:s=e[1],c=e[2],t=e[3],n=e[4],u=[`Q`,s,c,t,n];break;case`t`:e[1]+=t,e[2]+=n;case`T`:o===`Q`?(s=2*t-s,c=2*n-c):(s=t,c=n),t=e[1],n=e[2],u=[`Q`,s,c,t,n];break;case`a`:e[6]+=t,e[7]+=n;case`A`:Pa(t,n,e).forEach(e=>a.push(e)),t=e[6],n=e[7];break;case`z`:case`Z`:t=r,n=i,u=[`Z`]}u?(a.push(u),o=u[0]):o=``}return a},Ia=(e,t,n,r)=>Math.sqrt((n-e)**2+(r-t)**2),La=(e,t,n,r,i,a,o,s)=>c=>{let l=c**3,u=(e=>3*e**2*(1-e))(c),d=(e=>3*e*(1-e)**2)(c),f=(e=>(1-e)**3)(c);return new R(o*l+i*u+n*d+e*f,s*l+a*u+r*d+t*f)},Ra=e=>e**2,za=e=>2*e*(1-e),Ba=e=>(1-e)**2,Va=(e,t,n,r,i,a,o,s)=>c=>{let l=Ra(c),u=za(c),d=Ba(c),f=3*(d*(n-e)+u*(i-n)+l*(o-i)),p=3*(d*(r-t)+u*(a-r)+l*(s-a));return Math.atan2(p,f)},Ha=(e,t,n,r,i,a)=>o=>{let s=Ra(o),c=za(o),l=Ba(o);return new R(i*s+n*c+e*l,a*s+r*c+t*l)},Ua=(e,t,n,r,i,a)=>o=>{let s=1-o,c=2*(s*(n-e)+o*(i-n)),l=2*(s*(r-t)+o*(a-r));return Math.atan2(l,c)},Wa=(e,t,n)=>{let r=new R(t,n),i=0;for(let t=1;t<=100;t+=1){let n=e(t/100);i+=Ia(r.x,r.y,n.x,n.y),r=n}return i},Ga=(e,t)=>{let n,r=0,i=0,a={x:e.x,y:e.y},o={...a},s=.01,c=0,l=e.iterator,u=e.angleFinder;for(;i<t&&s>1e-4;)o=l(r),c=r,n=Ia(a.x,a.y,o.x,o.y),n+i>t?(r-=s,s/=2):(a=o,r+=s,i+=n);return{...o,angle:u(c)}},Ka=e=>{let t,n,r=0,i=0,a=0,o=0,s=0,c=[];for(let l of e){let e={x:i,y:a,command:l[0],length:0};switch(l[0]){case`M`:n=e,n.x=o=i=l[1],n.y=s=a=l[2];break;case`L`:n=e,n.length=Ia(i,a,l[1],l[2]),i=l[1],a=l[2];break;case`C`:t=La(i,a,l[1],l[2],l[3],l[4],l[5],l[6]),n=e,n.iterator=t,n.angleFinder=Va(i,a,l[1],l[2],l[3],l[4],l[5],l[6]),n.length=Wa(t,i,a),i=l[5],a=l[6];break;case`Q`:t=Ha(i,a,l[1],l[2],l[3],l[4]),n=e,n.iterator=t,n.angleFinder=Ua(i,a,l[1],l[2],l[3],l[4]),n.length=Wa(t,i,a),i=l[3],a=l[4];break;case`Z`:n=e,n.destX=o,n.destY=s,n.length=Ia(i,a,o,s),i=o,a=s}r+=n.length,c.push(n)}return c.push({length:r,x:i,y:a}),c},qa=(e,t,n=Ka(e))=>{let r=0;for(;t-n[r].length>0&&r<n.length-2;)t-=n[r].length,r++;let i=n[r],a=t/i.length,o=e[r];switch(i.command){case`M`:return{x:i.x,y:i.y,angle:0};case`Z`:return{...new R(i.x,i.y).lerp(new R(i.destX,i.destY),a),angle:Math.atan2(i.destY-i.y,i.destX-i.x)};case`L`:return{...new R(i.x,i.y).lerp(new R(o[1],o[2]),a),angle:Math.atan2(o[2]-i.y,o[1]-i.x)};case`C`:case`Q`:return Ga(i,t)}},Ja=RegExp(`[mzlhvcsqta][^mzlhvcsqta]*`,`gi`),Ya=new RegExp(ka,`g`),Xa=new RegExp(zn,`gi`),Za={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Qa=e=>{let t=[],n=e.match(Ja)??[];for(let e of n){let n=e[0];if(n===`z`||n===`Z`){t.push([n]);continue}let r=Za[n.toLowerCase()],i=[];if(n===`a`||n===`A`){let t;for(Ya.lastIndex=0;t=Ya.exec(e);)i.push(...t.slice(1))}else i=e.match(Xa)||[];for(let e=0;e<i.length;e+=r){let a=Array(r),o=Aa[n];a[0]=e>0&&o?o:n;for(let t=0;t<r;t++)a[t+1]=parseFloat(i[e+t]);t.push(a)}}return t},$a=(e,t=0)=>{let n=new R(e[0]),r=new R(e[1]),i=1,a=0,o=[],s=e.length,c=s>2,l;for(c&&(i=e[2].x<r.x?-1:e[2].x===r.x?0:1,a=e[2].y<r.y?-1:e[2].y===r.y?0:1),o.push([`M`,n.x-i*t,n.y-a*t]),l=1;l<s;l++){if(!n.eq(r)){let e=n.midPointFrom(r);o.push([`Q`,n.x,n.y,e.x,e.y])}n=e[l],l+1<e.length&&(r=e[l+1])}return c&&(i=n.x>e[l-2].x?1:n.x===e[l-2].x?0:-1,a=n.y>e[l-2].y?1:n.y===e[l-2].y?0:-1),o.push([`L`,n.x+i*t,n.y+a*t]),o},eo=(e,t,n)=>(n&&(t=B(t,[1,0,0,1,-n.x,-n.y])),e.map(e=>{let n=[...e];for(let r=1;r<e.length-1;r+=2){let{x:i,y:a}=Ue({x:e[r],y:e[r+1]},t);n[r]=i,n[r+1]=a}return n})),to=(e,t)=>{let n=2*Math.PI/e,r=-A;e%2==0&&(r+=n/2);let i=Array(e+1);for(let a=0;a<e;a++){let e=a*n+r,{x:o,y:s}=new R(Te(e),Ee(e)).scalarMultiply(t);i[a]=[a===0?`M`:`L`,o,s]}return i[e]=[`Z`],i},no=(e,t)=>e.map(e=>e.map((e,n)=>n===0||t===void 0?e:V(e,t)).join(` `)).join(` `),ro=(e,t)=>{let n=e,r=t;n.inverted&&!r.inverted&&(n=t,r=e),Ut(r,r.group?.calcTransformMatrix(),n.calcTransformMatrix());let i=n.inverted&&r.inverted;return i&&(n.inverted=r.inverted=!1),new Ca([n],{clipPath:r,inverted:i})},io=(e,t)=>Math.floor(Math.random()*(t-e+1))+e,ao=(e,t)=>{let n=e._findCenterFromElement();e.transformMatrix&&((e=>{if(e.transformMatrix){let{scaleX:t,scaleY:n,angle:r,skewX:i}=Ye(e.transformMatrix);e.flipX=!1,e.flipY=!1,e.set(pe,t),e.set(me,n),e.angle=r,e.skewX=i,e.skewY=0}})(e),n=n.transform(e.transformMatrix)),delete e.transformMatrix,t&&(e.scaleX*=t.scaleX,e.scaleY*=t.scaleY,e.cropX=t.cropX,e.cropY=t.cropY,n.x+=t.offsetLeft,n.y+=t.offsetTop,e.width=t.width,e.height=t.height),e.setPositionByOrigin(n,P,P)},oo=u({addTransformToObject:()=>Ft,animate:()=>Wr,animateColor:()=>Gr,applyTransformToObject:()=>It,calcAngleBetweenVectors:()=>Zt,calcDimensionsMatrix:()=>nt,calcPlaneChangeMatrix:()=>Bt,calcVectorRotation:()=>Qt,cancelAnimFrame:()=>Me,capValue:()=>$n,composeMatrix:()=>rt,copyCanvasElement:()=>Le,cos:()=>Te,createCanvasElement:()=>Fe,createImage:()=>Ie,createRotateMatrix:()=>Ze,createScaleMatrix:()=>Qe,createSkewXMatrix:()=>et,createSkewYMatrix:()=>tt,createTranslateMatrix:()=>Xe,createVector:()=>Yt,crossProduct:()=>tn,degreesToRadians:()=>z,dotProduct:()=>nn,ease:()=>rr,enlivenObjectEnlivables:()=>ot,enlivenObjects:()=>at,findScaleToCover:()=>Ea,findScaleToFit:()=>Ta,getBoundsOfCurve:()=>Na,getOrthonormalVector:()=>en,getPathSegmentsInfo:()=>Ka,getPointOnPath:()=>qa,getPointer:()=>At,getRandomInt:()=>io,getRegularPolygonPath:()=>to,getSmoothPathFromPoints:()=>$a,getSvgAttributes:()=>wn,getUnitVector:()=>$t,groupSVGElements:()=>wa,hasStyleChanged:()=>Bi,invertTransform:()=>We,isBetweenVectors:()=>rn,isIdentityMatrix:()=>He,isTouchEvent:()=>jt,isTransparent:()=>Ni,joinPath:()=>no,loadImage:()=>it,magnitude:()=>Xt,makeBoundingBoxFromPoints:()=>Nt,makePathSimpler:()=>Fa,matrixToSVG:()=>lt,mergeClipPaths:()=>ro,multiplyTransformMatrices:()=>B,multiplyTransformMatrixArray:()=>Ge,parsePath:()=>Qa,parsePreserveAspectRatioAttribute:()=>En,parseUnit:()=>Tn,pick:()=>st,projectStrokeOnPoints:()=>Ri,qrDecompose:()=>Ye,radiansToDegrees:()=>Ve,removeFromArray:()=>we,removeTransformFromObject:()=>Pt,removeTransformMatrixForSvgParsing:()=>ao,requestAnimFrame:()=>je,resetObjectTransform:()=>Lt,rotateVector:()=>Jt,saveObjectTransform:()=>Rt,sendObjectToPlane:()=>Ut,sendPointToPlane:()=>Vt,sendVectorToPlane:()=>Ht,sin:()=>Ee,sizeAfterTransform:()=>zt,string:()=>St,stylesFromArray:()=>Hi,stylesToArray:()=>Vi,toBlob:()=>Be,toDataURL:()=>ze,toFixed:()=>V,transformPath:()=>eo,transformPoint:()=>Ue});function so(e,t){let n=e.style;n&&Object.entries(t).forEach(([e,t])=>n.setProperty(e,t))}var co=class extends bt{constructor(e,{allowTouchScrolling:t=!1,containerClass:n=``}={}){super(e),p(this,`upper`,void 0),p(this,`container`,void 0);let{el:r}=this.lower,i=this.createUpperCanvas();this.upper={el:i,ctx:i.getContext(`2d`)},this.applyCanvasStyle(r,{allowTouchScrolling:t}),this.applyCanvasStyle(i,{allowTouchScrolling:t,styles:{position:`absolute`,left:`0`,top:`0`}});let a=this.createContainerElement();a.classList.add(n),r.parentNode&&r.parentNode.replaceChild(a,r),a.append(r,i),this.container=a}createUpperCanvas(){let{el:e}=this.lower,t=Fe();return t.className=e.className,t.classList.remove(`lower-canvas`),t.classList.add(`upper-canvas`),t.setAttribute(`data-fabric`,`top`),t.style.cssText=e.style.cssText,t.setAttribute(`draggable`,`true`),t}createContainerElement(){let e=w().createElement(`div`);return e.setAttribute(`data-fabric`,`wrapper`),so(e,{position:`relative`}),yt(e),e}applyCanvasStyle(e,t){let{styles:n,allowTouchScrolling:r}=t;so(e,{...n,"touch-action":r?`manipulation`:ne}),yt(e)}setDimensions(e,t){super.setDimensions(e,t);let{el:n,ctx:r}=this.upper;_t(n,r,e,t)}setCSSDimensions(e){super.setCSSDimensions(e),vt(this.upper.el,e),vt(this.container,e)}cleanupDOM(e){let t=this.container,{el:n}=this.lower,{el:r}=this.upper;super.cleanupDOM(e),t.removeChild(r),t.removeChild(n),t.parentNode&&t.parentNode.replaceChild(n,t)}dispose(){super.dispose(),C().dispose(this.upper.el),delete this.upper,delete this.container}},lo=(e,t,n,r)=>{let{target:i,offsetX:a,offsetY:o}=t,s=n-a,c=r-o,l=!cn(i,`lockMovementX`)&&i.left!==s,u=!cn(i,`lockMovementY`)&&i.top!==c;return l&&i.set(`left`,s),u&&i.set(`top`,c),(l||u)&&Yr(ie,ln(e,t,n,r)),l||u},uo=ue,fo=e=>function(t,n,r){let{points:i,pathOffset:a}=r;return new R(i[e]).subtract(a).transform(B(r.getViewportTransform(),r.calcTransformMatrix()))},po=(e,t,n,r)=>{let{target:i,pointIndex:a}=t,o=i,s=Vt(new R(n,r),void 0,o.calcOwnMatrix());return o.points[a]=s.add(o.pathOffset),o.setDimensions(),o.set(`dirty`,!0),!0},mo=(e,t)=>function(n,r,i,a){let o=r.target,s=new R(o.points[(e>0?e:o.points.length)-1]),c=s.subtract(o.pathOffset).transform(o.calcOwnMatrix()),l=t(n,{...r,pointIndex:e},i,a),u=s.subtract(o.pathOffset).transform(o.calcOwnMatrix()).subtract(c);return o.left-=u.x,o.top-=u.y,l},ho=e=>Xr(uo,mo(e,po));function go(e,t={}){let n={};for(let r=0;r<(typeof e==`number`?e:e.points.length);r++)n[`p${r}`]=new ai({actionName:uo,positionHandler:fo(r),actionHandler:ho(r),...t});return n}var _o=(e,t,n)=>{let{path:r,pathOffset:i}=e,a=r[t];return new R(a[n]-i.x,a[n+1]-i.y).transform(B(e.getViewportTransform(),e.calcTransformMatrix()))};function vo(e,t,n){let{commandIndex:r,pointIndex:i}=this;return _o(n,r,i)}function yo(e,t,n,r){let{target:i}=t,{commandIndex:a,pointIndex:o}=this,s=((e,t,n,r,i)=>{let{path:a,pathOffset:o}=e,s=a[(r>0?r:a.length)-1],c=new R(s[i],s[i+1]),l=c.subtract(o).transform(e.calcOwnMatrix()),u=Vt(new R(t,n),void 0,e.calcOwnMatrix());a[r][i]=u.x+o.x,a[r][i+1]=u.y+o.y,e.setDimensions();let d=c.subtract(e.pathOffset).transform(e.calcOwnMatrix()).subtract(l);return e.left-=d.x,e.top-=d.y,e.set(`dirty`,!0),!0})(i,n,r,a,o);return s&&Yr(this.actionName,{...ln(e,t,n,r),commandIndex:a,pointIndex:o}),s}var bo=class extends ai{constructor(e){super(e)}render(e,t,n,r,i){let a={...r,cornerColor:this.controlFill,cornerStrokeColor:this.controlStroke,transparentCorners:!this.controlFill};super.render(e,t,n,a,i)}},xo=class extends bo{constructor(e){super(e)}render(e,t,n,r,i){let{path:a}=i,{commandIndex:o,pointIndex:s,connectToCommandIndex:c,connectToPointIndex:l}=this;e.save(),e.strokeStyle=this.controlStroke,this.connectionDashArray&&e.setLineDash(this.connectionDashArray);let[u]=a[o],d=_o(i,c,l);if(u===`Q`){let r=_o(i,o,s+2);e.moveTo(r.x,r.y),e.lineTo(t,n)}else e.moveTo(t,n);e.lineTo(d.x,d.y),e.stroke(),e.restore(),super.render(e,t,n,r,i)}},So=(e,t,n,r,i,a)=>new(n?xo:bo)({commandIndex:e,pointIndex:t,actionName:`modifyPath`,positionHandler:vo,actionHandler:yo,connectToCommandIndex:i,connectToPointIndex:a,...r,...n?r.controlPointStyle:r.pointStyle});function Co(e,t={}){let n={},r=`M`;return e.path.forEach((e,i)=>{let a=e[0];switch(a!==`Z`&&(n[`c_${i}_${a}`]=So(i,e.length-2,!1,t)),a){case`C`:n[`c_${i}_C_CP_1`]=So(i,1,!0,t,i-1,(e=>e===`C`?5:e===`Q`?3:1)(r)),n[`c_${i}_C_CP_2`]=So(i,3,!0,t,i,5);break;case`Q`:n[`c_${i}_Q_CP_1`]=So(i,1,!0,t,i,3)}r=a}),n}u({changeHeight:()=>ni,changeObjectHeight:()=>ei,changeObjectWidth:()=>$r,changeWidth:()=>ti,createObjectDefaultControls:()=>Di,createPathControls:()=>Co,createPolyActionHandler:()=>ho,createPolyControls:()=>go,createPolyPositionHandler:()=>fo,createResizeControls:()=>Oi,createTextboxDefaultControls:()=>ki,dragHandler:()=>lo,factoryPolyActionHandler:()=>mo,getLocalPoint:()=>dn,polyActionHandler:()=>po,renderCircleControl:()=>ri,renderSquareControl:()=>ii,rotationStyleHandler:()=>oi,rotationWithSnapping:()=>si,scaleCursorStyleHandler:()=>di,scaleOrSkewActionName:()=>Ci,scaleSkewCursorStyleHandler:()=>wi,scalingEqually:()=>pi,scalingX:()=>mi,scalingXOrSkewingY:()=>Ti,scalingY:()=>hi,scalingYOrSkewingX:()=>Ei,skewCursorStyleHandler:()=>vi,skewHandlerX:()=>bi,skewHandlerY:()=>xi,wrapWithFireEvent:()=>Xr,wrapWithFixedAnchor:()=>Zr});var wo=class e extends Ot{constructor(...e){super(...e),p(this,`_hoveredTargets`,[]),p(this,`_currentTransform`,null),p(this,`_groupSelector`,null),p(this,`contextTopDirty`,!1)}static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}get upperCanvasEl(){return this.elements.upper?.el}get contextTop(){return this.elements.upper?.ctx}get wrapperEl(){return this.elements.container}initElements(e){this.elements=new co(e,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(e){this._objectsToRender=void 0,super._onObjectAdded(e)}_onObjectRemoved(e){this._objectsToRender=void 0,e===this._activeObject&&(this.fire(`before:selection:cleared`,{deselected:[e]}),this._discardActiveObject(),this.fire(`selection:cleared`,{deselected:[e]}),e.fire(`deselected`,{target:e})),e===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(e)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){let e=this._activeObject;return!this.preserveObjectStacking&&e?this._objects.filter(t=>!t.group&&t!==e).concat(e):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&=(this.renderTopLayer(this.contextTop),!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(e){e.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(e),this.contextTopDirty=!0),e.restore()}renderTop(){let e=this.contextTop;this.clearContext(e),this.renderTopLayer(e),this.fire(`after:render`,{ctx:e})}setTargetFindTolerance(e){e=Math.round(e),this.targetFindTolerance=e;let t=this.getRetinaScaling(),n=Math.ceil((2*e+1)*t);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=n,this.pixelFindContext.scale(t,t)}isTargetTransparent(e,t,n){let r=this.targetFindTolerance,i=this.pixelFindContext;this.clearContext(i),i.save(),i.translate(-t+r,-n+r),i.transform(...this.viewportTransform);let a=e.selectionBackgroundColor;e.selectionBackgroundColor=``,e.render(i),e.selectionBackgroundColor=a,i.restore();let o=Math.round(r*this.getRetinaScaling());return Ni(i,o,o,o)}_isSelectionKeyPressed(e){let t=this.selectionKey;return!!t&&(Array.isArray(t)?!!t.find(t=>!!t&&!0===e[t]):e[t])}_shouldClearSelection(e,t){let n=this.getActiveObjects(),r=this._activeObject;return!!(!t||t&&r&&n.length>1&&n.indexOf(t)===-1&&r!==t&&!this._isSelectionKeyPressed(e)||t&&!t.evented||t&&!t.selectable&&r&&r!==t)}_shouldCenterTransform(e,t,n){if(!e)return;let r;return t===`scale`||t===`scaleX`||t===`scaleY`||t===`resizing`?r=this.centeredScaling||e.centeredScaling:t===`rotate`&&(r=this.centeredRotation||e.centeredRotation),r?!n:n}_getOriginFromCorner(e,t){let n=t?e.controls[t].getTransformAnchorPoint():{x:e.originX,y:e.originY};return t?([`ml`,`tl`,`bl`].includes(t)?n.x=te:[`mr`,`tr`,`br`].includes(t)&&(n.x=F),[`tl`,`mt`,`tr`].includes(t)?n.y=I:[`bl`,`mb`,`br`].includes(t)&&(n.y=`top`),n):n}_setupCurrentTransform(e,t,n){let r=t.group?Vt(this.getScenePoint(e),void 0,t.group.calcTransformMatrix()):this.getScenePoint(e),{key:i=``,control:a}=t.getActiveControl()||{},o=n&&a?a.getActionHandler(e,t,a)?.bind(a):lo,s=((e,t,n,r)=>{if(!t||!e)return`drag`;let i=r.controls[t];return i.getActionName(n,i,r)})(n,i,e,t),c=e[this.centeredKey],l=this._shouldCenterTransform(t,s,c)?{x:P,y:P}:this._getOriginFromCorner(t,i),{scaleX:u,scaleY:d,skewX:f,skewY:p,left:m,top:h,angle:g,width:_,height:v,cropX:y,cropY:b}=t,x={target:t,action:s,actionHandler:o,actionPerformed:!1,corner:i,scaleX:u,scaleY:d,skewX:f,skewY:p,offsetX:r.x-m,offsetY:r.y-h,originX:l.x,originY:l.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:z(g),width:_,height:v,shiftKey:e.shiftKey,altKey:c,original:{...Rt(t),originX:l.x,originY:l.y,cropX:y,cropY:b}};this._currentTransform=x,this.fire(`before:transform`,{e,transform:x})}setCursor(e){this.upperCanvasEl.style.cursor=e}_drawSelection(e){let{x:t,y:n,deltaX:r,deltaY:i}=this._groupSelector,a=new R(t,n).transform(this.viewportTransform),o=new R(t+r,n+i).transform(this.viewportTransform),s=this.selectionLineWidth/2,c=Math.min(a.x,o.x),l=Math.min(a.y,o.y),u=Math.max(a.x,o.x),d=Math.max(a.y,o.y);this.selectionColor&&(e.fillStyle=this.selectionColor,e.fillRect(c,l,u-c,d-l)),this.selectionLineWidth&&this.selectionBorderColor&&(e.lineWidth=this.selectionLineWidth,e.strokeStyle=this.selectionBorderColor,c+=s,l+=s,u-=s,d-=s,Mi.prototype._setLineDash.call(this,e,this.selectionDashArray),e.strokeRect(c,l,u-c,d-l))}findTarget(e){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};let t=this.getScenePoint(e),n=this._activeObject,r=this.getActiveObjects(),i=this.searchPossibleTargets(this._objects,t),{subTargets:a,container:o,target:s}=i,c={...i,currentSubTargets:a,currentContainer:o,currentTarget:s};if(!n)return c;let l={...this.searchPossibleTargets([n],t),currentSubTargets:a,currentContainer:o,currentTarget:s};return n.findControl(this.getViewportPoint(e),jt(e))?{...l,target:n}:l.target&&(r.length>1||!this.preserveObjectStacking||this.preserveObjectStacking&&e[this.altSelectionKey])?l:c}_pointIsInObjectSelectionArea(e,t){let n=e.getCoords(),r=this.getZoom(),i=e.padding/r;if(i){let[e,t,r,a]=n,o=Math.atan2(t.y-e.y,t.x-e.x),s=Te(o)*i,c=Ee(o)*i,l=s+c,u=s-c;n=[new R(e.x-u,e.y-l),new R(t.x+l,t.y-u),new R(r.x+u,r.y+l),new R(a.x-l,a.y+u)]}return Kr.isPointInPolygon(t,n)}_checkTarget(e,t){if(e&&e.visible&&e.evented&&this._pointIsInObjectSelectionArea(e,t)){if(!this.perPixelTargetFind&&!e.perPixelTargetFind||e.isEditing)return!0;{let n=t.transform(this.viewportTransform);if(!this.isTargetTransparent(e,n.x,n.y))return!0}}return!1}_searchPossibleTargets(e,t,n){let r=e.length;for(;r--;){let i=e[r];if(this._checkTarget(i,t)){if(Oe(i)&&i.subTargetCheck){let{target:e}=this._searchPossibleTargets(i._objects,t,n);e&&n.push(e)}return{target:i,subTargets:n}}}return{subTargets:[]}}searchPossibleTargets(e,t){let n=this._searchPossibleTargets(e,t,[]);n.container=n.target;let{container:r,subTargets:i}=n;if(r&&Oe(r)&&r.interactive&&i[0]){for(let e=i.length-1;e>0;e--){let t=i[e];if(!Oe(t)||!t.interactive)return n.target=t,n}return n.target=i[0],n}return n}getViewportPoint(e){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(e,!0)}getScenePoint(e){return this._scenePoint?this._scenePoint:this._getPointerImpl(e)}_getPointerImpl(e,t=!1){let n=this.upperCanvasEl,r=n.getBoundingClientRect(),i=At(e),a=r.width||0,o=r.height||0;a&&o||(`top`in r&&`bottom`in r&&(o=Math.abs(r.top-r.bottom)),`right`in r&&`left`in r&&(a=Math.abs(r.right-r.left))),this.calcOffset(),i.x-=this._offset.left,i.y-=this._offset.top,t||(i=Vt(i,void 0,this.viewportTransform));let s=this.getRetinaScaling();s!==1&&(i.x/=s,i.y/=s);let c=a===0||o===0?new R(1,1):new R(n.width/a,n.height/o);return i.multiply(c)}_setDimensionsImpl(e,t){this._resetTransformEventData(),super._setDimensionsImpl(e,t),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Fe(),this.pixelFindContext=this.pixelFindCanvasEl.getContext(`2d`,{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){let e=this._activeObject;return pt(e)?e.getObjects():e?[e]:[]}_fireSelectionEvents(e,t){let n=!1,r=!1,i=this.getActiveObjects(),a=[],o=[];e.forEach(e=>{i.includes(e)||(n=!0,e.fire(`deselected`,{e:t,target:e}),o.push(e))}),i.forEach(r=>{e.includes(r)||(n=!0,r.fire(`selected`,{e:t,target:r}),a.push(r))}),e.length>0&&i.length>0?(r=!0,n&&this.fire(`selection:updated`,{e:t,selected:a,deselected:o})):i.length>0?(r=!0,this.fire(`selection:created`,{e:t,selected:a})):e.length>0&&(r=!0,this.fire(`selection:cleared`,{e:t,deselected:o})),r&&(this._objectsToRender=void 0)}setActiveObject(e,t){let n=this.getActiveObjects(),r=this._setActiveObject(e,t);return this._fireSelectionEvents(n,t),r}_setActiveObject(e,t){let n=this._activeObject;return n!==e&&!(!this._discardActiveObject(t,e)&&this._activeObject)&&!e.onSelect({e:t})&&(this._activeObject=e,pt(e)&&n!==e&&e.set(`canvas`,this),e.setCoords(),!0)}_discardActiveObject(e,t){let n=this._activeObject;return!!n&&!n.onDeselect({e,object:t})&&(this._currentTransform&&this._currentTransform.target===n&&this.endCurrentTransform(e),pt(n)&&n===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(e){let t=this.getActiveObjects(),n=this.getActiveObject();t.length&&this.fire(`before:selection:cleared`,{e,deselected:[n]});let r=this._discardActiveObject(e);return this._fireSelectionEvents(t,e),r}endCurrentTransform(e){let t=this._currentTransform;this._finalizeCurrentTransform(e),t&&t.target&&(t.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(e){let t=this._currentTransform,n=t.target,r={e,target:n,transform:t,action:t.action};n._scaling&&=!1,n.setCoords(),t.actionPerformed&&(this.fire(`object:modified`,r),n.fire(ye,r))}setViewportTransform(e){super.setViewportTransform(e);let t=this._activeObject;t&&t.setCoords()}destroy(){let e=this._activeObject;pt(e)&&(e.removeAll(),e.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(e){let t=this._activeObject;t&&t._renderControls(e)}_toObject(e,t,n){let r=this._realizeGroupTransformOnObject(e),i=super._toObject(e,t,n);return e.set(r),i}_realizeGroupTransformOnObject(e){let{group:t}=e;if(t&&pt(t)&&this._activeObject===t){let n=st(e,[`angle`,`flipX`,`flipY`,F,pe,me,he,ge,`top`]);return Ft(e,t.calcOwnMatrix()),n}return{}}_setSVGObject(e,t,n){let r=this._realizeGroupTransformOnObject(t);super._setSVGObject(e,t,n),t.set(r)}};p(wo,`ownDefaults`,{uniformScaling:!0,uniScaleKey:`shiftKey`,centeredScaling:!1,centeredRotation:!1,centeredKey:`altKey`,altActionKey:`shiftKey`,selection:!0,selectionKey:`shiftKey`,selectionColor:`rgba(100, 100, 255, 0.3)`,selectionDashArray:[],selectionBorderColor:`rgba(255, 255, 255, 0.3)`,selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:`move`,moveCursor:`move`,defaultCursor:`default`,freeDrawingCursor:`crosshair`,notAllowedCursor:`not-allowed`,perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!0,fireRightClick:!0,fireMiddleClick:!0,enablePointerEvents:!1,containerClass:`canvas-container`,preserveObjectStacking:!0});var To=class{constructor(e){p(this,`targets`,[]),p(this,`__disposer`,void 0);let t=()=>{let{hiddenTextarea:t}=e.getActiveObject()||{};t&&t.focus()},n=e.upperCanvasEl;n.addEventListener(`click`,t),this.__disposer=()=>n.removeEventListener(`click`,t)}exitTextEditing(){this.target=void 0,this.targets.forEach(e=>{e.isEditing&&e.exitEditing()})}add(e){this.targets.push(e)}remove(e){this.unregister(e),we(this.targets,e)}register(e){this.target=e}unregister(e){e===this.target&&(this.target=void 0)}onMouseMove(e){var t;(t=this.target)!=null&&t.isEditing&&this.target.updateSelectionOnMouseMove(e)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}},Eo={passive:!1},Do=(e,t)=>({viewportPoint:e.getViewportPoint(t),scenePoint:e.getScenePoint(t)}),Oo=(e,...t)=>e.addEventListener(...t),ko=(e,...t)=>e.removeEventListener(...t),Ao={mouse:{in:`over`,out:`out`,targetIn:`mouseover`,targetOut:`mouseout`,canvasIn:`mouse:over`,canvasOut:`mouse:out`},drag:{in:`enter`,out:`leave`,targetIn:`dragenter`,targetOut:`dragleave`,canvasIn:`drag:enter`,canvasOut:`drag:leave`}},jo=class extends wo{constructor(e,t={}){super(e,t),p(this,`_isClick`,void 0),p(this,`textEditingManager`,new To(this)),[`_onMouseDown`,`_onTouchStart`,`_onMouseMove`,`_onMouseUp`,`_onTouchEnd`,`_onResize`,`_onMouseWheel`,`_onMouseOut`,`_onMouseEnter`,`_onContextMenu`,`_onClick`,`_onDragStart`,`_onDragEnd`,`_onDragProgress`,`_onDragOver`,`_onDragEnter`,`_onDragLeave`,`_onDrop`].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(Oo)}_getEventPrefix(){return this.enablePointerEvents?`pointer`:`mouse`}addOrRemove(e,t=!1){let n=this.upperCanvasEl,r=this._getEventPrefix();e(gt(n),`resize`,this._onResize),e(n,r+`down`,this._onMouseDown),e(n,`${r}move`,this._onMouseMove,Eo),e(n,`${r}out`,this._onMouseOut),e(n,`${r}enter`,this._onMouseEnter),e(n,`wheel`,this._onMouseWheel,{passive:!1}),e(n,`contextmenu`,this._onContextMenu),t||(e(n,`click`,this._onClick),e(n,`dblclick`,this._onClick)),e(n,`dragstart`,this._onDragStart),e(n,`dragend`,this._onDragEnd),e(n,`dragover`,this._onDragOver),e(n,`dragenter`,this._onDragEnter),e(n,`dragleave`,this._onDragLeave),e(n,`drop`,this._onDrop),this.enablePointerEvents||e(n,`touchstart`,this._onTouchStart,Eo)}removeListeners(){this.addOrRemove(ko);let e=this._getEventPrefix(),t=ht(this.upperCanvasEl);ko(t,`${e}up`,this._onMouseUp),ko(t,`touchend`,this._onTouchEnd,Eo),ko(t,`${e}move`,this._onMouseMove,Eo),ko(t,`touchmove`,this._onMouseMove,Eo),clearTimeout(this._willAddMouseDown)}_onMouseWheel(e){this._cacheTransformEventData(e),this._handleEvent(e,`wheel`),this._resetTransformEventData()}_onMouseOut(e){let t=this._hoveredTarget,n={e,...Do(this,e)};this.fire(`mouse:out`,{...n,target:t}),this._hoveredTarget=void 0,t&&t.fire(`mouseout`,{...n}),this._hoveredTargets.forEach(e=>{this.fire(`mouse:out`,{...n,target:e}),e&&e.fire(`mouseout`,{...n})}),this._hoveredTargets=[]}_onMouseEnter(e){let{target:t}=this.findTarget(e);this._currentTransform||t||(this.fire(`mouse:over`,{e,...Do(this,e)}),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(e){this._isClick=!1;let t=this.getActiveObject();if(t&&t.onDragStart(e)){this._dragSource=t;let n={e,target:t};this.fire(`dragstart`,n),t.fire(`dragstart`,n),Oo(this.upperCanvasEl,`drag`,this._onDragProgress);return}Mt(e)}_renderDragEffects(e,t,n){let r=!1,i=this._dropTarget;i&&i!==t&&i!==n&&(i.clearContextTop(),r=!0),t?.clearContextTop(),n!==t&&n?.clearContextTop();let a=this.contextTop;a.save(),a.transform(...this.viewportTransform),t&&(a.save(),t.transform(a),t.renderDragSourceEffect(e),a.restore(),r=!0),n&&(a.save(),n.transform(a),n.renderDropTargetEffect(e),a.restore(),r=!0),a.restore(),r&&(this.contextTopDirty=!0)}_onDragEnd(e){let{currentSubTargets:t}=this.findTarget(e),n=!!e.dataTransfer&&e.dataTransfer.dropEffect!==`none`,r=n?this._activeObject:void 0,i={e,target:this._dragSource,subTargets:t,dragSource:this._dragSource,didDrop:n,dropTarget:r};ko(this.upperCanvasEl,`drag`,this._onDragProgress),this.fire(`dragend`,i),this._dragSource&&this._dragSource.fire(`dragend`,i),delete this._dragSource,this._onMouseUp(e)}_onDragProgress(e){let t={e,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire(`drag`,t),this._dragSource&&this._dragSource.fire(`drag`,t)}_onDragOver(e){let t=`dragover`,{currentContainer:n,currentSubTargets:r}=this.findTarget(e),i=this._dragSource,a={e,target:n,subTargets:r,dragSource:i,canDrop:!1,dropTarget:void 0},o;this.fire(t,a),this._fireEnterLeaveEvents(e,n,a),n&&(n.canDrop(e)&&(o=n),n.fire(t,a));for(let n=0;n<r.length;n++){let i=r[n];i.canDrop(e)&&(o=i),i.fire(t,a)}this._renderDragEffects(e,i,o),this._dropTarget=o}_onDragEnter(e){let{currentContainer:t,currentSubTargets:n}=this.findTarget(e),r={e,target:t,subTargets:n,dragSource:this._dragSource};this.fire(`dragenter`,r),this._fireEnterLeaveEvents(e,t,r)}_onDragLeave(e){let{currentSubTargets:t}=this.findTarget(e),n={e,target:this._draggedoverTarget,subTargets:t,dragSource:this._dragSource};this.fire(`dragleave`,n),this._fireEnterLeaveEvents(e,void 0,n),this._renderDragEffects(e,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(e){let{currentContainer:t,currentSubTargets:n}=this.findTarget(e),r=this._basicEventHandler(`drop:before`,{e,target:t,subTargets:n,dragSource:this._dragSource,...Do(this,e)});r.didDrop=!1,r.dropTarget=void 0,this._basicEventHandler(`drop`,r),this.fire(`drop:after`,r)}_onContextMenu(e){let{target:t,subTargets:n}=this.findTarget(e),r=this._basicEventHandler(`contextmenu:before`,{e,target:t,subTargets:n});return this.stopContextMenu&&Mt(e),this._basicEventHandler(`contextmenu`,r),!1}_onClick(e){let t=e.detail;t>3||t<2||(this._cacheTransformEventData(e),t==2&&e.type===`dblclick`&&this._handleEvent(e,`dblclick`),t==3&&this._handleEvent(e,`tripleclick`),this._resetTransformEventData())}fireEventFromPointerEvent(e,t,n,r={}){this._cacheTransformEventData(e);let{target:i,subTargets:a}=this.findTarget(e),o={e,target:i,subTargets:a,...Do(this,e),transform:this._currentTransform,...r};this.fire(t,o),i&&i.fire(n,o);for(let e=0;e<a.length;e++)a[e]!==i&&a[e].fire(n,o);this._resetTransformEventData()}getPointerId(e){let t=e.changedTouches;return t?t[0]&&t[0].identifier:this.enablePointerEvents?e.pointerId:-1}_isMainEvent(e){return!0===e.isPrimary||!1!==e.isPrimary&&(e.type===`touchend`&&e.touches.length===0||!e.changedTouches||e.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(e){this._cacheTransformEventData(e);let t=!this.allowTouchScrolling,n=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(e)),this.__onMouseDown(e);let{target:r}=this.findTarget(e);(this.isDrawingMode||n&&r===n)&&(t=!0),t&&e.preventDefault();let i=this.upperCanvasEl,a=this._getEventPrefix(),o=ht(i);Oo(o,`touchend`,this._onTouchEnd,Eo),t&&Oo(o,`touchmove`,this._onMouseMove,Eo),ko(i,`${a}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(e){this._cacheTransformEventData(e),this.__onMouseDown(e);let t=this.upperCanvasEl,n=this._getEventPrefix();ko(t,`${n}move`,this._onMouseMove,Eo);let r=ht(t);Oo(r,`${n}up`,this._onMouseUp),Oo(r,`${n}move`,this._onMouseMove,Eo),this._resetTransformEventData()}_onTouchEnd(e){if(e.touches.length>0)return;this._cacheTransformEventData(e),this.__onMouseUp(e),this._resetTransformEventData(),delete this.mainTouchId;let t=this._getEventPrefix(),n=ht(this.upperCanvasEl);ko(n,`touchend`,this._onTouchEnd,Eo),ko(n,`touchmove`,this._onMouseMove,Eo),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{Oo(this.upperCanvasEl,`${t}down`,this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(e){this._cacheTransformEventData(e),this.__onMouseUp(e);let t=this.upperCanvasEl,n=this._getEventPrefix();if(this._isMainEvent(e)){let e=ht(this.upperCanvasEl);ko(e,`${n}up`,this._onMouseUp),ko(e,`${n}move`,this._onMouseMove,Eo),Oo(t,`${n}move`,this._onMouseMove,Eo)}this._resetTransformEventData()}_onMouseMove(e){this._cacheTransformEventData(e);let t=this.getActiveObject();!this.allowTouchScrolling&&(!t||!t.shouldStartDragging(e))&&e.preventDefault&&e.preventDefault(),this.__onMouseMove(e),this._resetTransformEventData()}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(e){let t=this.getActiveObject();return!!t!=!!e||t&&e&&t!==e}__onMouseUp(e){var t;this._handleEvent(e,`up:before`);let n=this._currentTransform,r=this._isClick,{target:i}=this.findTarget(e),{button:a}=e;if(a)return void((this.fireMiddleClick&&a===1||this.fireRightClick&&a===2)&&this._handleEvent(e,`up`));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(e);if(!this._isMainEvent(e))return;let o,s,c=!1;if(n&&(this._finalizeCurrentTransform(e),c=n.actionPerformed),!r){let t=i===this._activeObject;this.handleSelection(e),c||=this._shouldRender(i)||!t&&i===this._activeObject}if(i){let{key:t,control:r}=i.findControl(this.getViewportPoint(e),jt(e))||{};if(s=t,i.selectable&&i!==this._activeObject&&i.activeOn===`up`)this.setActiveObject(i,e),c=!0;else if(r){let t=r.getMouseUpHandler(e,i,r);t&&(o=this.getScenePoint(e),t.call(r,e,n,o.x,o.y))}i.isMoving=!1}if(n&&(n.target!==i||n.corner!==s)){let t=n.target&&n.target.controls[n.corner],r=t&&t.getMouseUpHandler(e,n.target,t);o||=this.getScenePoint(e),r&&r.call(t,e,n,o.x,o.y)}this._setCursorFromEvent(e,i),this._handleEvent(e,`up`),this._groupSelector=null,this._currentTransform=null,i&&(i.__corner=void 0),c?this.requestRenderAll():r||(t=this._activeObject)!=null&&t.isEditing||this.renderTop()}_basicEventHandler(e,t){let{target:n,subTargets:r=[]}=t;this.fire(e,t),n&&n.fire(e,t);for(let i=0;i<r.length;i++)r[i]!==n&&r[i].fire(e,t);return t}_handleEvent(e,t,n){let{target:r,subTargets:i}=this.findTarget(e),a={e,target:r,subTargets:i,...Do(this,e),transform:this._currentTransform,...t===`down:before`||t===`down`?n:{}};t!==`up:before`&&t!==`up`||(a.isClick=this._isClick),this.fire(`mouse:${t}`,a),r&&r.fire(`mouse${t}`,a);for(let e=0;e<i.length;e++)i[e]!==r&&i[e].fire(`mouse${t}`,a)}_onMouseDownInDrawingMode(e){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(e),this.requestRenderAll());let t=this.getScenePoint(e);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(t,{e,pointer:t}),this._handleEvent(e,`down`,{alreadySelected:!1})}_onMouseMoveInDrawingMode(e){if(this._isCurrentlyDrawing){let t=this.getScenePoint(e);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(t,{e,pointer:t})}this.setCursor(this.freeDrawingCursor),this._handleEvent(e,`move`)}_onMouseUpInDrawingMode(e){let t=this.getScenePoint(e);this._isCurrentlyDrawing=this.freeDrawingBrush?!!this.freeDrawingBrush.onMouseUp({e,pointer:t}):!1,this._handleEvent(e,`up`)}__onMouseDown(e){this._isClick=!0,this._handleEvent(e,`down:before`);let{target:t}=this.findTarget(e),n=!!t&&t===this._activeObject,{button:r}=e;if(r)return void((this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(e,`down`,{alreadySelected:n}));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(e);if(!this._isMainEvent(e)||this._currentTransform)return;let i=this._shouldRender(t),a=!1;if(this.handleMultiSelection(e,t)?(t=this._activeObject,a=!0,i=!0):this._shouldClearSelection(e,t)&&this.discardActiveObject(e),this.selection&&(!t||!t.selectable&&!t.isEditing&&t!==this._activeObject)){let t=this.getScenePoint(e);this._groupSelector={x:t.x,y:t.y,deltaY:0,deltaX:0}}if(n=!!t&&t===this._activeObject,t){t.selectable&&t.activeOn===`down`&&this.setActiveObject(t,e);let r=t.findControl(this.getViewportPoint(e),jt(e));if(t===this._activeObject&&(r||!a)){this._setupCurrentTransform(e,t,n);let i=r?r.control:void 0,a=this.getScenePoint(e),o=i&&i.getMouseDownHandler(e,t,i);o&&o.call(i,e,this._currentTransform,a.x,a.y)}}i&&(this._objectsToRender=void 0),this._handleEvent(e,`down`,{alreadySelected:n}),i&&this.requestRenderAll()}_resetTransformEventData(){this._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(e){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(e),this._scenePoint=Vt(this._viewportPoint,void 0,this.viewportTransform),this._targetInfo=this.findTarget(e),this._currentTransform&&(this._targetInfo.target=this._currentTransform.target)}__onMouseMove(e){if(this._isClick=!1,this._handleEvent(e,`move:before`),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(e);if(!this._isMainEvent(e))return;let t=this._groupSelector;if(t){let n=this.getScenePoint(e);t.deltaX=n.x-t.x,t.deltaY=n.y-t.y,this.renderTop()}else if(this._currentTransform)this._transformObject(e);else{let{target:t}=this.findTarget(e);this._setCursorFromEvent(e,t),this._fireOverOutEvents(e,t)}this.textEditingManager.onMouseMove(e),this._handleEvent(e,`move`)}_fireOverOutEvents(e,t){let{_hoveredTarget:n,_hoveredTargets:r}=this,{subTargets:i,currentTarget:a}=this.findTarget(e),o=Math.max(r.length,i.length);this.fireSyntheticInOutEvents(`mouse`,{e,target:t,oldTarget:n,actualTarget:a,oldActualTarget:this._hoveredActualTarget,fireCanvas:!0});for(let a=0;a<o;a++)i[a]===t||r[a]&&r[a]===n||this.fireSyntheticInOutEvents(`mouse`,{e,target:i[a],oldTarget:r[a]});this._hoveredActualTarget=a,this._hoveredTarget=t,this._hoveredTargets=i}_fireEnterLeaveEvents(e,t,n){let r=this._draggedoverTarget,i=this._hoveredTargets,{subTargets:a}=this.findTarget(e),o=Math.max(i.length,a.length);this.fireSyntheticInOutEvents(`drag`,{...n,target:t,oldTarget:r,fireCanvas:!0});for(let e=0;e<o;e++)this.fireSyntheticInOutEvents(`drag`,{...n,target:a[e],oldTarget:i[e]});this._draggedoverTarget=t}fireSyntheticInOutEvents(e,{target:t,oldTarget:n,actualTarget:r,oldActualTarget:i,fireCanvas:a,e:o,...s}){let{targetIn:c,targetOut:l,canvasIn:u,canvasOut:d}=Ao[e],f=n!==t,p=i!==r,m=t&&f,h=r&&p,g=n&&f,_=i&&p,v={...s,e:o,...Do(this,o)},y={...v,target:n,nextTarget:t,actualTarget:i,nextActualTarget:r};(g||_)&&a&&this.fire(d,y),g&&n.fire(l,y),_&&n!==i&&i.fire(l,y);let b={...v,target:t,previousTarget:n,actualTarget:r,previousActualTarget:i};(m||h)&&a&&this.fire(u,b),m&&t.fire(c,b),h&&r!==t&&r.fire(c,b)}_transformObject(e){let t=this.getScenePoint(e),n=this._currentTransform,r=n.target,i=r.group?Vt(t,void 0,r.group.calcTransformMatrix()):t;n.shiftKey=e.shiftKey,n.altKey=!!this.centeredKey&&e[this.centeredKey],this._performTransformAction(e,n,i),n.actionPerformed&&this.requestRenderAll()}_performTransformAction(e,t,n){let{action:r,actionHandler:i,target:a}=t,o=!!i&&i(e,t,n.x,n.y);o&&a.setCoords(),r===`drag`&&o&&(t.target.isMoving=!0,this.setCursor(t.target.moveCursor||this.moveCursor)),t.actionPerformed=t.actionPerformed||o}_setCursorFromEvent(e,t){if(!t)return void this.setCursor(this.defaultCursor);let n=t.hoverCursor||this.hoverCursor,r=pt(this._activeObject)?this._activeObject:null,i=(!r||t.group!==r)&&t.findControl(this.getViewportPoint(e));if(i){let{control:n,coord:r}=i;this.setCursor(n.cursorStyleHandler(e,n,t,r))}else{if(t.subTargetCheck){let{subTargets:t}=this.findTarget(e);t.concat().reverse().forEach(e=>{n=e.hoverCursor||n})}this.setCursor(n)}}handleMultiSelection(e,t){let n=this._activeObject,r=pt(n);if(n&&this._isSelectionKeyPressed(e)&&this.selection&&t&&t.selectable&&(n!==t||r)&&(r||!t.isDescendantOf(n)&&!n.isDescendantOf(t))&&!t.onSelect({e})&&!n.getActiveControl()){if(r){let r=n.getObjects(),i=[];if(t===n){let n=this.getScenePoint(e),a=this.searchPossibleTargets(r,n);if(a.target?(t=a.target,i=a.subTargets):(a=this.searchPossibleTargets(this._objects,n),t=a.target,i=a.subTargets),!t||!t.selectable)return!1}t.group===n?(n.remove(t),this._hoveredTarget=t,this._hoveredTargets=i,n.size()===1&&this._setActiveObject(n.item(0),e)):(n.multiSelectAdd(t),this._hoveredTarget=n,this._hoveredTargets=i),this._fireSelectionEvents(r,e)}else{n.isEditing&&n.exitEditing();let r=new(L.getClass(`ActiveSelection`))([],{canvas:this});r.multiSelectAdd(n,t),this._hoveredTarget=r,this._setActiveObject(r,e),this._fireSelectionEvents([n],e)}return!0}return!1}handleSelection(e){if(!this.selection||!this._groupSelector)return!1;let{x:t,y:n,deltaX:r,deltaY:i}=this._groupSelector,a=new R(t,n),o=a.add(new R(r,i)),s=a.min(o),c=a.max(o).subtract(s),l=this.collectObjects({left:s.x,top:s.y,width:c.x,height:c.y},{includeIntersecting:!this.selectionFullyContained}),u=a.eq(o)?l[0]?[l[0]]:[]:l.length>1?l.filter(t=>!t.onSelect({e})).reverse():l;if(u.length===1)this.setActiveObject(u[0],e);else if(u.length>1){let t=L.getClass(`ActiveSelection`);this.setActiveObject(new t(u,{canvas:this}),e)}return this._groupSelector=null,!0}toCanvasElement(e=1,t){let{upper:n}=this.elements;n.ctx=void 0;let r=super.toCanvasElement(e,t);return n.ctx=n.el.getContext(`2d`),r}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}},Mo={x1:0,y1:0,x2:0,y2:0},No={...Mo,r1:0,r2:0},Po=(e,t)=>isNaN(e)&&typeof t==`number`?t:e;function Fo(e){return e&&/%$/.test(e)&&Number.isFinite(parseFloat(e))}function Io(e,t){return $n(0,Po(typeof e==`number`?e:typeof e==`string`?parseFloat(e)/(Fo(e)?100:1):NaN,t),1)}var Lo=/\s*;\s*/,Ro=/\s*:\s*/;function zo(e,t){let n,r,i=e.getAttribute(`style`);if(i){let e=i.split(Lo);e[e.length-1]===``&&e.pop();for(let t=e.length;t--;){let[i,a]=e[t].split(Ro).map(e=>e.trim());i===`stop-color`?n=a:i===`stop-opacity`&&(r=a)}}n=n||e.getAttribute(`stop-color`)||`rgb(0,0,0)`,r=Po(parseFloat(r||e.getAttribute(`stop-opacity`)||``),1);let a=new Cn(n);return a.setAlpha(a.getAlpha()*r*t),{offset:Io(e.getAttribute(`offset`),0),color:a.toRgba()}}function Bo(e,t){let n=[],r=e.getElementsByTagName(`stop`),i=Io(t,1);for(let e=r.length;e--;)n.push(zo(r[e],i));return n}function Vo(e){return e.nodeName===`linearGradient`||e.nodeName===`LINEARGRADIENT`?`linear`:`radial`}function Ho(e){return e.getAttribute(`gradientUnits`)===`userSpaceOnUse`?`pixels`:`percentage`}function Uo(e,t){return e.getAttribute(t)}function Wo(e,t){return function(e,{width:t,height:n,gradientUnits:r}){let i;return Object.entries(e).reduce((e,[a,o])=>{if(o===`Infinity`)i=1;else if(o===`-Infinity`)i=0;else{let e=typeof o==`string`;i=e?parseFloat(o):o,e&&Fo(o)&&(i*=.01,r===`pixels`&&(a!==`x1`&&a!==`x2`&&a!==`r2`||(i*=t),a!==`y1`&&a!==`y2`||(i*=n)))}return e[a]=i,e},{})}(Vo(e)===`linear`?function(e){return{x1:Uo(e,`x1`)||0,y1:Uo(e,`y1`)||0,x2:Uo(e,`x2`)||`100%`,y2:Uo(e,`y2`)||0}}(e):function(e){return{x1:Uo(e,`fx`)||Uo(e,`cx`)||`50%`,y1:Uo(e,`fy`)||Uo(e,`cy`)||`50%`,r1:0,x2:Uo(e,`cx`)||`50%`,y2:Uo(e,`cy`)||`50%`,r2:Uo(e,`r`)||`50%`}}(e),{...t,gradientUnits:Ho(e)})}var Go=class{constructor(e){let{type:t=`linear`,gradientUnits:n=`pixels`,coords:r={},colorStops:i=[],offsetX:a=0,offsetY:o=0,gradientTransform:s,id:c}=e||{};Object.assign(this,{type:t,gradientUnits:n,coords:{...t===`radial`?No:Mo,...r},colorStops:i,offsetX:a,offsetY:o,gradientTransform:s,id:c?`${c}_${Pe()}`:Pe()})}addColorStop(e){for(let t in e)this.colorStops.push({offset:parseFloat(t),color:e[t]});return this}toObject(e){return{...st(this,e),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map(e=>({...e})),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0}}toSVG(e,{additionalTransform:t}={}){let n=[],r=this.gradientTransform?this.gradientTransform.concat():N.concat(),i=this.gradientUnits===`pixels`?`userSpaceOnUse`:`objectBoundingBox`,a=this.colorStops.map(e=>({...e})).sort((e,t)=>e.offset-t.offset),o=-this.offsetX,s=-this.offsetY;var c;i===`objectBoundingBox`?(o/=e.width,s/=e.height):(o+=e.width/2,s+=e.height/2),(c=e)&&typeof c._renderPathCommands==`function`&&this.gradientUnits!==`percentage`&&(o-=e.pathOffset.x,s-=e.pathOffset.y),r[4]-=o,r[5]-=s;let l=[`id="SVGID_${H(String(this.id))}"`,`gradientUnits="${i}"`,`gradientTransform="${t?t+` `:``}${lt(r)}"`,``].join(` `),u=e=>parseFloat(String(e));if(this.type===`linear`){let{x1:e,y1:t,x2:r,y2:i}=this.coords,a=u(e),o=u(t),s=u(r),c=u(i);n.push(`<linearGradient `,l,` x1="`,a,`" y1="`,o,`" x2="`,s,`" y2="`,c,`">
|
|
18
18
|
`)}else if(this.type===`radial`){let{x1:e,y1:t,x2:r,y2:i,r1:o,r2:s}=this.coords,c=u(e),d=u(t),f=u(r),p=u(i),m=u(o),h=u(s),g=m>h;n.push(`<radialGradient `,l,` cx="`,g?c:f,`" cy="`,g?d:p,`" r="`,g?m:h,`" fx="`,g?f:c,`" fy="`,g?p:d,`">
|
|
19
19
|
`),g&&(a.reverse(),a.forEach(e=>{e.offset=1-e.offset}));let _=Math.min(m,h);if(_>0){let e=_/Math.max(m,h);a.forEach(t=>{t.offset+=e*(1-t.offset)})}}return a.forEach(({color:e,offset:t})=>{let r=String(e),i=pn(r)?r:new Cn(r).toRgba();n.push(`<stop offset="${100*t}%" style="stop-color:${H(i)};"/>\n`)}),n.push(this.type===`linear`?`</linearGradient>`:`</radialGradient>`,`
|
|
20
20
|
`),n.join(``)}toLive(e){let{x1:t,y1:n,x2:r,y2:i,r1:a,r2:o}=this.coords,s=this.type===`linear`?e.createLinearGradient(t,n,r,i):e.createRadialGradient(t,n,a,r,i,o);return this.colorStops.forEach(({color:e,offset:t})=>{s.addColorStop(t,e)}),s}static async fromObject(e){let{colorStops:t,gradientTransform:n}=e;return new this({...e,colorStops:t?t.map(e=>({...e})):void 0,gradientTransform:n?[...n]:void 0})}static fromElement(e,t,n){let r=Ho(e),i=t._findCenterFromElement();return new this({id:e.getAttribute(`id`)||void 0,type:Vo(e),coords:Wo(e,{width:n.viewBoxWidth||n.width,height:n.viewBoxHeight||n.height}),colorStops:Bo(e,n.opacity),gradientUnits:r,gradientTransform:sa(e.getAttribute(`gradientTransform`)||``),...r===`pixels`?{offsetX:t.width/2-i.x,offsetY:t.height/2-i.y}:{offsetX:0,offsetY:0}})}};p(Go,`type`,`Gradient`),L.setClass(Go,`gradient`),L.setClass(Go,`linear`),L.setClass(Go,`radial`);var Ko=class{get type(){return`pattern`}set type(e){g(`warn`,`Setting type has no effect`,e)}constructor(e){p(this,`repeat`,`repeat`),p(this,`offsetX`,0),p(this,`offsetY`,0),p(this,`crossOrigin`,``),this.id=Pe(),Object.assign(this,e)}isImageSource(){return!!this.source&&typeof this.source.src==`string`}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():``}toLive(e){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?e.createPattern(this.source,this.repeat):null}toObject(e=[]){let{repeat:t,crossOrigin:n}=this;return{...st(this,e),type:`pattern`,source:this.sourceToString(),repeat:t,crossOrigin:n,offsetX:V(this.offsetX,h.NUM_FRACTION_DIGITS),offsetY:V(this.offsetY,h.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null}}toSVG({width:e,height:t}){let{source:n,repeat:r,id:i}=this,a=Po(this.offsetX/e,0),o=Po(this.offsetY/t,0),s=r===`repeat-y`||r===`no-repeat`?1+Math.abs(a||0):Po(n.width/e,0),c=r===`repeat-x`||r===`no-repeat`?1+Math.abs(o||0):Po(n.height/t,0);return[`<pattern id="SVGID_${H(i)}" x="${a}" y="${o}" width="${s}" height="${c}">`,`<image x="0" y="0" width="${n.width}" height="${n.height}" xlink:href="${H(this.sourceToString())}"></image>`,`</pattern>`,``].join(`
|
|
21
21
|
`)}static async fromObject({type:e,source:t,patternTransform:n,...r},i){let a=await it(t,{...i,crossOrigin:r.crossOrigin});return new this({...r,patternTransform:n&&n.slice(0),source:a})}};p(Ko,`type`,`Pattern`),L.setClass(Ko),L.setClass(Ko,`pattern`);var qo=class e extends Mi{constructor(t,{path:n,left:r,top:i,...a}={}){super(),Object.assign(this,e.ownDefaults),this.setOptions(a),this._setPath(t||[],!0),typeof r==`number`&&this.set(`left`,r),typeof i==`number`&&this.set(`top`,i)}_setPath(e,t){this.path=Fa(Array.isArray(e)?e:Qa(e)),this.setBoundingBox(t)}_findCenterFromElement(){let e=this._calcBoundsFromPath();return new R(e.left+e.width/2,e.top+e.height/2)}_renderPathCommands(e){let t=-this.pathOffset.x,n=-this.pathOffset.y;e.beginPath();for(let r of this.path)switch(r[0]){case`L`:e.lineTo(r[1]+t,r[2]+n);break;case`M`:e.moveTo(r[1]+t,r[2]+n);break;case`C`:e.bezierCurveTo(r[1]+t,r[2]+n,r[3]+t,r[4]+n,r[5]+t,r[6]+n);break;case`Q`:e.quadraticCurveTo(r[1]+t,r[2]+n,r[3]+t,r[4]+n);break;case`Z`:e.closePath()}}_render(e){this._renderPathCommands(e),this._renderPaintInOrder(e)}toString(){return`#<Path (${this.complexity()}): { "top": ${this.top}, "left": ${this.left} }>`}toObject(e=[]){return{...super.toObject(e),path:this.path.map(e=>e.slice())}}toDatalessObject(e=[]){let t=this.toObject(e);return this.sourcePath&&(delete t.path,t.sourcePath=this.sourcePath),t}_toSVG(){return[`<path `,`COMMON_PARTS`,`d="${no(this.path,h.NUM_FRACTION_DIGITS)}" stroke-linecap="round" />\n`]}_getOffsetTransform(){let e=h.NUM_FRACTION_DIGITS;return` translate(${V(-this.pathOffset.x,e)}, ${V(-this.pathOffset.y,e)})`}toClipPathSVG(e){let t=this._getOffsetTransform();return` `+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})}toSVG(e){let t=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:e,additionalTransform:t})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(e){let{width:t,height:n,pathOffset:r}=this._calcDimensions();this.set({width:t,height:n,pathOffset:r}),e&&this.setPositionByOrigin(r,`center`,`center`)}_calcBoundsFromPath(){let e=[],t=0,n=0,r=0,i=0;for(let a of this.path)switch(a[0]){case`L`:r=a[1],i=a[2],e.push({x:t,y:n},{x:r,y:i});break;case`M`:r=a[1],i=a[2],t=r,n=i;break;case`C`:e.push(...Na(r,i,a[1],a[2],a[3],a[4],a[5],a[6])),r=a[5],i=a[6];break;case`Q`:e.push(...Na(r,i,a[1],a[2],a[1],a[2],a[3],a[4])),r=a[3],i=a[4];break;case`Z`:r=t,i=n}return Nt(e)}_calcDimensions(){let e=this._calcBoundsFromPath();return{...e,pathOffset:new R(e.left+e.width/2,e.top+e.height/2)}}static fromObject(e){return this._fromObject(e,{extraParam:`path`})}static async fromElement(e,t,n){let{d:r,...i}=fa(e,this.ATTRIBUTE_NAMES,n);return new this(r,{...i,...t,left:void 0,top:void 0})}};p(qo,`type`,`Path`),p(qo,`cacheProperties`,[...tr,`path`,`fillRule`]),p(qo,`ATTRIBUTE_NAMES`,[...Ui,`d`]),L.setClass(qo),L.setSVGClass(qo);var Jo=[`radius`,`startAngle`,`endAngle`,`counterClockwise`],Yo=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_set(e,t){return super._set(e,t),e===`radius`&&this.setRadius(t),this}_render(e){e.beginPath(),e.arc(0,0,this.radius,z(this.startAngle),z(this.endAngle),this.counterClockwise),this._renderPaintInOrder(e)}getRadiusX(){return this.get(`radius`)*this.get(pe)}getRadiusY(){return this.get(`radius`)*this.get(me)}setRadius(e){this.radius=e,this.set({width:2*e,height:2*e})}toObject(e=[]){return super.toObject([...Jo,...e])}_toSVG(){let{radius:e,startAngle:t,endAngle:n}=this,r=(n-t)%360;if(r===0)return[`<circle `,`COMMON_PARTS`,`cx="0" cy="0" `,`r="`,`${H(e)}`,`" />
|
|
22
22
|
`];{let i=z(t),a=z(n),o=Te(i)*e,s=Ee(i)*e,c=Te(a)*e,l=Ee(a)*e;return[`<path d="M ${o} ${s} A ${e} ${e} 0 ${+(r>180)} ${+!this.counterClockwise} ${c} ${l}" `,`COMMON_PARTS`,` />
|
|
23
|
-
`]}}static async fromElement(e,t,n){let{left:r=0,top:i=0,radius:a=0,...o}=fa(e,this.ATTRIBUTE_NAMES,n);return new this({...o,radius:a,left:r-a,top:i-a})}static fromObject(e){return super._fromObject(e)}};p(Yo,`type`,`Circle`),p(Yo,`cacheProperties`,[...tr,...Jo]),p(Yo,`ownDefaults`,{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),p(Yo,`ATTRIBUTE_NAMES`,[`cx`,`cy`,`r`,...Ui]),L.setClass(Yo),L.setSVGClass(Yo);var Xo=[`x1`,`x2`,`y1`,`y2`],Zo=class e extends Mi{constructor([t,n,r,i]=[0,0,0,0],a={}){super(),Object.assign(this,e.ownDefaults),this.setOptions(a),this.x1=t,this.x2=r,this.y1=n,this.y2=i,this._setWidthHeight();let{left:o,top:s}=a;typeof o==`number`&&this.set(`left`,o),typeof s==`number`&&this.set(`top`,s)}_setWidthHeight(){let{x1:e,y1:t,x2:n,y2:r}=this;this.width=Math.abs(n-e),this.height=Math.abs(r-t);let{left:i,top:a,width:o,height:s}=Nt([{x:e,y:t},{x:n,y:r}]),c=new R(i+o/2,a+s/2);this.setPositionByOrigin(c,P,P)}_set(e,t){return super._set(e,t),Xo.includes(e)&&this._setWidthHeight(),this}_render(e){e.beginPath();let t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;let n=e.strokeStyle;ut(this.stroke)?e.strokeStyle=this.stroke.toLive(e):e.strokeStyle=this.stroke??e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=n}_findCenterFromElement(){return new R((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(e=[]){return{...super.toObject(e),...this.calcLinePoints()}}_getNonTransformedDimensions(){let e=super._getNonTransformedDimensions();return this.strokeLineCap===`butt`&&(this.width===0&&(e.y-=this.strokeWidth),this.height===0&&(e.x-=this.strokeWidth)),e}calcLinePoints(){let{x1:e,x2:t,y1:n,y2:r,width:i,height:a}=this,o=e<=t?-.5:.5,s=n<=r?-.5:.5;return{x1:o*i,x2:o*-i,y1:s*a,y2:s*-a}}_toSVG(){let{x1:e,x2:t,y1:n,y2:r}=this.calcLinePoints();return[`<line `,`COMMON_PARTS`,`x1="${e}" y1="${n}" x2="${t}" y2="${r}" />\n`]}static async fromElement(e,t,n){let{x1:r=0,y1:i=0,x2:a=0,y2:o=0,...s}=fa(e,this.ATTRIBUTE_NAMES,n);return new this([r,i,a,o],s)}static fromObject({x1:e,y1:t,x2:n,y2:r,...i}){return this._fromObject({...i,points:[e,t,n,r]},{extraParam:`points`})}};p(Zo,`type`,`Line`),p(Zo,`cacheProperties`,[...tr,...Xo]),p(Zo,`ATTRIBUTE_NAMES`,Ui.concat(Xo)),L.setClass(Zo),L.setSVGClass(Zo);var Qo=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_render(e){let t=this.width/2,n=this.height/2;e.beginPath(),e.moveTo(-t,n),e.lineTo(0,-n),e.lineTo(t,n),e.closePath(),this._renderPaintInOrder(e)}_toSVG(){let e=this.width/2,t=this.height/2;return[`<polygon `,`COMMON_PARTS`,`points="`,`${-e} ${t},0 ${-t},${e} ${t}`,`" />`]}};p(Qo,`type`,`Triangle`),p(Qo,`ownDefaults`,{width:100,height:100}),L.setClass(Qo),L.setSVGClass(Qo);var $o=[`rx`,`ry`],es=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_set(e,t){switch(super._set(e,t),e){case`rx`:this.rx=t,this.set(`width`,2*t);break;case`ry`:this.ry=t,this.set(`height`,2*t)}return this}getRx(){return this.get(`rx`)*this.get(pe)}getRy(){return this.get(`ry`)*this.get(me)}toObject(e=[]){return super.toObject([...$o,...e])}_toSVG(){return[`<ellipse `,`COMMON_PARTS`,`cx="0" cy="0" rx="${H(this.rx)}" ry="${H(this.ry)}" />\n`]}_render(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,M,!1),e.restore(),this._renderPaintInOrder(e)}static async fromElement(e,t,n){let r=fa(e,this.ATTRIBUTE_NAMES,n);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}};p(es,`type`,`Ellipse`),p(es,`cacheProperties`,[...tr,...$o]),p(es,`ownDefaults`,{rx:0,ry:0}),p(es,`ATTRIBUTE_NAMES`,[...Ui,`cx`,`cy`,`rx`,`ry`]),L.setClass(es),L.setSVGClass(es);var ts={exactBoundingBox:!1},ns=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t=[],n={}){super(),p(this,`strokeDiff`,void 0),Object.assign(this,e.ownDefaults),this.setOptions(n),this.points=t;let{left:r,top:i}=n;this.initialized=!0,this.setBoundingBox(!0),typeof r==`number`&&this.set(`left`,r),typeof i==`number`&&this.set(`top`,i)}isOpen(){return!0}_projectStrokeOnPoints(e){return Ri(this.points,e,this.isOpen())}_calcDimensions(e){e={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth,...e||{}};let t=this.exactBoundingBox?this._projectStrokeOnPoints(e).map(e=>e.projectedPoint):this.points;if(t.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new R,strokeOffset:new R,strokeDiff:new R};let n=Nt(t),r=nt({...e,scaleX:1,scaleY:1}),i=Nt(this.points.map(e=>Ue(e,r,!0))),a=new R(this.scaleX,this.scaleY),o=n.left+n.width/2,s=n.top+n.height/2;return this.exactBoundingBox&&(o-=s*Math.tan(z(this.skewX)),s-=o*Math.tan(z(this.skewY))),{...n,pathOffset:new R(o,s),strokeOffset:new R(i.left,i.top).subtract(new R(n.left,n.top)).multiply(a),strokeDiff:new R(n.width,n.height).subtract(new R(i.width,i.height)).multiply(a)}}_findCenterFromElement(){let e=Nt(this.points);return new R(e.left+e.width/2,e.top+e.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(e){let{left:t,top:n,width:r,height:i,pathOffset:a,strokeOffset:o,strokeDiff:s}=this._calcDimensions();this.set({width:r,height:i,pathOffset:a,strokeOffset:o,strokeDiff:s}),e&&this.setPositionByOrigin(new R(t+r/2,n+i/2),`center`,`center`)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new R(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(e={}){if(this.exactBoundingBox){let t;if(Object.keys(e).some(e=>this.strokeUniform||this.constructor.layoutProperties.includes(e))){let{width:n,height:r}=this._calcDimensions(e);t=new R(e.width??n,e.height??r)}else t=new R(e.width??this.width,e.height??this.height);return t.multiply(new R(e.scaleX||this.scaleX,e.scaleY||this.scaleY))}return super._getTransformedDimensions(e)}_set(e,t){let n=this.initialized&&this[e]!==t,r=super._set(e,t);return this.exactBoundingBox&&n&&((e===`scaleX`||e===`scaleY`)&&this.strokeUniform&&this.constructor.layoutProperties.includes(`strokeUniform`)||this.constructor.layoutProperties.includes(e))&&this.setDimensions(),r}toObject(e=[]){return{...super.toObject(e),points:this.points.map(({x:e,y:t})=>({x:e,y:t}))}}_toSVG(){let e=this.pathOffset.x,t=this.pathOffset.y,n=h.NUM_FRACTION_DIGITS,r=this.points.map(({x:r,y:i})=>`${V(r-e,n)},${V(i-t,n)}`).join(` `);return[`<${H(this.constructor.type).toLowerCase()} `,`COMMON_PARTS`,`points="${r}" />\n`]}_render(e){let t=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(t&&!isNaN(this.points[t-1].y)){e.beginPath(),e.moveTo(this.points[0].x-n,this.points[0].y-r);for(let i=0;i<t;i++){let t=this.points[i];e.lineTo(t.x-n,t.y-r)}!this.isOpen()&&e.closePath(),this._renderPaintInOrder(e)}}complexity(){return this.points.length}static async fromElement(e,t,n){let r=function(e){if(!e)return[];let t=e.replace(/,/g,` `).trim().split(/\s+/),n=[];for(let e=0;e<t.length;e+=2)n.push({x:parseFloat(t[e]),y:parseFloat(t[e+1])});return n}(e.getAttribute(`points`)),{left:i,top:a,...o}=fa(e,this.ATTRIBUTE_NAMES,n);return new this(r,{...o,...t})}static fromObject(e){return this._fromObject(e,{extraParam:`points`})}};p(ns,`ownDefaults`,ts),p(ns,`type`,`Polyline`),p(ns,`layoutProperties`,[he,ge,`strokeLineCap`,`strokeLineJoin`,`strokeMiterLimit`,`strokeWidth`,`strokeUniform`,`points`]),p(ns,`cacheProperties`,[...tr,`points`]),p(ns,`ATTRIBUTE_NAMES`,[...Ui]),L.setClass(ns),L.setSVGClass(ns);var rs=class extends ns{isOpen(){return!1}};p(rs,`ownDefaults`,ts),p(rs,`type`,`Polygon`),L.setClass(rs),L.setSVGClass(rs);var is=class extends Mi{isEmptyStyles(e){if(!this.styles||e!==void 0&&!this.styles[e])return!0;let t=e===void 0?this.styles:{line:this.styles[e]};for(let e in t)for(let n in t[e])for(let r in t[e][n])return!1;return!0}styleHas(e,t){if(!this.styles||t!==void 0&&!this.styles[t])return!1;let n=t===void 0?this.styles:{0:this.styles[t]};for(let t in n)for(let r in n[t])if(n[t][r][e]!==void 0)return!0;return!1}cleanStyle(e){if(!this.styles)return!1;let t=this.styles,n,r,i=0,a=!0,o=0;for(let o in t){n=0;for(let s in t[o]){let c=t[o][s]||{};i++,c[e]===void 0?a=!1:(r?c[e]!==r&&(a=!1):r=c[e],c[e]===this[e]&&delete c[e]),Object.keys(c).length===0?delete t[o][s]:n++}n===0&&delete t[o]}for(let e=0;e<this._textLines.length;e++)o+=this._textLines[e].length;a&&i===o&&(this[e]=r,this.removeStyle(e))}removeStyle(e){if(!this.styles)return;let t=this.styles,n,r,i;for(r in t){for(i in n=t[r],n)delete n[i][e],Object.keys(n[i]).length===0&&delete n[i];Object.keys(n).length===0&&delete t[r]}}_extendStyles(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e);this._getLineStyle(n)||this._setLineStyle(n);let i=ct({...this._getStyleDeclaration(n,r),...t},e=>e!==void 0);this._setStyleDeclaration(n,r,i)}getSelectionStyles(e,t,n){let r=[];for(let i=e;i<(t||e);i++)r.push(this.getStyleAtPosition(i,n));return r}getStyleAtPosition(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e);return t?this.getCompleteStyleDeclaration(n,r):this._getStyleDeclaration(n,r)}setSelectionStyles(e,t,n){for(let r=t;r<(n||t);r++)this._extendStyles(r,e);this._forceClearCache=!0}_getStyleDeclaration(e,t){var n;let r=this.styles&&this.styles[e];return r&&(n=r[t])!=null?n:{}}getCompleteStyleDeclaration(e,t){return{...st(this,this.constructor._styleProperties),...this._getStyleDeclaration(e,t)}}_setStyleDeclaration(e,t,n){this.styles[e][t]=n}_deleteStyleDeclaration(e,t){delete this.styles[e][t]}_getLineStyle(e){return!!this.styles[e]}_setLineStyle(e){this.styles[e]={}}_deleteLineStyle(e){delete this.styles[e]}};p(is,`_styleProperties`,In);var as=/ +/g,os=/"/g;function ss(e,t,n,r,i){return`\t\t${((e,{left:t,top:n,width:r,height:i},a=h.NUM_FRACTION_DIGITS)=>{let o=Dn(_e,e,!1),[s,c,l,u]=[t,n,r,i].map(e=>V(e,a));return`<rect ${o} x="${s}" y="${c}" width="${l}" height="${u}"></rect>`})(e,{left:t,top:n,width:r,height:i})}\n`}var cs,ls=class e extends is{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(),p(this,`__charBounds`,[]),Object.assign(this,e.ownDefaults),this.setOptions(n),this.styles||={},this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){let e=this.path;e&&(e.segmentsInfo=Ka(e.path))}_splitText(){let e=this._splitTextIntoLines(this.text);return this.textLines=e.lines,this._textLines=e.graphemeLines,this._unwrappedTextLines=e._unwrappedLines,this._text=e.graphemeText,e}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(`justify`)&&this.enlargeSpaces()}enlargeSpaces(){let e,t,n,r,i,a,o;for(let s=0,c=this._textLines.length;s<c;s++)if((this.textAlign===`justify`||s!==c-1&&!this.isEndOfWrapping(s))&&(r=0,i=this._textLines[s],t=this.getLineWidth(s),t<this.width&&(o=this.textLines[s].match(this._reSpacesAndTabs)))){n=o.length,e=(this.width-t)/n;for(let t=0;t<=i.length;t++)a=this.__charBounds[s][t],this._reSpaceAndTab.test(i[t])?(a.width+=e,a.kernedWidth+=e,a.left+=r,r+=e):a.left+=r}}isEndOfWrapping(e){return e===this._textLines.length-1}missingNewlineOffset(e){return 1}get2DCursorLocation(e,t){let n=t?this._unwrappedTextLines:this._textLines,r;for(r=0;r<n.length;r++){if(e<=n[r].length)return{lineIndex:r,charIndex:e};e-=n[r].length+this.missingNewlineOffset(r,t)}return{lineIndex:r-1,charIndex:n[r-1].length<e?n[r-1].length:e}}toString(){return`#<Text (${this.complexity()}): { "text": "${this.text}", "fontFamily": "${this.fontFamily}" }>`}_getCacheCanvasDimensions(){let e=super._getCacheCanvasDimensions(),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e}_render(e){let t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,`underline`),this._renderText(e),this._renderTextDecoration(e,`overline`),this._renderTextDecoration(e,`linethrough`)}_renderText(e){this.paintFirst===`stroke`?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))}_setTextStyles(e,t,n){if(e.textBaseline=`alphabetic`,this.path)switch(this.pathAlign){case P:e.textBaseline=`middle`;break;case`ascender`:e.textBaseline=`top`;break;case`descender`:e.textBaseline=I}e.font=this._getFontDeclaration(t,n)}calcTextWidth(){let e=this.getLineWidth(0);for(let t=1,n=this._textLines.length;t<n;t++){let n=this.getLineWidth(t);n>e&&(e=n)}return e}_renderTextLine(e,t,n,r,i,a){this._renderChars(e,t,n,r,i,a)}_renderTextLinesBackground(e){if(!this.textBackgroundColor&&!this.styleHas(`textBackgroundColor`))return;let t=e.fillStyle,n=this._getLeftOffset(),r=this._getTopOffset();for(let t=0,i=this._textLines.length;t<i;t++){let i=this.getHeightOfLine(t);if(!this.textBackgroundColor&&!this.styleHas(`textBackgroundColor`,t)){r+=i;continue}let a=this._textLines[t].length,o=this._getLineLeftOffset(t),s,c,l=0,u=0,d=this.getValueOfPropertyAt(t,0,`textBackgroundColor`),f=this.getHeightOfLineImpl(t);for(let i=0;i<a;i++){let a=this.__charBounds[t][i];c=this.getValueOfPropertyAt(t,i,`textBackgroundColor`),this.path?(e.save(),e.translate(a.renderLeft,a.renderTop),e.rotate(a.angle),e.fillStyle=c,c&&e.fillRect(-a.width/2,-f*(1-this._fontSizeFraction),a.width,f),e.restore()):c===d?l+=a.kernedWidth:(s=n+o+u,this.direction===`rtl`&&(s=this.width-s-l),e.fillStyle=d,d&&e.fillRect(s,r,l,f),u=a.left,l=a.width,d=c)}c&&!this.path&&(s=n+o+u,this.direction===`rtl`&&(s=this.width-s-l),e.fillStyle=c,e.fillRect(s,r,l,f)),r+=i}e.fillStyle=t,this._removeShadow(e)}_measureChar(e,t,n,r){let i=D.getFontCache(t),a=this._getFontDeclaration(t),o=n?n+e:e,s=n&&a===this._getFontDeclaration(r),c=t.fontSize/this.CACHE_FONT_SIZE,l,u,d,f;if(n&&i.has(n)&&(d=i.get(n)),i.has(e)&&(f=l=i.get(e)),s&&i.has(o)&&(u=i.get(o),f=u-d),l===void 0||d===void 0||u===void 0){let r=(cs||=Re({width:0,height:0}).getContext(`2d`),cs);this._setTextStyles(r,t,!0),l===void 0&&(f=l=r.measureText(e).width,i.set(e,l)),d===void 0&&s&&n&&(d=r.measureText(n).width,i.set(n,d)),s&&u===void 0&&(u=r.measureText(o).width,i.set(o,u),f=u-d)}return{width:l*c,kernedWidth:f*c}}getHeightOfChar(e,t){return this.getValueOfPropertyAt(e,t,`fontSize`)}measureLine(e){let t=this._measureLine(e);return this.charSpacing!==0&&(t.width-=this._getWidthOfCharSpacing()),t.width<0&&(t.width=0),t}_measureLine(e){let t,n,r=0,i=this.pathSide===te,a=this.path,o=this._textLines[e],s=o.length,c=Array(s);this.__charBounds[e]=c;for(let i=0;i<s;i++){let a=o[i];n=this._getGraphemeBox(a,e,i,t),c[i]=n,r+=n.kernedWidth,t=a}if(c[s]={left:n?n.left+n.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},a&&a.segmentsInfo){let e=0,t=a.segmentsInfo[a.segmentsInfo.length-1].length;switch(this.textAlign){case F:e=i?t-r:0;break;case P:e=(t-r)/2;break;case te:e=i?0:t-r}e+=this.pathStartOffset*(i?-1:1);for(let r=i?s-1:0;i?r>=0:r<s;i?r--:r++)n=c[r],e>t?e%=t:e<0&&(e+=t),this._setGraphemeOnPath(e,n),e+=n.kernedWidth}return{width:r,numOfSpaces:0}}_setGraphemeOnPath(e,t){let n=e+t.kernedWidth/2,r=this.path,i=qa(r.path,n,r.segmentsInfo);t.renderLeft=i.x-r.pathOffset.x,t.renderTop=i.y-r.pathOffset.y,t.angle=i.angle+(this.pathSide===`right`?Math.PI:0)}_getGraphemeBox(e,t,n,r,i){let a=this.getCompleteStyleDeclaration(t,n),o=r?this.getCompleteStyleDeclaration(t,n-1):{},s=this._measureChar(e,a,r,o),c,l=s.kernedWidth,u=s.width;this.charSpacing!==0&&(c=this._getWidthOfCharSpacing(),u+=c,l+=c);let d={width:u,left:0,height:a.fontSize,kernedWidth:l,deltaY:a.deltaY};if(n>0&&!i){let e=this.__charBounds[t][n-1];d.left=e.left+e.width+s.kernedWidth-s.width}return d}getHeightOfLineImpl(e){let t=this.__lineHeights;if(t[e])return t[e];let n=this.getHeightOfChar(e,0);for(let t=1,r=this._textLines[e].length;t<r;t++)n=Math.max(this.getHeightOfChar(e,t),n);return t[e]=n*this._fontSizeMult}getHeightOfLine(e){return this.getHeightOfLineImpl(e)*this.lineHeight}calcTextHeight(){let e=0;for(let t=0,n=this._textLines.length;t<n;t++)e+=t===n-1?this.getHeightOfLineImpl(t):this.getHeightOfLine(t);return e}_getLeftOffset(){return this.direction===`ltr`?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(e,t){e.save();let n=0,r=this._getLeftOffset(),i=this._getTopOffset();for(let a=0,o=this._textLines.length;a<o;a++)this._renderTextLine(t,e,this._textLines[a],r+this._getLineLeftOffset(a),i+n+this.getHeightOfLineImpl(a),a),n+=this.getHeightOfLine(a);e.restore()}_renderTextFill(e){(this.fill||this.styleHas(`fill`))&&this._renderTextCommon(e,`fillText`)}_renderTextStroke(e){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this._setLineDash(e,this.strokeDashArray),e.beginPath(),this._renderTextCommon(e,`strokeText`),e.closePath(),e.restore())}_renderChars(e,t,n,r,i,a){let o=this.textAlign.includes(Rn),s=this.path,c=!o&&this.charSpacing===0&&this.isEmptyStyles(a)&&!s,l=this.direction===`ltr`,u=this.direction===`ltr`?1:-1,d=t.direction,f,p,m,h,g,_=``,v=0;if(t.save(),d!==this.direction&&(t.canvas.setAttribute(`dir`,l?`ltr`:`rtl`),t.direction=l?`ltr`:`rtl`,t.textAlign=l?F:te),i-=this.getHeightOfLineImpl(a)*this._fontSizeFraction,c)return this._renderChar(e,t,a,0,n.join(``),r,i),void t.restore();for(let c=0,l=n.length-1;c<=l;c++)h=c===l||this.charSpacing||s,_+=n[c],m=this.__charBounds[a][c],v===0?(r+=u*(m.kernedWidth-m.width),v+=m.width):v+=m.kernedWidth,o&&!h&&this._reSpaceAndTab.test(n[c])&&(h=!0),h||=(f||=this.getCompleteStyleDeclaration(a,c),p=this.getCompleteStyleDeclaration(a,c+1),Bi(f,p,!1)),h&&(s?(t.save(),t.translate(m.renderLeft,m.renderTop),t.rotate(m.angle),this._renderChar(e,t,a,c,_,-v/2,0),t.restore()):(g=r,this._renderChar(e,t,a,c,_,g,i)),_=``,f=p,r+=u*v,v=0);t.restore()}_applyPatternGradientTransformText(e){let t=this.width+this.strokeWidth,n=this.height+this.strokeWidth,r=Re({width:t,height:n}),i=r.getContext(`2d`);return r.width=t,r.height=n,i.beginPath(),i.moveTo(0,0),i.lineTo(t,0),i.lineTo(t,n),i.lineTo(0,n),i.closePath(),i.translate(t/2,n/2),i.fillStyle=e.toLive(i),this._applyPatternGradientTransform(i,e),i.fill(),i.createPattern(r,`no-repeat`)}handleFiller(e,t,n){let r,i;return ut(n)?n.gradientUnits===`percentage`||n.gradientTransform||n.patternTransform?(r=-this.width/2,i=-this.height/2,e.translate(r,i),e[t]=this._applyPatternGradientTransformText(n),{offsetX:r,offsetY:i}):(e[t]=n.toLive(e),this._applyPatternGradientTransform(e,n)):(e[t]=n,{offsetX:0,offsetY:0})}_setStrokeStyles(e,{stroke:t,strokeWidth:n}){return e.lineWidth=n,e.lineCap=this.strokeLineCap,e.lineDashOffset=this.strokeDashOffset,e.lineJoin=this.strokeLineJoin,e.miterLimit=this.strokeMiterLimit,this.handleFiller(e,`strokeStyle`,t)}_setFillStyles(e,{fill:t}){return this.handleFiller(e,`fillStyle`,t)}_renderChar(e,t,n,r,i,a,o){let s=this._getStyleDeclaration(n,r),c=this.getCompleteStyleDeclaration(n,r),l=e===`fillText`&&c.fill,u=e===`strokeText`&&c.stroke&&c.strokeWidth;if(u||l){if(t.save(),t.font=this._getFontDeclaration(c),s.textBackgroundColor&&this._removeShadow(t),s.deltaY&&(o+=s.deltaY),l){let e=this._setFillStyles(t,c);t.fillText(i,a-e.offsetX,o-e.offsetY)}if(u){let e=this._setStrokeStyles(t,c);t.strokeText(i,a-e.offsetX,o-e.offsetY)}t.restore()}}setSuperscript(e,t){this._setScript(e,t,this.superscript)}setSubscript(e,t){this._setScript(e,t,this.subscript)}_setScript(e,t,n){let r=this.get2DCursorLocation(e,!0),i=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,`fontSize`),a=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,`deltaY`),o={fontSize:i*n.size,deltaY:a+i*n.baseline};this.setSelectionStyles(o,e,t)}_getLineLeftOffset(e){let t=this.getLineWidth(e),n=this.width-t,r=this.textAlign,i=this.direction,a=this.isEndOfWrapping(e),o=0;return r===`justify`||r===`justify-center`&&!a||r===`justify-right`&&!a||r===`justify-left`&&!a?0:(r===`center`&&(o=n/2),r===`right`&&(o=n),r===`justify-center`&&(o=n/2),r===`justify-right`&&(o=n),i===`rtl`&&(r===`right`||r===`justify-right`?o=0:r===`left`||r===`justify-left`?o=-n:r!==`center`&&r!==`justify-center`||(o=-n/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(e){if(this.__lineWidths[e]!==void 0)return this.__lineWidths[e];let{width:t}=this.measureLine(e);return this.__lineWidths[e]=t,t}_getWidthOfCharSpacing(){return this.charSpacing===0?0:this.fontSize*this.charSpacing/1e3}getValueOfPropertyAt(e,t,n){return this._getStyleDeclaration(e,t)[n]??this[n]}_renderTextDecoration(e,t){if(!this[t]&&!this.styleHas(t))return;let n=this._getTopOffset(),r=this._getLeftOffset(),i=this.path,a=this._getWidthOfCharSpacing(),o=t===`linethrough`?.5:+(t===`overline`),s=this.offsets[t];for(let c=0,l=this._textLines.length;c<l;c++){let l=this.getHeightOfLine(c);if(!this[t]&&!this.styleHas(t,c)){n+=l;continue}let u=this._textLines[c],d=l/this.lineHeight,f=this._getLineLeftOffset(c),p,m=0,h=0,g=this.getValueOfPropertyAt(c,0,t),_=this.getValueOfPropertyAt(c,0,_e),v=this.getValueOfPropertyAt(c,0,`textDecorationColor`)||_,y=this.getValueOfPropertyAt(c,0,An),b=g,x=v,S=y,C=n+d*(1-this._fontSizeFraction),w=this.getHeightOfChar(c,0),T=this.getValueOfPropertyAt(c,0,`deltaY`);for(let n=0,a=u.length;n<a;n++){let a=this.__charBounds[c][n];b=this.getValueOfPropertyAt(c,n,t),p=this.getValueOfPropertyAt(c,n,_e),x=this.getValueOfPropertyAt(c,n,`textDecorationColor`)||p,S=this.getValueOfPropertyAt(c,n,An);let l=this.getHeightOfChar(c,n),u=this.getValueOfPropertyAt(c,n,`deltaY`);if(i&&b&&p){let t=this.fontSize*S/1e3;e.save(),e.fillStyle=x,e.translate(a.renderLeft,a.renderTop),e.rotate(a.angle),e.fillRect(-a.kernedWidth/2,s*l+u-o*t,a.kernedWidth,t),e.restore()}else if((b!==g||p!==_||x!==v||l!==w||S!==y||u!==T)&&h>0){let t=this.fontSize*y/1e3,n=r+f+m;this.direction===`rtl`&&(n=this.width-n-h),g&&v&&y&&(e.fillStyle=v,e.fillRect(n,C+s*w+T-o*t,h,t)),m=a.left,h=a.width,g=b,v=x,y=S,_=p,w=l,T=u}else h+=a.kernedWidth}let E=r+f+m;this.direction===`rtl`&&(E=this.width-E-h),e.fillStyle=x;let D=this.fontSize*S/1e3;b&&x&&S&&e.fillRect(E,C+s*w+T-o*D,h-a,D),n+=l}this._removeShadow(e)}_getFontDeclaration({fontFamily:t=this.fontFamily,fontStyle:n=this.fontStyle,fontWeight:r=this.fontWeight,fontSize:i=this.fontSize}={},a){let o=t.includes(`'`)||t.includes(`"`)||t.includes(`,`)||e.genericFonts.includes(t.toLowerCase())?t:`"${t}"`;return[n,r,`${a?this.CACHE_FONT_SIZE:i}px`,o].join(` `)}render(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(e)))}graphemeSplit(e){return Tt(e)}_splitTextIntoLines(e){let t=e.split(this._reNewline),n=Array(t.length),r=[`
|
|
23
|
+
`]}}static async fromElement(e,t,n){let{left:r=0,top:i=0,radius:a=0,...o}=fa(e,this.ATTRIBUTE_NAMES,n);return new this({...o,radius:a,left:r-a,top:i-a})}static fromObject(e){return super._fromObject(e)}};p(Yo,`type`,`Circle`),p(Yo,`cacheProperties`,[...tr,...Jo]),p(Yo,`ownDefaults`,{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),p(Yo,`ATTRIBUTE_NAMES`,[`cx`,`cy`,`r`,...Ui]),L.setClass(Yo),L.setSVGClass(Yo);var Xo=[`x1`,`x2`,`y1`,`y2`],Zo=class e extends Mi{constructor([t,n,r,i]=[0,0,0,0],a={}){super(),Object.assign(this,e.ownDefaults),this.setOptions(a),this.x1=t,this.x2=r,this.y1=n,this.y2=i,this._setWidthHeight();let{left:o,top:s}=a;typeof o==`number`&&this.set(`left`,o),typeof s==`number`&&this.set(`top`,s)}_setWidthHeight(){let{x1:e,y1:t,x2:n,y2:r}=this;this.width=Math.abs(n-e),this.height=Math.abs(r-t);let{left:i,top:a,width:o,height:s}=Nt([{x:e,y:t},{x:n,y:r}]),c=new R(i+o/2,a+s/2);this.setPositionByOrigin(c,P,P)}_set(e,t){return super._set(e,t),Xo.includes(e)&&this._setWidthHeight(),this}_render(e){e.beginPath();let t=this.calcLinePoints();e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),e.lineWidth=this.strokeWidth;let n=e.strokeStyle;e.strokeStyle=ut(this.stroke)?this.stroke.toLive(e):this.stroke??e.fillStyle,this.stroke&&this._renderStroke(e),e.strokeStyle=n}_findCenterFromElement(){return new R((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(e=[]){return{...super.toObject(e),...this.calcLinePoints()}}_getNonTransformedDimensions(){let e=super._getNonTransformedDimensions();return this.strokeLineCap===`butt`&&(this.width===0&&(e.y-=this.strokeWidth),this.height===0&&(e.x-=this.strokeWidth)),e}calcLinePoints(){let{x1:e,x2:t,y1:n,y2:r,width:i,height:a}=this,o=e<=t?-.5:.5,s=n<=r?-.5:.5;return{x1:o*i,x2:o*-i,y1:s*a,y2:s*-a}}_toSVG(){let{x1:e,x2:t,y1:n,y2:r}=this.calcLinePoints();return[`<line `,`COMMON_PARTS`,`x1="${e}" y1="${n}" x2="${t}" y2="${r}" />\n`]}static async fromElement(e,t,n){let{x1:r=0,y1:i=0,x2:a=0,y2:o=0,...s}=fa(e,this.ATTRIBUTE_NAMES,n);return new this([r,i,a,o],s)}static fromObject({x1:e,y1:t,x2:n,y2:r,...i}){return this._fromObject({...i,points:[e,t,n,r]},{extraParam:`points`})}};p(Zo,`type`,`Line`),p(Zo,`cacheProperties`,[...tr,...Xo]),p(Zo,`ATTRIBUTE_NAMES`,Ui.concat(Xo)),L.setClass(Zo),L.setSVGClass(Zo);var Qo=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_render(e){let t=this.width/2,n=this.height/2;e.beginPath(),e.moveTo(-t,n),e.lineTo(0,-n),e.lineTo(t,n),e.closePath(),this._renderPaintInOrder(e)}_toSVG(){let e=this.width/2,t=this.height/2;return[`<polygon `,`COMMON_PARTS`,`points="`,`${-e} ${t},0 ${-t},${e} ${t}`,`" />`]}};p(Qo,`type`,`Triangle`),p(Qo,`ownDefaults`,{width:100,height:100}),L.setClass(Qo),L.setSVGClass(Qo);var $o=[`rx`,`ry`],es=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t){super(),Object.assign(this,e.ownDefaults),this.setOptions(t)}_set(e,t){switch(super._set(e,t),e){case`rx`:this.rx=t,this.set(`width`,2*t);break;case`ry`:this.ry=t,this.set(`height`,2*t)}return this}getRx(){return this.get(`rx`)*this.get(pe)}getRy(){return this.get(`ry`)*this.get(me)}toObject(e=[]){return super.toObject([...$o,...e])}_toSVG(){return[`<ellipse `,`COMMON_PARTS`,`cx="0" cy="0" rx="${H(this.rx)}" ry="${H(this.ry)}" />\n`]}_render(e){e.beginPath(),e.save(),e.transform(1,0,0,this.ry/this.rx,0,0),e.arc(0,0,this.rx,0,M,!1),e.restore(),this._renderPaintInOrder(e)}static async fromElement(e,t,n){let r=fa(e,this.ATTRIBUTE_NAMES,n);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}};p(es,`type`,`Ellipse`),p(es,`cacheProperties`,[...tr,...$o]),p(es,`ownDefaults`,{rx:0,ry:0}),p(es,`ATTRIBUTE_NAMES`,[...Ui,`cx`,`cy`,`rx`,`ry`]),L.setClass(es),L.setSVGClass(es);var ts={exactBoundingBox:!1},ns=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t=[],n={}){super(),p(this,`strokeDiff`,void 0),Object.assign(this,e.ownDefaults),this.setOptions(n),this.points=t;let{left:r,top:i}=n;this.initialized=!0,this.setBoundingBox(!0),typeof r==`number`&&this.set(`left`,r),typeof i==`number`&&this.set(`top`,i)}isOpen(){return!0}_projectStrokeOnPoints(e){return Ri(this.points,e,this.isOpen())}_calcDimensions(e){e={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth,...e||{}};let t=this.exactBoundingBox?this._projectStrokeOnPoints(e).map(e=>e.projectedPoint):this.points;if(t.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new R,strokeOffset:new R,strokeDiff:new R};let n=Nt(t),r=nt({...e,scaleX:1,scaleY:1}),i=Nt(this.points.map(e=>Ue(e,r,!0))),a=new R(this.scaleX,this.scaleY),o=n.left+n.width/2,s=n.top+n.height/2;return this.exactBoundingBox&&(o-=s*Math.tan(z(this.skewX)),s-=o*Math.tan(z(this.skewY))),{...n,pathOffset:new R(o,s),strokeOffset:new R(i.left,i.top).subtract(new R(n.left,n.top)).multiply(a),strokeDiff:new R(n.width,n.height).subtract(new R(i.width,i.height)).multiply(a)}}_findCenterFromElement(){let e=Nt(this.points);return new R(e.left+e.width/2,e.top+e.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(e){let{left:t,top:n,width:r,height:i,pathOffset:a,strokeOffset:o,strokeDiff:s}=this._calcDimensions();this.set({width:r,height:i,pathOffset:a,strokeOffset:o,strokeDiff:s}),e&&this.setPositionByOrigin(new R(t+r/2,n+i/2),`center`,`center`)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new R(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(e={}){if(this.exactBoundingBox){let t;if(Object.keys(e).some(e=>this.strokeUniform||this.constructor.layoutProperties.includes(e))){let{width:n,height:r}=this._calcDimensions(e);t=new R(e.width??n,e.height??r)}else t=new R(e.width??this.width,e.height??this.height);return t.multiply(new R(e.scaleX||this.scaleX,e.scaleY||this.scaleY))}return super._getTransformedDimensions(e)}_set(e,t){let n=this.initialized&&this[e]!==t,r=super._set(e,t);return this.exactBoundingBox&&n&&((e===`scaleX`||e===`scaleY`)&&this.strokeUniform&&this.constructor.layoutProperties.includes(`strokeUniform`)||this.constructor.layoutProperties.includes(e))&&this.setDimensions(),r}toObject(e=[]){return{...super.toObject(e),points:this.points.map(({x:e,y:t})=>({x:e,y:t}))}}_toSVG(){let e=this.pathOffset.x,t=this.pathOffset.y,n=h.NUM_FRACTION_DIGITS,r=this.points.map(({x:r,y:i})=>`${V(r-e,n)},${V(i-t,n)}`).join(` `);return[`<${H(this.constructor.type).toLowerCase()} `,`COMMON_PARTS`,`points="${r}" />\n`]}_render(e){let t=this.points.length,n=this.pathOffset.x,r=this.pathOffset.y;if(t&&!isNaN(this.points[t-1].y)){e.beginPath(),e.moveTo(this.points[0].x-n,this.points[0].y-r);for(let i=0;i<t;i++){let t=this.points[i];e.lineTo(t.x-n,t.y-r)}!this.isOpen()&&e.closePath(),this._renderPaintInOrder(e)}}complexity(){return this.points.length}static async fromElement(e,t,n){let r=function(e){if(!e)return[];let t=e.replace(/,/g,` `).trim().split(/\s+/),n=[];for(let e=0;e<t.length;e+=2)n.push({x:parseFloat(t[e]),y:parseFloat(t[e+1])});return n}(e.getAttribute(`points`)),{left:i,top:a,...o}=fa(e,this.ATTRIBUTE_NAMES,n);return new this(r,{...o,...t})}static fromObject(e){return this._fromObject(e,{extraParam:`points`})}};p(ns,`ownDefaults`,ts),p(ns,`type`,`Polyline`),p(ns,`layoutProperties`,[he,ge,`strokeLineCap`,`strokeLineJoin`,`strokeMiterLimit`,`strokeWidth`,`strokeUniform`,`points`]),p(ns,`cacheProperties`,[...tr,`points`]),p(ns,`ATTRIBUTE_NAMES`,[...Ui]),L.setClass(ns),L.setSVGClass(ns);var rs=class extends ns{isOpen(){return!1}};p(rs,`ownDefaults`,ts),p(rs,`type`,`Polygon`),L.setClass(rs),L.setSVGClass(rs);var is=class extends Mi{isEmptyStyles(e){if(!this.styles||e!==void 0&&!this.styles[e])return!0;let t=e===void 0?this.styles:{line:this.styles[e]};for(let e in t)for(let n in t[e])for(let r in t[e][n])return!1;return!0}styleHas(e,t){if(!this.styles||t!==void 0&&!this.styles[t])return!1;let n=t===void 0?this.styles:{0:this.styles[t]};for(let t in n)for(let r in n[t])if(n[t][r][e]!==void 0)return!0;return!1}cleanStyle(e){if(!this.styles)return!1;let t=this.styles,n,r,i=0,a=!0,o=0;for(let o in t){n=0;for(let s in t[o]){let c=t[o][s]||{};i++,c[e]===void 0?a=!1:(r?c[e]!==r&&(a=!1):r=c[e],c[e]===this[e]&&delete c[e]),Object.keys(c).length===0?delete t[o][s]:n++}n===0&&delete t[o]}for(let e=0;e<this._textLines.length;e++)o+=this._textLines[e].length;a&&i===o&&(this[e]=r,this.removeStyle(e))}removeStyle(e){if(!this.styles)return;let t=this.styles,n,r,i;for(r in t){for(i in n=t[r],n)delete n[i][e],Object.keys(n[i]).length===0&&delete n[i];Object.keys(n).length===0&&delete t[r]}}_extendStyles(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e);this._getLineStyle(n)||this._setLineStyle(n);let i=ct({...this._getStyleDeclaration(n,r),...t},e=>e!==void 0);this._setStyleDeclaration(n,r,i)}getSelectionStyles(e,t,n){let r=[];for(let i=e;i<(t||e);i++)r.push(this.getStyleAtPosition(i,n));return r}getStyleAtPosition(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e);return t?this.getCompleteStyleDeclaration(n,r):this._getStyleDeclaration(n,r)}setSelectionStyles(e,t,n){for(let r=t;r<(n||t);r++)this._extendStyles(r,e);this._forceClearCache=!0}_getStyleDeclaration(e,t){var n;let r=this.styles&&this.styles[e];return r&&(n=r[t])!=null?n:{}}getCompleteStyleDeclaration(e,t){return{...st(this,this.constructor._styleProperties),...this._getStyleDeclaration(e,t)}}_setStyleDeclaration(e,t,n){this.styles[e][t]=n}_deleteStyleDeclaration(e,t){delete this.styles[e][t]}_getLineStyle(e){return!!this.styles[e]}_setLineStyle(e){this.styles[e]={}}_deleteLineStyle(e){delete this.styles[e]}};p(is,`_styleProperties`,In);var as=/ +/g,os=/"/g;function ss(e,t,n,r,i){return`\t\t${((e,{left:t,top:n,width:r,height:i},a=h.NUM_FRACTION_DIGITS)=>{let o=Dn(_e,e,!1),[s,c,l,u]=[t,n,r,i].map(e=>V(e,a));return`<rect ${o} x="${s}" y="${c}" width="${l}" height="${u}"></rect>`})(e,{left:t,top:n,width:r,height:i})}\n`}var cs,ls=class e extends is{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(),p(this,`__charBounds`,[]),Object.assign(this,e.ownDefaults),this.setOptions(n),this.styles||={},this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){let e=this.path;e&&(e.segmentsInfo=Ka(e.path))}_splitText(){let e=this._splitTextIntoLines(this.text);return this.textLines=e.lines,this._textLines=e.graphemeLines,this._unwrappedTextLines=e._unwrappedLines,this._text=e.graphemeText,e}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(`justify`)&&this.enlargeSpaces()}enlargeSpaces(){let e,t,n,r,i,a,o;for(let s=0,c=this._textLines.length;s<c;s++)if((this.textAlign===`justify`||s!==c-1&&!this.isEndOfWrapping(s))&&(r=0,i=this._textLines[s],t=this.getLineWidth(s),t<this.width&&(o=this.textLines[s].match(this._reSpacesAndTabs)))){n=o.length,e=(this.width-t)/n;for(let t=0;t<=i.length;t++)a=this.__charBounds[s][t],this._reSpaceAndTab.test(i[t])?(a.width+=e,a.kernedWidth+=e,a.left+=r,r+=e):a.left+=r}}isEndOfWrapping(e){return e===this._textLines.length-1}missingNewlineOffset(e){return 1}get2DCursorLocation(e,t){let n=t?this._unwrappedTextLines:this._textLines,r;for(r=0;r<n.length;r++){if(e<=n[r].length)return{lineIndex:r,charIndex:e};e-=n[r].length+this.missingNewlineOffset(r,t)}return{lineIndex:r-1,charIndex:n[r-1].length<e?n[r-1].length:e}}toString(){return`#<Text (${this.complexity()}): { "text": "${this.text}", "fontFamily": "${this.fontFamily}" }>`}_getCacheCanvasDimensions(){let e=super._getCacheCanvasDimensions(),t=this.fontSize;return e.width+=t*e.zoomX,e.height+=t*e.zoomY,e}_render(e){let t=this.path;t&&!t.isNotVisible()&&t._render(e),this._setTextStyles(e),this._renderTextLinesBackground(e),this._renderTextDecoration(e,`underline`),this._renderText(e),this._renderTextDecoration(e,`overline`),this._renderTextDecoration(e,`linethrough`)}_renderText(e){this.paintFirst===`stroke`?(this._renderTextStroke(e),this._renderTextFill(e)):(this._renderTextFill(e),this._renderTextStroke(e))}_setTextStyles(e,t,n){if(e.textBaseline=`alphabetic`,this.path)switch(this.pathAlign){case P:e.textBaseline=`middle`;break;case`ascender`:e.textBaseline=`top`;break;case`descender`:e.textBaseline=I}e.font=this._getFontDeclaration(t,n)}calcTextWidth(){let e=this.getLineWidth(0);for(let t=1,n=this._textLines.length;t<n;t++){let n=this.getLineWidth(t);n>e&&(e=n)}return e}_renderTextLine(e,t,n,r,i,a){this._renderChars(e,t,n,r,i,a)}_renderTextLinesBackground(e){if(!this.textBackgroundColor&&!this.styleHas(`textBackgroundColor`))return;let t=e.fillStyle,n=this._getLeftOffset(),r=this._getTopOffset();for(let t=0,i=this._textLines.length;t<i;t++){let i=this.getHeightOfLine(t);if(!this.textBackgroundColor&&!this.styleHas(`textBackgroundColor`,t)){r+=i;continue}let a=this._textLines[t].length,o=this._getLineLeftOffset(t),s,c,l=0,u=0,d=this.getValueOfPropertyAt(t,0,`textBackgroundColor`),f=this.getHeightOfLineImpl(t);for(let i=0;i<a;i++){let a=this.__charBounds[t][i];c=this.getValueOfPropertyAt(t,i,`textBackgroundColor`),this.path?(e.save(),e.translate(a.renderLeft,a.renderTop),e.rotate(a.angle),e.fillStyle=c,c&&e.fillRect(-a.width/2,-f*(1-this._fontSizeFraction),a.width,f),e.restore()):c===d?l+=a.kernedWidth:(s=n+o+u,this.direction===`rtl`&&(s=this.width-s-l),e.fillStyle=d,d&&e.fillRect(s,r,l,f),u=a.left,l=a.width,d=c)}c&&!this.path&&(s=n+o+u,this.direction===`rtl`&&(s=this.width-s-l),e.fillStyle=c,e.fillRect(s,r,l,f)),r+=i}e.fillStyle=t,this._removeShadow(e)}_measureChar(e,t,n,r){let i=D.getFontCache(t),a=this._getFontDeclaration(t),o=n?n+e:e,s=n&&a===this._getFontDeclaration(r),c=t.fontSize/this.CACHE_FONT_SIZE,l,u,d,f;if(n&&i.has(n)&&(d=i.get(n)),i.has(e)&&(f=l=i.get(e)),s&&i.has(o)&&(u=i.get(o),f=u-d),l===void 0||d===void 0||u===void 0){let r=(cs||=Re({width:0,height:0}).getContext(`2d`),cs);this._setTextStyles(r,t,!0),l===void 0&&(f=l=r.measureText(e).width,i.set(e,l)),d===void 0&&s&&n&&(d=r.measureText(n).width,i.set(n,d)),s&&u===void 0&&(u=r.measureText(o).width,i.set(o,u),f=u-d)}return{width:l*c,kernedWidth:f*c}}getHeightOfChar(e,t){return this.getValueOfPropertyAt(e,t,`fontSize`)}measureLine(e){let t=this._measureLine(e);return this.charSpacing!==0&&(t.width-=this._getWidthOfCharSpacing()),t.width<0&&(t.width=0),t}_measureLine(e){let t,n,r=0,i=this.pathSide===te,a=this.path,o=this._textLines[e],s=o.length,c=Array(s);this.__charBounds[e]=c;for(let i=0;i<s;i++){let a=o[i];n=this._getGraphemeBox(a,e,i,t),c[i]=n,r+=n.kernedWidth,t=a}if(c[s]={left:n?n.left+n.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},a&&a.segmentsInfo){let e=0,t=a.segmentsInfo[a.segmentsInfo.length-1].length;switch(this.textAlign){case F:e=i?t-r:0;break;case P:e=(t-r)/2;break;case te:e=i?0:t-r}e+=this.pathStartOffset*(i?-1:1);for(let r=i?s-1:0;i?r>=0:r<s;i?r--:r++)n=c[r],e>t?e%=t:e<0&&(e+=t),this._setGraphemeOnPath(e,n),e+=n.kernedWidth}return{width:r,numOfSpaces:0}}_setGraphemeOnPath(e,t){let n=e+t.kernedWidth/2,r=this.path,i=qa(r.path,n,r.segmentsInfo);t.renderLeft=i.x-r.pathOffset.x,t.renderTop=i.y-r.pathOffset.y,t.angle=i.angle+(this.pathSide===`right`?Math.PI:0)}_getGraphemeBox(e,t,n,r,i){let a=this.getCompleteStyleDeclaration(t,n),o=r?this.getCompleteStyleDeclaration(t,n-1):{},s=this._measureChar(e,a,r,o),c,l=s.kernedWidth,u=s.width;this.charSpacing!==0&&(c=this._getWidthOfCharSpacing(),u+=c,l+=c);let d={width:u,left:0,height:a.fontSize,kernedWidth:l,deltaY:a.deltaY};if(n>0&&!i){let e=this.__charBounds[t][n-1];d.left=e.left+e.width+s.kernedWidth-s.width}return d}getHeightOfLineImpl(e){let t=this.__lineHeights;if(t[e])return t[e];let n=this.getHeightOfChar(e,0);for(let t=1,r=this._textLines[e].length;t<r;t++)n=Math.max(this.getHeightOfChar(e,t),n);return t[e]=n*this._fontSizeMult}getHeightOfLine(e){return this.getHeightOfLineImpl(e)*this.lineHeight}calcTextHeight(){let e=0;for(let t=0,n=this._textLines.length;t<n;t++)e+=t===n-1?this.getHeightOfLineImpl(t):this.getHeightOfLine(t);return e}_getLeftOffset(){return this.direction===`ltr`?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(e,t){e.save();let n=0,r=this._getLeftOffset(),i=this._getTopOffset();for(let a=0,o=this._textLines.length;a<o;a++)this._renderTextLine(t,e,this._textLines[a],r+this._getLineLeftOffset(a),i+n+this.getHeightOfLineImpl(a),a),n+=this.getHeightOfLine(a);e.restore()}_renderTextFill(e){(this.fill||this.styleHas(`fill`))&&this._renderTextCommon(e,`fillText`)}_renderTextStroke(e){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(e),e.save(),this._setLineDash(e,this.strokeDashArray),e.beginPath(),this._renderTextCommon(e,`strokeText`),e.closePath(),e.restore())}_renderChars(e,t,n,r,i,a){let o=this.textAlign.includes(Rn),s=this.path,c=!o&&this.charSpacing===0&&this.isEmptyStyles(a)&&!s,l=this.direction===`ltr`,u=this.direction===`ltr`?1:-1,d=t.direction,f,p,m,h,g,_=``,v=0;if(t.save(),d!==this.direction&&(t.canvas.setAttribute(`dir`,l?`ltr`:`rtl`),t.direction=l?`ltr`:`rtl`,t.textAlign=l?F:te),i-=this.getHeightOfLineImpl(a)*this._fontSizeFraction,c)return this._renderChar(e,t,a,0,n.join(``),r,i),void t.restore();for(let c=0,l=n.length-1;c<=l;c++)h=c===l||this.charSpacing||s,_+=n[c],m=this.__charBounds[a][c],v===0?(r+=u*(m.kernedWidth-m.width),v+=m.width):v+=m.kernedWidth,o&&!h&&this._reSpaceAndTab.test(n[c])&&(h=!0),h||=(f||=this.getCompleteStyleDeclaration(a,c),p=this.getCompleteStyleDeclaration(a,c+1),Bi(f,p,!1)),h&&(s?(t.save(),t.translate(m.renderLeft,m.renderTop),t.rotate(m.angle),this._renderChar(e,t,a,c,_,-v/2,0),t.restore()):(g=r,this._renderChar(e,t,a,c,_,g,i)),_=``,f=p,r+=u*v,v=0);t.restore()}_applyPatternGradientTransformText(e){let t=this.width+this.strokeWidth,n=this.height+this.strokeWidth,r=Re({width:t,height:n}),i=r.getContext(`2d`);return r.width=t,r.height=n,i.beginPath(),i.moveTo(0,0),i.lineTo(t,0),i.lineTo(t,n),i.lineTo(0,n),i.closePath(),i.translate(t/2,n/2),i.fillStyle=e.toLive(i),this._applyPatternGradientTransform(i,e),i.fill(),i.createPattern(r,`no-repeat`)}handleFiller(e,t,n){let r,i;return ut(n)?n.gradientUnits===`percentage`||n.gradientTransform||n.patternTransform?(r=-this.width/2,i=-this.height/2,e.translate(r,i),e[t]=this._applyPatternGradientTransformText(n),{offsetX:r,offsetY:i}):(e[t]=n.toLive(e),this._applyPatternGradientTransform(e,n)):(e[t]=n,{offsetX:0,offsetY:0})}_setStrokeStyles(e,{stroke:t,strokeWidth:n}){return e.lineWidth=n,e.lineCap=this.strokeLineCap,e.lineDashOffset=this.strokeDashOffset,e.lineJoin=this.strokeLineJoin,e.miterLimit=this.strokeMiterLimit,this.handleFiller(e,`strokeStyle`,t)}_setFillStyles(e,{fill:t}){return this.handleFiller(e,`fillStyle`,t)}_renderChar(e,t,n,r,i,a,o){let s=this._getStyleDeclaration(n,r),c=this.getCompleteStyleDeclaration(n,r),l=e===`fillText`&&c.fill,u=e===`strokeText`&&c.stroke&&c.strokeWidth;if(u||l){if(t.save(),t.font=this._getFontDeclaration(c),s.textBackgroundColor&&this._removeShadow(t),s.deltaY&&(o+=s.deltaY),l){let e=this._setFillStyles(t,c);t.fillText(i,a-e.offsetX,o-e.offsetY)}if(u){let e=this._setStrokeStyles(t,c);t.strokeText(i,a-e.offsetX,o-e.offsetY)}t.restore()}}setSuperscript(e,t){this._setScript(e,t,this.superscript)}setSubscript(e,t){this._setScript(e,t,this.subscript)}_setScript(e,t,n){let r=this.get2DCursorLocation(e,!0),i=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,`fontSize`),a=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,`deltaY`),o={fontSize:i*n.size,deltaY:a+i*n.baseline};this.setSelectionStyles(o,e,t)}_getLineLeftOffset(e){let t=this.getLineWidth(e),n=this.width-t,r=this.textAlign,i=this.direction,a=this.isEndOfWrapping(e),o=0;return r===`justify`||r===`justify-center`&&!a||r===`justify-right`&&!a||r===`justify-left`&&!a?0:(r===`center`&&(o=n/2),r===`right`&&(o=n),r===`justify-center`&&(o=n/2),r===`justify-right`&&(o=n),i===`rtl`&&(r===`right`||r===`justify-right`?o=0:r===`left`||r===`justify-left`?o=-n:r!==`center`&&r!==`justify-center`||(o=-n/2)),o)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(e){if(this.__lineWidths[e]!==void 0)return this.__lineWidths[e];let{width:t}=this.measureLine(e);return this.__lineWidths[e]=t,t}_getWidthOfCharSpacing(){return this.charSpacing===0?0:this.fontSize*this.charSpacing/1e3}getValueOfPropertyAt(e,t,n){return this._getStyleDeclaration(e,t)[n]??this[n]}_renderTextDecoration(e,t){if(!this[t]&&!this.styleHas(t))return;let n=this._getTopOffset(),r=this._getLeftOffset(),i=this.path,a=this._getWidthOfCharSpacing(),o=t===`linethrough`?.5:+(t===`overline`),s=this.offsets[t];for(let c=0,l=this._textLines.length;c<l;c++){let l=this.getHeightOfLine(c);if(!this[t]&&!this.styleHas(t,c)){n+=l;continue}let u=this._textLines[c],d=l/this.lineHeight,f=this._getLineLeftOffset(c),p,m=0,h=0,g=this.getValueOfPropertyAt(c,0,t),_=this.getValueOfPropertyAt(c,0,_e),v=this.getValueOfPropertyAt(c,0,`textDecorationColor`)||_,y=this.getValueOfPropertyAt(c,0,An),b=g,x=v,S=y,C=n+d*(1-this._fontSizeFraction),w=this.getHeightOfChar(c,0),T=this.getValueOfPropertyAt(c,0,`deltaY`);for(let n=0,a=u.length;n<a;n++){let a=this.__charBounds[c][n];b=this.getValueOfPropertyAt(c,n,t),p=this.getValueOfPropertyAt(c,n,_e),x=this.getValueOfPropertyAt(c,n,`textDecorationColor`)||p,S=this.getValueOfPropertyAt(c,n,An);let l=this.getHeightOfChar(c,n),u=this.getValueOfPropertyAt(c,n,`deltaY`);if(i&&b&&p){let t=this.fontSize*S/1e3;e.save(),e.fillStyle=x,e.translate(a.renderLeft,a.renderTop),e.rotate(a.angle),e.fillRect(-a.kernedWidth/2,s*l+u-o*t,a.kernedWidth,t),e.restore()}else if((b!==g||p!==_||x!==v||l!==w||S!==y||u!==T)&&h>0){let t=this.fontSize*y/1e3,n=r+f+m;this.direction===`rtl`&&(n=this.width-n-h),g&&v&&y&&(e.fillStyle=v,e.fillRect(n,C+s*w+T-o*t,h,t)),m=a.left,h=a.width,g=b,v=x,y=S,_=p,w=l,T=u}else h+=a.kernedWidth}let E=r+f+m;this.direction===`rtl`&&(E=this.width-E-h),e.fillStyle=x;let D=this.fontSize*S/1e3;b&&x&&S&&e.fillRect(E,C+s*w+T-o*D,h-a,D),n+=l}this._removeShadow(e)}_getFontDeclaration({fontFamily:t=this.fontFamily,fontStyle:n=this.fontStyle,fontWeight:r=this.fontWeight,fontSize:i=this.fontSize}={},a){let o=t.includes(`'`)||t.includes(`"`)||t.includes(`,`)||e.genericFonts.includes(t.toLowerCase())?t:`"${t}"`;return[n,r,`${a?this.CACHE_FONT_SIZE:i}px`,o].join(` `)}render(e){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(e)))}graphemeSplit(e){return Tt(e)}_splitTextIntoLines(e){let t=e.split(this._reNewline),n=Array(t.length),r=[`
|
|
24
24
|
`],i=[];for(let e=0;e<t.length;e++)n[e]=this.graphemeSplit(t[e]),i=i.concat(n[e],r);return i.pop(),{_unwrappedLines:n,lines:t,graphemeText:i,graphemeLines:n}}toObject(e=[]){return{...super.toObject([...Fn,...e]),styles:Vi(this.styles,this.text),...this.path?{path:this.path.toObject()}:{}}}set(e,t){let{textLayoutProperties:n}=this.constructor;super.set(e,t);let r=!1,i=!1;if(typeof e==`object`)for(let t in e)t===`path`&&this.setPathInfo(),r||=n.includes(t),i||=t===`path`;else r=n.includes(e),i=e===`path`;return i&&this.setPathInfo(),r&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,n,r){let i=fa(t,e.ATTRIBUTE_NAMES,r),{textAnchor:a=F,textDecoration:o=``,dx:s=0,dy:c=0,top:l=0,left:u=0,fontSize:d=16,strokeWidth:f=1,...p}={...n,...i},m=new this(gn(t.textContent||``).trim(),{left:u+s,top:l+c,underline:o.includes(`underline`),overline:o.includes(`overline`),linethrough:o.includes(`line-through`),strokeWidth:0,fontSize:d,...p}),h=m.getScaledHeight()/m.height,g=((m.height+m.strokeWidth)*m.lineHeight-m.height)*h,_=m.getScaledHeight()+g,v=0;return a===`center`&&(v=m.getScaledWidth()/2),a===`right`&&(v=m.getScaledWidth()),m.set({left:m.left-v,top:m.top-(_-m.fontSize*(.07+m._fontSizeFraction))/m.lineHeight,strokeWidth:f}),m}static fromObject(e){return this._fromObject({...e,styles:Hi(e.styles||{},e.text)},{extraParam:`text`})}};p(ls,`textLayoutProperties`,Pn),p(ls,`cacheProperties`,[...tr,...Fn]),p(ls,`ownDefaults`,Ln),p(ls,`type`,`Text`),p(ls,`genericFonts`,[`serif`,`sans-serif`,`monospace`,`cursive`,`fantasy`,`system-ui`,`ui-serif`,`ui-sans-serif`,`ui-monospace`,`ui-rounded`,`math`,`emoji`,`fangsong`]),p(ls,`ATTRIBUTE_NAMES`,Ui.concat(`x`,`y`,`dx`,`dy`,`font-family`,`font-style`,`font-weight`,`font-size`,`letter-spacing`,`text-decoration`,`text-decoration-thickness`,`text-decoration-color`,`text-anchor`)),ji(ls,[class extends On{_toSVG(){let e=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(e.textTop,e.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(e){let t=this._createBaseSVGMarkup(this._toSVG(),{reviver:e,noStyle:!0,withShadow:!0}),n=this.path;return n?t+n._createBaseSVGMarkup(n._toSVG(),{reviver:e,withShadow:!0,additionalTransform:lt(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg({textBgRects:e,textSpans:t}){let n=this.getSvgTextDecoration(this);return[e.join(``),` <text xml:space="preserve" `,`font-family="${H(this.fontFamily.replace(os,`'`))}" `,`font-size="${H(this.fontSize)}" `,this.fontStyle?`font-style="${H(this.fontStyle)}" `:``,this.fontWeight?`font-weight="${H(this.fontWeight)}" `:``,n?`text-decoration="${n}" `:``,this.direction===`rtl`?`direction="rtl" `:``,`style="`,this.getSvgStyles(!0),`"`,this.addPaintOrder(),` >`,t.join(``),`</text>
|
|
25
25
|
`]}_getSVGTextAndBg(e,t){let n=[],r=[],i,a=e;this.backgroundColor&&r.push(ss(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let e=0,o=this._textLines.length;e<o;e++)i=this._getLineLeftOffset(e),this.direction===`rtl`&&(i+=this.width),(this.textBackgroundColor||this.styleHas(`textBackgroundColor`,e))&&this._setSVGTextLineBg(r,e,t+i,a),this._setSVGTextLineText(n,e,t+i,a),a+=this.getHeightOfLine(e);return{textSpans:n,textBgRects:r}}_createTextCharSpan(e,t,n,r,i){let a=h.NUM_FRACTION_DIGITS,o=this.getSvgSpanStyles(t,e!==e.trim()||!!e.match(as)),s=o?`style="${o}"`:``,c=t.deltaY,l=c?` dy="${V(c,a)}" `:``,{angle:u,renderLeft:d,renderTop:f,width:p}=i,m=``;if(d!==void 0){let e=p/2;u&&(m=` rotate="${V(Ve(u),a)}"`);let t=Ze({angle:Ve(u)});t[4]=d,t[5]=f;let i=new R(-e,0).transform(t);n=i.x,r=i.y}return`<tspan x="${V(n,a)}" y="${V(r,a)}" ${l}${m}${s}>${H(e)}</tspan>`}_setSVGTextLineText(e,t,n,r){let i=this.getHeightOfLine(t),a=this.textAlign.includes(Rn),o=this._textLines[t],s,c,l,u,d,f=``,p=0;r+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let i=0,m=o.length-1;i<=m;i++)d=i===m||this.charSpacing||this.path,f+=o[i],l=this.__charBounds[t][i],p===0?(n+=l.kernedWidth-l.width,p+=l.width):p+=l.kernedWidth,a&&!d&&this._reSpaceAndTab.test(o[i])&&(d=!0),d||=(s||=this.getCompleteStyleDeclaration(t,i),c=this.getCompleteStyleDeclaration(t,i+1),Bi(s,c,!0)),d&&(u=this._getStyleDeclaration(t,i),e.push(this._createTextCharSpan(f,u,n,r,l)),f=``,s=c,this.direction===`rtl`?n-=p:n+=p,p=0)}_setSVGTextLineBg(e,t,n,r){let i=this._textLines[t],a=this.getHeightOfLine(t)/this.lineHeight,o,s=0,c=0,l=this.getValueOfPropertyAt(t,0,`textBackgroundColor`);for(let u=0;u<i.length;u++){let{left:i,width:d,kernedWidth:f}=this.__charBounds[t][u];o=this.getValueOfPropertyAt(t,u,`textBackgroundColor`),o===l?s+=f:(l&&e.push(ss(l,n+c,r,s,a)),c=i,s=d,l=o)}o&&e.push(ss(l,n+c,r,s,a))}getSvgStyles(e){let t=pn(this.textDecorationColor)?` text-decoration-color: ${H(this[jn])};`:``;return`${super.getSvgStyles(e)} text-decoration-thickness: ${V(this.textDecorationThickness*this.getObjectScaling().y/10,h.NUM_FRACTION_DIGITS)}%;${t} white-space: pre;`}getSvgSpanStyles(e,t){let{fontFamily:n,strokeWidth:r,stroke:i,fill:a,fontSize:o,fontStyle:s,fontWeight:c,textDecorationThickness:l,textDecorationColor:u,linethrough:d,overline:f,underline:p}=e,m=this.getSvgTextDecoration({underline:p??this.underline,overline:f??this.overline,linethrough:d??this.linethrough}),g=l||this.textDecorationThickness,_=u||this.textDecorationColor,v=mn(r),y=hn(n),b=mn(o),x=hn(s),S=mn(c)||hn(c),C=hn(_);return[i?Dn(ve,i):``,v?`stroke-width: ${H(v)}; `:``,y?`font-family: ${y.includes(`'`)||y.includes(`"`)?H(y):`'${H(y)}'`}; `:``,b?`font-size: ${H(b)}px; `:``,x?`font-style: ${H(x)}; `:``,S?`font-weight: ${H(S)}; `:``,m?`text-decoration: ${m}; text-decoration-thickness: ${V(g*this.getObjectScaling().y/10,h.NUM_FRACTION_DIGITS)}%;${C?` text-decoration-color: ${H(C)};`:``} `:``,a?Dn(_e,a):``,t?`white-space: pre; `:``].join(``)}getSvgTextDecoration(e){return[`overline`,`underline`,`line-through`].filter(t=>e[t.replace(`-`,``)]).join(` `)}}]),L.setClass(ls),L.setSVGClass(ls);var us=class{constructor(e){p(this,`target`,void 0),p(this,`__mouseDownInPlace`,!1),p(this,`__dragStartFired`,!1),p(this,`__isDraggingOver`,!1),p(this,`__dragStartSelection`,void 0),p(this,`__dragImageDisposer`,void 0),p(this,`_dispose`,void 0),this.target=e;let t=[this.target.on(`dragenter`,this.dragEnterHandler.bind(this)),this.target.on(`dragover`,this.dragOverHandler.bind(this)),this.target.on(`dragleave`,this.dragLeaveHandler.bind(this)),this.target.on(`dragend`,this.dragEndHandler.bind(this)),this.target.on(`drop`,this.dropHandler.bind(this))];this._dispose=()=>{t.forEach(e=>e()),this._dispose=void 0}}isPointerOverSelection(e){let t=this.target,n=t.getSelectionStartFromPointer(e);return t.isEditing&&n>=t.selectionStart&&n<=t.selectionEnd&&t.selectionStart<t.selectionEnd}start(e){return this.__mouseDownInPlace=this.isPointerOverSelection(e)}isActive(){return this.__mouseDownInPlace}end(e){let t=this.isActive();return t&&!this.__dragStartFired&&(this.target.setCursorByClick(e),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,t}getDragStartSelection(){return this.__dragStartSelection}setDragImage(e,{selectionStart:t,selectionEnd:n}){var r;let i=this.target,a=i.canvas,o=new R(i.flipX?-1:1,i.flipY?-1:1),s=i._getCursorBoundaries(t),c=new R(s.left+s.leftOffset,s.top+s.topOffset).multiply(o).transform(i.calcTransformMatrix()),l=a.getScenePoint(e).subtract(c),u=i.getCanvasRetinaScaling(),d=i.getBoundingRect(),f=c.subtract(new R(d.left,d.top)),p=a.viewportTransform,m=f.add(l).transform(p,!0),h=i.backgroundColor,g=zi(i.styles);i.backgroundColor=``;let _={stroke:`transparent`,fill:`transparent`,textBackgroundColor:`transparent`};i.setSelectionStyles(_,0,t),i.setSelectionStyles(_,n,i.text.length),i.dirty=!0;let v=i.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});i.backgroundColor=h,i.styles=g,i.dirty=!0,so(v,{position:`fixed`,left:-v.width+`px`,border:ne,width:v.width/u+`px`,height:v.height/u+`px`}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{v.remove()},ht(e.target||this.target.hiddenTextarea).body.appendChild(v),(r=e.dataTransfer)==null||r.setDragImage(v,m.x,m.y)}onDragStart(e){this.__dragStartFired=!0;let t=this.target,n=this.isActive();if(n&&e.dataTransfer){let n=this.__dragStartSelection={selectionStart:t.selectionStart,selectionEnd:t.selectionEnd},r=t._text.slice(n.selectionStart,n.selectionEnd).join(``),i={text:t.text,value:r,...n};e.dataTransfer.setData(`text/plain`,r),e.dataTransfer.setData(`application/fabric`,JSON.stringify({value:r,styles:t.getSelectionStyles(n.selectionStart,n.selectionEnd,!0)})),e.dataTransfer.effectAllowed=`copyMove`,this.setDragImage(e,i)}return t.abortCursorAnimation(),n}canDrop(e){if(this.target.editable&&!this.target.getActiveControl()&&!e.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){let t=this.target.getSelectionStartFromPointer(e),n=this.__dragStartSelection;return t<n.selectionStart||t>n.selectionEnd}return!0}return!1}targetCanDrop(e){return this.target.canDrop(e)}dragEnterHandler({e}){let t=this.targetCanDrop(e);!this.__isDraggingOver&&t&&(this.__isDraggingOver=!0)}dragOverHandler(e){let{e:t}=e,n=this.targetCanDrop(t);!this.__isDraggingOver&&n?this.__isDraggingOver=!0:this.__isDraggingOver&&!n&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(t.preventDefault(),e.canDrop=!0,e.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(e){let{e:t}=e,n=t.defaultPrevented;this.__isDraggingOver=!1,t.preventDefault();let r=t.dataTransfer?.getData(`text/plain`);if(r&&!n){let n=this.target,i=n.canvas,a=n.getSelectionStartFromPointer(t),{styles:o}=t.dataTransfer.types.includes(`application/fabric`)?JSON.parse(t.dataTransfer.getData(`application/fabric`)):{},s=r[Math.max(0,r.length-1)];if(this.__dragStartSelection){let e=this.__dragStartSelection.selectionStart,t=this.__dragStartSelection.selectionEnd;a>e&&a<=t?a=e:a>t&&(a-=t-e),n.removeChars(e,t),delete this.__dragStartSelection}n._reNewline.test(s)&&(n._reNewline.test(n._text[a])||a===n._text.length)&&(r=r.trimEnd()),e.didDrop=!0,e.dropTarget=n,n.insertChars(r,o,a),i.setActiveObject(n),n.enterEditing(t),n.selectionStart=Math.min(a+0,n._text.length),n.selectionEnd=Math.min(n.selectionStart+r.length,n._text.length),n.hiddenTextarea.value=n.text,n._updateTextarea(),n.hiddenTextarea.focus(),n.fire(de,{index:a+0,action:`drop`}),i.fire(`text:changed`,{target:n}),i.contextTopDirty=!0,i.requestRenderAll()}}dragEndHandler({e}){if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){let t=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:i}=this.__dragStartSelection,a=e.dataTransfer?.dropEffect||`none`;a===`none`?(t.selectionStart=r,t.selectionEnd=i,t._updateTextarea(),t.hiddenTextarea.focus()):(t.clearContextTop(),a===`move`&&(t.removeChars(r,i),t.selectionStart=t.selectionEnd=r,t.hiddenTextarea&&(t.hiddenTextarea.value=t.text),t._updateTextarea(),t.fire(de,{index:r,action:`dragend`}),n.fire(`text:changed`,{target:t}),n.requestRenderAll()),t.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}},ds=/[ \n\.,;!\?\-]/,fs=class extends ls{constructor(...e){super(...e),p(this,`_currentCursorOpacity`,1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(e){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(e)}_animateCursor({toValue:e,duration:t,delay:n,onComplete:r}){return Wr({startValue:this._currentCursorOpacity,endValue:e,duration:t,delay:n,onComplete:r,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:e=>{this._currentCursorOpacity=e,this.renderCursorOrSelection()}})}_tick(e){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(e||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var e;(e=this._currentTickCompleteState)==null||e.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(e){this.abortCursorAnimation(),this._tick(e?0:this.cursorDelay)}abortCursorAnimation(){let e=!1;[this._currentTickState,this._currentTickCompleteState].forEach(t=>{t&&!t.isDone()&&(e=!0,t.abort())}),this._currentCursorOpacity=1,e&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(e=>!e||e.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join(``)}findWordBoundaryLeft(e){let t=0,n=e-1;if(this._reSpace.test(this._text[n]))for(;this._reSpace.test(this._text[n]);)t++,n--;for(;/\S/.test(this._text[n])&&n>-1;)t++,n--;return e-t}findWordBoundaryRight(e){let t=0,n=e;if(this._reSpace.test(this._text[n]))for(;this._reSpace.test(this._text[n]);)t++,n++;for(;/\S/.test(this._text[n])&&n<this._text.length;)t++,n++;return e+t}findLineBoundaryLeft(e){let t=0,n=e-1;for(;!/\n/.test(this._text[n])&&n>-1;)t++,n--;return e-t}findLineBoundaryRight(e){let t=0,n=e;for(;!/\n/.test(this._text[n])&&n<this._text.length;)t++,n++;return e+t}searchWordBoundary(e,t){let n=this._text,r=e>0&&this._reSpace.test(n[e])&&(t===-1||!re.test(n[e-1]))?e-1:e,i=n[r];for(;r>0&&r<n.length&&!ds.test(i);)r+=t,i=n[r];return t===-1&&ds.test(i)&&r++,r}selectWord(e){e??=this.selectionStart;let t=this.searchWordBoundary(e,-1),n=Math.max(t,this.searchWordBoundary(e,1));this.selectionStart=t,this.selectionEnd=n,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(e){e??=this.selectionStart;let t=this.findLineBoundaryLeft(e),n=this.findLineBoundaryRight(e);this.selectionStart=t,this.selectionEnd=n,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(e){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire(`editing:entered`,e?{e}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire(`text:editing:entered`,{target:this,e}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(e){if(this.getActiveControl())return;let t=this.hiddenTextarea;ht(t).activeElement!==t&&t.focus();let n=this.getSelectionStartFromPointer(e),r=this.selectionStart,i=this.selectionEnd;(n===this.__selectionStartOnMouseDown&&r!==i||r!==n&&i!==n)&&(n>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=n):(this.selectionStart=n,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===r&&this.selectionEnd===i||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor=`text`,this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor=`text`),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(e,t,n){let r=n.slice(0,e),i=this.graphemeSplit(r).length;if(e===t)return{selectionStart:i,selectionEnd:i};let a=n.slice(e,t);return{selectionStart:i,selectionEnd:i+this.graphemeSplit(a).length}}fromGraphemeToStringSelection(e,t,n){let r=n.slice(0,e).join(``).length;return e===t?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+n.slice(e,t).join(``).length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){let e=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=e.selectionStart,this.hiddenTextarea.selectionEnd=e.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){let{hiddenTextarea:e,direction:t,textAlign:n,inCompositionMode:r}=this;if(!e)return;let i=n===`justify`?t===`ltr`?F:te:n.replace(`justify-`,``),a=this.getPositionByOrigin(i,`top`);this.cursorOffsetCache={},this.text=e.value,this.set(`dirty`,!0),this.initDimensions(),this.setPositionByOrigin(a,i,`top`),this.setCoords();let o=this.fromStringToGraphemeSelection(e.selectionStart,e.selectionEnd,e.value);this.selectionEnd=this.selectionStart=o.selectionEnd,r||(this.selectionStart=o.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){let e=this._calcTextareaPosition();this.hiddenTextarea.style.left=e.left,this.hiddenTextarea.style.top=e.top}}_calcTextareaPosition(){if(!this.canvas)return{left:`1px`,top:`1px`};let e=this.inCompositionMode?this.compositionStart:this.selectionStart,t=this._getCursorBoundaries(e),n=this.get2DCursorLocation(e),r=n.lineIndex,i=n.charIndex,a=this.getValueOfPropertyAt(r,i,`fontSize`)*this.lineHeight,o=t.leftOffset,s=this.getCanvasRetinaScaling(),c=this.canvas.upperCanvasEl,l=c.width/s,u=c.height/s,d=l-a,f=u-a,p=new R(t.left+o,t.top+t.topOffset+a).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new R(c.clientWidth/l,c.clientHeight/u));return p.x<0&&(p.x=0),p.x>d&&(p.x=d),p.y<0&&(p.y=0),p.y>f&&(p.y=f),p.x+=this.canvas._offset.left,p.y+=this.canvas._offset.top,{left:`${p.x}px`,top:`${p.y}px`,fontSize:`${a}px`,charHeight:a}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}exitEditingImpl(){let e=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,e&&(e.blur&&e.blur(),e.parentNode&&e.parentNode.removeChild(e)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){let e=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire(`editing:exited`),e&&this.fire(`modified`),this.canvas&&(this.canvas.fire(`text:editing:exited`,{target:this}),e&&this.canvas.fire(`object:modified`,{target:this})),this}_removeExtraneousStyles(){for(let e in this.styles)this._textLines[e]||delete this.styles[e]}removeStyleFromTo(e,t){let{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0),{lineIndex:i,charIndex:a}=this.get2DCursorLocation(t,!0);if(n!==i){if(this.styles[n])for(let e=r;e<this._unwrappedTextLines[n].length;e++)delete this.styles[n][e];if(this.styles[i])for(let e=a;e<this._unwrappedTextLines[i].length;e++){let t=this.styles[i][e];t&&(this.styles[n]||(this.styles[n]={}),this.styles[n][r+e-a]=t)}for(let e=n+1;e<=i;e++)delete this.styles[e];this.shiftLineStyles(i,n-i)}else if(this.styles[n]){let e=this.styles[n],t=a-r;for(let t=r;t<a;t++)delete e[t];for(let r in this.styles[n]){let n=parseInt(r,10);n>=a&&(e[n-t]=e[r],delete e[r])}}}shiftLineStyles(e,t){let n=Object.assign({},this.styles);for(let r in this.styles){let i=parseInt(r,10);i>e&&(this.styles[i+t]=n[i],n[i-t]||delete this.styles[i])}}insertNewlineStyleObject(e,t,n,r){let i={},a=this._unwrappedTextLines[e].length,o=a===t,s=!1;n||=1,this.shiftLineStyles(e,n);let c=this.styles[e]?this.styles[e][t===0?t:t-1]:void 0;for(let n in this.styles[e]){let r=parseInt(n,10);r>=t&&(s=!0,i[r-t]=this.styles[e][n],o&&t===0||delete this.styles[e][n])}let l=!1;for(s&&!o&&(this.styles[e+n]=i,l=!0),(l||a>t)&&n--;n>0;)r&&r[n-1]?this.styles[e+n]={0:{...r[n-1]}}:c?this.styles[e+n]={0:{...c}}:delete this.styles[e+n],n--;this._forceClearCache=!0}insertCharStyleObject(e,t,n,r){this.styles||={};let i=this.styles[e],a=i?{...i}:{};n||=1;for(let e in a){let r=parseInt(e,10);r>=t&&(i[r+n]=a[r],a[r-n]||delete i[r])}if(this._forceClearCache=!0,r){for(;n--;)Object.keys(r[n]).length&&(this.styles[e]||(this.styles[e]={}),this.styles[e][t+n]={...r[n]});return}if(!i)return;let o=i[t?t-1:1];for(;o&&n--;)this.styles[e][t+n]={...o}}insertNewStyleBlock(e,t,n){let r=this.get2DCursorLocation(t,!0),i=[0],a,o=0;for(let t=0;t<e.length;t++)e[t]===`
|
|
26
|
-
`?(o++,i[o]=0):i[o]++;for(i[0]>0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,i[0],n),n&&=n.slice(i[0]+1)),o&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+i[0],o),a=1;a<o;a++)i[a]>0?this.insertCharStyleObject(r.lineIndex+a,0,i[a],n):n&&this.styles[r.lineIndex+a]&&n[0]&&(this.styles[r.lineIndex+a][0]=n[0]),n&&=n.slice(i[a]+1);i[a]>0&&this.insertCharStyleObject(r.lineIndex+a,0,i[a],n)}removeChars(e,t=e+1){this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(``),this.set(`dirty`,!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(e,t,n,r=n){r>n&&this.removeStyleFromTo(n,r);let i=this.graphemeSplit(e);this.insertNewStyleBlock(i,n,t),this._text=[...this._text.slice(0,n),...i,...this._text.slice(r)],this.text=this._text.join(``),this.set(`dirty`,!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(e,t,n){n<=e?(t===e?this._selectionDirection=F:this._selectionDirection===`right`&&(this._selectionDirection=F,this.selectionEnd=e),this.selectionStart=n):n>e&&n<t?this._selectionDirection===`right`?this.selectionEnd=n:this.selectionStart=n:(t===e?this._selectionDirection=te:this._selectionDirection===`left`&&(this._selectionDirection=te,this.selectionStart=t),this.selectionEnd=n)}},ps=class extends fs{initHiddenTextarea(){let e=this.canvas&&ht(this.canvas.getElement())||w(),t=e.createElement(`textarea`);Object.entries({autocapitalize:`off`,autocorrect:`off`,autocomplete:`off`,spellcheck:`false`,"data-fabric":`textarea`,wrap:`off`,name:`fabricTextarea`}).map(([e,n])=>t.setAttribute(e,n));let{top:n,left:r,fontSize:i}=this._calcTextareaPosition();t.style.cssText=`position: absolute; top: ${n}; left: ${r}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${i};`,(this.hiddenTextareaContainer||e.body).appendChild(t),Object.entries({blur:`blur`,keydown:`onKeyDown`,keyup:`onKeyUp`,input:`onInput`,copy:`copy`,cut:`copy`,paste:`paste`,compositionstart:`onCompositionStart`,compositionupdate:`onCompositionUpdate`,compositionend:`onCompositionEnd`}).map(([e,n])=>t.addEventListener(e,this[n].bind(this))),this.hiddenTextarea=t}blur(){this.abortCursorAnimation()}onKeyDown(e){if(!this.isEditing)return;let t=this.direction===`rtl`?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(e){let t=this.fromPaste,{value:n,selectionStart:r,selectionEnd:i}=this.hiddenTextarea;if(this.fromPaste=!1,e&&e.stopPropagation(),!this.isEditing)return;let a=()=>{this.updateFromTextArea(),this.fire(de),this.canvas&&(this.canvas.fire(`text:changed`,{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value===``)return this.styles={},void a();let o=this._splitTextIntoLines(n).graphemeText,s=this._text.length,c=o.length,l=this.selectionStart,u=this.selectionEnd,d=l!==u,f,p,m,g,_=c-s,v=this.fromStringToGraphemeSelection(r,i,n),y=l>v.selectionStart;d?(p=this._text.slice(l,u),_+=u-l):c<s&&(p=y?this._text.slice(u+_,u):this._text.slice(l,l-_));let b=o.slice(v.selectionEnd-_,v.selectionEnd);if(p&&p.length&&(b.length&&(f=this.getSelectionStyles(l,l+1,!1),f=b.map(()=>f[0])),d?(m=l,g=u):y?(m=u-p.length,g=u):(m=u,g=u+p.length),this.removeStyleFromTo(m,g)),b.length){let{copyPasteData:e}=C();t&&b.join(``)===e.copiedText&&!h.disableStyleCopyPaste&&(f=e.copiedTextStyle),this.insertNewStyleBlock(b,l,f)}a()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate({target:e}){let{selectionStart:t,selectionEnd:n}=e;this.compositionStart=t,this.compositionEnd=n,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;let{copyPasteData:e}=C();e.copiedText=this.getSelectedText(),h.disableStyleCopyPaste?e.copiedTextStyle=void 0:e.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(e,t){let n,r=this._getLineLeftOffset(e);return t>0&&(n=this.__charBounds[e][t-1],r+=n.left+n.width),r}getDownCursorOffset(e,t){let n=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(n),i=r.lineIndex;if(i===this._textLines.length-1||e.metaKey||e.keyCode===34)return this._text.length-n;let a=r.charIndex,o=this._getWidthBeforeCursor(i,a),s=this._getIndexOnLine(i+1,o);return this._textLines[i].slice(a).length+s+1+this.missingNewlineOffset(i)}_getSelectionForOffset(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart}getUpCursorOffset(e,t){let n=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(n),i=r.lineIndex;if(i===0||e.metaKey||e.keyCode===33)return-n;let a=r.charIndex,o=this._getWidthBeforeCursor(i,a),s=this._getIndexOnLine(i-1,o),c=this._textLines[i].slice(0,a),l=this.missingNewlineOffset(i-1);return-this._textLines[i-1].length+s-c.length+(1-l)}_getIndexOnLine(e,t){let n=this._textLines[e],r,i,a=this._getLineLeftOffset(e),o=0;for(let s=0,c=n.length;s<c;s++)if(r=this.__charBounds[e][s].width,a+=r,a>t){i=!0;let e=a-r,n=a,c=Math.abs(e-t);o=Math.abs(n-t)<c?s:s-1;break}return i||(o=n.length-1),o}moveCursorDown(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown(`Down`,e)}moveCursorUp(e){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown(`Up`,e)}_moveCursorUpOrDown(e,t){let n=this[`get${e}CursorOffset`](t,this._selectionDirection===te);if(t.shiftKey?this.moveCursorWithShift(n):this.moveCursorWithoutShift(n),n!==0){let e=this.text.length;this.selectionStart=$n(0,this.selectionStart,e),this.selectionEnd=$n(0,this.selectionEnd,e),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(e){let t=this._selectionDirection===`left`?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),e!==0}moveCursorWithoutShift(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),e!==0}moveCursorLeft(e){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight(`Left`,e)}_move(e,t,n){let r;if(e.altKey)r=this[`findWordBoundary${n}`](this[t]);else{if(!e.metaKey&&e.keyCode!==35&&e.keyCode!==36)return this[t]+=n===`Left`?-1:1,!0;r=this[`findLineBoundary${n}`](this[t])}return r!==void 0&&this[t]!==r&&(this[t]=r,!0)}_moveLeft(e,t){return this._move(e,t,`Left`)}_moveRight(e,t){return this._move(e,t,`Right`)}moveCursorLeftWithoutShift(e){let t=!0;return this._selectionDirection=F,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(t=this._moveLeft(e,`selectionStart`)),this.selectionEnd=this.selectionStart,t}moveCursorLeftWithShift(e){return this._selectionDirection===`right`&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,`selectionEnd`):this.selectionStart===0?void 0:(this._selectionDirection=F,this._moveLeft(e,`selectionStart`))}moveCursorRight(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight(`Right`,e)}_moveCursorLeftOrRight(e,t){let n=`moveCursor${e}${t.shiftKey?`WithShift`:`WithoutShift`}`;this._currentCursorOpacity=1,this[n](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(e){return this._selectionDirection===`left`&&this.selectionStart!==this.selectionEnd?this._moveRight(e,`selectionStart`):this.selectionEnd===this._text.length?void 0:(this._selectionDirection=te,this._moveRight(e,`selectionEnd`))}moveCursorRightWithoutShift(e){let t=!0;return this._selectionDirection=te,this.selectionStart===this.selectionEnd?(t=this._moveRight(e,`selectionStart`),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t}},ms=e=>!!e.button,hs=class extends ps{constructor(...e){super(...e),p(this,`draggableTextDelegate`,void 0)}initBehavior(){this.on(`mousedown`,this._mouseDownHandler),this.on(`mouseup`,this.mouseUpHandler),this.on(`mousedblclick`,this.doubleClickHandler),this.on(`mousetripleclick`,this.tripleClickHandler),this.draggableTextDelegate=new us(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(e){return this.draggableTextDelegate.onDragStart(e)}canDrop(e){return this.draggableTextDelegate.canDrop(e)}doubleClickHandler(e){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(e.e)),this.renderCursorOrSelection())}tripleClickHandler(e){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(e.e)),this.renderCursorOrSelection())}_mouseDownHandler({e,alreadySelected:t}){this.canvas&&this.editable&&!ms(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),t&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||=t||this.isEditing))}mouseUpHandler({e,transform:t}){let n=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);let e=this.canvas._activeObject;if(e&&e!==this)return}!this.editable||this.group&&!this.group.interactive||t&&t.actionPerformed||ms(e)||n||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(e){let t=this.getSelectionStartFromPointer(e),n=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(n,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(e){let t=this.canvas.getScenePoint(e).transform(We(this.calcTransformMatrix())).add(new R(-this._getLeftOffset(),-this._getTopOffset())),n=0,r=0,i=0;for(let e=0;e<this._textLines.length&&n<=t.y;e++)n+=this.getHeightOfLine(e),i=e,e>0&&(r+=this._textLines[e-1].length+this.missingNewlineOffset(e-1));let a=Math.abs(this._getLineLeftOffset(i)),o=this._textLines[i].length,s=this.__charBounds[i];for(let e=0;e<o;e++){let n=a+s[e].kernedWidth;if(t.x<=n){Math.abs(t.x-n)<=Math.abs(t.x-a)&&r++;break}a=n,r++}return Math.min(this.flipX?o-r:r,this._text.length)}},gs=`moveCursorUp`,_s=`moveCursorDown`,vs=`moveCursorLeft`,ys=`moveCursorRight`,bs=`exitEditing`,xs=(e,t)=>{let n=t.getRetinaScaling();e.setTransform(n,0,0,n,0,0);let r=t.viewportTransform;e.transform(r[0],r[1],r[2],r[3],r[4],r[5])},Ss={selectionStart:0,selectionEnd:0,selectionColor:`rgba(17,119,255,0.3)`,isEditing:!1,editable:!0,editingBorderColor:`rgba(102,153,255,0.25)`,cursorWidth:2,cursorColor:``,cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:bs,27:bs,33:gs,34:_s,35:ys,36:vs,37:vs,38:gs,39:ys,40:_s},keysMapRtl:{9:bs,27:bs,33:gs,34:_s,35:vs,36:ys,37:ys,38:gs,39:vs,40:_s},ctrlKeysMapDown:{65:`cmdAll`},ctrlKeysMapUp:{67:`copy`,88:`cut`},_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1},Cs=class e extends hs{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}get type(){let e=super.type;return e===`itext`?`i-text`:e}constructor(t,n){super(t,{...e.ownDefaults,...n}),this.initBehavior()}_set(e,t){return this.isEditing&&this._savedProps&&e in this._savedProps?(this._savedProps[e]=t,this):(e===`canvas`&&(this.canvas instanceof jo&&this.canvas.textEditingManager.remove(this),t instanceof jo&&t.textEditingManager.add(this)),super._set(e,t))}setSelectionStart(e){e=Math.max(e,0),this._updateAndFire(`selectionStart`,e)}setSelectionEnd(e){e=Math.min(e,this.text.length),this._updateAndFire(`selectionEnd`,e)}_updateAndFire(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()}_fireSelectionChanged(){this.fire(`selection:changed`),this.canvas&&this.canvas.fire(`text:selection:changed`,{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(e=this.selectionStart||0,t=this.selectionEnd,n){return super.getSelectionStyles(e,t,n)}setSelectionStyles(e,t=this.selectionStart||0,n=this.selectionEnd){return super.setSelectionStyles(e,t,n)}get2DCursorLocation(e=this.selectionStart,t){return super.get2DCursorLocation(e,t)}render(e){super.render(e),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(e){let t=this.isEditing;this.isEditing=!1;let n=super.toCanvasElement(e);return this.isEditing=t,n}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;let e=this.clearContextTop(!0);if(!e)return;let t=this._getCursorBoundaries(),n=this.findAncestorsWithClipPath(),r=n.length>0,i,a=e;if(r){i=Re(e.canvas),a=i.getContext(`2d`),xs(a,this.canvas);let t=this.calcTransformMatrix();a.transform(t[0],t[1],t[2],t[3],t[4],t[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(a,t):this.renderCursor(a,t),r)for(let t of n){let n=t.clipPath,r=Re(e.canvas),i=r.getContext(`2d`);if(xs(i,this.canvas),!n.absolutePositioned){let e=t.calcTransformMatrix();i.transform(e[0],e[1],e[2],e[3],e[4],e[5])}n.transform(i),n.drawObject(i,!0,{}),this.drawClipPathOnCache(a,n,r)}r&&(e.setTransform(1,0,0,1,0,0),e.drawImage(i,0,0)),this.canvas.contextTopDirty=!0,e.restore()}findAncestorsWithClipPath(){let e=[],t=this;for(;t;)t.clipPath&&e.push(t),t=t.parent;return e}_getCursorBoundaries(e=this.selectionStart,t){let n=this._getLeftOffset(),r=this._getTopOffset(),i=this._getCursorBoundariesOffsets(e,t);return{left:n,top:r,leftOffset:i.left,topOffset:i.top}}_getCursorBoundariesOffsets(e,t){return t?this.__getCursorBoundariesOffsets(e):this.cursorOffsetCache&&`top`in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(e)}__getCursorBoundariesOffsets(e){let t=0,n=0,{charIndex:r,lineIndex:i}=this.get2DCursorLocation(e),{textAlign:a,direction:o}=this;for(let e=0;e<i;e++)t+=this.getHeightOfLine(e);let s=this._getLineLeftOffset(i),c=this.__charBounds[i][r];c&&(n=c.left),this.charSpacing!==0&&r===this._textLines[i].length&&(n-=this._getWidthOfCharSpacing());let l=s+(n>0?n:0);return o===`rtl`&&(a===`right`||a===`justify`||a===`justify-right`?l*=-1:a===`left`||a===`justify-left`?l=s-(n>0?n:0):a!==`center`&&a!==`justify-center`||(l=s-(n>0?n:0))),{top:t,left:l}}renderCursorAt(e){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(e,!0),e)}renderCursor(e,t){this._renderCursor(e,t,this.selectionStart)}getCursorRenderingData(e=this.selectionStart,t=this._getCursorBoundaries(e)){let n=this.get2DCursorLocation(e),r=n.lineIndex,i=n.charIndex>0?n.charIndex-1:0,a=this.getValueOfPropertyAt(r,i,`fontSize`),o=this.getObjectScaling().x*this.canvas.getZoom(),s=this.cursorWidth/o,c=this.getValueOfPropertyAt(r,i,`deltaY`),l=t.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-a*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(r,i,`fill`),opacity:this._currentCursorOpacity,left:t.left+t.leftOffset-s/2,top:l+t.top+c,width:s,height:a}}_renderCursor(e,t,n){let{color:r,opacity:i,left:a,top:o,width:s,height:c}=this.getCursorRenderingData(n,t);e.fillStyle=r,e.globalAlpha=i,e.fillRect(a,o,s,c)}renderSelection(e,t){let n={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(e,n,t)}renderDragSourceEffect(){let e=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,e,this._getCursorBoundaries(e.selectionStart,!0))}renderDropTargetEffect(e){let t=this.getSelectionStartFromPointer(e);this.renderCursorAt(t)}_renderSelection(e,t,n){let{textAlign:r,direction:i}=this,a=t.selectionStart,o=t.selectionEnd,s=r.includes(Rn),c=this.get2DCursorLocation(a),l=this.get2DCursorLocation(o),u=c.lineIndex,d=l.lineIndex,f=c.charIndex<0?0:c.charIndex,p=l.charIndex<0?0:l.charIndex;for(let t=u;t<=d;t++){let a=this._getLineLeftOffset(t)||0,o=this.getHeightOfLine(t),c=0,l=0;if(t===u&&(c=this.__charBounds[u][f].left),t>=u&&t<d)l=s&&!this.isEndOfWrapping(t)?this.width:this.getLineWidth(t)||5;else if(t===d)if(p===0)l=this.__charBounds[d][p].left;else{let e=this._getWidthOfCharSpacing();l=this.__charBounds[d][p-1].left+this.__charBounds[d][p-1].width-e}let m=o;(this.lineHeight<1||t===d&&this.lineHeight>1)&&(o/=this.lineHeight);let h=n.left+a+c,g=o,_=0,v=l-c;this.inCompositionMode?(e.fillStyle=this.compositionColor||`black`,g=1,_=o):e.fillStyle=this.selectionColor,i===`rtl`&&(r===`right`||r===`justify`||r===`justify-right`?h=this.width-h-v:r===`left`||r===`justify-left`?h=n.left+a-l:r!==`center`&&r!==`justify-center`||(h=n.left+a-l)),e.fillRect(h,n.top+n.topOffset+_,v,g),n.topOffset+=m}}getCurrentCharFontSize(){let e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,`fontSize`)}getCurrentCharColor(){let e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,_e)}_getCurrentCharIndex(){let e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}};p(Cs,`ownDefaults`,Ss),p(Cs,`type`,`IText`),L.setClass(Cs),L.setClass(Cs,`i-text`);var ws=class e extends Cs{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(t,{...e.ownDefaults,...n})}static createControls(){return{controls:ki()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set(`width`,this.dynamicMinWidth),this.textAlign.includes(`justify`)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(e){let t=0,n=0,r=0,i={};for(let a=0;a<e.graphemeLines.length;a++)e.graphemeText[r]===`
|
|
26
|
+
`?(o++,i[o]=0):i[o]++;for(i[0]>0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,i[0],n),n&&=n.slice(i[0]+1)),o&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+i[0],o),a=1;a<o;a++)i[a]>0?this.insertCharStyleObject(r.lineIndex+a,0,i[a],n):n&&this.styles[r.lineIndex+a]&&n[0]&&(this.styles[r.lineIndex+a][0]=n[0]),n&&=n.slice(i[a]+1);i[a]>0&&this.insertCharStyleObject(r.lineIndex+a,0,i[a],n)}removeChars(e,t=e+1){this.removeStyleFromTo(e,t),this._text.splice(e,t-e),this.text=this._text.join(``),this.set(`dirty`,!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(e,t,n,r=n){r>n&&this.removeStyleFromTo(n,r);let i=this.graphemeSplit(e);this.insertNewStyleBlock(i,n,t),this._text=[...this._text.slice(0,n),...i,...this._text.slice(r)],this.text=this._text.join(``),this.set(`dirty`,!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(e,t,n){n<=e?(t===e?this._selectionDirection=F:this._selectionDirection===`right`&&(this._selectionDirection=F,this.selectionEnd=e),this.selectionStart=n):n>e&&n<t?this._selectionDirection===`right`?this.selectionEnd=n:this.selectionStart=n:(t===e?this._selectionDirection=te:this._selectionDirection===`left`&&(this._selectionDirection=te,this.selectionStart=t),this.selectionEnd=n)}},ps=class extends fs{initHiddenTextarea(){let e=this.canvas&&ht(this.canvas.getElement())||w(),t=e.createElement(`textarea`);Object.entries({autocapitalize:`off`,autocorrect:`off`,autocomplete:`off`,spellcheck:`false`,"data-fabric":`textarea`,wrap:`off`,name:`fabricTextarea`}).map(([e,n])=>t.setAttribute(e,n));let{top:n,left:r,fontSize:i}=this._calcTextareaPosition();t.style.cssText=`position: absolute; top: ${n}; left: ${r}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${i};`,(this.hiddenTextareaContainer||e.body).appendChild(t),Object.entries({blur:`blur`,keydown:`onKeyDown`,keyup:`onKeyUp`,input:`onInput`,copy:`copy`,cut:`copy`,paste:`paste`,compositionstart:`onCompositionStart`,compositionupdate:`onCompositionUpdate`,compositionend:`onCompositionEnd`}).map(([e,n])=>t.addEventListener(e,this[n].bind(this))),this.hiddenTextarea=t}blur(){this.abortCursorAnimation()}onKeyDown(e){if(!this.isEditing)return;let t=this.direction===`rtl`?this.keysMapRtl:this.keysMap;if(e.keyCode in t)this[t[e.keyCode]](e);else{if(!(e.keyCode in this.ctrlKeysMapDown)||!e.ctrlKey&&!e.metaKey)return;this[this.ctrlKeysMapDown[e.keyCode]](e)}e.stopImmediatePropagation(),e.preventDefault(),e.keyCode>=33&&e.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(e){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:e.keyCode in this.ctrlKeysMapUp&&(e.ctrlKey||e.metaKey)&&(this[this.ctrlKeysMapUp[e.keyCode]](e),e.stopImmediatePropagation(),e.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(e){let t=this.fromPaste,{value:n,selectionStart:r,selectionEnd:i}=this.hiddenTextarea;if(this.fromPaste=!1,e&&e.stopPropagation(),!this.isEditing)return;let a=()=>{this.updateFromTextArea(),this.fire(de),this.canvas&&(this.canvas.fire(`text:changed`,{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value===``)return this.styles={},void a();let o=this._splitTextIntoLines(n).graphemeText,s=this._text.length,c=o.length,l=this.selectionStart,u=this.selectionEnd,d=l!==u,f,p,m,g,_=c-s,v=this.fromStringToGraphemeSelection(r,i,n),y=l>v.selectionStart;d?(p=this._text.slice(l,u),_+=u-l):c<s&&(p=y?this._text.slice(u+_,u):this._text.slice(l,l-_));let b=o.slice(v.selectionEnd-_,v.selectionEnd);if(p&&p.length&&(b.length&&(f=this.getSelectionStyles(l,l+1,!1),f=b.map(()=>f[0])),d?(m=l,g=u):y?(m=u-p.length,g=u):(m=u,g=u+p.length),this.removeStyleFromTo(m,g)),b.length){let{copyPasteData:e}=C();t&&b.join(``)===e.copiedText&&!h.disableStyleCopyPaste&&(f=e.copiedTextStyle),this.insertNewStyleBlock(b,l,f)}a()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate({target:e}){let{selectionStart:t,selectionEnd:n}=e;this.compositionStart=t,this.compositionEnd=n,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;let{copyPasteData:e}=C();e.copiedText=this.getSelectedText(),e.copiedTextStyle=h.disableStyleCopyPaste?void 0:this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(e,t){let n,r=this._getLineLeftOffset(e);return t>0&&(n=this.__charBounds[e][t-1],r+=n.left+n.width),r}getDownCursorOffset(e,t){let n=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(n),i=r.lineIndex;if(i===this._textLines.length-1||e.metaKey||e.keyCode===34)return this._text.length-n;let a=r.charIndex,o=this._getWidthBeforeCursor(i,a),s=this._getIndexOnLine(i+1,o);return this._textLines[i].slice(a).length+s+1+this.missingNewlineOffset(i)}_getSelectionForOffset(e,t){return e.shiftKey&&this.selectionStart!==this.selectionEnd&&t?this.selectionEnd:this.selectionStart}getUpCursorOffset(e,t){let n=this._getSelectionForOffset(e,t),r=this.get2DCursorLocation(n),i=r.lineIndex;if(i===0||e.metaKey||e.keyCode===33)return-n;let a=r.charIndex,o=this._getWidthBeforeCursor(i,a),s=this._getIndexOnLine(i-1,o),c=this._textLines[i].slice(0,a),l=this.missingNewlineOffset(i-1);return-this._textLines[i-1].length+s-c.length+(1-l)}_getIndexOnLine(e,t){let n=this._textLines[e],r,i,a=this._getLineLeftOffset(e),o=0;for(let s=0,c=n.length;s<c;s++)if(r=this.__charBounds[e][s].width,a+=r,a>t){i=!0;let e=a-r,n=a,c=Math.abs(e-t);o=Math.abs(n-t)<c?s:s-1;break}return i||(o=n.length-1),o}moveCursorDown(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown(`Down`,e)}moveCursorUp(e){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown(`Up`,e)}_moveCursorUpOrDown(e,t){let n=this[`get${e}CursorOffset`](t,this._selectionDirection===te);if(t.shiftKey?this.moveCursorWithShift(n):this.moveCursorWithoutShift(n),n!==0){let e=this.text.length;this.selectionStart=$n(0,this.selectionStart,e),this.selectionEnd=$n(0,this.selectionEnd,e),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(e){let t=this._selectionDirection===`left`?this.selectionStart+e:this.selectionEnd+e;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,t),e!==0}moveCursorWithoutShift(e){return e<0?(this.selectionStart+=e,this.selectionEnd=this.selectionStart):(this.selectionEnd+=e,this.selectionStart=this.selectionEnd),e!==0}moveCursorLeft(e){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight(`Left`,e)}_move(e,t,n){let r;if(e.altKey)r=this[`findWordBoundary${n}`](this[t]);else{if(!e.metaKey&&e.keyCode!==35&&e.keyCode!==36)return this[t]+=n===`Left`?-1:1,!0;r=this[`findLineBoundary${n}`](this[t])}return r!==void 0&&this[t]!==r&&(this[t]=r,!0)}_moveLeft(e,t){return this._move(e,t,`Left`)}_moveRight(e,t){return this._move(e,t,`Right`)}moveCursorLeftWithoutShift(e){let t=!0;return this._selectionDirection=F,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(t=this._moveLeft(e,`selectionStart`)),this.selectionEnd=this.selectionStart,t}moveCursorLeftWithShift(e){return this._selectionDirection===`right`&&this.selectionStart!==this.selectionEnd?this._moveLeft(e,`selectionEnd`):this.selectionStart===0?void 0:(this._selectionDirection=F,this._moveLeft(e,`selectionStart`))}moveCursorRight(e){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight(`Right`,e)}_moveCursorLeftOrRight(e,t){let n=`moveCursor${e}${t.shiftKey?`WithShift`:`WithoutShift`}`;this._currentCursorOpacity=1,this[n](t)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(e){return this._selectionDirection===`left`&&this.selectionStart!==this.selectionEnd?this._moveRight(e,`selectionStart`):this.selectionEnd===this._text.length?void 0:(this._selectionDirection=te,this._moveRight(e,`selectionEnd`))}moveCursorRightWithoutShift(e){let t=!0;return this._selectionDirection=te,this.selectionStart===this.selectionEnd?(t=this._moveRight(e,`selectionStart`),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,t}},ms=e=>!!e.button,hs=class extends ps{constructor(...e){super(...e),p(this,`draggableTextDelegate`,void 0)}initBehavior(){this.on(`mousedown`,this._mouseDownHandler),this.on(`mouseup`,this.mouseUpHandler),this.on(`mousedblclick`,this.doubleClickHandler),this.on(`mousetripleclick`,this.tripleClickHandler),this.draggableTextDelegate=new us(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(e){return this.draggableTextDelegate.onDragStart(e)}canDrop(e){return this.draggableTextDelegate.canDrop(e)}doubleClickHandler(e){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(e.e)),this.renderCursorOrSelection())}tripleClickHandler(e){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(e.e)),this.renderCursorOrSelection())}_mouseDownHandler({e,alreadySelected:t}){this.canvas&&this.editable&&!ms(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),t&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||=t||this.isEditing))}mouseUpHandler({e,transform:t}){let n=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);let e=this.canvas._activeObject;if(e&&e!==this)return}!this.editable||this.group&&!this.group.interactive||t&&t.actionPerformed||ms(e)||n||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(e){let t=this.getSelectionStartFromPointer(e),n=this.selectionStart,r=this.selectionEnd;e.shiftKey?this.setSelectionStartEndWithShift(n,r,t):(this.selectionStart=t,this.selectionEnd=t),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(e){let t=this.canvas.getScenePoint(e).transform(We(this.calcTransformMatrix())).add(new R(-this._getLeftOffset(),-this._getTopOffset())),n=0,r=0,i=0;for(let e=0;e<this._textLines.length&&n<=t.y;e++)n+=this.getHeightOfLine(e),i=e,e>0&&(r+=this._textLines[e-1].length+this.missingNewlineOffset(e-1));let a=Math.abs(this._getLineLeftOffset(i)),o=this._textLines[i].length,s=this.__charBounds[i];for(let e=0;e<o;e++){let n=a+s[e].kernedWidth;if(t.x<=n){Math.abs(t.x-n)<=Math.abs(t.x-a)&&r++;break}a=n,r++}return Math.min(this.flipX?o-r:r,this._text.length)}},gs=`moveCursorUp`,_s=`moveCursorDown`,vs=`moveCursorLeft`,ys=`moveCursorRight`,bs=`exitEditing`,xs=(e,t)=>{let n=t.getRetinaScaling();e.setTransform(n,0,0,n,0,0);let r=t.viewportTransform;e.transform(r[0],r[1],r[2],r[3],r[4],r[5])},Ss={selectionStart:0,selectionEnd:0,selectionColor:`rgba(17,119,255,0.3)`,isEditing:!1,editable:!0,editingBorderColor:`rgba(102,153,255,0.25)`,cursorWidth:2,cursorColor:``,cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:bs,27:bs,33:gs,34:_s,35:ys,36:vs,37:vs,38:gs,39:ys,40:_s},keysMapRtl:{9:bs,27:bs,33:gs,34:_s,35:vs,36:ys,37:ys,38:gs,39:vs,40:_s},ctrlKeysMapDown:{65:`cmdAll`},ctrlKeysMapUp:{67:`copy`,88:`cut`},_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1},Cs=class e extends hs{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}get type(){let e=super.type;return e===`itext`?`i-text`:e}constructor(t,n){super(t,{...e.ownDefaults,...n}),this.initBehavior()}_set(e,t){return this.isEditing&&this._savedProps&&e in this._savedProps?(this._savedProps[e]=t,this):(e===`canvas`&&(this.canvas instanceof jo&&this.canvas.textEditingManager.remove(this),t instanceof jo&&t.textEditingManager.add(this)),super._set(e,t))}setSelectionStart(e){e=Math.max(e,0),this._updateAndFire(`selectionStart`,e)}setSelectionEnd(e){e=Math.min(e,this.text.length),this._updateAndFire(`selectionEnd`,e)}_updateAndFire(e,t){this[e]!==t&&(this._fireSelectionChanged(),this[e]=t),this._updateTextarea()}_fireSelectionChanged(){this.fire(`selection:changed`),this.canvas&&this.canvas.fire(`text:selection:changed`,{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(e=this.selectionStart||0,t=this.selectionEnd,n){return super.getSelectionStyles(e,t,n)}setSelectionStyles(e,t=this.selectionStart||0,n=this.selectionEnd){return super.setSelectionStyles(e,t,n)}get2DCursorLocation(e=this.selectionStart,t){return super.get2DCursorLocation(e,t)}render(e){super.render(e),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(e){let t=this.isEditing;this.isEditing=!1;let n=super.toCanvasElement(e);return this.isEditing=t,n}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;let e=this.clearContextTop(!0);if(!e)return;let t=this._getCursorBoundaries(),n=this.findAncestorsWithClipPath(),r=n.length>0,i,a=e;if(r){i=Re(e.canvas),a=i.getContext(`2d`),xs(a,this.canvas);let t=this.calcTransformMatrix();a.transform(t[0],t[1],t[2],t[3],t[4],t[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(a,t):this.renderCursor(a,t),r)for(let t of n){let n=t.clipPath,r=Re(e.canvas),i=r.getContext(`2d`);if(xs(i,this.canvas),!n.absolutePositioned){let e=t.calcTransformMatrix();i.transform(e[0],e[1],e[2],e[3],e[4],e[5])}n.transform(i),n.drawObject(i,!0,{}),this.drawClipPathOnCache(a,n,r)}r&&(e.setTransform(1,0,0,1,0,0),e.drawImage(i,0,0)),this.canvas.contextTopDirty=!0,e.restore()}findAncestorsWithClipPath(){let e=[],t=this;for(;t;)t.clipPath&&e.push(t),t=t.parent;return e}_getCursorBoundaries(e=this.selectionStart,t){let n=this._getLeftOffset(),r=this._getTopOffset(),i=this._getCursorBoundariesOffsets(e,t);return{left:n,top:r,leftOffset:i.left,topOffset:i.top}}_getCursorBoundariesOffsets(e,t){return t?this.__getCursorBoundariesOffsets(e):this.cursorOffsetCache&&`top`in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(e)}__getCursorBoundariesOffsets(e){let t=0,n=0,{charIndex:r,lineIndex:i}=this.get2DCursorLocation(e),{textAlign:a,direction:o}=this;for(let e=0;e<i;e++)t+=this.getHeightOfLine(e);let s=this._getLineLeftOffset(i),c=this.__charBounds[i][r];c&&(n=c.left),this.charSpacing!==0&&r===this._textLines[i].length&&(n-=this._getWidthOfCharSpacing());let l=s+(n>0?n:0);return o===`rtl`&&(a===`right`||a===`justify`||a===`justify-right`?l*=-1:a===`left`||a===`justify-left`?l=s-(n>0?n:0):a!==`center`&&a!==`justify-center`||(l=s-(n>0?n:0))),{top:t,left:l}}renderCursorAt(e){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(e,!0),e)}renderCursor(e,t){this._renderCursor(e,t,this.selectionStart)}getCursorRenderingData(e=this.selectionStart,t=this._getCursorBoundaries(e)){let n=this.get2DCursorLocation(e),r=n.lineIndex,i=n.charIndex>0?n.charIndex-1:0,a=this.getValueOfPropertyAt(r,i,`fontSize`),o=this.getObjectScaling().x*this.canvas.getZoom(),s=this.cursorWidth/o,c=this.getValueOfPropertyAt(r,i,`deltaY`),l=t.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-a*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(r,i,`fill`),opacity:this._currentCursorOpacity,left:t.left+t.leftOffset-s/2,top:l+t.top+c,width:s,height:a}}_renderCursor(e,t,n){let{color:r,opacity:i,left:a,top:o,width:s,height:c}=this.getCursorRenderingData(n,t);e.fillStyle=r,e.globalAlpha=i,e.fillRect(a,o,s,c)}renderSelection(e,t){let n={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(e,n,t)}renderDragSourceEffect(){let e=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,e,this._getCursorBoundaries(e.selectionStart,!0))}renderDropTargetEffect(e){let t=this.getSelectionStartFromPointer(e);this.renderCursorAt(t)}_renderSelection(e,t,n){let{textAlign:r,direction:i}=this,a=t.selectionStart,o=t.selectionEnd,s=r.includes(Rn),c=this.get2DCursorLocation(a),l=this.get2DCursorLocation(o),u=c.lineIndex,d=l.lineIndex,f=c.charIndex<0?0:c.charIndex,p=l.charIndex<0?0:l.charIndex;for(let t=u;t<=d;t++){let a=this._getLineLeftOffset(t)||0,o=this.getHeightOfLine(t),c=0,l=0;if(t===u&&(c=this.__charBounds[u][f].left),t>=u&&t<d)l=s&&!this.isEndOfWrapping(t)?this.width:this.getLineWidth(t)||5;else if(t===d){if(p===0)l=this.__charBounds[d][p].left;else{let e=this._getWidthOfCharSpacing();l=this.__charBounds[d][p-1].left+this.__charBounds[d][p-1].width-e}}let m=o;(this.lineHeight<1||t===d&&this.lineHeight>1)&&(o/=this.lineHeight);let h=n.left+a+c,g=o,_=0,v=l-c;this.inCompositionMode?(e.fillStyle=this.compositionColor||`black`,g=1,_=o):e.fillStyle=this.selectionColor,i===`rtl`&&(r===`right`||r===`justify`||r===`justify-right`?h=this.width-h-v:r===`left`||r===`justify-left`?h=n.left+a-l:r!==`center`&&r!==`justify-center`||(h=n.left+a-l)),e.fillRect(h,n.top+n.topOffset+_,v,g),n.topOffset+=m}}getCurrentCharFontSize(){let e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,`fontSize`)}getCurrentCharColor(){let e=this._getCurrentCharIndex();return this.getValueOfPropertyAt(e.l,e.c,_e)}_getCurrentCharIndex(){let e=this.get2DCursorLocation(this.selectionStart,!0),t=e.charIndex>0?e.charIndex-1:0;return{l:e.lineIndex,c:t}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}};p(Cs,`ownDefaults`,Ss),p(Cs,`type`,`IText`),L.setClass(Cs),L.setClass(Cs,`i-text`);var ws=class e extends Cs{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(t,{...e.ownDefaults,...n})}static createControls(){return{controls:ki()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set(`width`,this.dynamicMinWidth),this.textAlign.includes(`justify`)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(e){let t=0,n=0,r=0,i={};for(let a=0;a<e.graphemeLines.length;a++)e.graphemeText[r]===`
|
|
27
27
|
`&&a>0?(n=0,r++,t++):!this.splitByGrapheme&&this._reSpaceAndTab.test(e.graphemeText[r])&&a>0&&(n++,r++),i[a]={line:t,offset:n},r+=e.graphemeLines[a].length,n+=e.graphemeLines[a].length;return i}styleHas(e,t){if(this._styleMap&&!this.isWrapping){let e=this._styleMap[t];e&&(t=e.line)}return super.styleHas(e,t)}isEmptyStyles(e){if(!this.styles)return!0;let t,n,r=0,i=!1,a=this._styleMap[e],o=this._styleMap[e+1];a&&(e=a.line,r=a.offset),o&&(t=o.line,i=t===e,n=o.offset);let s=e===void 0?this.styles:{line:this.styles[e]};for(let e in s)for(let t in s[e]){let a=parseInt(t,10);if(a>=r&&(!i||a<n))for(let n in s[e][t])return!1}return!0}_getStyleDeclaration(e,t){if(this._styleMap&&!this.isWrapping){let n=this._styleMap[e];if(!n)return{};e=n.line,t=n.offset+t}return super._getStyleDeclaration(e,t)}_setStyleDeclaration(e,t,n){let r=this._styleMap[e];super._setStyleDeclaration(r.line,r.offset+t,n)}_deleteStyleDeclaration(e,t){let n=this._styleMap[e];super._deleteStyleDeclaration(n.line,n.offset+t)}_getLineStyle(e){let t=this._styleMap[e];return!!this.styles[t.line]}_setLineStyle(e){let t=this._styleMap[e];super._setLineStyle(t.line)}_wrapText(e,t){this.isWrapping=!0;let n=this.getGraphemeDataForRender(e),r=[];for(let e=0;e<n.wordsData.length;e++)r.push(...this._wrapLine(e,t,n));return this.isWrapping=!1,r}getGraphemeDataForRender(e){let t=this.splitByGrapheme,n=t?``:` `,r=0;return{wordsData:e.map((e,i)=>{let a=0,o=t?this.graphemeSplit(e):this.wordSplit(e);return o.length===0?[{word:[],width:0}]:o.map(e=>{let o=t?[e]:this.graphemeSplit(e),s=this._measureWord(o,i,a);return r=Math.max(s,r),a+=o.length+n.length,{word:o,width:s}})}),largestWordWidth:r}}_measureWord(e,t,n=0){let r,i=0;for(let a=0,o=e.length;a<o;a++)i+=this._getGraphemeBox(e[a],t,a+n,r,!0).kernedWidth,r=e[a];return i}wordSplit(e){return e.split(this._wordJoiners)}_wrapLine(e,t,{largestWordWidth:n,wordsData:r},i=0){let a=this._getWidthOfCharSpacing(),o=this.splitByGrapheme,s=[],c=o?``:` `,l=0,u=[],d=0,f=0,p=!0;t-=i;let m=Math.max(t,n,this.dynamicMinWidth),h=r[e],g;for(g=0;g<h.length;g++){let{word:t,width:n}=h[g];d+=t.length,l+=f+n-a,l>m&&!p?(s.push(u),u=[],l=n,p=!0):l+=a,p||o||u.push(c),u=u.concat(t),f=o?0:this._measureWord([c],e,d),d++,p=!1}return g&&s.push(u),n+i>this.dynamicMinWidth&&(this.dynamicMinWidth=n-a+i),s}isEndOfWrapping(e){return!this._styleMap[e+1]||this._styleMap[e+1].line!==this._styleMap[e].line}missingNewlineOffset(e,t){return this.splitByGrapheme&&!t?+!!this.isEndOfWrapping(e):1}_splitTextIntoLines(e){let t=super._splitTextIntoLines(e),n=this._wrapText(t.lines,this.width),r=Array(n.length);for(let e=0;e<n.length;e++)r[e]=n[e].join(``);return t.lines=r,t.graphemeLines=n,t}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){let e=new Map;for(let t in this._styleMap){let n=parseInt(t,10);if(this._textLines[n]){let n=this._styleMap[t].line;e.set(`${n}`,!0)}}for(let t in this.styles)e.has(t)||delete this.styles[t]}toObject(e=[]){return super.toObject([`minWidth`,`splitByGrapheme`,...e])}};p(ws,`type`,`Textbox`),p(ws,`textLayoutProperties`,[...Cs.textLayoutProperties,`width`]),p(ws,`ownDefaults`,{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),L.setClass(ws);var Ts=class extends va{shouldPerformLayout(e){return!!e.target.clipPath&&super.shouldPerformLayout(e)}shouldLayoutClipPath(){return!1}calcLayoutResult(e,t){let{target:n}=e,{clipPath:r,group:i}=n;if(!r||!this.shouldPerformLayout(e))return;let{width:a,height:o}=Nt(_a(n,r)),s=new R(a,o);if(r.absolutePositioned)return{center:Vt(r.getRelativeCenterPoint(),void 0,i?i.calcTransformMatrix():void 0),size:s};{let i=r.getRelativeCenterPoint().transform(n.calcOwnMatrix(),!0);if(this.shouldPerformLayout(e)){let{center:n=new R,correction:r=new R}=this.calcBoundingBox(t,e)||{};return{center:n.add(i),correction:r.subtract(i),size:s}}return{center:n.getRelativeCenterPoint().add(i),size:s}}}};p(Ts,`type`,`clip-path`),L.setClass(Ts);var Es=class extends va{getInitialSize({target:e},{size:t}){return new R(e.width||t.x,e.height||t.y)}};p(Es,`type`,`fixed`),L.setClass(Es);var Ds=class extends xa{subscribeTargets(e){let t=e.target;e.targets.reduce((e,t)=>(t.parent&&e.add(t.parent),e),new Set).forEach(e=>{e.layoutManager.subscribeTargets({target:e,targets:[t]})})}unsubscribeTargets(e){let t=e.target,n=t.getObjects();e.targets.reduce((e,t)=>(t.parent&&e.add(t.parent),e),new Set).forEach(e=>{!n.some(t=>t.parent===e)&&e.layoutManager.unsubscribeTargets({target:e,targets:[t]})})}},Os=class e extends Ca{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t=[],n={}){super(),Object.assign(this,e.ownDefaults),this.setOptions(n);let{left:r,top:i,layoutManager:a}=n;this.groupInit(t,{left:r,top:i,layoutManager:a??new Ds})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(...e){this.multiSelectionStacking===`selection-order`?this.add(...e):e.forEach(e=>{let t=this._objects.findIndex(t=>t.isInFrontOf(e)),n=t===-1?this.size():t;this.insertAt(n,e)})}canEnterGroup(e){return this.getObjects().some(t=>t.isDescendantOf(e)||e.isDescendantOf(t))?(g(`error`,`ActiveSelection: circular object trees are not supported, this call has no effect`),!1):super.canEnterGroup(e)}enterGroup(e,t){e.parent&&e.parent===e.group?e.parent._exitGroup(e):e.group&&e.parent!==e.group&&e.group.remove(e),this._enterGroup(e,t)}exitGroup(e,t){this._exitGroup(e,t),e.parent&&e.parent._enterGroup(e,!0)}_onAfterObjectsChange(e,t){super._onAfterObjectsChange(e,t);let n=new Set;t.forEach(e=>{let{parent:t}=e;t&&n.add(t)}),e===`removed`?n.forEach(e=>{e._onAfterObjectsChange(ga,t)}):n.forEach(e=>{e._set(`dirty`,!0)})}onDeselect(){return this.removeAll(),!1}toString(){return`#<ActiveSelection: (${this.complexity()})>`}shouldCache(){return!1}isOnACache(){return!1}_renderControls(e,t,n){e.save(),e.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;let r={hasControls:!1,...n,forActiveSelection:!0};for(let t=0;t<this._objects.length;t++)this._objects[t]._renderControls(e,r);super._renderControls(e,t),e.restore()}};p(Os,`type`,`ActiveSelection`),p(Os,`ownDefaults`,{multiSelectionStacking:`canvas-stacking`}),L.setClass(Os),L.setClass(Os,`activeSelection`);var ks=class{constructor(){p(this,`resources`,{})}applyFilters(e,t,n,r,i){let a=i.getContext(`2d`,{willReadFrequently:!0,desynchronized:!0});if(!a)return;a.drawImage(t,0,0,n,r);let o={sourceWidth:n,sourceHeight:r,imageData:a.getImageData(0,0,n,r),originalEl:t,originalImageData:a.getImageData(0,0,n,r),canvasEl:i,ctx:a,filterBackend:this};e.forEach(e=>{e.applyTo(o)});let{imageData:s}=o;return s.width===n&&s.height===r||(i.width=s.width,i.height=s.height),a.putImageData(s,0,0),o}},As=class{constructor({tileSize:e=h.textureSize}={}){p(this,`aPosition`,new Float32Array([0,0,0,1,1,0,1,1])),p(this,`resources`,{}),this.tileSize=e,this.setupGLContext(e,e),this.captureGPUInfo()}setupGLContext(e,t){this.dispose(),this.createWebGLCanvas(e,t)}createWebGLCanvas(e,t){let n=Re({width:e,height:t}),r=n.getContext(`webgl`,{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});r&&(r.clearColor(0,0,0,0),this.canvas=n,this.gl=r)}applyFilters(e,t,n,r,i,a){let o=this.gl,s=i.getContext(`2d`);if(!o||!s)return;let c;a&&(c=this.getCachedTexture(a,t));let l={originalWidth:t.width||t.naturalWidth||0,originalHeight:t.height||t.naturalHeight||0,sourceWidth:n,sourceHeight:r,destinationWidth:n,destinationHeight:r,context:o,sourceTexture:this.createTexture(o,n,r,c?void 0:t),targetTexture:this.createTexture(o,n,r),originalTexture:c||this.createTexture(o,n,r,c?void 0:t),passes:e.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:i},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),e.forEach(e=>{e&&e.applyTo(l)}),function(e){let t=e.targetCanvas,n=t.width,r=t.height,i=e.destinationWidth,a=e.destinationHeight;n===i&&r===a||(t.width=i,t.height=a)}(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(u),s.setTransform(1,0,0,1,0,0),l}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(e,t,n,r,i){let{NEAREST:a,TEXTURE_2D:o,RGBA:s,UNSIGNED_BYTE:c,CLAMP_TO_EDGE:l,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:p}=e,m=e.createTexture();return e.bindTexture(o,m),e.texParameteri(o,u,i||a),e.texParameteri(o,d,i||a),e.texParameteri(o,f,l),e.texParameteri(o,p,l),r?e.texImage2D(o,0,s,s,c,r):e.texImage2D(o,0,s,t,n,0,s,c,null),m}getCachedTexture(e,t,n){let{textureCache:r}=this;if(r[e])return r[e];{let i=this.createTexture(this.gl,t.width,t.height,t,n);return i&&(r[e]=i),i}}evictCachesForKey(e){this.textureCache[e]&&(this.gl.deleteTexture(this.textureCache[e]),delete this.textureCache[e])}copyGLTo2D(e,t){let n=e.canvas,r=t.targetCanvas,i=r.getContext(`2d`);if(!i)return;i.translate(0,r.height),i.scale(1,-1);let a=n.height-r.height;i.drawImage(n,0,a,r.width,r.height,0,0,r.width,r.height)}copyGLTo2DPutImageData(e,t){let n=t.targetCanvas.getContext(`2d`),r=t.destinationWidth,i=t.destinationHeight,a=r*i*4;if(!n)return;let o=new Uint8Array(this.imageBuffer,0,a),s=new Uint8ClampedArray(this.imageBuffer,0,a);e.readPixels(0,0,r,i,e.RGBA,e.UNSIGNED_BYTE,o);let c=new ImageData(s,r,i);n.putImageData(c,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;let e=this.gl,t={renderer:``,vendor:``};if(!e)return t;let n=e.getExtension(`WEBGL_debug_renderer_info`);if(n){let r=e.getParameter(n.UNMASKED_RENDERER_WEBGL),i=e.getParameter(n.UNMASKED_VENDOR_WEBGL);r&&(t.renderer=r.toLowerCase()),i&&(t.vendor=i.toLowerCase())}return this.gpuInfo=t,t}},js;function Ms(){let{WebGLProbe:e}=C();return e.queryWebGL(Fe()),h.enableGLFiltering&&e.isSupported(h.textureSize)?new As({tileSize:h.textureSize}):new ks}function Ns(e=!0){return!js&&e&&(js=Ms()),js}var Ps=[`cropX`,`cropY`],Fs=class e extends Mi{static getDefaults(){return{...super.getDefaults(),...e.ownDefaults}}constructor(t,n){super(),p(this,`_lastScaleX`,1),p(this,`_lastScaleY`,1),p(this,`_filterScalingX`,1),p(this,`_filterScalingY`,1),this.filters=[],Object.assign(this,e.ownDefaults),this.setOptions(n),this.cacheKey=`texture${Pe()}`,this.setElement(typeof t==`string`?(this.canvas&&ht(this.canvas.getElement())||w()).getElementById(t):t,n)}getElement(){return this._element}setElement(e,t={}){this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._element=e,this._originalElement=e,this._setWidthHeight(t),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(e){let t=Ns(!1);t instanceof As&&t.evictCachesForKey(e)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._cacheContext=null,[`_originalElement`,`_element`,`_filteredEl`,`_cacheCanvas`].forEach(e=>{let t=this[e];t&&C().dispose(t),this[e]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){let e=this.getElement();return e?{width:e.naturalWidth||e.width,height:e.naturalHeight||e.height}:{width:0,height:0}}_stroke(e){if(!this.stroke||this.strokeWidth===0)return;let t=this.width/2,n=this.height/2;e.beginPath(),e.moveTo(-t,-n),e.lineTo(t,-n),e.lineTo(t,n),e.lineTo(-t,n),e.lineTo(-t,-n),e.closePath()}toObject(e=[]){let t=[];return this.filters.forEach(e=>{e&&t.push(e.toObject())}),{...super.toObject([...Ps,...e]),src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:t,...this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{}}}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){let e=[],t=this._element,n=-this.width/2,r=-this.height/2,i=[],a=[],o=``,s=``;if(!t)return[];if(this.hasCrop()){let e=Pe();i.push(`<clipPath id="imageCrop_`+e+`">
|
|
28
28
|
`,` <rect x="`+n+`" y="`+r+`" width="`+H(this.width)+`" height="`+H(this.height)+`" />
|
|
29
29
|
`,`</clipPath>
|
|
30
|
-
`),o=` clip-path="url(#imageCrop_`+e+`)" `}if(this.imageSmoothing||(s=` image-rendering="optimizeSpeed"`),e.push(` <image `,`COMMON_PARTS`,`xlink:href="${H(this.getSrc(!0))}" x="${n-this.cropX}" y="${r-this.cropY}" width="${t.width||t.naturalWidth}" height="${t.height||t.naturalHeight}"${s}${o}></image>\n`),this.stroke||this.strokeDashArray){let e=this.fill;this.fill=null,a=[`\t<rect x="${n}" y="${r}" width="${H(this.width)}" height="${H(this.height)}" style="${this.getSvgStyles()}" />\n`],this.fill=e}return i=this.paintFirst===`fill`?i.concat(e,a):i.concat(a,e),i}getSrc(e){let t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute(`src`)||``:t.src:this.src||``}getSvgSrc(e){return this.getSrc(e)}setSrc(e,{crossOrigin:t,signal:n}={}){return it(e,{crossOrigin:t,signal:n}).then(e=>{t!==void 0&&this.set({crossOrigin:t}),this.setElement(e)})}toString(){return`#<Image: { src: "${this.getSrc()}" }>`}applyResizeFilters(){let e=this.resizeFilter,t=this.minimumScaleTrigger,n=this.getTotalObjectScaling(),r=n.x,i=n.y,a=this._filteredEl||this._originalElement;if(this.group&&this.set(`dirty`,!0),!e||r>t&&i>t)return this._element=a,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=i);let o=Re(a),{width:s,height:c}=a;this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=i,Ns().applyFilters([e],a,s,c,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(e=this.filters||[]){if(e=e.filter(e=>e&&!e.isNeutralState()),this.set(`dirty`,!0),this.removeTexture(`${this.cacheKey}_filtered`),e.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);let t=this._originalElement,n=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){let e=Re({width:n,height:r});this._element=e,this._filteredEl=e}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext(`2d`).clearRect(0,0,n,r),this._lastScaleX=1,this._lastScaleY=1);Ns().applyFilters(e,this._originalElement,n,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(e){e.imageSmoothingEnabled=this.imageSmoothing,!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)}drawCacheOnCanvas(e){e.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(e)}shouldCache(){return this.needsItsOwnCache()}_renderFill(e){let t=this._element;if(!t)return;let n=this._filterScalingX,r=this._filterScalingY,i=this.width,a=this.height,o=Math.max(this.cropX,0),s=Math.max(this.cropY,0),c=t.naturalWidth||t.width,l=t.naturalHeight||t.height,u=o*n,d=s*r,f=Math.min(i*n,c-u),p=Math.min(a*r,l-d),m=-i/2,h=-a/2,g=Math.min(i,c/n-o),_=Math.min(a,l/r-s);t&&e.drawImage(t,u,d,f,p,m,h,g,_)}_needsResize(){let e=this.getTotalObjectScaling();return e.x!==this._lastScaleX||e.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight({width:e,height:t}={}){let n=this.getOriginalSize();this.width=e||n.width,this.height=t||n.height}parsePreserveAspectRatioAttribute(){let e=En(this.preserveAspectRatio||``),t=this.width,n=this.height,r={width:t,height:n},i,a=this._element.width,o=this._element.height,s=1,c=1,l=0,u=0,d=0,f=0;return!e||e.alignX===`none`&&e.alignY===`none`?(s=t/a,c=n/o):(e.meetOrSlice===`meet`&&(s=c=Ta(this._element,r),i=(t-a*s)/2,e.alignX===`Min`&&(l=-i),e.alignX===`Max`&&(l=i),i=(n-o*c)/2,e.alignY===`Min`&&(u=-i),e.alignY===`Max`&&(u=i)),e.meetOrSlice===`slice`&&(s=c=Ea(this._element,r),i=a-t/s,e.alignX===`Mid`&&(d=i/2),e.alignX===`Max`&&(d=i),i=o-n/c,e.alignY===`Mid`&&(f=i/2),e.alignY===`Max`&&(f=i),a=t/s,o=n/c)),{width:a,height:o,scaleX:s,scaleY:c,offsetLeft:l,offsetTop:u,cropX:d,cropY:f}}static fromObject({filters:e,resizeFilter:t,src:n,crossOrigin:r,type:i,...a},o){return Promise.all([it(n,{...o,crossOrigin:r}),e&&at(e,o),t?at([t],o):[],ot(a,o)]).then(([e,t=[],[r],i={}])=>new this(e,{...a,src:n,filters:t,resizeFilter:r,...i}))}static fromURL(e,{crossOrigin:t=null,signal:n}={},r){return it(e,{crossOrigin:t,signal:n}).then(e=>new this(e,r))}static async fromElement(e,t={},n){let r=fa(e,this.ATTRIBUTE_NAMES,n);return this.fromURL(r[`xlink:href`]||r.href,t,r).catch(e=>(g(`log`,`Unable to parse Image`,e),null))}};function Is(e){if(!qn.test(e.nodeName))return{};let t=e.getAttribute(`viewBox`),n,r,i=1,a=1,o=e.getAttribute(`width`),s=e.getAttribute(`height`),c=e.getAttribute(`x`)||0,l=e.getAttribute(`y`)||0,u=!(t&&Yn.test(t)),d=!o||!s||o===`100%`||s===`100%`,f=``,p=0,m=0;if(u&&(c||l)&&e.parentNode&&e.parentNode.nodeName!==`#document`&&(f=` translate(`+Tn(c||`0`)+` `+Tn(l||`0`)+`) `,n=(e.getAttribute(`transform`)||``)+f,e.setAttribute(`transform`,n),e.removeAttribute(`x`),e.removeAttribute(`y`)),u&&d)return{width:0,height:0};let h={width:0,height:0};if(u)return h.width=Tn(o),h.height=Tn(s),h;let g=t.match(Yn),_=-parseFloat(g[1]),v=-parseFloat(g[2]),y=parseFloat(g[3]),b=parseFloat(g[4]);h.minX=_,h.minY=v,h.viewBoxWidth=y,h.viewBoxHeight=b,d?(h.width=y,h.height=b):(h.width=Tn(o),h.height=Tn(s),i=h.width/y,a=h.height/b);let x=En(e.getAttribute(`preserveAspectRatio`)||``);if(x.alignX!==`none`&&(x.meetOrSlice===`meet`&&(a=i=i>a?a:i),x.meetOrSlice===`slice`&&(a=i=i>a?i:a),p=h.width-y*i,m=h.height-b*i,x.alignX===`Mid`&&(p/=2),x.alignY===`Mid`&&(m/=2),x.alignX===`Min`&&(p=0),x.alignY===`Min`&&(m=0)),i===1&&a===1&&_===0&&v===0&&c===0&&l===0)return h;if((c||l)&&e.parentNode.nodeName!==`#document`&&(f=` translate(`+Tn(c||`0`)+` `+Tn(l||`0`)+`) `),n=f+` matrix(`+i+` 0 0 `+a+` `+(_*i+p)+` `+(v*a+m)+`) `,e.nodeName===`svg`){for(r=e.ownerDocument.createElementNS(Vn,`g`);e.firstChild;)r.appendChild(e.firstChild);e.appendChild(r)}else r=e,r.removeAttribute(`x`),r.removeAttribute(`y`),n=r.getAttribute(`transform`)+n;return r.setAttribute(`transform`,n),h}p(Fs,`type`,`Image`),p(Fs,`cacheProperties`,[...tr,...Ps]),p(Fs,`ownDefaults`,{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),p(Fs,`ATTRIBUTE_NAMES`,[...Ui,`x`,`y`,`width`,`height`,`preserveAspectRatio`,`xlink:href`,`href`,`crossOrigin`,`image-rendering`]),L.setClass(Fs),L.setSVGClass(Fs);var Ls=e=>e.tagName.replace(`svg:`,``),Rs=kn([`pattern`,`defs`,`symbol`,`metadata`,`clipPath`,`mask`,`desc`]);function zs(e,t){let n,r,i,a,o=[];for(i=0,a=t.length;i<a;i++)n=t[i],r=e.getElementsByTagNameNS(`http://www.w3.org/2000/svg`,n),o=o.concat(Array.from(r));return o}var Bs=[`gradientTransform`,`x1`,`x2`,`y1`,`y2`,`gradientUnits`,`cx`,`cy`,`r`,`fx`,`fy`],Vs=`xlink:href`;function Hs(e,t){let n=t.getAttribute(Vs)?.slice(1)||``,r=e.getElementById(n);if(r&&r.getAttribute(Vs)&&Hs(e,r),r&&(Bs.forEach(e=>{let n=r.getAttribute(e);!t.hasAttribute(e)&&n&&t.setAttribute(e,n)}),!t.children.length)){let e=r.cloneNode(!0);for(;e.firstChild;)t.appendChild(e.firstChild)}t.removeAttribute(Vs)}var Us=[`linearGradient`,`radialGradient`,`svg:linearGradient`,`svg:radialGradient`],Ws=e=>L.getSVGClass(Ls(e).toLowerCase()),Gs=class{constructor(e,t,n,r,i){this.elements=e,this.options=t,this.reviver=n,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=r,this.clipPaths=i,this.gradientDefs=function(e){let t=zs(e,Us),n={},r=t.length;for(;r--;){let i=t[r];i.getAttribute(`xlink:href`)&&Hs(e,i);let a=i.getAttribute(`id`);a&&(n[a]=i)}return n}(r),this.cssRules=function(e){let t=e.getElementsByTagName(`style`),n={};for(let e=0;e<t.length;e++){let r=(t[e].textContent||``).replace(/\/\*[\s\S]*?\*\//g,``);r.trim()!==``&&r.split(`}`).filter((e,t,n)=>n.length>1&&e.trim()).forEach(e=>{if((e.match(/{/g)||[]).length>1&&e.trim().startsWith(`@`))return;let t=e.split(`{`),r={},i=t[1].trim().split(`;`).filter(function(e){return e.trim()});for(let e=0;e<i.length;e++){let t=i[e].split(`:`),n=t[0].trim();r[n]=t[1].trim()}(e=t[0].trim()).split(`,`).forEach(e=>{(e=e.replace(/^svg/i,``).trim())!==``&&(n[e]={...n[e]||{},...r})})})}return n}(r)}parse(){return Promise.all(this.elements.map(e=>this.createObject(e)))}async createObject(e){let t=Ws(e);if(t){let n=await t.fromElement(e,this.options,this.cssRules);return this.resolveGradient(n,e,_e),this.resolveGradient(n,e,ve),n instanceof Fs&&n._originalElement?ao(n,n.parsePreserveAspectRatioAttribute()):ao(n),await this.resolveClipPath(n,e),this.reviver&&this.reviver(e,n),n}return null}extractPropertyDefinition(e,t,n){let r=e[t],i=this.regexUrl;if(!i.test(r))return;i.lastIndex=0;let a=i.exec(r)[1];return i.lastIndex=0,n[a]}resolveGradient(e,t,n){let r=this.extractPropertyDefinition(e,n,this.gradientDefs);if(r){let i=t.getAttribute(n+`-opacity`),a=Go.fromElement(r,e,{...this.options,opacity:i});e.set(n,a)}}async resolveClipPath(e,t,n){let r=this.extractPropertyDefinition(e,`clipPath`,this.clipPaths);if(r){let i=We(e.calcTransformMatrix()),a=r[0].parentElement,o=t;for(;!n&&o.parentElement&&o.getAttribute(`clip-path`)!==e.clipPath;)o=o.parentElement;o.parentElement.appendChild(a);let s=sa(`${o.getAttribute(`transform`)||``} ${a.getAttribute(`originalTransform`)||``}`);a.setAttribute(`transform`,`matrix(${s.join(`,`)})`);let c=await Promise.all(r.map(e=>Ws(e).fromElement(e,this.options,this.cssRules).then(e=>(ao(e),e.fillRule=e.clipRule,delete e.clipRule,e)))),l=c.length===1?c[0]:new Ca(c),u=B(i,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,o,a.getAttribute(`clip-path`)?o:void 0);let{scaleX:d,scaleY:f,angle:p,skewX:m,translateX:h,translateY:g}=Ye(u);l.set({flipX:!1,flipY:!1}),l.set({scaleX:d,scaleY:f,angle:p,skewX:m,skewY:0}),l.setPositionByOrigin(new R(h,g),P,P),e.clipPath=l}else delete e.clipPath}},Ks=e=>Kn.test(Ls(e));async function qs(e,t,{crossOrigin:n,signal:r}={}){if(r&&r.aborted)return g(`log`,new v(`parseSVGDocument`)),{objects:[],elements:[],options:{},allElements:[]};let i=e.documentElement;(function(e){let t=zs(e,[`use`,`svg:use`]),n=[`x`,`y`,`xlink:href`,`href`,`transform`];for(let r of t){let t=r.attributes,i={};for(let e of t)e.value&&(i[e.name]=e.value);let a=(i[`xlink:href`]||i.href||``).slice(1);if(a===``)return;let o=e.getElementById(a);if(o===null)return;let s=o.cloneNode(!0),c=s.attributes,l={};for(let e of c)e.value&&(l[e.name]=e.value);let{x:u=0,y:d=0,transform:f=``}=i,p=`${f} ${l.transform||``} translate(${u}, ${d})`;if(Is(s),/^svg$/i.test(s.nodeName)){let e=s.ownerDocument.createElementNS(Vn,`g`);Object.entries(l).forEach(([t,n])=>e.setAttributeNS(Vn,t,n)),e.append(...s.childNodes),s=e}for(let e of t){if(!e)continue;let{name:t,value:r}=e;if(!n.includes(t))if(t===`style`){let e={};la(r,e),Object.entries(l).forEach(([t,n])=>{e[t]=n}),la(l.style||``,e);let n=Object.entries(e).map(e=>e.join(`:`)).join(`;`);s.setAttribute(t,n)}else!l[t]&&s.setAttribute(t,r)}s.setAttribute(`transform`,p),s.setAttribute(`instantiated_by_use`,`1`),s.removeAttribute(`id`),r.parentNode.replaceChild(s,r)}})(e);let a=Array.from(i.getElementsByTagName(`*`)),o={...Is(i),crossOrigin:n,signal:r},s=a.filter(e=>(Is(e),Ks(e)&&!function(e){let t=e;for(;t&&=t.parentElement;)if(t&&t.nodeName&&Rs.test(Ls(t))&&!t.getAttribute(`instantiated_by_use`))return!0;return!1}(e)));if(!s||s&&!s.length)return{objects:[],elements:[],options:{},allElements:[],options:o,allElements:a};let c={};return a.filter(e=>Ls(e)===`clipPath`).forEach(e=>{e.setAttribute(`originalTransform`,e.getAttribute(`transform`)||``);let t=e.getAttribute(`id`);c[t]=Array.from(e.getElementsByTagName(`*`)).filter(e=>Ks(e))}),{objects:await new Gs(s,o,t,e,c).parse(),elements:s,options:o,allElements:a}}function Js(e,t,n){return qs(new(T()).DOMParser().parseFromString(e.trim(),`text/xml`),t,n)}function Ys(e,t,n={}){return fetch(e.replace(/^\n\s*/,``).trim(),{signal:n.signal}).then(e=>{if(!e.ok)throw new _(`HTTP error! status: ${e.status}`);return e.text()}).then(e=>Js(e,t,n)).catch(()=>({objects:[],elements:[],options:{},allElements:[]}))}var Xs=e=>e.webgl!==void 0,Zs=`precision highp float`,Qs=`\n ${Zs};\n varying vec2 vTexCoord;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n }`,$s=new RegExp(Zs,`g`),U=class{get type(){return this.constructor.type}constructor({type:e,...t}={}){Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Qs}getVertexSource(){return`
|
|
30
|
+
`),o=` clip-path="url(#imageCrop_`+e+`)" `}if(this.imageSmoothing||(s=` image-rendering="optimizeSpeed"`),e.push(` <image `,`COMMON_PARTS`,`xlink:href="${H(this.getSrc(!0))}" x="${n-this.cropX}" y="${r-this.cropY}" width="${t.width||t.naturalWidth}" height="${t.height||t.naturalHeight}"${s}${o}></image>\n`),this.stroke||this.strokeDashArray){let e=this.fill;this.fill=null,a=[`\t<rect x="${n}" y="${r}" width="${H(this.width)}" height="${H(this.height)}" style="${this.getSvgStyles()}" />\n`],this.fill=e}return i=this.paintFirst===`fill`?i.concat(e,a):i.concat(a,e),i}getSrc(e){let t=e?this._element:this._originalElement;return t?t.toDataURL?t.toDataURL():this.srcFromAttribute?t.getAttribute(`src`)||``:t.src:this.src||``}getSvgSrc(e){return this.getSrc(e)}setSrc(e,{crossOrigin:t,signal:n}={}){return it(e,{crossOrigin:t,signal:n}).then(e=>{t!==void 0&&this.set({crossOrigin:t}),this.setElement(e)})}toString(){return`#<Image: { src: "${this.getSrc()}" }>`}applyResizeFilters(){let e=this.resizeFilter,t=this.minimumScaleTrigger,n=this.getTotalObjectScaling(),r=n.x,i=n.y,a=this._filteredEl||this._originalElement;if(this.group&&this.set(`dirty`,!0),!e||r>t&&i>t)return this._element=a,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=i);let o=Re(a),{width:s,height:c}=a;this._element=o,this._lastScaleX=e.scaleX=r,this._lastScaleY=e.scaleY=i,Ns().applyFilters([e],a,s,c,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(e=this.filters||[]){if(e=e.filter(e=>e&&!e.isNeutralState()),this.set(`dirty`,!0),this.removeTexture(`${this.cacheKey}_filtered`),e.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);let t=this._originalElement,n=t.naturalWidth||t.width,r=t.naturalHeight||t.height;if(this._element===this._originalElement){let e=Re({width:n,height:r});this._element=e,this._filteredEl=e}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext(`2d`).clearRect(0,0,n,r),this._lastScaleX=1,this._lastScaleY=1);Ns().applyFilters(e,this._originalElement,n,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(e){e.imageSmoothingEnabled=this.imageSmoothing,!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(e),this._renderPaintInOrder(e)}drawCacheOnCanvas(e){e.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(e)}shouldCache(){return this.needsItsOwnCache()}_renderFill(e){let t=this._element;if(!t)return;let n=this._filterScalingX,r=this._filterScalingY,i=this.width,a=this.height,o=Math.max(this.cropX,0),s=Math.max(this.cropY,0),c=t.naturalWidth||t.width,l=t.naturalHeight||t.height,u=o*n,d=s*r,f=Math.min(i*n,c-u),p=Math.min(a*r,l-d),m=-i/2,h=-a/2,g=Math.min(i,c/n-o),_=Math.min(a,l/r-s);t&&e.drawImage(t,u,d,f,p,m,h,g,_)}_needsResize(){let e=this.getTotalObjectScaling();return e.x!==this._lastScaleX||e.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight({width:e,height:t}={}){let n=this.getOriginalSize();this.width=e||n.width,this.height=t||n.height}parsePreserveAspectRatioAttribute(){let e=En(this.preserveAspectRatio||``),t=this.width,n=this.height,r={width:t,height:n},i,a=this._element.width,o=this._element.height,s=1,c=1,l=0,u=0,d=0,f=0;return!e||e.alignX===`none`&&e.alignY===`none`?(s=t/a,c=n/o):(e.meetOrSlice===`meet`&&(s=c=Ta(this._element,r),i=(t-a*s)/2,e.alignX===`Min`&&(l=-i),e.alignX===`Max`&&(l=i),i=(n-o*c)/2,e.alignY===`Min`&&(u=-i),e.alignY===`Max`&&(u=i)),e.meetOrSlice===`slice`&&(s=c=Ea(this._element,r),i=a-t/s,e.alignX===`Mid`&&(d=i/2),e.alignX===`Max`&&(d=i),i=o-n/c,e.alignY===`Mid`&&(f=i/2),e.alignY===`Max`&&(f=i),a=t/s,o=n/c)),{width:a,height:o,scaleX:s,scaleY:c,offsetLeft:l,offsetTop:u,cropX:d,cropY:f}}static fromObject({filters:e,resizeFilter:t,src:n,crossOrigin:r,type:i,...a},o){return Promise.all([it(n,{...o,crossOrigin:r}),e&&at(e,o),t?at([t],o):[],ot(a,o)]).then(([e,t=[],[r],i={}])=>new this(e,{...a,src:n,filters:t,resizeFilter:r,...i}))}static fromURL(e,{crossOrigin:t=null,signal:n}={},r){return it(e,{crossOrigin:t,signal:n}).then(e=>new this(e,r))}static async fromElement(e,t={},n){let r=fa(e,this.ATTRIBUTE_NAMES,n);return this.fromURL(r[`xlink:href`]||r.href,t,r).catch(e=>(g(`log`,`Unable to parse Image`,e),null))}};function Is(e){if(!qn.test(e.nodeName))return{};let t=e.getAttribute(`viewBox`),n,r,i=1,a=1,o=e.getAttribute(`width`),s=e.getAttribute(`height`),c=e.getAttribute(`x`)||0,l=e.getAttribute(`y`)||0,u=!(t&&Yn.test(t)),d=!o||!s||o===`100%`||s===`100%`,f=``,p=0,m=0;if(u&&(c||l)&&e.parentNode&&e.parentNode.nodeName!==`#document`&&(f=` translate(`+Tn(c||`0`)+` `+Tn(l||`0`)+`) `,n=(e.getAttribute(`transform`)||``)+f,e.setAttribute(`transform`,n),e.removeAttribute(`x`),e.removeAttribute(`y`)),u&&d)return{width:0,height:0};let h={width:0,height:0};if(u)return h.width=Tn(o),h.height=Tn(s),h;let g=t.match(Yn),_=-parseFloat(g[1]),v=-parseFloat(g[2]),y=parseFloat(g[3]),b=parseFloat(g[4]);h.minX=_,h.minY=v,h.viewBoxWidth=y,h.viewBoxHeight=b,d?(h.width=y,h.height=b):(h.width=Tn(o),h.height=Tn(s),i=h.width/y,a=h.height/b);let x=En(e.getAttribute(`preserveAspectRatio`)||``);if(x.alignX!==`none`&&(x.meetOrSlice===`meet`&&(a=i=i>a?a:i),x.meetOrSlice===`slice`&&(a=i=i>a?i:a),p=h.width-y*i,m=h.height-b*i,x.alignX===`Mid`&&(p/=2),x.alignY===`Mid`&&(m/=2),x.alignX===`Min`&&(p=0),x.alignY===`Min`&&(m=0)),i===1&&a===1&&_===0&&v===0&&c===0&&l===0)return h;if((c||l)&&e.parentNode.nodeName!==`#document`&&(f=` translate(`+Tn(c||`0`)+` `+Tn(l||`0`)+`) `),n=f+` matrix(`+i+` 0 0 `+a+` `+(_*i+p)+` `+(v*a+m)+`) `,e.nodeName===`svg`){for(r=e.ownerDocument.createElementNS(Vn,`g`);e.firstChild;)r.appendChild(e.firstChild);e.appendChild(r)}else r=e,r.removeAttribute(`x`),r.removeAttribute(`y`),n=r.getAttribute(`transform`)+n;return r.setAttribute(`transform`,n),h}p(Fs,`type`,`Image`),p(Fs,`cacheProperties`,[...tr,...Ps]),p(Fs,`ownDefaults`,{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),p(Fs,`ATTRIBUTE_NAMES`,[...Ui,`x`,`y`,`width`,`height`,`preserveAspectRatio`,`xlink:href`,`href`,`crossOrigin`,`image-rendering`]),L.setClass(Fs),L.setSVGClass(Fs);var Ls=e=>e.tagName.replace(`svg:`,``),Rs=kn([`pattern`,`defs`,`symbol`,`metadata`,`clipPath`,`mask`,`desc`]);function zs(e,t){let n,r,i,a,o=[];for(i=0,a=t.length;i<a;i++)n=t[i],r=e.getElementsByTagNameNS(`http://www.w3.org/2000/svg`,n),o=o.concat(Array.from(r));return o}var Bs=[`gradientTransform`,`x1`,`x2`,`y1`,`y2`,`gradientUnits`,`cx`,`cy`,`r`,`fx`,`fy`],Vs=`xlink:href`;function Hs(e,t){let n=t.getAttribute(Vs)?.slice(1)||``,r=e.getElementById(n);if(r&&r.getAttribute(Vs)&&Hs(e,r),r&&(Bs.forEach(e=>{let n=r.getAttribute(e);!t.hasAttribute(e)&&n&&t.setAttribute(e,n)}),!t.children.length)){let e=r.cloneNode(!0);for(;e.firstChild;)t.appendChild(e.firstChild)}t.removeAttribute(Vs)}var Us=[`linearGradient`,`radialGradient`,`svg:linearGradient`,`svg:radialGradient`],Ws=e=>L.getSVGClass(Ls(e).toLowerCase()),Gs=class{constructor(e,t,n,r,i){this.elements=e,this.options=t,this.reviver=n,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=r,this.clipPaths=i,this.gradientDefs=function(e){let t=zs(e,Us),n={},r=t.length;for(;r--;){let i=t[r];i.getAttribute(`xlink:href`)&&Hs(e,i);let a=i.getAttribute(`id`);a&&(n[a]=i)}return n}(r),this.cssRules=function(e){let t=e.getElementsByTagName(`style`),n={};for(let e=0;e<t.length;e++){let r=(t[e].textContent||``).replace(/\/\*[\s\S]*?\*\//g,``);r.trim()!==``&&r.split(`}`).filter((e,t,n)=>n.length>1&&e.trim()).forEach(e=>{if((e.match(/{/g)||[]).length>1&&e.trim().startsWith(`@`))return;let t=e.split(`{`),r={},i=t[1].trim().split(`;`).filter(function(e){return e.trim()});for(let e=0;e<i.length;e++){let t=i[e].split(`:`),n=t[0].trim();r[n]=t[1].trim()}(e=t[0].trim()).split(`,`).forEach(e=>{(e=e.replace(/^svg/i,``).trim())!==``&&(n[e]={...n[e]||{},...r})})})}return n}(r)}parse(){return Promise.all(this.elements.map(e=>this.createObject(e)))}async createObject(e){let t=Ws(e);if(t){let n=await t.fromElement(e,this.options,this.cssRules);return this.resolveGradient(n,e,_e),this.resolveGradient(n,e,ve),n instanceof Fs&&n._originalElement?ao(n,n.parsePreserveAspectRatioAttribute()):ao(n),await this.resolveClipPath(n,e),this.reviver&&this.reviver(e,n),n}return null}extractPropertyDefinition(e,t,n){let r=e[t],i=this.regexUrl;if(!i.test(r))return;i.lastIndex=0;let a=i.exec(r)[1];return i.lastIndex=0,n[a]}resolveGradient(e,t,n){let r=this.extractPropertyDefinition(e,n,this.gradientDefs);if(r){let i=t.getAttribute(n+`-opacity`),a=Go.fromElement(r,e,{...this.options,opacity:i});e.set(n,a)}}async resolveClipPath(e,t,n){let r=this.extractPropertyDefinition(e,`clipPath`,this.clipPaths);if(r){let i=We(e.calcTransformMatrix()),a=r[0].parentElement,o=t;for(;!n&&o.parentElement&&o.getAttribute(`clip-path`)!==e.clipPath;)o=o.parentElement;o.parentElement.appendChild(a);let s=sa(`${o.getAttribute(`transform`)||``} ${a.getAttribute(`originalTransform`)||``}`);a.setAttribute(`transform`,`matrix(${s.join(`,`)})`);let c=await Promise.all(r.map(e=>Ws(e).fromElement(e,this.options,this.cssRules).then(e=>(ao(e),e.fillRule=e.clipRule,delete e.clipRule,e)))),l=c.length===1?c[0]:new Ca(c),u=B(i,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,o,a.getAttribute(`clip-path`)?o:void 0);let{scaleX:d,scaleY:f,angle:p,skewX:m,translateX:h,translateY:g}=Ye(u);l.set({flipX:!1,flipY:!1}),l.set({scaleX:d,scaleY:f,angle:p,skewX:m,skewY:0}),l.setPositionByOrigin(new R(h,g),P,P),e.clipPath=l}else delete e.clipPath}},Ks=e=>Kn.test(Ls(e));async function qs(e,t,{crossOrigin:n,signal:r}={}){if(r&&r.aborted)return g(`log`,new v(`parseSVGDocument`)),{objects:[],elements:[],options:{},allElements:[]};let i=e.documentElement;(function(e){let t=zs(e,[`use`,`svg:use`]),n=[`x`,`y`,`xlink:href`,`href`,`transform`];for(let r of t){let t=r.attributes,i={};for(let e of t)e.value&&(i[e.name]=e.value);let a=(i[`xlink:href`]||i.href||``).slice(1);if(a===``)return;let o=e.getElementById(a);if(o===null)return;let s=o.cloneNode(!0),c=s.attributes,l={};for(let e of c)e.value&&(l[e.name]=e.value);let{x:u=0,y:d=0,transform:f=``}=i,p=`${f} ${l.transform||``} translate(${u}, ${d})`;if(Is(s),/^svg$/i.test(s.nodeName)){let e=s.ownerDocument.createElementNS(Vn,`g`);Object.entries(l).forEach(([t,n])=>e.setAttributeNS(Vn,t,n)),e.append(...s.childNodes),s=e}for(let e of t){if(!e)continue;let{name:t,value:r}=e;if(!n.includes(t)){if(t===`style`){let e={};la(r,e),Object.entries(l).forEach(([t,n])=>{e[t]=n}),la(l.style||``,e);let n=Object.entries(e).map(e=>e.join(`:`)).join(`;`);s.setAttribute(t,n)}else!l[t]&&s.setAttribute(t,r)}}s.setAttribute(`transform`,p),s.setAttribute(`instantiated_by_use`,`1`),s.removeAttribute(`id`),r.parentNode.replaceChild(s,r)}})(e);let a=Array.from(i.getElementsByTagName(`*`)),o={...Is(i),crossOrigin:n,signal:r},s=a.filter(e=>(Is(e),Ks(e)&&!function(e){let t=e;for(;t&&=t.parentElement;)if(t&&t.nodeName&&Rs.test(Ls(t))&&!t.getAttribute(`instantiated_by_use`))return!0;return!1}(e)));if(!s||s&&!s.length)return{objects:[],elements:[],options:{},allElements:[],options:o,allElements:a};let c={};return a.filter(e=>Ls(e)===`clipPath`).forEach(e=>{e.setAttribute(`originalTransform`,e.getAttribute(`transform`)||``);let t=e.getAttribute(`id`);c[t]=Array.from(e.getElementsByTagName(`*`)).filter(e=>Ks(e))}),{objects:await new Gs(s,o,t,e,c).parse(),elements:s,options:o,allElements:a}}function Js(e,t,n){return qs(new(T()).DOMParser().parseFromString(e.trim(),`text/xml`),t,n)}function Ys(e,t,n={}){return fetch(e.replace(/^\n\s*/,``).trim(),{signal:n.signal}).then(e=>{if(!e.ok)throw new _(`HTTP error! status: ${e.status}`);return e.text()}).then(e=>Js(e,t,n)).catch(()=>({objects:[],elements:[],options:{},allElements:[]}))}var Xs=e=>e.webgl!==void 0,Zs=`precision highp float`,Qs=`\n ${Zs};\n varying vec2 vTexCoord;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n }`,$s=new RegExp(Zs,`g`),ec=class{get type(){return this.constructor.type}constructor({type:e,...t}={}){Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Qs}getVertexSource(){return`
|
|
31
31
|
attribute vec2 aPosition;
|
|
32
32
|
varying vec2 vTexCoord;
|
|
33
33
|
void main() {
|
|
34
34
|
vTexCoord = aPosition;
|
|
35
35
|
gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
|
|
36
|
-
}`}createProgram(e,t=this.getFragmentSource(),n=this.getVertexSource()){let{WebGLProbe:{GLPrecision:r=`highp`}}=C();r!==`highp`&&(t=t.replace($s,Zs.replace(`highp`,r)));let i=e.createShader(e.VERTEX_SHADER),a=e.createShader(e.FRAGMENT_SHADER),o=e.createProgram();if(!i||!a||!o)throw new _(`Vertex, fragment shader or program creation error`);if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS))throw new _(`Vertex shader compile error for ${this.type}: ${e.getShaderInfoLog(i)}`);if(e.shaderSource(a,t),e.compileShader(a),!e.getShaderParameter(a,e.COMPILE_STATUS))throw new _(`Fragment shader compile error for ${this.type}: ${e.getShaderInfoLog(a)}`);if(e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS))throw new _(`Shader link error for "${this.type}" ${e.getProgramInfoLog(o)}`);let s=this.getUniformLocations(e,o)||{};return s.uStepW=e.getUniformLocation(o,`uStepW`),s.uStepH=e.getUniformLocation(o,`uStepH`),{program:o,attributeLocations:this.getAttributeLocations(e,o),uniformLocations:s}}getAttributeLocations(e,t){return{aPosition:e.getAttribLocation(t,`aPosition`)}}getUniformLocations(e,t){let n=this.constructor.uniformLocations,r={};for(let i=0;i<n.length;i++)r[n[i]]=e.getUniformLocation(t,n[i]);return r}sendAttributeData(e,t,n){let r=t.aPosition,i=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,i),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW)}_setupFrameBuffer(e){let t=e.context;if(e.passes>1){let n=e.destinationWidth,r=e.destinationHeight;e.sourceWidth===n&&e.sourceHeight===r||(t.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(t,n,r)),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e.targetTexture,0)}else t.bindFramebuffer(t.FRAMEBUFFER,null),t.finish()}_swapTextures(e){e.passes--,e.pass++;let t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t}isNeutralState(e){return!1}applyTo(e){Xs(e)?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)}applyTo2d(e){}getCacheKey(){return this.type}retrieveShader(e){let t=this.getCacheKey();return e.programCache[t]||(e.programCache[t]=this.createProgram(e.context)),e.programCache[t]}applyToWebGL(e){let t=e.context,n=this.retrieveShader(e);e.pass===0&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(n.program),this.sendAttributeData(t,n.attributeLocations,e.aPosition),t.uniform1f(n.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(n.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,n.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(e,t,n){e.activeTexture(n),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)}unbindAdditionalTexture(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)}sendUniformData(e,t){}createHelpLayer(e){if(!e.helpLayer){let{sourceWidth:t,sourceHeight:n}=e;e.helpLayer=Re({width:t,height:n})}}toObject(){let e=Object.keys(this.constructor.defaults||{});return{type:this.type,...e.reduce((e,t)=>(e[t]=this[t],e),{})}}toJSON(){return this.toObject()}static async fromObject({type:e,...t},n){return new this(t)}};p(
|
|
36
|
+
}`}createProgram(e,t=this.getFragmentSource(),n=this.getVertexSource()){let{WebGLProbe:{GLPrecision:r=`highp`}}=C();r!==`highp`&&(t=t.replace($s,Zs.replace(`highp`,r)));let i=e.createShader(e.VERTEX_SHADER),a=e.createShader(e.FRAGMENT_SHADER),o=e.createProgram();if(!i||!a||!o)throw new _(`Vertex, fragment shader or program creation error`);if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS))throw new _(`Vertex shader compile error for ${this.type}: ${e.getShaderInfoLog(i)}`);if(e.shaderSource(a,t),e.compileShader(a),!e.getShaderParameter(a,e.COMPILE_STATUS))throw new _(`Fragment shader compile error for ${this.type}: ${e.getShaderInfoLog(a)}`);if(e.attachShader(o,i),e.attachShader(o,a),e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS))throw new _(`Shader link error for "${this.type}" ${e.getProgramInfoLog(o)}`);let s=this.getUniformLocations(e,o)||{};return s.uStepW=e.getUniformLocation(o,`uStepW`),s.uStepH=e.getUniformLocation(o,`uStepH`),{program:o,attributeLocations:this.getAttributeLocations(e,o),uniformLocations:s}}getAttributeLocations(e,t){return{aPosition:e.getAttribLocation(t,`aPosition`)}}getUniformLocations(e,t){let n=this.constructor.uniformLocations,r={};for(let i=0;i<n.length;i++)r[n[i]]=e.getUniformLocation(t,n[i]);return r}sendAttributeData(e,t,n){let r=t.aPosition,i=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,i),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),e.bufferData(e.ARRAY_BUFFER,n,e.STATIC_DRAW)}_setupFrameBuffer(e){let t=e.context;if(e.passes>1){let n=e.destinationWidth,r=e.destinationHeight;e.sourceWidth===n&&e.sourceHeight===r||(t.deleteTexture(e.targetTexture),e.targetTexture=e.filterBackend.createTexture(t,n,r)),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e.targetTexture,0)}else t.bindFramebuffer(t.FRAMEBUFFER,null),t.finish()}_swapTextures(e){e.passes--,e.pass++;let t=e.targetTexture;e.targetTexture=e.sourceTexture,e.sourceTexture=t}isNeutralState(e){return!1}applyTo(e){Xs(e)?(this._setupFrameBuffer(e),this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)}applyTo2d(e){}getCacheKey(){return this.type}retrieveShader(e){let t=this.getCacheKey();return e.programCache[t]||(e.programCache[t]=this.createProgram(e.context)),e.programCache[t]}applyToWebGL(e){let t=e.context,n=this.retrieveShader(e);e.pass===0&&e.originalTexture?t.bindTexture(t.TEXTURE_2D,e.originalTexture):t.bindTexture(t.TEXTURE_2D,e.sourceTexture),t.useProgram(n.program),this.sendAttributeData(t,n.attributeLocations,e.aPosition),t.uniform1f(n.uniformLocations.uStepW,1/e.sourceWidth),t.uniform1f(n.uniformLocations.uStepH,1/e.sourceHeight),this.sendUniformData(t,n.uniformLocations),t.viewport(0,0,e.destinationWidth,e.destinationHeight),t.drawArrays(t.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(e,t,n){e.activeTexture(n),e.bindTexture(e.TEXTURE_2D,t),e.activeTexture(e.TEXTURE0)}unbindAdditionalTexture(e,t){e.activeTexture(t),e.bindTexture(e.TEXTURE_2D,null),e.activeTexture(e.TEXTURE0)}sendUniformData(e,t){}createHelpLayer(e){if(!e.helpLayer){let{sourceWidth:t,sourceHeight:n}=e;e.helpLayer=Re({width:t,height:n})}}toObject(){let e=Object.keys(this.constructor.defaults||{});return{type:this.type,...e.reduce((e,t)=>(e[t]=this[t],e),{})}}toJSON(){return this.toObject()}static async fromObject({type:e,...t},n){return new this(t)}};p(ec,`type`,`BaseFilter`),p(ec,`uniformLocations`,[]);var tc={multiply:`gl_FragColor.rgb *= uColor.rgb;
|
|
37
37
|
`,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
|
|
38
38
|
`,add:`gl_FragColor.rgb += uColor.rgb;
|
|
39
39
|
`,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
|
|
@@ -60,7 +60,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
60
60
|
`,tint:`
|
|
61
61
|
gl_FragColor.rgb *= (1.0 - uColor.a);
|
|
62
62
|
gl_FragColor.rgb += uColor.rgb;
|
|
63
|
-
`},
|
|
63
|
+
`},nc=class extends ec{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n gl_FragColor = color;\n if (color.a > 0.0) {\n ${tc[this.mode]}\n }\n }\n `}applyTo2d({imageData:{data:e}}){let t=new Cn(this.color).getSource(),n=this.alpha,r=t[0]*n,i=t[1]*n,a=t[2]*n,o=1-n;for(let t=0;t<e.length;t+=4){let n=e[t],s=e[t+1],c=e[t+2],l,u,d;switch(this.mode){case`multiply`:l=n*r/255,u=s*i/255,d=c*a/255;break;case`screen`:l=255-(255-n)*(255-r)/255,u=255-(255-s)*(255-i)/255,d=255-(255-c)*(255-a)/255;break;case`add`:l=n+r,u=s+i,d=c+a;break;case`difference`:l=Math.abs(n-r),u=Math.abs(s-i),d=Math.abs(c-a);break;case`subtract`:l=n-r,u=s-i,d=c-a;break;case`darken`:l=Math.min(n,r),u=Math.min(s,i),d=Math.min(c,a);break;case`lighten`:l=Math.max(n,r),u=Math.max(s,i),d=Math.max(c,a);break;case`overlay`:l=r<128?2*n*r/255:255-2*(255-n)*(255-r)/255,u=i<128?2*s*i/255:255-2*(255-s)*(255-i)/255,d=a<128?2*c*a/255:255-2*(255-c)*(255-a)/255;break;case`exclusion`:l=r+n-2*r*n/255,u=i+s-2*i*s/255,d=a+c-2*a*c/255;break;case`tint`:l=r+n*o,u=i+s*o,d=a+c*o}e[t]=l,e[t+1]=u,e[t+2]=d}}sendUniformData(e,t){let n=new Cn(this.color).getSource();n[0]=this.alpha*n[0]/255,n[1]=this.alpha*n[1]/255,n[2]=this.alpha*n[2]/255,n[3]=this.alpha,e.uniform4fv(t.uColor,n)}};p(nc,`defaults`,{color:`#F95C63`,mode:`multiply`,alpha:1}),p(nc,`type`,`BlendColor`),p(nc,`uniformLocations`,[`uColor`]),L.setClass(nc);var rc={multiply:`
|
|
64
64
|
precision highp float;
|
|
65
65
|
uniform sampler2D uTexture;
|
|
66
66
|
uniform sampler2D uImage;
|
|
@@ -86,7 +86,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
86
86
|
color.a = color2.a;
|
|
87
87
|
gl_FragColor = color;
|
|
88
88
|
}
|
|
89
|
-
`},
|
|
89
|
+
`},ic=class extends ec{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return rc[this.mode]}getVertexSource(){return`
|
|
90
90
|
attribute vec2 aPosition;
|
|
91
91
|
varying vec2 vTexCoord;
|
|
92
92
|
varying vec2 vTexCoord2;
|
|
@@ -96,7 +96,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
96
96
|
vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
|
|
97
97
|
gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
|
|
98
98
|
}
|
|
99
|
-
`}applyToWebGL(e){let t=e.context,n=this.createTexture(e.filterBackend,this.image);this.bindAdditionalTexture(t,n,t.TEXTURE1),super.applyToWebGL(e),this.unbindAdditionalTexture(t,t.TEXTURE1)}createTexture(e,t){return e.getCachedTexture(t.cacheKey,t.getElement())}calculateMatrix(){let e=this.image,{width:t,height:n}=e.getElement();return[1/e.scaleX,0,0,0,1/e.scaleY,0,-e.left/t,-e.top/n,1]}applyTo2d({imageData:{data:e,width:t,height:n},filterBackend:{resources:r}}){let i=this.image;r.blendImage||=Fe();let a=r.blendImage,o=a.getContext(`2d`);a.width!==t||a.height!==n?(a.width=t,a.height=n):o.clearRect(0,0,t,n),o.setTransform(i.scaleX,0,0,i.scaleY,i.left,i.top),o.drawImage(i.getElement(),0,0,t,n);let s=o.getImageData(0,0,t,n).data;for(let t=0;t<e.length;t+=4){let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=s[t],c=s[t+1],l=s[t+2],u=s[t+3];switch(this.mode){case`multiply`:e[t]=n*o/255,e[t+1]=r*c/255,e[t+2]=i*l/255,e[t+3]=a*u/255;break;case`mask`:e[t+3]=u}}}sendUniformData(e,t){let n=this.calculateMatrix();e.uniform1i(t.uImage,1),e.uniformMatrix3fv(t.uTransformMatrix,!1,n)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject({type:e,image:t,...n},r){return Fs.fromObject(t,r).then(e=>new this({...n,image:e}))}};p(
|
|
99
|
+
`}applyToWebGL(e){let t=e.context,n=this.createTexture(e.filterBackend,this.image);this.bindAdditionalTexture(t,n,t.TEXTURE1),super.applyToWebGL(e),this.unbindAdditionalTexture(t,t.TEXTURE1)}createTexture(e,t){return e.getCachedTexture(t.cacheKey,t.getElement())}calculateMatrix(){let e=this.image,{width:t,height:n}=e.getElement();return[1/e.scaleX,0,0,0,1/e.scaleY,0,-e.left/t,-e.top/n,1]}applyTo2d({imageData:{data:e,width:t,height:n},filterBackend:{resources:r}}){let i=this.image;r.blendImage||=Fe();let a=r.blendImage,o=a.getContext(`2d`);a.width!==t||a.height!==n?(a.width=t,a.height=n):o.clearRect(0,0,t,n),o.setTransform(i.scaleX,0,0,i.scaleY,i.left,i.top),o.drawImage(i.getElement(),0,0,t,n);let s=o.getImageData(0,0,t,n).data;for(let t=0;t<e.length;t+=4){let n=e[t],r=e[t+1],i=e[t+2],a=e[t+3],o=s[t],c=s[t+1],l=s[t+2],u=s[t+3];switch(this.mode){case`multiply`:e[t]=n*o/255,e[t+1]=r*c/255,e[t+2]=i*l/255,e[t+3]=a*u/255;break;case`mask`:e[t+3]=u}}}sendUniformData(e,t){let n=this.calculateMatrix();e.uniform1i(t.uImage,1),e.uniformMatrix3fv(t.uTransformMatrix,!1,n)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject({type:e,image:t,...n},r){return Fs.fromObject(t,r).then(e=>new this({...n,image:e}))}};p(ic,`type`,`BlendImage`),p(ic,`defaults`,{mode:`multiply`,alpha:1}),p(ic,`uniformLocations`,[`uTransformMatrix`,`uImage`]),L.setClass(ic);var ac=class extends ec{getFragmentSource(){return`
|
|
100
100
|
precision highp float;
|
|
101
101
|
uniform sampler2D uTexture;
|
|
102
102
|
uniform vec2 uDelta;
|
|
@@ -125,7 +125,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
125
125
|
gl_FragColor.rgb = color.rgb / totalC;
|
|
126
126
|
gl_FragColor.a = color.a / totalA;
|
|
127
127
|
}
|
|
128
|
-
`}applyTo(e){Xs(e)?(this.aspectRatio=e.sourceWidth/e.sourceHeight,e.passes++,this._setupFrameBuffer(e),this.horizontal=!0,this.applyToWebGL(e),this._swapTextures(e),this._setupFrameBuffer(e),this.horizontal=!1,this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)}applyTo2d({imageData:{data:e,width:t,height:n}}){this.aspectRatio=t/n,this.horizontal=!0;let r=this.getBlurValue()*t,i=new Uint8ClampedArray(e),a=4*t;for(let t=0;t<e.length;t+=4){let n=0,o=0,s=0,c=0,l=0,u=t-t%a,d=u+a;for(let i=-14;i<15;i++){let a=i/15,f=4*Math.floor(r*a),p=1-Math.abs(a),m=t+f;m<u?m=u:m>d&&(m=d);let h=e[m+3]*p;n+=e[m]*h,o+=e[m+1]*h,s+=e[m+2]*h,c+=h,l+=p}i[t]=n/c,i[t+1]=o/c,i[t+2]=s/c,i[t+3]=c/l}this.horizontal=!1,r=this.getBlurValue()*n;for(let t=0;t<i.length;t+=4){let n=0,o=0,s=0,c=0,l=0,u=t%a,d=i.length-a+u;for(let e=-14;e<15;e++){let f=e/15,p=Math.floor(r*f)*a,m=1-Math.abs(f),h=t+p;h<u?h=u:h>d&&(h=d);let g=i[h+3]*m;n+=i[h]*g,o+=i[h+1]*g,s+=i[h+2]*g,c+=g,l+=m}e[t]=n/c,e[t+1]=o/c,e[t+2]=s/c,e[t+3]=c/l}}sendUniformData(e,t){let n=this.chooseRightDelta();e.uniform2fv(t.uDelta,n)}isNeutralState(){return this.blur===0}getBlurValue(){let e=1,{horizontal:t,aspectRatio:n}=this;return t?n>1&&(e=1/n):n<1&&(e=n),e*this.blur*.12}chooseRightDelta(){let e=this.getBlurValue();return this.horizontal?[e,0]:[0,e]}};p(
|
|
128
|
+
`}applyTo(e){Xs(e)?(this.aspectRatio=e.sourceWidth/e.sourceHeight,e.passes++,this._setupFrameBuffer(e),this.horizontal=!0,this.applyToWebGL(e),this._swapTextures(e),this._setupFrameBuffer(e),this.horizontal=!1,this.applyToWebGL(e),this._swapTextures(e)):this.applyTo2d(e)}applyTo2d({imageData:{data:e,width:t,height:n}}){this.aspectRatio=t/n,this.horizontal=!0;let r=this.getBlurValue()*t,i=new Uint8ClampedArray(e),a=4*t;for(let t=0;t<e.length;t+=4){let n=0,o=0,s=0,c=0,l=0,u=t-t%a,d=u+a;for(let i=-14;i<15;i++){let a=i/15,f=4*Math.floor(r*a),p=1-Math.abs(a),m=t+f;m<u?m=u:m>d&&(m=d);let h=e[m+3]*p;n+=e[m]*h,o+=e[m+1]*h,s+=e[m+2]*h,c+=h,l+=p}i[t]=n/c,i[t+1]=o/c,i[t+2]=s/c,i[t+3]=c/l}this.horizontal=!1,r=this.getBlurValue()*n;for(let t=0;t<i.length;t+=4){let n=0,o=0,s=0,c=0,l=0,u=t%a,d=i.length-a+u;for(let e=-14;e<15;e++){let f=e/15,p=Math.floor(r*f)*a,m=1-Math.abs(f),h=t+p;h<u?h=u:h>d&&(h=d);let g=i[h+3]*m;n+=i[h]*g,o+=i[h+1]*g,s+=i[h+2]*g,c+=g,l+=m}e[t]=n/c,e[t+1]=o/c,e[t+2]=s/c,e[t+3]=c/l}}sendUniformData(e,t){let n=this.chooseRightDelta();e.uniform2fv(t.uDelta,n)}isNeutralState(){return this.blur===0}getBlurValue(){let e=1,{horizontal:t,aspectRatio:n}=this;return t?n>1&&(e=1/n):n<1&&(e=n),e*this.blur*.12}chooseRightDelta(){let e=this.getBlurValue();return this.horizontal?[e,0]:[0,e]}};p(ac,`type`,`Blur`),p(ac,`defaults`,{blur:0}),p(ac,`uniformLocations`,[`uDelta`]),L.setClass(ac);var oc=class extends ec{getFragmentSource(){return`
|
|
129
129
|
precision highp float;
|
|
130
130
|
uniform sampler2D uTexture;
|
|
131
131
|
uniform float uBrightness;
|
|
@@ -135,7 +135,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
135
135
|
color.rgb += uBrightness;
|
|
136
136
|
gl_FragColor = color;
|
|
137
137
|
}
|
|
138
|
-
`}applyTo2d({imageData:{data:e}}){let t=Math.round(255*this.brightness);for(let n=0;n<e.length;n+=4)e[n]+=t,e[n+1]+=t,e[n+2]+=t}isNeutralState(){return this.brightness===0}sendUniformData(e,t){e.uniform1f(t.uBrightness,this.brightness)}};p(
|
|
138
|
+
`}applyTo2d({imageData:{data:e}}){let t=Math.round(255*this.brightness);for(let n=0;n<e.length;n+=4)e[n]+=t,e[n+1]+=t,e[n+2]+=t}isNeutralState(){return this.brightness===0}sendUniformData(e,t){e.uniform1f(t.uBrightness,this.brightness)}};p(oc,`type`,`Brightness`),p(oc,`defaults`,{brightness:0}),p(oc,`uniformLocations`,[`uBrightness`]),L.setClass(oc);var sc={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0},cc=class extends ec{getFragmentSource(){return`
|
|
139
139
|
precision highp float;
|
|
140
140
|
uniform sampler2D uTexture;
|
|
141
141
|
varying vec2 vTexCoord;
|
|
@@ -146,7 +146,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
146
146
|
color *= uColorMatrix;
|
|
147
147
|
color += uConstants;
|
|
148
148
|
gl_FragColor = color;
|
|
149
|
-
}`}applyTo2d(e){let t=e.imageData.data,n=this.matrix,r=this.colorsOnly;for(let e=0;e<t.length;e+=4){let i=t[e],a=t[e+1],o=t[e+2];if(t[e]=i*n[0]+a*n[1]+o*n[2]+255*n[4],t[e+1]=i*n[5]+a*n[6]+o*n[7]+255*n[9],t[e+2]=i*n[10]+a*n[11]+o*n[12]+255*n[14],!r){let r=t[e+3];t[e]+=r*n[3],t[e+1]+=r*n[8],t[e+2]+=r*n[13],t[e+3]=i*n[15]+a*n[16]+o*n[17]+r*n[18]+255*n[19]}}}sendUniformData(e,t){let n=this.matrix,r=[n[0],n[1],n[2],n[3],n[5],n[6],n[7],n[8],n[10],n[11],n[12],n[13],n[15],n[16],n[17],n[18]],i=[n[4],n[9],n[14],n[19]];e.uniformMatrix4fv(t.uColorMatrix,!1,r),e.uniform4fv(t.uConstants,i)}toObject(){return{...super.toObject(),matrix:[...this.matrix]}}};function
|
|
149
|
+
}`}applyTo2d(e){let t=e.imageData.data,n=this.matrix,r=this.colorsOnly;for(let e=0;e<t.length;e+=4){let i=t[e],a=t[e+1],o=t[e+2];if(t[e]=i*n[0]+a*n[1]+o*n[2]+255*n[4],t[e+1]=i*n[5]+a*n[6]+o*n[7]+255*n[9],t[e+2]=i*n[10]+a*n[11]+o*n[12]+255*n[14],!r){let r=t[e+3];t[e]+=r*n[3],t[e+1]+=r*n[8],t[e+2]+=r*n[13],t[e+3]=i*n[15]+a*n[16]+o*n[17]+r*n[18]+255*n[19]}}}sendUniformData(e,t){let n=this.matrix,r=[n[0],n[1],n[2],n[3],n[5],n[6],n[7],n[8],n[10],n[11],n[12],n[13],n[15],n[16],n[17],n[18]],i=[n[4],n[9],n[14],n[19]];e.uniformMatrix4fv(t.uColorMatrix,!1,r),e.uniform4fv(t.uConstants,i)}toObject(){return{...super.toObject(),matrix:[...this.matrix]}}};function lc(e,t){var n;let r=(p(n=class extends cc{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},`type`,e),p(n,`defaults`,{colorsOnly:!1,matrix:t}),n);return L.setClass(r,e),r}p(cc,`type`,`ColorMatrix`),p(cc,`defaults`,sc),p(cc,`uniformLocations`,[`uColorMatrix`,`uConstants`]),L.setClass(cc);var uc=lc(`Brownie`,[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),dc=lc(`Vintage`,[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),fc=lc(`Kodachrome`,[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),pc=lc(`Technicolor`,[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),mc=lc(`Polaroid`,[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),hc=lc(`Sepia`,[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),gc=lc(`BlackWhite`,[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]),_c=class extends ec{constructor(e={}){super(e),this.subFilters=e.subFilters||[]}applyTo(e){Xs(e)&&(e.passes+=this.subFilters.length-1),this.subFilters.forEach(t=>{t.applyTo(e)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(e=>e.toObject())}}isNeutralState(){return!this.subFilters.some(e=>!e.isNeutralState())}static fromObject(e,t){return Promise.all((e.subFilters||[]).map(e=>L.getClass(e.type).fromObject(e,t))).then(e=>new this({subFilters:e}))}};p(_c,`type`,`Composed`),L.setClass(_c);var vc=class extends ec{getFragmentSource(){return`
|
|
150
150
|
precision highp float;
|
|
151
151
|
uniform sampler2D uTexture;
|
|
152
152
|
uniform float uContrast;
|
|
@@ -156,7 +156,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
156
156
|
float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
|
|
157
157
|
color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
|
|
158
158
|
gl_FragColor = color;
|
|
159
|
-
}`}isNeutralState(){return this.contrast===0}applyTo2d({imageData:{data:e}}){let t=Math.floor(255*this.contrast),n=259*(t+255)/(255*(259-t));for(let t=0;t<e.length;t+=4)e[t]=n*(e[t]-128)+128,e[t+1]=n*(e[t+1]-128)+128,e[t+2]=n*(e[t+2]-128)+128}sendUniformData(e,t){e.uniform1f(t.uContrast,this.contrast)}};p(
|
|
159
|
+
}`}isNeutralState(){return this.contrast===0}applyTo2d({imageData:{data:e}}){let t=Math.floor(255*this.contrast),n=259*(t+255)/(255*(259-t));for(let t=0;t<e.length;t+=4)e[t]=n*(e[t]-128)+128,e[t+1]=n*(e[t+1]-128)+128,e[t+2]=n*(e[t+2]-128)+128}sendUniformData(e,t){e.uniform1f(t.uContrast,this.contrast)}};p(vc,`type`,`Contrast`),p(vc,`defaults`,{contrast:0}),p(vc,`uniformLocations`,[`uContrast`]),L.setClass(vc);var yc={Convolute_3_1:`
|
|
160
160
|
precision highp float;
|
|
161
161
|
uniform sampler2D uTexture;
|
|
162
162
|
uniform float uMatrix[9];
|
|
@@ -300,7 +300,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
300
300
|
gl_FragColor = color;
|
|
301
301
|
gl_FragColor.a = alpha;
|
|
302
302
|
}
|
|
303
|
-
`},
|
|
303
|
+
`},bc=class extends ec{getCacheKey(){return`${this.type}_${Math.sqrt(this.matrix.length)}_${+!!this.opaque}`}getFragmentSource(){return yc[this.getCacheKey()]}applyTo2d(e){let t=e.imageData,n=t.data,r=this.matrix,i=Math.round(Math.sqrt(r.length)),a=Math.floor(i/2),o=t.width,s=t.height,c=e.ctx.createImageData(o,s),l=c.data,u=+!!this.opaque,d,f,p,m,h,g,_,v,y,b,x,S,C;for(x=0;x<s;x++)for(b=0;b<o;b++){for(h=4*(x*o+b),d=0,f=0,p=0,m=0,C=0;C<i;C++)for(S=0;S<i;S++)_=x+C-a,g=b+S-a,_<0||_>=s||g<0||g>=o||(v=4*(_*o+g),y=r[C*i+S],d+=n[v]*y,f+=n[v+1]*y,p+=n[v+2]*y,u||(m+=n[v+3]*y));l[h]=d,l[h+1]=f,l[h+2]=p,l[h+3]=u?n[h+3]:m}e.imageData=c}sendUniformData(e,t){e.uniform1fv(t.uMatrix,this.matrix)}toObject(){return{...super.toObject(),opaque:this.opaque,matrix:[...this.matrix]}}};p(bc,`type`,`Convolute`),p(bc,`defaults`,{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),p(bc,`uniformLocations`,[`uMatrix`,`uOpaque`,`uHalfSize`,`uSize`]),L.setClass(bc);var xc=`Gamma`,Sc=class extends ec{getFragmentSource(){return`
|
|
304
304
|
precision highp float;
|
|
305
305
|
uniform sampler2D uTexture;
|
|
306
306
|
uniform vec3 uGamma;
|
|
@@ -314,7 +314,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
314
314
|
gl_FragColor = color;
|
|
315
315
|
gl_FragColor.rgb *= color.a;
|
|
316
316
|
}
|
|
317
|
-
`}constructor(e={}){super(e),this.gamma=e.gamma||this.constructor.defaults.gamma.concat()}applyTo2d({imageData:{data:e}}){let t=this.gamma,n=1/t[0],r=1/t[1],i=1/t[2];this.rgbValues||={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)};let a=this.rgbValues;for(let e=0;e<256;e++)a.r[e]=255*(e/255)**n,a.g[e]=255*(e/255)**r,a.b[e]=255*(e/255)**i;for(let t=0;t<e.length;t+=4)e[t]=a.r[e[t]],e[t+1]=a.g[e[t+1]],e[t+2]=a.b[e[t+2]]}sendUniformData(e,t){e.uniform3fv(t.uGamma,this.gamma)}isNeutralState(){let{gamma:e}=this;return e[0]===1&&e[1]===1&&e[2]===1}toObject(){return{type:
|
|
317
|
+
`}constructor(e={}){super(e),this.gamma=e.gamma||this.constructor.defaults.gamma.concat()}applyTo2d({imageData:{data:e}}){let t=this.gamma,n=1/t[0],r=1/t[1],i=1/t[2];this.rgbValues||={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)};let a=this.rgbValues;for(let e=0;e<256;e++)a.r[e]=255*(e/255)**n,a.g[e]=255*(e/255)**r,a.b[e]=255*(e/255)**i;for(let t=0;t<e.length;t+=4)e[t]=a.r[e[t]],e[t+1]=a.g[e[t+1]],e[t+2]=a.b[e[t+2]]}sendUniformData(e,t){e.uniform3fv(t.uGamma,this.gamma)}isNeutralState(){let{gamma:e}=this;return e[0]===1&&e[1]===1&&e[2]===1}toObject(){return{type:xc,gamma:this.gamma.concat()}}};p(Sc,`type`,xc),p(Sc,`defaults`,{gamma:[1,1,1]}),p(Sc,`uniformLocations`,[`uGamma`]),L.setClass(Sc);var Cc={average:`
|
|
318
318
|
precision highp float;
|
|
319
319
|
uniform sampler2D uTexture;
|
|
320
320
|
varying vec2 vTexCoord;
|
|
@@ -343,7 +343,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
343
343
|
float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
|
|
344
344
|
gl_FragColor = vec4(average, average, average, col.a);
|
|
345
345
|
}
|
|
346
|
-
`},
|
|
346
|
+
`},wc=class extends ec{applyTo2d({imageData:{data:e}}){for(let t,n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2];switch(this.mode){case`average`:t=(r+i+a)/3;break;case`lightness`:t=(Math.min(r,i,a)+Math.max(r,i,a))/2;break;case`luminosity`:t=.21*r+.72*i+.07*a}e[n+2]=e[n+1]=e[n]=t}}getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Cc[this.mode]}sendUniformData(e,t){e.uniform1i(t.uMode,1)}isNeutralState(){return!1}};p(wc,`type`,`Grayscale`),p(wc,`defaults`,{mode:`average`}),p(wc,`uniformLocations`,[`uMode`]),L.setClass(wc);var Tc={...sc,rotation:0},Ec=class extends cc{calculateMatrix(){let e=this.rotation*Math.PI,t=Te(e),n=Ee(e),r=1/3,i=Math.sqrt(r)*n,a=1-t;this.matrix=[t+a/3,r*a-i,r*a+i,0,0,r*a+i,t+r*a,r*a-i,0,0,r*a-i,r*a+i,t+r*a,0,0,0,0,0,1,0]}isNeutralState(){return this.rotation===0}applyTo(e){this.calculateMatrix(),super.applyTo(e)}toObject(){return{type:this.type,rotation:this.rotation}}};p(Ec,`type`,`HueRotation`),p(Ec,`defaults`,Tc),L.setClass(Ec);var Dc=class extends ec{applyTo2d({imageData:{data:e}}){for(let t=0;t<e.length;t+=4)e[t]=255-e[t],e[t+1]=255-e[t+1],e[t+2]=255-e[t+2],this.alpha&&(e[t+3]=255-e[t+3])}getFragmentSource(){return`
|
|
347
347
|
precision highp float;
|
|
348
348
|
uniform sampler2D uTexture;
|
|
349
349
|
uniform int uInvert;
|
|
@@ -361,7 +361,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
361
361
|
gl_FragColor = color;
|
|
362
362
|
}
|
|
363
363
|
}
|
|
364
|
-
`}isNeutralState(){return!this.invert}sendUniformData(e,t){e.uniform1i(t.uInvert,Number(this.invert)),e.uniform1i(t.uAlpha,Number(this.alpha))}};p(
|
|
364
|
+
`}isNeutralState(){return!this.invert}sendUniformData(e,t){e.uniform1i(t.uInvert,Number(this.invert)),e.uniform1i(t.uAlpha,Number(this.alpha))}};p(Dc,`type`,`Invert`),p(Dc,`defaults`,{alpha:!1,invert:!0}),p(Dc,`uniformLocations`,[`uInvert`,`uAlpha`]),L.setClass(Dc);var Oc=class extends ec{getFragmentSource(){return`
|
|
365
365
|
precision highp float;
|
|
366
366
|
uniform sampler2D uTexture;
|
|
367
367
|
uniform float uStepH;
|
|
@@ -376,7 +376,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
376
376
|
color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
|
|
377
377
|
gl_FragColor = color;
|
|
378
378
|
}
|
|
379
|
-
`}applyTo2d({imageData:{data:e}}){let t=this.noise;for(let n=0;n<e.length;n+=4){let r=(.5-Math.random())*t;e[n]+=r,e[n+1]+=r,e[n+2]+=r}}sendUniformData(e,t){e.uniform1f(t.uNoise,this.noise/255),e.uniform1f(t.uSeed,Math.random())}isNeutralState(){return this.noise===0}};p(
|
|
379
|
+
`}applyTo2d({imageData:{data:e}}){let t=this.noise;for(let n=0;n<e.length;n+=4){let r=(.5-Math.random())*t;e[n]+=r,e[n+1]+=r,e[n+2]+=r}}sendUniformData(e,t){e.uniform1f(t.uNoise,this.noise/255),e.uniform1f(t.uSeed,Math.random())}isNeutralState(){return this.noise===0}};p(Oc,`type`,`Noise`),p(Oc,`defaults`,{noise:0}),p(Oc,`uniformLocations`,[`uNoise`,`uSeed`]),L.setClass(Oc);var kc=class extends ec{applyTo2d({imageData:{data:e,width:t,height:n}}){for(let r=0;r<n;r+=this.blocksize)for(let i=0;i<t;i+=this.blocksize){let a=4*r*t+4*i,o=e[a],s=e[a+1],c=e[a+2],l=e[a+3];for(let a=r;a<Math.min(r+this.blocksize,n);a++)for(let n=i;n<Math.min(i+this.blocksize,t);n++){let r=4*a*t+4*n;e[r]=o,e[r+1]=s,e[r+2]=c,e[r+3]=l}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
|
|
380
380
|
precision highp float;
|
|
381
381
|
uniform sampler2D uTexture;
|
|
382
382
|
uniform float uBlocksize;
|
|
@@ -394,7 +394,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
394
394
|
vec4 color = texture2D(uTexture, squareCoords);
|
|
395
395
|
gl_FragColor = color;
|
|
396
396
|
}
|
|
397
|
-
`}sendUniformData(e,t){e.uniform1f(t.uBlocksize,this.blocksize)}};p(
|
|
397
|
+
`}sendUniformData(e,t){e.uniform1f(t.uBlocksize,this.blocksize)}};p(kc,`type`,`Pixelate`),p(kc,`defaults`,{blocksize:4}),p(kc,`uniformLocations`,[`uBlocksize`]),L.setClass(kc);var Ac=class extends ec{getFragmentSource(){return`
|
|
398
398
|
precision highp float;
|
|
399
399
|
uniform sampler2D uTexture;
|
|
400
400
|
uniform vec4 uLow;
|
|
@@ -406,8 +406,8 @@ void main() {
|
|
|
406
406
|
gl_FragColor.a = 0.0;
|
|
407
407
|
}
|
|
408
408
|
}
|
|
409
|
-
`}applyTo2d({imageData:{data:e}}){let t=255*this.distance,n=new Cn(this.color).getSource(),r=[n[0]-t,n[1]-t,n[2]-t],i=[n[0]+t,n[1]+t,n[2]+t];for(let t=0;t<e.length;t+=4){let n=e[t],a=e[t+1],o=e[t+2];n>r[0]&&a>r[1]&&o>r[2]&&n<i[0]&&a<i[1]&&o<i[2]&&(e[t+3]=0)}}sendUniformData(e,t){let n=new Cn(this.color).getSource(),r=this.distance,i=[0+n[0]/255-r,0+n[1]/255-r,0+n[2]/255-r,1],a=[n[0]/255+r,n[1]/255+r,n[2]/255+r,1];e.uniform4fv(t.uLow,i),e.uniform4fv(t.uHigh,a)}};p(
|
|
410
|
-
`)}\n gl_FragColor = color / sum;\n }\n `}applyToForWebgl(e){e.passes++,this.width=e.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=e.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),e.destinationWidth=this.dW,super.applyTo(e),e.sourceWidth=e.destinationWidth,this.height=e.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),e.destinationHeight=this.dH,super.applyTo(e),e.sourceHeight=e.destinationHeight}applyTo(e){Xs(e)?this.applyToForWebgl(e):this.applyTo2d(e)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(e){return t=>{if(t>=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;let n=(t*=Math.PI)/e;return Math.sin(t)/t*Math.sin(n)/n}}applyTo2d(e){let t=e.imageData,n=this.scaleX,r=this.scaleY;this.rcpScaleX=1/n,this.rcpScaleY=1/r;let i=t.width,a=t.height,o=Math.round(i*n),s=Math.round(a*r),c;c=this.resizeType===`sliceHack`?this.sliceByTwo(e,i,a,o,s):this.resizeType===`hermite`?this.hermiteFastResize(e,i,a,o,s):this.resizeType===`bilinear`?this.bilinearFiltering(e,i,a,o,s):this.resizeType===`lanczos`?this.lanczosResize(e,i,a,o,s):new ImageData(o,s),e.imageData=c}sliceByTwo(e,t,n,r,i){let a=e.imageData,o=.5,s=!1,c=!1,l=t*o,u=n*o,d=e.filterBackend.resources,f=0,p=0,m=t,h=0;d.sliceByTwo||=Fe();let g=d.sliceByTwo;(g.width<1.5*t||g.height<n)&&(g.width=1.5*t,g.height=n);let _=g.getContext(`2d`);for(_.clearRect(0,0,1.5*t,n),_.putImageData(a,0,0),r=Math.floor(r),i=Math.floor(i);!s||!c;)t=l,n=u,r<Math.floor(l*o)?l=Math.floor(l*o):(l=r,s=!0),i<Math.floor(u*o)?u=Math.floor(u*o):(u=i,c=!0),_.drawImage(g,f,p,t,n,m,h,l,u),f=m,p=h,h+=u;return _.getImageData(f,p,r,i)}lanczosResize(e,t,n,r,i){let a=e.imageData.data,o=e.ctx.createImageData(r,i),s=o.data,c=this.lanczosCreate(this.lanczosLobes),l=this.rcpScaleX,u=this.rcpScaleY,d=2/this.rcpScaleX,f=2/this.rcpScaleY,p=Math.ceil(l*this.lanczosLobes/2),m=Math.ceil(u*this.lanczosLobes/2),h={},g={x:0,y:0},_={x:0,y:0};return function e(v){let y,b,x,S,C,w,T,E,D,O,k;for(g.x=(v+.5)*l,_.x=Math.floor(g.x),y=0;y<i;y++){for(g.y=(y+.5)*u,_.y=Math.floor(g.y),C=0,w=0,T=0,E=0,D=0,b=_.x-p;b<=_.x+p;b++)if(!(b<0||b>=t)){O=Math.floor(1e3*Math.abs(b-g.x)),h[O]||(h[O]={});for(let e=_.y-m;e<=_.y+m;e++)e<0||e>=n||(k=Math.floor(1e3*Math.abs(e-g.y)),h[O][k]||(h[O][k]=c(Math.sqrt((O*d)**2+(k*f)**2)/1e3)),x=h[O][k],x>0&&(S=4*(e*t+b),C+=x,w+=x*a[S],T+=x*a[S+1],E+=x*a[S+2],D+=x*a[S+3]))}S=4*(y*r+v),s[S]=w/C,s[S+1]=T/C,s[S+2]=E/C,s[S+3]=D/C}return++v<r?e(v):o}(0)}bilinearFiltering(e,t,n,r,i){let a,o,s,c,l,u,d,f,p,m,h,g,_,v=0,y=this.rcpScaleX,b=this.rcpScaleY,x=4*(t-1),S=e.imageData.data,C=e.ctx.createImageData(r,i),w=C.data;for(d=0;d<i;d++)for(f=0;f<r;f++)for(l=Math.floor(y*f),u=Math.floor(b*d),p=y*f-l,m=b*d-u,_=4*(u*t+l),h=0;h<4;h++)a=S[_+h],o=S[_+4+h],s=S[_+x+h],c=S[_+x+4+h],g=a*(1-p)*(1-m)+o*p*(1-m)+s*m*(1-p)+c*p*m,w[v++]=g;return C}hermiteFastResize(e,t,n,r,i){let a=this.rcpScaleX,o=this.rcpScaleY,s=Math.ceil(a/2),c=Math.ceil(o/2),l=e.imageData.data,u=e.ctx.createImageData(r,i),d=u.data;for(let e=0;e<i;e++)for(let n=0;n<r;n++){let i=4*(n+e*r),u,f=0,p=0,m=0,h=0,g=0,_=0,v=(e+.5)*o;for(let r=Math.floor(e*o);r<(e+1)*o;r++){let e=Math.abs(v-(r+.5))/c,i=(n+.5)*a,o=e*e;for(let e=Math.floor(n*a);e<(n+1)*a;e++){let n=Math.abs(i-(e+.5))/s,a=Math.sqrt(o+n*n);a>1&&a<-1||(u=2*a*a*a-3*a*a+1,u>0&&(n=4*(e+r*t),_+=u*l[n+3],p+=u,l[n+3]<255&&(u=u*l[n+3]/250),m+=u*l[n],h+=u*l[n+1],g+=u*l[n+2],f+=u))}}d[i]=m/f,d[i+1]=h/f,d[i+2]=g/f,d[i+3]=_/p}return u}};p(
|
|
409
|
+
`}applyTo2d({imageData:{data:e}}){let t=255*this.distance,n=new Cn(this.color).getSource(),r=[n[0]-t,n[1]-t,n[2]-t],i=[n[0]+t,n[1]+t,n[2]+t];for(let t=0;t<e.length;t+=4){let n=e[t],a=e[t+1],o=e[t+2];n>r[0]&&a>r[1]&&o>r[2]&&n<i[0]&&a<i[1]&&o<i[2]&&(e[t+3]=0)}}sendUniformData(e,t){let n=new Cn(this.color).getSource(),r=this.distance,i=[0+n[0]/255-r,0+n[1]/255-r,0+n[2]/255-r,1],a=[n[0]/255+r,n[1]/255+r,n[2]/255+r,1];e.uniform4fv(t.uLow,i),e.uniform4fv(t.uHigh,a)}};p(Ac,`type`,`RemoveColor`),p(Ac,`defaults`,{color:`#FFFFFF`,distance:.02,useAlpha:!1}),p(Ac,`uniformLocations`,[`uLow`,`uHigh`]),L.setClass(Ac);var jc=class extends ec{sendUniformData(e,t){e.uniform2fv(t.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),e.uniform1fv(t.uTaps,this.taps)}getFilterWindow(){let e=this.tempScale;return Math.ceil(this.lanczosLobes/e)}getCacheKey(){let e=this.getFilterWindow();return`${this.type}_${e}`}getFragmentSource(){let e=this.getFilterWindow();return this.generateShader(e)}getTaps(){let e=this.lanczosCreate(this.lanczosLobes),t=this.tempScale,n=this.getFilterWindow(),r=Array(n);for(let i=1;i<=n;i++)r[i-1]=e(i*t);return r}generateShader(e){let t=Array(e);for(let n=1;n<=e;n++)t[n-1]=`${n}.0 * uDelta`;return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n uniform float uTaps[${e}];\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float sum = 1.0;\n ${t.map((e,t)=>`\n color += texture2D(uTexture, vTexCoord + ${e}) * uTaps[${t}] + texture2D(uTexture, vTexCoord - ${e}) * uTaps[${t}];\n sum += 2.0 * uTaps[${t}];\n `).join(`
|
|
410
|
+
`)}\n gl_FragColor = color / sum;\n }\n `}applyToForWebgl(e){e.passes++,this.width=e.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=e.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),e.destinationWidth=this.dW,super.applyTo(e),e.sourceWidth=e.destinationWidth,this.height=e.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),e.destinationHeight=this.dH,super.applyTo(e),e.sourceHeight=e.destinationHeight}applyTo(e){Xs(e)?this.applyToForWebgl(e):this.applyTo2d(e)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(e){return t=>{if(t>=e||t<=-e)return 0;if(t<1.1920929e-7&&t>-1.1920929e-7)return 1;let n=(t*=Math.PI)/e;return Math.sin(t)/t*Math.sin(n)/n}}applyTo2d(e){let t=e.imageData,n=this.scaleX,r=this.scaleY;this.rcpScaleX=1/n,this.rcpScaleY=1/r;let i=t.width,a=t.height,o=Math.round(i*n),s=Math.round(a*r),c;c=this.resizeType===`sliceHack`?this.sliceByTwo(e,i,a,o,s):this.resizeType===`hermite`?this.hermiteFastResize(e,i,a,o,s):this.resizeType===`bilinear`?this.bilinearFiltering(e,i,a,o,s):this.resizeType===`lanczos`?this.lanczosResize(e,i,a,o,s):new ImageData(o,s),e.imageData=c}sliceByTwo(e,t,n,r,i){let a=e.imageData,o=.5,s=!1,c=!1,l=t*o,u=n*o,d=e.filterBackend.resources,f=0,p=0,m=t,h=0;d.sliceByTwo||=Fe();let g=d.sliceByTwo;(g.width<1.5*t||g.height<n)&&(g.width=1.5*t,g.height=n);let _=g.getContext(`2d`);for(_.clearRect(0,0,1.5*t,n),_.putImageData(a,0,0),r=Math.floor(r),i=Math.floor(i);!s||!c;)t=l,n=u,r<Math.floor(l*o)?l=Math.floor(l*o):(l=r,s=!0),i<Math.floor(u*o)?u=Math.floor(u*o):(u=i,c=!0),_.drawImage(g,f,p,t,n,m,h,l,u),f=m,p=h,h+=u;return _.getImageData(f,p,r,i)}lanczosResize(e,t,n,r,i){let a=e.imageData.data,o=e.ctx.createImageData(r,i),s=o.data,c=this.lanczosCreate(this.lanczosLobes),l=this.rcpScaleX,u=this.rcpScaleY,d=2/this.rcpScaleX,f=2/this.rcpScaleY,p=Math.ceil(l*this.lanczosLobes/2),m=Math.ceil(u*this.lanczosLobes/2),h={},g={x:0,y:0},_={x:0,y:0};return function e(v){let y,b,x,S,C,w,T,E,D,O,k;for(g.x=(v+.5)*l,_.x=Math.floor(g.x),y=0;y<i;y++){for(g.y=(y+.5)*u,_.y=Math.floor(g.y),C=0,w=0,T=0,E=0,D=0,b=_.x-p;b<=_.x+p;b++)if(!(b<0||b>=t)){O=Math.floor(1e3*Math.abs(b-g.x)),h[O]||(h[O]={});for(let e=_.y-m;e<=_.y+m;e++)e<0||e>=n||(k=Math.floor(1e3*Math.abs(e-g.y)),h[O][k]||(h[O][k]=c(Math.sqrt((O*d)**2+(k*f)**2)/1e3)),x=h[O][k],x>0&&(S=4*(e*t+b),C+=x,w+=x*a[S],T+=x*a[S+1],E+=x*a[S+2],D+=x*a[S+3]))}S=4*(y*r+v),s[S]=w/C,s[S+1]=T/C,s[S+2]=E/C,s[S+3]=D/C}return++v<r?e(v):o}(0)}bilinearFiltering(e,t,n,r,i){let a,o,s,c,l,u,d,f,p,m,h,g,_,v=0,y=this.rcpScaleX,b=this.rcpScaleY,x=4*(t-1),S=e.imageData.data,C=e.ctx.createImageData(r,i),w=C.data;for(d=0;d<i;d++)for(f=0;f<r;f++)for(l=Math.floor(y*f),u=Math.floor(b*d),p=y*f-l,m=b*d-u,_=4*(u*t+l),h=0;h<4;h++)a=S[_+h],o=S[_+4+h],s=S[_+x+h],c=S[_+x+4+h],g=a*(1-p)*(1-m)+o*p*(1-m)+s*m*(1-p)+c*p*m,w[v++]=g;return C}hermiteFastResize(e,t,n,r,i){let a=this.rcpScaleX,o=this.rcpScaleY,s=Math.ceil(a/2),c=Math.ceil(o/2),l=e.imageData.data,u=e.ctx.createImageData(r,i),d=u.data;for(let e=0;e<i;e++)for(let n=0;n<r;n++){let i=4*(n+e*r),u,f=0,p=0,m=0,h=0,g=0,_=0,v=(e+.5)*o;for(let r=Math.floor(e*o);r<(e+1)*o;r++){let e=Math.abs(v-(r+.5))/c,i=(n+.5)*a,o=e*e;for(let e=Math.floor(n*a);e<(n+1)*a;e++){let n=Math.abs(i-(e+.5))/s,a=Math.sqrt(o+n*n);a>1&&a<-1||(u=2*a*a*a-3*a*a+1,u>0&&(n=4*(e+r*t),_+=u*l[n+3],p+=u,l[n+3]<255&&(u=u*l[n+3]/250),m+=u*l[n],h+=u*l[n+1],g+=u*l[n+2],f+=u))}}d[i]=m/f,d[i+1]=h/f,d[i+2]=g/f,d[i+3]=_/p}return u}};p(jc,`type`,`Resize`),p(jc,`defaults`,{resizeType:`hermite`,scaleX:1,scaleY:1,lanczosLobes:3}),p(jc,`uniformLocations`,[`uDelta`,`uTaps`]),L.setClass(jc);var Mc=class extends ec{getFragmentSource(){return`
|
|
411
411
|
precision highp float;
|
|
412
412
|
uniform sampler2D uTexture;
|
|
413
413
|
uniform float uSaturation;
|
|
@@ -421,7 +421,7 @@ void main() {
|
|
|
421
421
|
color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
|
|
422
422
|
gl_FragColor = color;
|
|
423
423
|
}
|
|
424
|
-
`}applyTo2d({imageData:{data:e}}){let t=-this.saturation;for(let n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2],o=Math.max(r,i,a);e[n]+=o===r?0:(o-r)*t,e[n+1]+=o===i?0:(o-i)*t,e[n+2]+=o===a?0:(o-a)*t}}sendUniformData(e,t){e.uniform1f(t.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}};p(
|
|
424
|
+
`}applyTo2d({imageData:{data:e}}){let t=-this.saturation;for(let n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2],o=Math.max(r,i,a);e[n]+=o===r?0:(o-r)*t,e[n+1]+=o===i?0:(o-i)*t,e[n+2]+=o===a?0:(o-a)*t}}sendUniformData(e,t){e.uniform1f(t.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}};p(Mc,`type`,`Saturation`),p(Mc,`defaults`,{saturation:0}),p(Mc,`uniformLocations`,[`uSaturation`]),L.setClass(Mc);var Nc=class extends ec{getFragmentSource(){return`
|
|
425
425
|
precision highp float;
|
|
426
426
|
uniform sampler2D uTexture;
|
|
427
427
|
uniform float uVibrance;
|
|
@@ -436,19 +436,14 @@ void main() {
|
|
|
436
436
|
color.b += max != color.b ? (max - color.b) * amt : 0.00;
|
|
437
437
|
gl_FragColor = color;
|
|
438
438
|
}
|
|
439
|
-
`}applyTo2d({imageData:{data:e}}){let t=-this.vibrance;for(let n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2],o=Math.max(r,i,a),s=(r+i+a)/3,c=2*Math.abs(o-s)/255*t;e[n]+=o===r?0:(o-r)*c,e[n+1]+=o===i?0:(o-i)*c,e[n+2]+=o===a?0:(o-a)*c}}sendUniformData(e,t){e.uniform1f(t.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}};p(Mc,`type`,`Vibrance`),p(Mc,`defaults`,{vibrance:0}),p(Mc,`uniformLocations`,[`uVibrance`]),L.setClass(Mc),u({BaseFilter:()=>U,BlackWhite:()=>hc,BlendColor:()=>tc,BlendImage:()=>rc,Blur:()=>ic,Brightness:()=>ac,Brownie:()=>lc,ColorMatrix:()=>sc,Composed:()=>gc,Contrast:()=>_c,Convolute:()=>yc,Gamma:()=>xc,Grayscale:()=>Cc,HueRotation:()=>Tc,Invert:()=>Ec,Kodachrome:()=>dc,Noise:()=>Dc,Pixelate:()=>Oc,Polaroid:()=>pc,RemoveColor:()=>kc,Resize:()=>Ac,Saturation:()=>jc,Sepia:()=>mc,Technicolor:()=>fc,Vibrance:()=>Mc,Vintage:()=>uc});var Nc={};Nc.d=(e,t)=>{for(var n in t)Nc.o(t,n)&&!Nc.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Nc.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var W=globalThis.pdfjsLib={};Nc.d(W,{AbortException:()=>ul,AnnotationEditorLayer:()=>yp,AnnotationEditorParamsType:()=>K,AnnotationEditorType:()=>G,AnnotationEditorUIManager:()=>eu,AnnotationLayer:()=>tp,AnnotationMode:()=>Bc,ColorPicker:()=>up,DOMSVGFactory:()=>Sf,DrawLayer:()=>bp,FeatureTest:()=>_l,GlobalWorkerOptions:()=>ud,ImageKind:()=>Wc,InvalidPDFException:()=>ol,MissingPDFException:()=>sl,OPS:()=>Jc,OutputScale:()=>Gl,PDFDataRangeTransport:()=>of,PDFDateString:()=>zl,PDFWorker:()=>uf,PasswordResponses:()=>Yc,PermissionFlag:()=>Hc,PixelsPerInch:()=>Dl,RenderingCancelledException:()=>Al,TextLayer:()=>Gd,TouchManager:()=>nu,UnexpectedResponseException:()=>cl,Util:()=>X,VerbosityLevel:()=>qc,XfaLayer:()=>Cf,build:()=>_f,createValidAbsoluteUrl:()=>nl,fetchData:()=>Ol,getDocument:()=>ef,getFilenameFromUrl:()=>Nl,getPdfFilenameFromUrl:()=>Pl,getXfaPageViewport:()=>Bl,isDataScheme:()=>jl,isPdfFile:()=>Ml,noContextMenu:()=>Ll,normalizeUnicode:()=>Sl,setLayerDimensions:()=>Wl,shadow:()=>Y,stopEvent:()=>Rl,version:()=>gf});var Pc=typeof process==`object`&&process+``==`[object process]`&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!==`browser`),Fc=[1,0,0,1,0,0],Ic=[.001,0,0,.001,0,0],Lc=1e7,Rc=1.35,zc={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Bc={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Vc=`pdfjs_internal_editor_`,G={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},K={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},Hc={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Uc={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Wc={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Gc={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},Kc={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},qc={ERRORS:0,WARNINGS:1,INFOS:5},Jc={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},Yc={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},Xc=qc.WARNINGS;function Zc(e){Number.isInteger(e)&&(Xc=e)}function Qc(){return Xc}function $c(e){Xc>=qc.INFOS&&console.log(`Info: ${e}`)}function q(e){Xc>=qc.WARNINGS&&console.log(`Warning: ${e}`)}function J(e){throw Error(e)}function el(e,t){e||J(t)}function tl(e){switch(e?.protocol){case`http:`:case`https:`:case`ftp:`:case`mailto:`:case`tel:`:return!0;default:return!1}}function nl(e,t=null,n=null){if(!e)return null;try{if(n&&typeof e==`string`&&(n.addDefaultProtocol&&e.startsWith(`www.`)&&e.match(/\./g)?.length>=2&&(e=`http://${e}`),n.tryConvertEncoding))try{e=yl(e)}catch{}let r=t?new URL(e,t):new URL(e);if(tl(r))return r}catch{}return null}function Y(e,t,n,r=!1){return Object.defineProperty(e,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var rl=function(){function e(e,t){this.message=e,this.name=t}return e.prototype=Error(),e.constructor=e,e}(),il=class extends rl{constructor(e,t){super(e,`PasswordException`),this.code=t}},al=class extends rl{constructor(e,t){super(e,`UnknownErrorException`),this.details=t}},ol=class extends rl{constructor(e){super(e,`InvalidPDFException`)}},sl=class extends rl{constructor(e){super(e,`MissingPDFException`)}},cl=class extends rl{constructor(e,t){super(e,`UnexpectedResponseException`),this.status=t}},ll=class extends rl{constructor(e){super(e,`FormatError`)}},ul=class extends rl{constructor(e){super(e,`AbortException`)}};function dl(e){(typeof e!=`object`||e?.length===void 0)&&J(`Invalid argument for bytesToString`);let t=e.length,n=8192;if(t<n)return String.fromCharCode.apply(null,e);let r=[];for(let i=0;i<t;i+=n){let a=Math.min(i+n,t),o=e.subarray(i,a);r.push(String.fromCharCode.apply(null,o))}return r.join(``)}function fl(e){typeof e!=`string`&&J(`Invalid argument for stringToBytes`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;++r)n[r]=e.charCodeAt(r)&255;return n}function pl(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,e&255)}function ml(e){let t=Object.create(null);for(let[n,r]of e)t[n]=r;return t}function hl(){let e=new Uint8Array(4);return e[0]=1,new Uint32Array(e.buffer,0,1)[0]===1}function gl(){try{return Function(``),!0}catch{return!1}}var _l=class{static get isLittleEndian(){return Y(this,`isLittleEndian`,hl())}static get isEvalSupported(){return Y(this,`isEvalSupported`,gl())}static get isOffscreenCanvasSupported(){return Y(this,`isOffscreenCanvasSupported`,typeof OffscreenCanvas<`u`)}static get isImageDecoderSupported(){return Y(this,`isImageDecoderSupported`,typeof ImageDecoder<`u`)}static get platform(){return typeof navigator<`u`&&typeof navigator?.platform==`string`?Y(this,`platform`,{isMac:navigator.platform.includes(`Mac`),isWindows:navigator.platform.includes(`Win`),isFirefox:typeof navigator?.userAgent==`string`&&navigator.userAgent.includes(`Firefox`)}):Y(this,`platform`,{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return Y(this,`isCSSRoundSupported`,globalThis.CSS?.supports?.(`width: round(1.5px, 1px)`))}},vl=Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,`0`)),X=class{static makeHexColor(e,t,n){return`#${vl[e]}${vl[t]}${vl[n]}`}static scaleMinMax(e,t){let n;e[0]?(e[0]<0&&(n=t[0],t[0]=t[2],t[2]=n),t[0]*=e[0],t[2]*=e[0],e[3]<0&&(n=t[1],t[1]=t[3],t[3]=n),t[1]*=e[3],t[3]*=e[3]):(n=t[0],t[0]=t[1],t[1]=n,n=t[2],t[2]=t[3],t[3]=n,e[1]<0&&(n=t[1],t[1]=t[3],t[3]=n),t[1]*=e[1],t[3]*=e[1],e[2]<0&&(n=t[0],t[0]=t[2],t[2]=n),t[0]*=e[2],t[2]*=e[2]),t[0]+=e[4],t[1]+=e[5],t[2]+=e[4],t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){let n=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/n,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/n]}static getAxialAlignedBoundingBox(e,t){let n=this.applyTransform(e,t),r=this.applyTransform(e.slice(2,4),t),i=this.applyTransform([e[0],e[3]],t),a=this.applyTransform([e[2],e[1]],t);return[Math.min(n[0],r[0],i[0],a[0]),Math.min(n[1],r[1],i[1],a[1]),Math.max(n[0],r[0],i[0],a[0]),Math.max(n[1],r[1],i[1],a[1])]}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){let t=[e[0],e[2],e[1],e[3]],n=e[0]*t[0]+e[1]*t[2],r=e[0]*t[1]+e[1]*t[3],i=e[2]*t[0]+e[3]*t[2],a=e[2]*t[1]+e[3]*t[3],o=(n+a)/2,s=Math.sqrt((n+a)**2-4*(n*a-i*r))/2,c=o+s||1,l=o-s||1;return[Math.sqrt(c),Math.sqrt(l)]}static normalizeRect(e){let t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>r)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>a?null:[n,i,r,a]}static#e(e,t,n,r,i,a,o,s,c,l){if(c<=0||c>=1)return;let u=1-c,d=c*c,f=d*c,p=u*(u*(u*e+3*c*t)+3*d*n)+f*r,m=u*(u*(u*i+3*c*a)+3*d*o)+f*s;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],m),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],m)}static#t(e,t,n,r,i,a,o,s,c,l,u,d){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,n,r,i,a,o,s,-u/l,d);return}let f=l**2-4*u*c;if(f<0)return;let p=Math.sqrt(f),m=2*c;this.#e(e,t,n,r,i,a,o,s,(-l+p)/m,d),this.#e(e,t,n,r,i,a,o,s,(-l-p)/m,d)}static bezierBoundingBox(e,t,n,r,i,a,o,s,c){return c?(c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,s),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,s)):c=[Math.min(e,o),Math.min(t,s),Math.max(e,o),Math.max(t,s)],this.#t(e,n,i,o,t,r,a,s,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,r,a,s,3*(-t+3*(r-a)+s),6*(t-2*r+a),3*(r-t),c),c}};function yl(e){return decodeURIComponent(escape(e))}var bl=null,xl=null;function Sl(e){return bl||(bl=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,xl=new Map([[`ſt`,`ſt`]])),e.replaceAll(bl,(e,t,n)=>t?t.normalize(`NFKC`):xl.get(n))}function Cl(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),dl(e)}var wl=`pdfjs_internal_id_`;function Tl(e){return Uint8Array.prototype.toBase64?e.toBase64():btoa(dl(e))}typeof Promise.try!=`function`&&(Promise.try=function(e,...t){return new Promise(n=>{n(e(...t))})});var El=`http://www.w3.org/2000/svg`,Dl=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function Ol(e,t=`text`){if(Il(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case`arraybuffer`:return n.arrayBuffer();case`blob`:return n.blob();case`json`:return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(`GET`,e,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case`arraybuffer`:case`blob`:case`json`:n(i.response);return}n(i.responseText);return}r(Error(i.statusText))}},i.send(null)})}var kl=class e{constructor({viewBox:e,userUnit:t,scale:n,rotation:r,offsetX:i=0,offsetY:a=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=r,this.offsetX=i,this.offsetY=a,n*=t;let s=(e[2]+e[0])/2,c=(e[3]+e[1])/2,l,u,d,f;switch(r%=360,r<0&&(r+=360),r){case 180:l=-1,u=0,d=0,f=1;break;case 90:l=0,u=1,d=1,f=0;break;case 270:l=0,u=-1,d=-1,f=0;break;case 0:l=1,u=0,d=0,f=-1;break;default:throw Error(`PageViewport: Invalid rotation, must be a multiple of 90 degrees.`)}o&&(d=-d,f=-f);let p,m,h,g;l===0?(p=Math.abs(c-e[1])*n+i,m=Math.abs(s-e[0])*n+a,h=(e[3]-e[1])*n,g=(e[2]-e[0])*n):(p=Math.abs(s-e[0])*n+i,m=Math.abs(c-e[1])*n+a,h=(e[2]-e[0])*n,g=(e[3]-e[1])*n),this.transform=[l*n,u*n,d*n,f*n,p-l*n*s-d*n*c,m-u*n*s-f*n*c],this.width=h,this.height=g}get rawDims(){let{userUnit:e,viewBox:t}=this,n=t.map(t=>t*e);return Y(this,`rawDims`,{pageWidth:n[2]-n[0],pageHeight:n[3]-n[1],pageX:n[0],pageY:n[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:a=!1}={}){return new e({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:n,offsetX:r,offsetY:i,dontFlip:a})}convertToViewportPoint(e,t){return X.applyTransform([e,t],this.transform)}convertToViewportRectangle(e){let t=X.applyTransform([e[0],e[1]],this.transform),n=X.applyTransform([e[2],e[3]],this.transform);return[t[0],t[1],n[0],n[1]]}convertToPdfPoint(e,t){return X.applyInverseTransform([e,t],this.transform)}},Al=class extends rl{constructor(e,t=0){super(e,`RenderingCancelledException`),this.extraDelay=t}};function jl(e){let t=e.length,n=0;for(;n<t&&e[n].trim()===``;)n++;return e.substring(n,n+5).toLowerCase()===`data:`}function Ml(e){return typeof e==`string`&&/\.pdf$/i.test(e)}function Nl(e){return[e]=e.split(/[#?]/,1),e.substring(e.lastIndexOf(`/`)+1)}function Pl(e,t=`document.pdf`){if(typeof e!=`string`)return t;if(jl(e))return q(`getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.`),t;let n=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,r=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=n.exec(e),a=r.exec(i[1])||r.exec(i[2])||r.exec(i[3]);if(a&&(a=a[0],a.includes(`%`)))try{a=r.exec(decodeURIComponent(a))[0]}catch{}return a||t}var Fl=class{started=Object.create(null);times=[];time(e){e in this.started&&q(`Timer is already running for ${e}`),this.started[e]=Date.now()}timeEnd(e){e in this.started||q(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e]}toString(){let e=[],t=0;for(let{name:e}of this.times)t=Math.max(e.length,t);for(let{name:n,start:r,end:i}of this.times)e.push(`${n.padEnd(t)} ${i-r}ms\n`);return e.join(``)}};function Il(e,t){try{let{protocol:n}=t?new URL(e,t):new URL(e);return n===`http:`||n===`https:`}catch{return!1}}function Ll(e){e.preventDefault()}function Rl(e){e.preventDefault(),e.stopPropagation()}var zl=class{static#e;static toDateObject(e){if(!e||typeof e!=`string`)return null;this.#e||=RegExp(`^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?`);let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),r=parseInt(t[2],10);r=r>=1&&r<=12?r-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let s=parseInt(t[6],10);s=s>=0&&s<=59?s:0;let c=t[7]||`Z`,l=parseInt(t[8],10);l=l>=0&&l<=23?l:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c===`-`?(a+=l,o+=u):c===`+`&&(a-=l,o-=u),new Date(Date.UTC(n,r,i,a,o,s))}};function Bl(e,{scale:t=1,rotation:n=0}){let{width:r,height:i}=e.attributes.style;return new kl({viewBox:[0,0,parseInt(r),parseInt(i)],userUnit:1,scale:t,rotation:n})}function Vl(e){if(e.startsWith(`#`)){let t=parseInt(e.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return e.startsWith(`rgb(`)?e.slice(4,-1).split(`,`).map(e=>parseInt(e)):e.startsWith(`rgba(`)?e.slice(5,-1).split(`,`).map(e=>parseInt(e)).slice(0,3):(q(`Not a valid color format: "${e}"`),[0,0,0])}function Hl(e){let t=document.createElement(`span`);t.style.visibility=`hidden`,document.body.append(t);for(let n of e.keys()){t.style.color=n;let r=window.getComputedStyle(t).color;e.set(n,Vl(r))}t.remove()}function Z(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform();return[t,n,r,i,a,o]}function Ul(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform().invertSelf();return[t,n,r,i,a,o]}function Wl(e,t,n=!1,r=!0){if(t instanceof kl){let{pageWidth:r,pageHeight:i}=t.rawDims,{style:a}=e,o=_l.isCSSRoundSupported,s=`var(--scale-factor) * ${r}px`,c=`var(--scale-factor) * ${i}px`,l=o?`round(down, ${s}, var(--scale-round-x, 1px))`:`calc(${s})`,u=o?`round(down, ${c}, var(--scale-round-y, 1px))`:`calc(${c})`;!n||t.rotation%180==0?(a.width=l,a.height=u):(a.width=u,a.height=l)}r&&e.setAttribute(`data-main-rotation`,t.rotation)}var Gl=class{constructor(){let e=window.devicePixelRatio||1;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}},Kl=class e{#e=null;#t=null;#n;#r=null;#i=null;static#a=null;constructor(t){this.#n=t,e.#a||=Object.freeze({freetext:`pdfjs-editor-remove-freetext-button`,highlight:`pdfjs-editor-remove-highlight-button`,ink:`pdfjs-editor-remove-ink-button`,stamp:`pdfjs-editor-remove-stamp-button`})}render(){let t=this.#e=document.createElement(`div`);t.classList.add(`editToolbar`,`hidden`),t.setAttribute(`role`,`toolbar`);let n=this.#n._uiManager._signal;t.addEventListener(`contextmenu`,Ll,{signal:n}),t.addEventListener(`pointerdown`,e.#o,{signal:n});let r=this.#r=document.createElement(`div`);r.className=`buttons`,t.append(r);let i=this.#n.toolbarPosition;if(i){let{style:e}=t;e.insetInlineEnd=`${100*(this.#n._uiManager.direction===`ltr`?1-i[0]:i[0])}%`,e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#u(),t}get div(){return this.#e}static#o(e){e.stopPropagation()}#s(e){this.#n._focusEventsAllowed=!1,Rl(e)}#c(e){this.#n._focusEventsAllowed=!0,Rl(e)}#l(e){let t=this.#n._uiManager._signal;e.addEventListener(`focusin`,this.#s.bind(this),{capture:!0,signal:t}),e.addEventListener(`focusout`,this.#c.bind(this),{capture:!0,signal:t}),e.addEventListener(`contextmenu`,Ll,{signal:t})}hide(){this.#e.classList.add(`hidden`),this.#t?.hideDropdown()}show(){this.#e.classList.remove(`hidden`),this.#i?.shown()}#u(){let{editorType:t,_uiManager:n}=this.#n,r=document.createElement(`button`);r.className=`delete`,r.tabIndex=0,r.setAttribute(`data-l10n-id`,e.#a[t]),this.#l(r),r.addEventListener(`click`,e=>{n.delete()},{signal:n._signal}),this.#r.append(r)}get#d(){let e=document.createElement(`div`);return e.className=`divider`,e}async addAltText(e){let t=await e.render();this.#l(t),this.#r.prepend(t,this.#d),this.#i=e}addColorPicker(e){this.#t=e;let t=e.renderButton();this.#l(t),this.#r.prepend(t,this.#d)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},ql=class{#e=null;#t=null;#n;constructor(e){this.#n=e}#r(){let e=this.#t=document.createElement(`div`);e.className=`editToolbar`,e.setAttribute(`role`,`toolbar`),e.addEventListener(`contextmenu`,Ll,{signal:this.#n._signal});let t=this.#e=document.createElement(`div`);return t.className=`buttons`,e.append(t),this.#a(),e}#i(e,t){let n=0,r=0;for(let i of e){let e=i.y+i.height;if(e<n)continue;let a=i.x+(t?i.width:0);if(e>n){r=a,n=e;continue}t?a>r&&(r=a):a<r&&(r=a)}return[t?1-r:r,n]}show(e,t,n){let[r,i]=this.#i(t,n),{style:a}=this.#t||=this.#r();e.append(this.#t),a.insetInlineEnd=`${100*r}%`,a.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){this.#t.remove()}#a(){let e=document.createElement(`button`);e.className=`highlightButton`,e.tabIndex=0,e.setAttribute(`data-l10n-id`,`pdfjs-highlight-floating-button1`);let t=document.createElement(`span`);e.append(t),t.className=`visuallyHidden`,t.setAttribute(`data-l10n-id`,`pdfjs-highlight-floating-button-label`);let n=this.#n._signal;e.addEventListener(`contextmenu`,Ll,{signal:n}),e.addEventListener(`click`,()=>{this.#n.highlightSelection(`floating_button`)},{signal:n}),this.#e.append(e)}};function Jl(e,t,n){for(let r of n)t.addEventListener(r,e[r].bind(e))}var Yl=class{#e=0;get id(){return`${Vc}${this.#e++}`}},Xl=class e{#e=Cl();#t=0;#n=null;static get _isSVGFittingCanvas(){let e=new OffscreenCanvas(1,3).getContext(`2d`,{willReadFrequently:!0}),t=new Image;t.src=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;let n=t.decode().then(()=>(e.drawImage(t,0,0,1,1,0,0,1,3),new Uint32Array(e.getImageData(0,0,1,1).data.buffer)[0]===0));return Y(this,`_isSVGFittingCanvas`,n)}async#r(t,n){this.#n||=new Map;let r=this.#n.get(t);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let t;if(typeof n==`string`?(r.url=n,t=await Ol(n,`blob`)):n instanceof File?t=r.file=n:n instanceof Blob&&(t=n),t.type===`image/svg+xml`){let n=e._isSVGFittingCanvas,i=new FileReader,a=new Image,o=new Promise((e,t)=>{a.onload=()=>{r.bitmap=a,r.isSvg=!0,e()},i.onload=async()=>{let e=r.svgUrl=i.result;a.src=await n?`${e}#svgView(preserveAspectRatio(none))`:e},a.onerror=i.onerror=t});i.readAsDataURL(t),await o}else r.bitmap=await createImageBitmap(t);r.refCounter=1}catch(e){q(e),r=null}return this.#n.set(t,r),r&&this.#n.set(r.id,r),r}async getFromFile(e){let{lastModified:t,name:n,size:r,type:i}=e;return this.#r(`${t}_${n}_${r}_${i}`,e)}async getFromUrl(e){return this.#r(e,e)}async getFromBlob(e,t){let n=await t;return this.#r(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:e}=t;return delete t.blobPromise,this.getFromBlob(t.id,e)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let r=new OffscreenCanvas(t.width,t.height);return r.getContext(`2d`).drawImage(t,0,0),n={bitmap:r.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);return t?.isSvg?t.svgUrl:null}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t||(--t.refCounter,t.refCounter!==0))return;let{bitmap:n}=t;if(!t.url&&!t.file){let e=new OffscreenCanvas(n.width,n.height);e.getContext(`bitmaprenderer`).transferFromImageBitmap(n),t.blobPromise=e.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},Zl=class{#e=[];#t=!1;#n;#r=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:r,type:i=NaN,overwriteIfSameType:a=!1,keepUndo:o=!1}){if(r&&e(),this.#t)return;let s={cmd:e,undo:t,post:n,type:i};if(this.#r===-1){this.#e.length>0&&(this.#e.length=0),this.#r=0,this.#e.push(s);return}if(a&&this.#e[this.#r].type===i){o&&(s.undo=this.#e[this.#r].undo),this.#e[this.#r]=s;return}let c=this.#r+1;c===this.#n?this.#e.splice(0,1):(this.#r=c,c<this.#e.length&&this.#e.splice(c)),this.#e.push(s)}undo(){if(this.#r===-1)return;this.#t=!0;let{undo:e,post:t}=this.#e[this.#r];e(),t?.(),this.#t=!1,--this.#r}redo(){if(this.#r<this.#e.length-1){this.#r+=1,this.#t=!0;let{cmd:e,post:t}=this.#e[this.#r];e(),t?.(),this.#t=!1}}hasSomethingToUndo(){return this.#r!==-1}hasSomethingToRedo(){return this.#r<this.#e.length-1}cleanType(e){if(this.#r!==-1){for(let t=this.#r;t>=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#r-t),this.#r=t;return}this.#e.length=0,this.#r=-1}}destroy(){this.#e=null}},Ql=class{constructor(e){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:t}=_l.platform;for(let[n,r,i={}]of e)for(let e of n){let n=e.startsWith(`mac+`);t&&n?(this.callbacks.set(e.slice(4),{callback:r,options:i}),this.allKeys.add(e.split(`+`).at(-1))):!t&&!n&&(this.callbacks.set(e,{callback:r,options:i}),this.allKeys.add(e.split(`+`).at(-1)))}}#e(e){e.altKey&&this.buffer.push(`alt`),e.ctrlKey&&this.buffer.push(`ctrl`),e.metaKey&&this.buffer.push(`meta`),e.shiftKey&&this.buffer.push(`shift`),this.buffer.push(e.key);let t=this.buffer.join(`+`);return this.buffer.length=0,t}exec(e,t){if(!this.allKeys.has(t.key))return;let n=this.callbacks.get(this.#e(t));if(!n)return;let{callback:r,options:{bubbles:i=!1,args:a=[],checker:o=null}}=n;o&&!o(e,t)||(r.bind(e,...a,t)(),i||Rl(t))}},$l=class e{static _colorsMapping=new Map([[`CanvasText`,[0,0,0]],[`Canvas`,[255,255,255]]]);get _colors(){let e=new Map([[`CanvasText`,null],[`Canvas`,null]]);return Hl(e),Y(this,`_colors`,e)}convert(t){let n=Vl(t);if(!window.matchMedia(`(forced-colors: active)`).matches)return n;for(let[t,r]of this._colors)if(r.every((e,t)=>e===n[t]))return e._colorsMapping.get(t);return n}getHexCode(e){let t=this._colors.get(e);return t?X.makeHexColor(...t):e}},eu=class e{#e=new AbortController;#t=null;#n=new Map;#r=new Map;#i=null;#a=null;#o=null;#s=new Zl;#c=null;#l=null;#u=0;#d=new Set;#f=null;#p=null;#m=new Set;_editorUndoBar=null;#h=!1;#g=!1;#_=!1;#v=null;#y=null;#b=null;#x=null;#S=!1;#C=null;#w=new Yl;#T=!1;#E=!1;#D=null;#O=null;#k=null;#A=null;#j=G.NONE;#M=new Set;#N=null;#P=null;#F=null;#I={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#L=[0,0];#R=null;#z=null;#B=null;#V=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.#z.contains(document.activeElement)&&document.activeElement.tagName!==`BUTTON`&&e.hasSomethingToControl(),r=(e,{target:t})=>{if(t instanceof HTMLInputElement){let{type:e}=t;return e!==`text`&&e!==`number`}return!0},i=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return Y(this,`_keyboardManager`,new Ql([[[`ctrl+a`,`mac+meta+a`],t.selectAll,{checker:r}],[[`ctrl+z`,`mac+meta+z`],t.undo,{checker:r}],[[`ctrl+y`,`ctrl+shift+z`,`mac+meta+shift+z`,`ctrl+shift+Z`,`mac+meta+shift+Z`],t.redo,{checker:r}],[[`Backspace`,`alt+Backspace`,`ctrl+Backspace`,`shift+Backspace`,`mac+Backspace`,`mac+alt+Backspace`,`mac+ctrl+Backspace`,`Delete`,`ctrl+Delete`,`shift+Delete`,`mac+Delete`],t.delete,{checker:r}],[[`Enter`,`mac+Enter`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#z.contains(t)&&!e.isEnterHandled}],[[` `,`mac+ `],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#z.contains(document.activeElement)}],[[`Escape`,`mac+Escape`],t.unselectAll],[[`ArrowLeft`,`mac+ArrowLeft`],t.translateSelectedEditors,{args:[-i,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t.translateSelectedEditors,{args:[-a,0],checker:n}],[[`ArrowRight`,`mac+ArrowRight`],t.translateSelectedEditors,{args:[i,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t.translateSelectedEditors,{args:[a,0],checker:n}],[[`ArrowUp`,`mac+ArrowUp`],t.translateSelectedEditors,{args:[0,-i],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t.translateSelectedEditors,{args:[0,-a],checker:n}],[[`ArrowDown`,`mac+ArrowDown`],t.translateSelectedEditors,{args:[0,i],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t.translateSelectedEditors,{args:[0,a],checker:n}]]))}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=this._signal=this.#e.signal;this.#z=e,this.#B=t,this.#i=n,this._eventBus=r,r._on(`editingaction`,this.onEditingAction.bind(this),{signal:p}),r._on(`pagechanging`,this.onPageChanging.bind(this),{signal:p}),r._on(`scalechanging`,this.onScaleChanging.bind(this),{signal:p}),r._on(`rotationchanging`,this.onRotationChanging.bind(this),{signal:p}),r._on(`setpreference`,this.onSetPreference.bind(this),{signal:p}),r._on(`switchannotationeditorparams`,e=>this.updateParams(e.type,e.value),{signal:p}),this.#q(),this.#ee(),this.#X(),this.#a=i.annotationStorage,this.#v=i.filterFactory,this.#P=a,this.#x=o||null,this.#h=s,this.#g=c,this.#_=l,this.#A=u||null,this.viewParameters={realScale:Dl.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#V?.resolve(),this.#V=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#r.values())e.destroy();this.#r.clear(),this.#n.clear(),this.#m.clear(),this.#t=null,this.#M.clear(),this.#s.destroy(),this.#i?.destroy(),this.#C?.hide(),this.#C=null,this.#y&&=(clearTimeout(this.#y),null),this.#R&&=(clearTimeout(this.#R),null),this._editorUndoBar?.destroy()}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#A}get useNewAltTextFlow(){return this.#g}get useNewAltTextWhenAddingImage(){return this.#_}get hcmFilter(){return Y(this,`hcmFilter`,this.#P?this.#v.addHCMFilter(this.#P.foreground,this.#P.background):`none`)}get direction(){return Y(this,`direction`,getComputedStyle(this.#z).direction)}get highlightColors(){return Y(this,`highlightColors`,this.#x?new Map(this.#x.split(`,`).map(e=>e.split(`=`).map(e=>e.trim()))):null)}get highlightColorNames(){return Y(this,`highlightColorNames`,this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#l=e}setMainHighlightColorPicker(e){this.#k=e}editAltText(e,t=!1){this.#i?.editAltText(this,e,t)}switchToMode(e,t){this._eventBus.on(`annotationeditormodechanged`,t,{once:!0,signal:this._signal}),this._eventBus.dispatch(`showannotationeditorui`,{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch(`setpreference`,{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){switch(e){case`enableNewAltTextWhenAddingImage`:this.#_=t;break}}onPageChanging({pageNumber:e}){this.#u=e-1}focusMainContainer(){this.#z.focus()}findParent(e,t){for(let n of this.#r.values()){let{x:r,y:i,width:a,height:o}=n.div.getBoundingClientRect();if(e>=r&&e<=r+a&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#B.classList.toggle(`noUserSelect`,e)}addShouldRescale(e){this.#m.add(e)}removeShouldRescale(e){this.#m.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Dl.PDF_TO_CSS_UNITS;for(let e of this.#m)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#H({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#U(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let t of this.#r.values())if(t.hasTextLayer(e))return t;return null}highlightSelection(e=``){let t=document.getSelection();if(!t||t.isCollapsed)return;let{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a}=t,o=t.toString(),s=this.#H(t).closest(`.textLayer`),c=this.getSelectionBoxes(s);if(!c)return;t.empty();let l=this.#U(s),u=this.#j===G.NONE,d=()=>{l?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:c,anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a,text:o}),u&&this.showAllEditors(`highlight`,!0,!0)};if(u){this.switchToMode(G.HIGHLIGHT,d);return}d()}#W(){let e=document.getSelection();if(!e||e.isCollapsed)return;let t=this.#H(e).closest(`.textLayer`),n=this.getSelectionBoxes(t);n&&(this.#C||=new ql(this),this.#C.show(t,n,this.direction===`ltr`))}addToAnnotationStorage(e){!e.isEmpty()&&this.#a&&!this.#a.has(e.id)&&this.#a.setValue(e.id,e)}#G(){let e=document.getSelection();if(!e||e.isCollapsed){this.#N&&(this.#C?.hide(),this.#N=null,this.#te({hasSelectedText:!1}));return}let{anchorNode:t}=e;if(t===this.#N)return;let n=this.#H(e).closest(`.textLayer`);if(!n){this.#N&&(this.#C?.hide(),this.#N=null,this.#te({hasSelectedText:!1}));return}if(this.#C?.hide(),this.#N=t,this.#te({hasSelectedText:!0}),!(this.#j!==G.HIGHLIGHT&&this.#j!==G.NONE)&&(this.#j===G.HIGHLIGHT&&this.showAllEditors(`highlight`,!0,!0),this.#S=this.isShiftKeyDown,!this.isShiftKeyDown)){let e=this.#j===G.HIGHLIGHT?this.#U(n):null;e?.toggleDrawing();let t=new AbortController,r=this.combinedSignal(t),i=n=>{n.type===`pointerup`&&n.button!==0||(t.abort(),e?.toggleDrawing(!0),n.type===`pointerup`&&this.#K(`main_toolbar`))};window.addEventListener(`pointerup`,i,{signal:r}),window.addEventListener(`blur`,i,{signal:r})}}#K(e=``){this.#j===G.HIGHLIGHT?this.highlightSelection(e):this.#h&&this.#W()}#q(){document.addEventListener(`selectionchange`,this.#G.bind(this),{signal:this._signal})}#J(){if(this.#b)return;this.#b=new AbortController;let e=this.combinedSignal(this.#b);window.addEventListener(`focus`,this.focus.bind(this),{signal:e}),window.addEventListener(`blur`,this.blur.bind(this),{signal:e})}#Y(){this.#b?.abort(),this.#b=null}blur(){if(this.isShiftKeyDown=!1,this.#S&&(this.#S=!1,this.#K(`main_toolbar`)),!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#M)if(t.div.contains(e)){this.#O=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;let[e,t]=this.#O;this.#O=null,t.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#X(){if(this.#D)return;this.#D=new AbortController;let e=this.combinedSignal(this.#D);window.addEventListener(`keydown`,this.keydown.bind(this),{signal:e}),window.addEventListener(`keyup`,this.keyup.bind(this),{signal:e})}#Z(){this.#D?.abort(),this.#D=null}#Q(){if(this.#c)return;this.#c=new AbortController;let e=this.combinedSignal(this.#c);document.addEventListener(`copy`,this.copy.bind(this),{signal:e}),document.addEventListener(`cut`,this.cut.bind(this),{signal:e}),document.addEventListener(`paste`,this.paste.bind(this),{signal:e})}#$(){this.#c?.abort(),this.#c=null}#ee(){let e=this._signal;document.addEventListener(`dragover`,this.dragOver.bind(this),{signal:e}),document.addEventListener(`drop`,this.drop.bind(this),{signal:e})}addEditListeners(){this.#X(),this.#Q()}removeEditListeners(){this.#Z(),this.#$()}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#p)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect=`copy`,e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#p)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let e of this.#M){let n=e.serialize(!0);n&&t.push(n)}t.length!==0&&e.clipboardData.setData(`application/pdfjs`,JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let e of t.items)for(let t of this.#p)if(t.isHandlingMimeForPasting(e.type)){t.paste(e,this.currentLayer);return}let n=t.getData(`application/pdfjs`);if(!n)return;try{n=JSON.parse(n)}catch(e){q(`paste: "${e.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let r=this.currentLayer;try{let e=[];for(let t of n){let n=await r.deserialize(t);if(!n)return;e.push(n)}this.addCommands({cmd:()=>{for(let t of e)this.#ae(t);this.#ce(e)},undo:()=>{for(let t of e)t.remove()},mustExec:!0})}catch(e){q(`paste: "${e.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key===`Shift`&&(this.isShiftKeyDown=!0),this.#j!==G.NONE&&!this.isEditorHandlingKeyboard&&e._keyboardManager.exec(this,t)}keyup(e){this.isShiftKeyDown&&e.key===`Shift`&&(this.isShiftKeyDown=!1,this.#S&&(this.#S=!1,this.#K(`main_toolbar`)))}onEditingAction({name:e}){switch(e){case`undo`:case`redo`:case`delete`:case`selectAll`:this[e]();break;case`highlightSelection`:this.highlightSelection(`context_menu`);break}}#te(e){Object.entries(e).some(([e,t])=>this.#I[e]!==t)&&(this._eventBus.dispatch(`annotationeditorstateschanged`,{source:this,details:Object.assign(this.#I,e)}),this.#j===G.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#ne([[K.HIGHLIGHT_FREE,!0]]))}#ne(e){this._eventBus.dispatch(`annotationeditorparamschanged`,{source:this,details:e})}setEditingState(e){e?(this.#J(),this.#Q(),this.#te({isEditing:this.#j!==G.NONE,isEmpty:this.#se(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#$(),this.#te({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#p){this.#p=e;for(let e of this.#p)this.#ne(e.defaultPropertiesToUpdate)}}getId(){return this.#w.id}get currentLayer(){return this.#r.get(this.#u)}getLayer(e){return this.#r.get(e)}get currentPageIndex(){return this.#u}addLayer(e){this.#r.set(e.pageIndex,e),this.#T?e.enable():e.disable()}removeLayer(e){this.#r.delete(e.pageIndex)}async updateMode(e,t=null,n=!1){if(this.#j!==e&&!(this.#V&&(await this.#V.promise,!this.#V))){if(this.#V=Promise.withResolvers(),this.#j=e,e===G.NONE){this.setEditingState(!1),this.#ie(),this._editorUndoBar?.hide(),this.#V.resolve();return}this.setEditingState(!0),await this.#re(),this.unselectAll();for(let t of this.#r.values())t.updateMode(e);if(!t){n&&this.addNewEditorFromKeyboard(),this.#V.resolve();return}for(let e of this.#n.values())e.annotationElementId===t?(this.setSelected(e),e.enterInEditMode()):e.unselect();this.#V.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e!==this.#j&&this._eventBus.dispatch(`switchannotationeditormode`,{source:this,mode:e})}updateParams(e,t){if(this.#p){switch(e){case K.CREATE:this.currentLayer.addNewEditor();return;case K.HIGHLIGHT_DEFAULT_COLOR:this.#k?.updateColor(t);break;case K.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:{type:`highlight`,action:`toggle_visibility`}}}),(this.#F||=new Map).set(e,t),this.showAllEditors(`highlight`,t);break}for(let n of this.#M)n.updateParams(e,t);for(let n of this.#p)n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){for(let n of this.#n.values())n.editorType===e&&n.show(t);(this.#F?.get(K.HIGHLIGHT_SHOW_ALL)??!0)!==t&&this.#ne([[K.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#E!==e){this.#E=e;for(let t of this.#r.values())e?t.disableClick():t.enableClick(),t.div.classList.toggle(`waiting`,e)}}async#re(){if(!this.#T){this.#T=!0;let e=[];for(let t of this.#r.values())e.push(t.enable());await Promise.all(e);for(let e of this.#n.values())e.enable()}}#ie(){if(this.unselectAll(),this.#T){this.#T=!1;for(let e of this.#r.values())e.disable();for(let e of this.#n.values())e.disable()}}getEditors(e){let t=[];for(let n of this.#n.values())n.pageIndex===e&&t.push(n);return t}getEditor(e){return this.#n.get(e)}addEditor(e){this.#n.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.focusMainContainer(),this.#y=null},0)),this.#n.delete(e.id),this.unselect(e),(!e.annotationElementId||!this.#d.has(e.annotationElementId))&&this.#a?.remove(e.id)}addDeletedAnnotationElement(e){this.#d.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#d.has(e)}removeDeletedAnnotationElement(e){this.#d.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#ae(e){let t=this.#r.get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#ne(e.propertiesToUpdate))}get#oe(){let e=null;for(e of this.#M);return e}updateUI(e){this.#oe===e&&this.#ne(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#ne(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#M.has(e)){this.#M.delete(e),e.unselect(),this.#te({hasSelectedEditor:this.hasSelection});return}this.#M.add(e),e.select(),this.#ne(e.propertiesToUpdate),this.#te({hasSelectedEditor:!0})}setSelected(e){this.#l?.commitOrRemove();for(let t of this.#M)t!==e&&t.unselect();this.#M.clear(),this.#M.add(e),e.select(),this.#ne(e.propertiesToUpdate),this.#te({hasSelectedEditor:!0})}isSelected(e){return this.#M.has(e)}get firstSelectedEditor(){return this.#M.values().next().value}unselect(e){e.unselect(),this.#M.delete(e),this.#te({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#M.size!==0}get isEnterHandled(){return this.#M.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#s.undo(),this.#te({hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#se()}),this._editorUndoBar?.hide()}redo(){this.#s.redo(),this.#te({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#se()})}addCommands(e){this.#s.add(e),this.#te({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#se()})}cleanUndoStack(e){this.#s.cleanType(e)}#se(){if(this.#n.size===0)return!0;if(this.#n.size===1)for(let e of this.#n.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#M],n=()=>{this._editorUndoBar?.show(r,t.length===1?t[0].editorType:t.length);for(let e of t)e.remove()},r=()=>{for(let e of t)this.#ae(e)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#ce(e){for(let e of this.#M)e.unselect();this.#M.clear();for(let t of e)t.isEmpty()||(this.#M.add(t),t.select());this.#te({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#M)e.commit();this.#ce(this.#n.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#j!==G.NONE))&&!this.#l?.commitOrRemove()&&this.hasSelection){for(let e of this.#M)e.unselect();this.#M.clear(),this.#te({hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#L[0]+=e,this.#L[1]+=t;let[r,i]=this.#L,a=[...this.#M];this.#R&&clearTimeout(this.#R),this.#R=setTimeout(()=>{this.#R=null,this.#L[0]=this.#L[1]=0,this.addCommands({cmd:()=>{for(let e of a)this.#n.has(e.id)&&e.translateInPage(r,i)},undo:()=>{for(let e of a)this.#n.has(e.id)&&e.translateInPage(-r,-i)},mustExec:!1})},1e3);for(let n of a)n.translateInPage(e,t)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(let e of this.#M)this.#f.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);let e=this.#f;this.#f=null;let t=!1;for(let[{x:n,y:r,pageIndex:i},a]of e)a.newX=n,a.newY=r,a.newPageIndex=i,t||=n!==a.savedX||r!==a.savedY||i!==a.savedPageIndex;if(!t)return!1;let n=(e,t,n,r)=>{if(this.#n.has(e.id)){let i=this.#r.get(r);i?e._setParentAndPosition(i,t,n):(e.pageIndex=r,e.x=t,e.y=n)}};return this.addCommands({cmd:()=>{for(let[t,{newX:r,newY:i,newPageIndex:a}]of e)n(t,r,i,a)},undo:()=>{for(let[t,{savedX:r,savedY:i,savedPageIndex:a}]of e)n(t,r,i,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(this.#f)for(let n of this.#f.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#M.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#j}get imageManager(){return Y(this,`imageManager`,new Xl)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let n=0,r=t.rangeCount;n<r;n++)if(!e.contains(t.getRangeAt(n).commonAncestorContainer))return null;let{x:n,y:r,width:i,height:a}=e.getBoundingClientRect(),o;switch(e.getAttribute(`data-main-rotation`)){case`90`:o=(e,t,o,s)=>({x:(t-r)/a,y:1-(e+o-n)/i,width:s/a,height:o/i});break;case`180`:o=(e,t,o,s)=>({x:1-(e+o-n)/i,y:1-(t+s-r)/a,width:o/i,height:s/a});break;case`270`:o=(e,t,o,s)=>({x:1-(t+s-r)/a,y:(e-n)/i,width:s/a,height:o/i});break;default:o=(e,t,o,s)=>({x:(e-n)/i,y:(t-r)/a,width:o/i,height:s/a});break}let s=[];for(let e=0,n=t.rangeCount;e<n;e++){let n=t.getRangeAt(e);if(!n.collapsed)for(let{x:e,y:t,width:r,height:i}of n.getClientRects())r===0||i===0||s.push(o(e,t,r,i))}return s.length===0?null:s}addChangedExistingAnnotation({annotationElementId:e,id:t}){(this.#o||=new Map).set(e,t)}removeChangedExistingAnnotation({annotationElementId:e}){this.#o?.delete(e)}renderAnnotationElement(e){let t=this.#o?.get(e.data.id);if(!t)return;let n=this.#a.getRawValue(t);n&&(this.#j===G.NONE&&!n.hasBeenModified||n.renderAnnotationElement(e))}},tu=class e{#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=!1;#s=null;#c=null;#l=null;#u=null;#d=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#d=t._uiManager.useNewAltTextFlow,e.#f||=Object.freeze({added:`pdfjs-editor-new-alt-text-added-button`,"added-label":`pdfjs-editor-new-alt-text-added-button-label`,missing:`pdfjs-editor-new-alt-text-missing-button`,"missing-label":`pdfjs-editor-new-alt-text-missing-button-label`,review:`pdfjs-editor-new-alt-text-to-review-button`,"review-label":`pdfjs-editor-new-alt-text-to-review-button-label`})}static initialize(t){e._l10n??=t}async render(){let t=this.#n=document.createElement(`button`);t.className=`altText`,t.tabIndex=`0`;let n=this.#r=document.createElement(`span`);t.append(n),this.#d?(t.classList.add(`new`),t.setAttribute(`data-l10n-id`,e.#f.missing),n.setAttribute(`data-l10n-id`,e.#f[`missing-label`])):(t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-button`),n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-button-label`));let r=this.#c._uiManager._signal;t.addEventListener(`contextmenu`,Ll,{signal:r}),t.addEventListener(`pointerdown`,e=>e.stopPropagation(),{signal:r});let i=e=>{e.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_clicked`,data:{label:this.#p}})};return t.addEventListener(`click`,i,{capture:!0,signal:r}),t.addEventListener(`keydown`,e=>{e.target===t&&e.key===`Enter`&&(this.#o=!0,i(e))},{signal:r}),await this.#m(),t}get#p(){return this.#e&&`added`||this.#e===null&&this.guessedText&&`review`||`missing`}finish(){this.#n&&(this.#n.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#e===null&&(this.#l=t,this.#u=await e._l10n.get(`pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer`,{generatedAltText:t}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let e=this.#s=document.createElement(`div`);e.className=`noAltTextBadge`,this.#c.div.append(e)}this.#s.classList.toggle(`hidden`,!e)}serialize(e){let t=this.#e;return!e&&this.#l===t&&(t=this.#u),{altText:t,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:r,cancel:i=!1}){n&&(this.#l=n,this.#u=r),!(this.#e===e&&this.#t===t)&&(i||(this.#e=e,this.#t=t),this.#m())}toggle(e=!1){this.#n&&(!e&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n.disabled=!e)}shown(){this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_displayed`,data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#r=null,this.#i=null,this.#s?.remove(),this.#s=null}async#m(){let t=this.#n;if(!t)return;if(this.#d){if(t.classList.toggle(`done`,!!this.#e),t.setAttribute(`data-l10n-id`,e.#f[this.#p]),this.#r?.setAttribute(`data-l10n-id`,e.#f[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){t.classList.remove(`done`),this.#i?.remove();return}t.classList.add(`done`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-edit-button`)}let n=this.#i;if(!n){this.#i=n=document.createElement(`span`),n.className=`tooltip`,n.setAttribute(`role`,`tooltip`),n.id=`alt-text-tooltip-${this.#c.id}`;let e=this.#c._uiManager._signal;e.addEventListener(`abort`,()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener(`mouseenter`,()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add(`show`),this.#c._reportTelemetry({action:`alt_text_tooltip`})},100)},{signal:e}),t.addEventListener(`mouseleave`,()=>{this.#a&&=(clearTimeout(this.#a),null),this.#i?.classList.remove(`show`)},{signal:e})}this.#t?n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-decorative-tooltip`):(n.removeAttribute(`data-l10n-id`),n.textContent=this.#e),n.parentNode||t.append(n),this.#c.getImageForAltText()?.setAttribute(`aria-describedby`,n.id)}},nu=class e{#e;#t=!1;#n=null;#r;#i;#a;#o;#s;#c=null;#l;#u=null;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:r=null,onPinching:i=null,onPinchEnd:a=null,signal:o}){this.#e=e,this.#n=n,this.#r=t,this.#i=r,this.#a=i,this.#o=a,this.#l=new AbortController,this.#s=AbortSignal.any([o,this.#l.signal]),e.addEventListener(`touchstart`,this.#d.bind(this),{passive:!1,signal:this.#s})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return Y(this,`MIN_TOUCH_DISTANCE_TO_PINCH`,35/(window.devicePixelRatio||1))}#d(e){if(this.#r?.()||e.touches.length<2)return;if(!this.#u){this.#u=new AbortController;let e=AbortSignal.any([this.#s,this.#u.signal]),t=this.#e,n={signal:e,passive:!1};t.addEventListener(`touchmove`,this.#f.bind(this),n),t.addEventListener(`touchend`,this.#p.bind(this),n),t.addEventListener(`touchcancel`,this.#p.bind(this),n),this.#i?.()}if(Rl(e),e.touches.length!==2||this.#n?.()){this.#c=null;return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),this.#c={touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[n,r]=t.touches;n.identifier>r.identifier&&([n,r]=[r,n]);let{screenX:i,screenY:a}=n,{screenX:o,screenY:s}=r,c=this.#c,{touch0X:l,touch0Y:u,touch1X:d,touch1Y:f}=c,p=d-l,m=f-u,h=o-i,g=s-a,_=Math.hypot(h,g)||1,v=Math.hypot(p,m)||1;if(!this.#t&&Math.abs(v-_)<=e.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=a,c.touch1X=o,c.touch1Y=s,t.preventDefault(),!this.#t){this.#t=!0;return}let y=[(i+o)/2,(a+s)/2];this.#a?.(y,v,_)}#p(e){this.#u.abort(),this.#u=null,this.#o?.(),this.#c&&(e.preventDefault(),this.#c=null,this.#t=!1)}destroy(){this.#l?.abort(),this.#l=null}},Q=class e{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=``;#o=!1;#s=null;#c=null;#l=null;#u=null;#d=``;#f=!1;#p=null;#m=!1;#h=!1;#g=!1;#_=null;#v=0;#y=0;#b=null;#x=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#S=!1;#C=e._zIndex++;static _borderLineWidth=-1;static _colorManager=new $l;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=e.prototype._resizeWithKeyboard,n=eu.TRANSLATE_SMALL,r=eu.TRANSLATE_BIG;return Y(this,`_resizerKeyboardManager`,new Ql([[[`ArrowLeft`,`mac+ArrowLeft`],t,{args:[-n,0]}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t,{args:[-r,0]}],[[`ArrowRight`,`mac+ArrowRight`],t,{args:[n,0]}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t,{args:[r,0]}],[[`ArrowUp`,`mac+ArrowUp`],t,{args:[0,-n]}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t,{args:[0,-r]}],[[`ArrowDown`,`mac+ArrowDown`],t,{args:[0,n]}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t,{args:[0,r]}],[[`Escape`,`mac+Escape`],e.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null;let{rotation:t,rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,r],this.pageTranslation=[i,a];let[o,s]=this.parentDimensions;this.x=e.x/o,this.y=e.y/s,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return Y(this,`_defaultLineColor`,this._colorManager.getHexCode(`CanvasText`))}static deleteAnnotationElement(e){let t=new ru({id:e.parent.getNextId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(t,n){if(e._l10n??=t,e._l10nResizer||=Object.freeze({topLeft:`pdfjs-editor-resizer-top-left`,topMiddle:`pdfjs-editor-resizer-top-middle`,topRight:`pdfjs-editor-resizer-top-right`,middleRight:`pdfjs-editor-resizer-middle-right`,bottomRight:`pdfjs-editor-resizer-bottom-right`,bottomMiddle:`pdfjs-editor-resizer-bottom-middle`,bottomLeft:`pdfjs-editor-resizer-bottom-left`,middleLeft:`pdfjs-editor-resizer-middle-left`}),e._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);e._borderLineWidth=parseFloat(r.getPropertyValue(`--outline-width`))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){J(`Not implemented`)}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(e){this.#S=e,this.div?.classList.toggle(`draggable`,e)}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#C}setParent(e){e===null?this.#H():(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(e){this._focusEventsAllowed&&this.isAttachedToDOM&&(e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,r){let[i,a]=this.parentDimensions;[n,r]=this.screenToPageTranslation(n,r),this.x=(e+n)/i,this.y=(t+r)/a,this.fixAndSetPosition()}#w([e,t],n,r){[n,r]=this.screenToPageTranslation(n,r),this.x+=n/e,this.y+=r/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#w(this.parentDimensions,e,t)}translateInPage(e,t){this.#p||=[this.x,this.y,this.width,this.height],this.#w(this.pageDimensions,e,t),this.div.scrollIntoView({block:`nearest`})}drag(e,t){this.#p||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[r,i]}=this;if(this.x+=e/r,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:e,y:t}=this.div.getBoundingClientRect();this.parent.findNewParent(this,e,t)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:o}=this,[s,c]=this.getBaseTranslation();a+=s,o+=c;let{style:l}=n;l.left=`${(100*a).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(a,o),n.scrollIntoView({block:`nearest`})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#p&&(this.#p[0]!==this.x||this.#p[1]!==this.y)}get _hasBeenResized(){return!!this.#p&&(this.#p[2]!==this.width||this.#p[3]!==this.height)}getBaseTranslation(){let[t,n]=this.parentDimensions,{_borderLineWidth:r}=e,i=r/t,a=r/n;switch(this.rotation){case 90:return[-i,a];case 180:return[i,a];case 270:return[i,-a];default:return[-i,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,r]}=this,{x:i,y:a,width:o,height:s}=this;if(o*=n,s*=r,i*=n,a*=r,this._mustFixPosition)switch(e){case 0:i=Math.max(0,Math.min(n-o,i)),a=Math.max(0,Math.min(r-s,a));break;case 90:i=Math.max(0,Math.min(n-s,i)),a=Math.min(r,Math.max(o,a));break;case 180:i=Math.min(n,Math.max(o,i)),a=Math.min(r,Math.max(s,a));break;case 270:i=Math.min(n,Math.max(s,i)),a=Math.max(0,Math.min(r-o,a));break}this.x=i/=n,this.y=a/=r;let[c,l]=this.getBaseTranslation();i+=c,a+=l,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#T(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(t,n){return e.#T(t,n,this.parentRotation)}pageTranslationToScreen(t,n){return e.#T(t,n,360-this.parentRotation)}#E(e){switch(e){case 90:{let[e,t]=this.pageDimensions;return[0,-e/t,t/e,0]}case 180:return[-1,0,0,-1];case 270:{let[e,t]=this.pageDimensions;return[0,e/t,-t/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(e,t){let[n,r]=this.parentDimensions,{style:i}=this.div;i.width=`${(100*e/n).toFixed(2)}%`,this.#o||(i.height=`${(100*t/r).toFixed(2)}%`)}fixDims(){let{style:e}=this.div,{height:t,width:n}=e,r=n.endsWith(`%`),i=!this.#o&&t.endsWith(`%`);if(r&&i)return;let[a,o]=this.parentDimensions;r||(e.width=`${(100*parseFloat(n)/a).toFixed(2)}%`),!this.#o&&!i&&(e.height=`${(100*parseFloat(t)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#D(){if(this.#s)return;this.#s=document.createElement(`div`),this.#s.classList.add(`resizers`);let e=this._willKeepAspectRatio?[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`]:[`topLeft`,`topMiddle`,`topRight`,`middleRight`,`bottomRight`,`bottomMiddle`,`bottomLeft`,`middleLeft`],t=this._uiManager._signal;for(let n of e){let e=document.createElement(`div`);this.#s.append(e),e.classList.add(`resizer`,n),e.setAttribute(`data-resizer-name`,n),e.addEventListener(`pointerdown`,this.#O.bind(this,n),{signal:t}),e.addEventListener(`contextmenu`,Ll,{signal:t}),e.tabIndex=-1}this.div.prepend(this.#s)}#O(e,t){t.preventDefault();let{isMac:n}=_l.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let r=this._isDraggable;this._isDraggable=!1,this.#c=[t.screenX,t.screenY];let i=new AbortController,a=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener(`pointermove`,this.#j.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener(`touchmove`,Rl,{passive:!1,signal:a}),window.addEventListener(`contextmenu`,Ll,{signal:a}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,s=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=r,this.parent.div.style.cursor=o,this.div.style.cursor=s,this.#A()};window.addEventListener(`pointerup`,c,{signal:a}),window.addEventListener(`blur`,c,{signal:a})}#k(e,t,n,r){this.width=n,this.height=r,this.x=e,this.y=t;let[i,a]=this.parentDimensions;this.setDims(i*n,a*r),this.fixAndSetPosition(),this._onResized()}_onResized(){}#A(){if(!this.#l)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:r}=this.#l;this.#l=null;let i=this.x,a=this.y,o=this.width,s=this.height;i===e&&a===t&&o===n&&s===r||this.addCommands({cmd:this.#k.bind(this,i,a,o,s),undo:this.#k.bind(this,e,t,n,r),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#j(t,n){let[r,i]=this.parentDimensions,a=this.x,o=this.y,s=this.width,c=this.height,l=e.MIN_SIZE/r,u=e.MIN_SIZE/i,d=this.#E(this.rotation),f=(e,t)=>[d[0]*e+d[2]*t,d[1]*e+d[3]*t],p=this.#E(360-this.rotation),m=(e,t)=>[p[0]*e+p[2]*t,p[1]*e+p[3]*t],h,g,_=!1,v=!1;switch(t){case`topLeft`:_=!0,h=(e,t)=>[0,0],g=(e,t)=>[e,t];break;case`topMiddle`:h=(e,t)=>[e/2,0],g=(e,t)=>[e/2,t];break;case`topRight`:_=!0,h=(e,t)=>[e,0],g=(e,t)=>[0,t];break;case`middleRight`:v=!0,h=(e,t)=>[e,t/2],g=(e,t)=>[0,t/2];break;case`bottomRight`:_=!0,h=(e,t)=>[e,t],g=(e,t)=>[0,0];break;case`bottomMiddle`:h=(e,t)=>[e/2,t],g=(e,t)=>[e/2,0];break;case`bottomLeft`:_=!0,h=(e,t)=>[0,t],g=(e,t)=>[e,0];break;case`middleLeft`:v=!0,h=(e,t)=>[0,t/2],g=(e,t)=>[e,t/2];break}let y=h(s,c),b=g(s,c),x=f(...b),S=e._round(a+x[0]),C=e._round(o+x[1]),w=1,T=1,E,D;if(n.fromKeyboard)({deltaX:E,deltaY:D}=n);else{let{screenX:e,screenY:t}=n,[r,i]=this.#c;[E,D]=this.screenToPageTranslation(e-r,t-i),this.#c[0]=e,this.#c[1]=t}if([E,D]=m(E/r,D/i),_){let e=Math.hypot(s,c);w=T=Math.max(Math.min(Math.hypot(b[0]-y[0]-E,b[1]-y[1]-D)/e,1/s,1/c),l/s,u/c)}else v?w=Math.max(l,Math.min(1,Math.abs(b[0]-y[0]-E)))/s:T=Math.max(u,Math.min(1,Math.abs(b[1]-y[1]-D)))/c;let O=e._round(s*w),k=e._round(c*T);x=f(...g(O,k));let A=S-x[0],j=C-x[1];this.#p||=[this.x,this.y,this.width,this.height],this.width=O,this.height=k,this.x=A,this.y=j,this.setDims(r*O,i*k),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}async addEditToolbar(){return this._editToolbar||this.#h?this._editToolbar:(this._editToolbar=new Kl(this),this.div.append(this._editToolbar.render()),this.#n&&await this._editToolbar.addAltText(this.#n),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#n?.destroy())}addContainer(e){let t=this._editToolbar?.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#n||(tu.initialize(e._l10n),this.#n=new tu(this),this.#e&&=(this.#n.data=this.#e,null),await this.addEditToolbar())}get altTextData(){return this.#n?.data}set altTextData(e){this.#n&&(this.#n.data=e)}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.hasData()??!1}render(){this.div=document.createElement(`div`),this.div.setAttribute(`data-editor-rotation`,(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute(`id`,this.id),this.div.tabIndex=this.#r?-1:0,this._isVisible||this.div.classList.add(`hidden`),this.setInForeground(),this.#L();let[e,t]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*t/e).toFixed(2)}%`,this.div.style.maxHeight=`${(100*e/t).toFixed(2)}%`);let[n,r]=this.getInitialTranslation();return this.translate(n,r),Jl(this,this.div,[`pointerdown`]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#x||=new nu({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#M.bind(this),onPinching:this.#N.bind(this),onPinchEnd:this.#P.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#M(){this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#N(t,n,r){let i=.7,a=r/n*i+1-i;if(a===1)return;let o=this.#E(this.rotation),s=(e,t)=>[o[0]*e+o[2]*t,o[1]*e+o[3]*t],[c,l]=this.parentDimensions,u=this.x,d=this.y,f=this.width,p=this.height,m=e.MIN_SIZE/c,h=e.MIN_SIZE/l;a=Math.max(Math.min(a,1/f,1/p),m/f,h/p);let g=e._round(f*a),_=e._round(p*a);if(g===f&&_===p)return;this.#p||=[u,d,f,p];let v=s(f/2,p/2),y=e._round(u+v[0]),b=e._round(d+v[1]),x=s(g/2,_/2);this.x=y-x[0],this.y=b-x[1],this.width=g,this.height=_,this.setDims(c*g,l*_),this.fixAndSetPosition(),this._onResizing()}#P(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#A()}pointerdown(e){let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#I(e);return}this.#F(e)}get isSelected(){return this._uiManager.isSelected(this)}#F(e){let{isMac:t}=_l.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)}#I(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,r=new AbortController,i=this._uiManager.combinedSignal(r),a={capture:!0,passive:!1,signal:i},o=e=>{r.abort(),this.#i=null,this.#f=!1,this._uiManager.endDragSession()||this.#F(e),n&&this._onStopDragging()};t&&(this.#v=e.clientX,this.#y=e.clientY,this.#i=e.pointerId,this.#a=e.pointerType,window.addEventListener(`pointermove`,e=>{n||(n=!0,this._onStartDragging());let{clientX:t,clientY:r,pointerId:i}=e;if(i!==this.#i){Rl(e);return}let[a,o]=this.screenToPageTranslation(t-this.#v,r-this.#y);this.#v=t,this.#y=r,this._uiManager.dragSelectedEditors(a,o)},a),window.addEventListener(`touchmove`,Rl,a),window.addEventListener(`pointerdown`,e=>{e.pointerType===this.#a&&(this.#x||e.isPrimary)&&o(e),Rl(e)},a));let s=e=>{if(!this.#i||this.#i===e.pointerId){o(e);return}Rl(e)};window.addEventListener(`pointerup`,s,{signal:i}),window.addEventListener(`blur`,s,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#_&&clearTimeout(this.#_),this.#_=setTimeout(()=>{this.#_=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let r=this.parentScale,[i,a]=this.pageDimensions,[o,s]=this.pageTranslation,c=e/r,l=t/r,u=this.x*i,d=this.y*a,f=this.width*i,p=this.height*a;switch(n){case 0:return[u+c+o,a-d-l-p+s,u+c+f+o,a-d-l+s];case 90:return[u+l+o,a-d+c+s,u+l+p+o,a-d+c+f+s];case 180:return[u-c-f+o,a-d+l+s,u-c+o,a-d+l+p+s];case 270:return[u-l-p+o,a-d-c-f+s,u-l+o,a-d-c+s];default:throw Error(`Invalid rotation`)}}getRectInCurrentCoords(e,t){let[n,r,i,a]=e,o=i-n,s=a-r;switch(this.rotation){case 0:return[n,t-a,o,s];case 90:return[n,t-r,s,o];case 180:return[i,t-r,o,s];case 270:return[i,t-a,s,o];default:throw Error(`Invalid rotation`)}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){this.#h=!0}disableEditMode(){this.#h=!1}isInEditMode(){return this.#h}shouldGetKeyboardEvents(){return this.#g}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:r}=this.getClientDimensions(),{innerHeight:i,innerWidth:a}=window;return t<a&&r>0&&e<i&&n>0}#L(){if(this.#u||!this.div)return;this.#u=new AbortController;let e=this._uiManager.combinedSignal(this.#u);this.div.addEventListener(`focusin`,this.focusin.bind(this),{signal:e}),this.div.addEventListener(`focusout`,this.focusout.bind(this),{signal:e})}rebuild(){this.#L()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||``}}serialize(e=!1,t=null){J(`An editor must be serializable`)}static async deserialize(e,t,n){let r=new this.prototype.constructor({parent:t,id:t.getNextId(),uiManager:n});r.rotation=e.rotation,r.#e=e.accessibilityData;let[i,a]=r.pageDimensions,[o,s,c,l]=r.getRectInCurrentCoords(e.rect,a);return r.x=o/i,r.y=s/a,r.width=c/i,r.height=l/a,r}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#u?.abort(),this.#u=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#_&&=(clearTimeout(this.#_),null),this.#H(),this.removeEditToolbar(),this.#b){for(let e of this.#b.values())clearTimeout(e);this.#b=null}this.parent=null,this.#x?.destroy(),this.#x=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#D(),this.#s.classList.remove(`hidden`),Jl(this,this.div,[`keydown`]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!==`Enter`)return;this._uiManager.setSelected(this),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#s.children;if(!this.#t){this.#t=Array.from(n);let t=this.#R.bind(this),r=this.#z.bind(this),i=this._uiManager._signal;for(let n of this.#t){let a=n.getAttribute(`data-resizer-name`);n.setAttribute(`role`,`spinbutton`),n.addEventListener(`keydown`,t,{signal:i}),n.addEventListener(`blur`,r,{signal:i}),n.addEventListener(`focus`,this.#B.bind(this,a),{signal:i}),n.setAttribute(`data-l10n-id`,e._l10nResizer[a])}}let r=this.#t[0],i=0;for(let e of n){if(e===r)break;i++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(a!==i){if(a<i)for(let e=0;e<i-a;e++)this.#s.append(this.#s.firstChild);else if(a>i)for(let e=0;e<a-i;e++)this.#s.firstChild.before(this.#s.lastChild);let t=0;for(let r of n){let n=this.#t[t++].getAttribute(`data-resizer-name`);r.setAttribute(`data-l10n-id`,e._l10nResizer[n])}}this.#V(0),this.#g=!0,this.#s.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#R(t){e._resizerKeyboardManager.exec(this,t)}#z(e){this.#g&&e.relatedTarget?.parentNode!==this.#s&&this.#H()}#B(e){this.#d=this.#g?e:``}#V(e){if(this.#t)for(let t of this.#t)t.tabIndex=e}_resizeWithKeyboard(e,t){this.#g&&this.#j(this.#d,{deltaX:e,deltaY:t,fromKeyboard:!0})}#H(){this.#g=!1,this.#V(-1),this.#A()}_stopResizingWithKeyboard(){this.#H(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add(`selectedEditor`),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains(`selectedEditor`)&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#n?.toggleAltTextBadge(!1)}unselect(){this.#s?.classList.add(`hidden`),this.div?.classList.remove(`selectedEditor`),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0)}updateParams(e,t){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#m}set isEditing(e){this.#m=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(e,t){this.#o=!0;let n=e/t,{style:r}=this.div;r.aspectRatio=n,r.height=`auto`}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:`added`}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){this.#b||=new Map;let{action:n}=t,r=this.#b.get(n);r&&clearTimeout(r),r=setTimeout(()=>{this._reportTelemetry(t),this.#b.delete(n),this.#b.size===0&&(this.#b=null)},e._telemetryTimeout),this.#b.set(n,r);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:t}})}show(e=this._isVisible){this.div.classList.toggle(`hidden`,!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#r=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#r=!0}renderAnnotationElement(e){let t=e.container.querySelector(`.annotationContent`);if(!t)t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.container.prepend(t);else if(t.nodeName===`CANVAS`){let e=t;t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.before(t)}return t}resetAnnotationElement(e){let{firstChild:t}=e.container;t?.nodeName===`DIV`&&t.classList.contains(`annotationContent`)&&t.remove()}},ru=class extends Q{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},iu=3285377520,au=4294901760,ou=65535,su=class{constructor(e){this.h1=e?e&4294967295:iu,this.h2=e?e&4294967295:iu}update(e){let t,n;if(typeof e==`string`){t=new Uint8Array(e.length*2),n=0;for(let r=0,i=e.length;r<i;r++){let i=e.charCodeAt(r);i<=255?t[n++]=i:(t[n++]=i>>>8,t[n++]=i&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error(`Invalid data format, must be a string or TypedArray.`);let r=n>>2,i=n-r*4,a=new Uint32Array(t.buffer,0,r),o=0,s=0,c=this.h1,l=this.h2,u=3432918353,d=461845907,f=11601,p=13715;for(let e=0;e<r;e++)e&1?(o=a[e],o=o*u&au|o*f&ou,o=o<<15|o>>>17,o=o*d&au|o*p&ou,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(s=a[e],s=s*u&au|s*f&ou,s=s<<15|s>>>17,s=s*d&au|s*p&ou,l^=s,l=l<<13|l>>>19,l=l*5+3864292196);switch(o=0,i){case 3:o^=t[r*4+2]<<16;case 2:o^=t[r*4+1]<<8;case 1:o^=t[r*4],o=o*u&au|o*f&ou,o=o<<15|o>>>17,o=o*d&au|o*p&ou,r&1?c^=o:l^=o}this.h1=c,this.h2=l}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&au|e*36045&ou,t=t*4283543511&au|((t<<16|e>>>16)*2950163797&au)>>>16,e^=t>>>1,e=e*444984403&au|e*60499&ou,t=t*3301882366&au|((t<<16|e>>>16)*3120437893&au)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}},cu=Object.freeze({map:null,hash:``,transfer:void 0}),lu=class{#e=!1;#t=null;#n=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(e,t){let n=this.#n.get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return this.#n.get(e)}remove(e){if(this.#n.delete(e),this.#n.size===0&&this.resetModified(),typeof this.onAnnotationEditor==`function`){for(let e of this.#n.values())if(e instanceof Q)return;this.onAnnotationEditor(null)}}setValue(e,t){let n=this.#n.get(e),r=!1;if(n!==void 0)for(let[e,i]of Object.entries(t))n[e]!==i&&(r=!0,n[e]=i);else r=!0,this.#n.set(e,t);r&&this.#r(),t instanceof Q&&typeof this.onAnnotationEditor==`function`&&this.onAnnotationEditor(t.constructor._type)}has(e){return this.#n.has(e)}getAll(){return this.#n.size>0?ml(this.#n):null}setAll(e){for(let[t,n]of Object.entries(e))this.setValue(t,n)}get size(){return this.#n.size}#r(){this.#e||(this.#e=!0,typeof this.onSetModified==`function`&&this.onSetModified())}resetModified(){this.#e&&(this.#e=!1,typeof this.onResetModified==`function`&&this.onResetModified())}get print(){return new uu(this)}get serializable(){if(this.#n.size===0)return cu;let e=new Map,t=new su,n=[],r=Object.create(null),i=!1;for(let[n,a]of this.#n){let o=a instanceof Q?a.serialize(!1,r):a;o&&(e.set(n,o),t.update(`${n}:${JSON.stringify(o)}`),i||=!!o.bitmap)}if(i)for(let t of e.values())t.bitmap&&n.push(t.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:cu}get editorStats(){let e=null,t=new Map;for(let n of this.#n.values()){if(!(n instanceof Q))continue;let r=n.telemetryFinalData;if(!r)continue;let{type:i}=r;t.has(i)||t.set(i,Object.getPrototypeOf(n).constructor),e||=Object.create(null);let a=e[i]||=new Map;for(let[e,t]of Object.entries(r)){if(e===`type`)continue;let n=a.get(e);n||(n=new Map,a.set(e,n));let r=n.get(t)??0;n.set(t,r+1)}}for(let[n,r]of t)e[n]=r.computeTelemetryFinalData(e[n]);return e}resetModifiedIds(){this.#t=null}get modifiedIds(){if(this.#t)return this.#t;let e=[];for(let t of this.#n.values())!(t instanceof Q)||!t.annotationElementId||!t.serialize()||e.push(t.annotationElementId);return this.#t={ids:new Set(e),hash:e.join(`,`)}}},uu=class extends lu{#e;constructor(e){super();let{map:t,hash:n,transfer:r}=e.serializable,i=structuredClone(t,r?{transfer:r}:null);this.#e={map:i,hash:n,transfer:r}}get print(){J(`Should not call PrintAnnotationStorage.print`)}get serializable(){return this.#e}get modifiedIds(){return Y(this,`modifiedIds`,{ids:new Set,hash:``})}},du=class{#e=new Set;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement(`style`),this._document.documentElement.getElementsByTagName(`head`)[0].append(this.styleElement));let t=this.styleElement.sheet;t.insertRule(e,t.cssRules.length)}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),this.#e.clear(),this.styleElement&&=(this.styleElement.remove(),null)}async loadSystemFont({systemFontInfo:e,_inspectFont:t}){if(!(!e||this.#e.has(e.loadedName))){if(el(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:n,src:r,style:i}=e,a=new FontFace(n,r,i);this.addNativeFontFace(a);try{await a.load(),this.#e.add(n),t?.(e)}catch{q(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}J(`Not implemented: loadSystemFont without the Font Loading API.`)}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let t=e.createNativeFontFace();if(t){this.addNativeFontFace(t);try{await t.loaded}catch(n){throw q(`Failed to load font '${t.family}': '${n}'.`),e.disableFontFace=!0,n}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(t=>{let n=this._queueLoadingCallback(t);this._prepareFontLoadEvent(e,n)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return Y(this,`isFontLoadingAPISupported`,e)}get isSyncFontLoadingSupported(){let e=!1;return(Pc||typeof navigator<`u`&&typeof navigator?.userAgent==`string`&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(e=!0),Y(this,`isSyncFontLoadingSupported`,e)}_queueLoadingCallback(e){function t(){for(el(!r.done,`completeRequest() cannot be called twice.`),r.done=!0;n.length>0&&n[0].done;){let e=n.shift();setTimeout(e.callback,0)}}let{loadingRequests:n}=this,r={done:!1,complete:t,callback:e};return n.push(r),r}get _loadTestFont(){let e=atob(`T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==`);return Y(this,`_loadTestFont`,e)}_prepareFontLoadEvent(e,t){function n(e,t){return e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3)&255}function r(e,t,n,r){let i=e.substring(0,t),a=e.substring(t+n);return i+r+a}let i,a,o=this._document.createElement(`canvas`);o.width=1,o.height=1;let s=o.getContext(`2d`),c=0;function l(e,t){if(++c>30){q(`Load test font never loaded.`),t();return}if(s.font=`30px `+e,s.fillText(`.`,0,20),s.getImageData(0,0,1,1).data[3]>0){t();return}setTimeout(l.bind(null,e,t))}let u=`lt${Date.now()}${this.loadTestFontId++}`,d=this._loadTestFont;d=r(d,976,u.length,u);let f=1482184792,p=n(d,16);for(i=0,a=u.length-3;i<a;i+=4)p=p-f+n(u,i)|0;i<u.length&&(p=p-f+n(u+`XXX`,i)|0),d=r(d,16,4,pl(p));let m=`@font-face {font-family:"${u}";src:${`url(data:font/opentype;base64,${btoa(d)});`}}`;this.insertRule(m);let h=this._document.createElement(`div`);h.style.visibility=`hidden`,h.style.width=h.style.height=`10px`,h.style.position=`absolute`,h.style.top=h.style.left=`0px`;for(let t of[e.loadedName,u]){let e=this._document.createElement(`span`);e.textContent=`Hi`,e.style.fontFamily=t,h.append(e)}this._document.body.append(h),l(u,()=>{h.remove(),t.complete()})}},fu=class{constructor(e,{disableFontFace:t=!1,fontExtraProperties:n=!1,inspectFont:r=null}){this.compiledGlyphs=Object.create(null);for(let t in e)this[t]=e[t];this.disableFontFace=t===!0,this.fontExtraProperties=n===!0,this._inspectFont=r}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(t.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${Tl(this.data)});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+`_path_`+t,r;try{r=e.get(n)}catch(e){q(`getPathGenerator - ignoring character: "${e}".`)}let i=new Path2D(r||``);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=i}},pu={DATA:1,ERROR:2},mu={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function hu(){}function gu(e){if(e instanceof ul||e instanceof ol||e instanceof sl||e instanceof il||e instanceof cl||e instanceof al)return e;switch(e instanceof Error||typeof e==`object`&&e||J(`wrapReason: Expected "reason" to be a (possibly cloned) Error.`),e.name){case`AbortException`:return new ul(e.message);case`InvalidPDFException`:return new ol(e.message);case`MissingPDFException`:return new sl(e.message);case`PasswordException`:return new il(e.message,e.code);case`UnexpectedResponseException`:return new cl(e.message,e.status);case`UnknownErrorException`:return new al(e.message,e.details)}return new al(e.message,e.toString())}var _u=class{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener(`message`,this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#r(e);return}if(e.callback){let t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===pu.DATA)n.resolve(e.data);else if(e.callback===pu.ERROR)n.reject(gu(e.reason));else throw Error(`Unexpected callback case`);return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:n,targetName:r,callback:pu.DATA,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:n,targetName:r,callback:pu.ERROR,callbackId:e.callbackId,reason:gu(t)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},n)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,n,r){let i=this.streamId++,a=this.sourceName,o=this.targetName,s=this.comObj;return new ReadableStream({start:n=>{let c=Promise.withResolvers();return this.streamControllers[i]={controller:n,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},s.postMessage({sourceName:a,targetName:o,action:e,streamId:i,data:t,desiredSize:n.desiredSize},r),c.promise},pull:e=>{let t=Promise.withResolvers();return this.streamControllers[i].pullCall=t,s.postMessage({sourceName:a,targetName:o,stream:mu.PULL,streamId:i,desiredSize:e.desiredSize}),t.promise},cancel:e=>{el(e instanceof Error,`cancel must have a valid reason`);let t=Promise.withResolvers();return this.streamControllers[i].cancelCall=t,this.streamControllers[i].isClosed=!0,s.postMessage({sourceName:a,targetName:o,stream:mu.CANCEL,streamId:i,reason:gu(e)}),t.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this,o=this.actionHandler[e.action],s={enqueue(e,a=1,o){if(this.isCancelled)return;let s=this.desiredSize;this.desiredSize-=a,s>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:n,targetName:r,stream:mu.ENQUEUE,streamId:t,chunk:e},o)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:mu.CLOSE,streamId:t}),delete a.streamSinks[t])},error(e){el(e instanceof Error,`error must have a valid reason`),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:mu.ERROR,streamId:t,reason:gu(e)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};s.sinkCapability.resolve(),s.ready=s.sinkCapability.promise,this.streamSinks[t]=s,Promise.try(o,e.data,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.START_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.START_COMPLETE,streamId:t,reason:gu(e)})})}#r(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case mu.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(gu(e.reason));break;case mu.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(gu(e.reason));break;case mu.PULL:if(!o){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,success:!0});break}o.desiredSize<=0&&e.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=e.desiredSize,Promise.try(o.onPull||hu).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,reason:gu(e)})});break;case mu.ENQUEUE:if(el(a,`enqueue should have stream controller`),a.isClosed)break;a.controller.enqueue(e.chunk);break;case mu.CLOSE:if(el(a,`close should have stream controller`),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#i(a,t);break;case mu.ERROR:el(a,`error should have stream controller`),a.controller.error(gu(e.reason)),this.#i(a,t);break;case mu.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(gu(e.reason)),this.#i(a,t);break;case mu.CANCEL:if(!o)break;let s=gu(e.reason);Promise.try(o.onCancel||hu,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.CANCEL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.CANCEL_COMPLETE,streamId:t,reason:gu(e)})}),o.sinkCapability.reject(s),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error(`Unexpected stream case`)}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}},vu=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error(`Invalid canvas size`);let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset(e,t,n){if(!e.canvas)throw Error(`Canvas is not specified`);if(t<=0||n<=0)throw Error(`Invalid canvas size`);e.canvas.width=t,e.canvas.height=n}destroy(e){if(!e.canvas)throw Error(`Canvas is not specified`);e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){J("Abstract method `_createCanvas` called.")}},yu=class extends vu{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},bu=class{constructor({baseUrl:e=null,isCompressed:t=!0}){this.baseUrl=e,this.isCompressed=t}async fetch({name:e}){if(!this.baseUrl)throw Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!e)throw Error(`CMap name must be specified.`);let t=this.baseUrl+e+(this.isCompressed?`.bcmap`:``);return this._fetch(t).then(e=>({cMapData:e,isCompressed:this.isCompressed})).catch(e=>{throw Error(`Unable to load ${this.isCompressed?`binary `:``}CMap at: ${t}`)})}async _fetch(e){J("Abstract method `_fetch` called.")}},xu=class extends bu{async _fetch(e){let t=await Ol(e,this.isCompressed?`arraybuffer`:`text`);return t instanceof ArrayBuffer?new Uint8Array(t):fl(t)}},Su=class{addFilter(e){return`none`}addHCMFilter(e,t){return`none`}addAlphaFilter(e){return`none`}addLuminosityFilter(e){return`none`}addHighlightHCMFilter(e,t,n,r,i){return`none`}destroy(e=!1){}},Cu=class extends Su{#e;#t;#n;#r;#i;#a;#o=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super(),this.#r=e,this.#i=t}get#s(){return this.#t||=new Map}get#c(){return this.#a||=new Map}get#l(){if(!this.#n){let e=this.#i.createElement(`div`),{style:t}=e;t.visibility=`hidden`,t.contain=`strict`,t.width=t.height=0,t.position=`absolute`,t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS(El,`svg`);n.setAttribute(`width`,0),n.setAttribute(`height`,0),this.#n=this.#i.createElementNS(El,`defs`),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let t=e[0],n=Array(256);for(let e=0;e<256;e++)n[e]=t[e]/255;let r=n.join(`,`);return[r,r,r]}let[t,n,r]=e,i=Array(256),a=Array(256),o=Array(256);for(let e=0;e<256;e++)i[e]=t[e]/255,a[e]=n[e]/255,o[e]=r[e]/255;return[i.join(`,`),a.join(`,`),o.join(`,`)]}#d(e){if(this.#e===void 0){this.#e=``;let e=this.#i.URL;e!==this.#i.baseURI&&(jl(e)?q(`#createUrl: ignore "data:"-URL for performance reasons.`):this.#e=e.split(`#`,1)[0])}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return`none`;let t=this.#s.get(e);if(t)return t;let[n,r,i]=this.#u(e),a=e.length===1?n:`${n}${r}${i}`;if(t=this.#s.get(a),t)return this.#s.set(e,t),t;let o=`g_${this.#r}_transfer_map_${this.#o++}`,s=this.#d(o);this.#s.set(e,s),this.#s.set(a,s);let c=this.#m(o);return this.#g(n,r,i,c),s}addHCMFilter(e,t){let n=`${e}-${t}`,r=`base`,i=this.#c.get(r);if(i?.key===n||(i?(i.filter?.remove(),i.key=n,i.url=`none`,i.filter=null):(i={key:n,url:`none`,filter:null},this.#c.set(r,i)),!e||!t))return i.url;let a=this.#v(e);e=X.makeHexColor(...a);let o=this.#v(t);if(t=X.makeHexColor(...o),this.#l.style.color=``,e===`#000000`&&t===`#ffffff`||e===t)return i.url;let s=Array(256);for(let e=0;e<=255;e++){let t=e/255;s[e]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}let c=s.join(`,`),l=`g_${this.#r}_hcm_filter`,u=i.filter=this.#m(l);this.#g(c,c,c,u),this.#p(u);let d=(e,t)=>{let n=a[e]/255,r=o[e]/255,i=Array(t+1);for(let e=0;e<=t;e++)i[e]=n+e/t*(r-n);return i.join(`,`)};return this.#g(d(0,5),d(1,5),d(2,5),u),i.url=this.#d(l),i.url}addAlphaFilter(e){let t=this.#s.get(e);if(t)return t;let[n]=this.#u([e]),r=`alpha_${n}`;if(t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_alpha_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#_(n,o),a}addLuminosityFilter(e){let t=this.#s.get(e||`luminosity`);if(t)return t;let n,r;if(e?([n]=this.#u([e]),r=`luminosity_${n}`):r=`luminosity`,t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_luminosity_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#f(o),e&&this.#_(n,o),a}addHighlightHCMFilter(e,t,n,r,i){let a=`${t}-${n}-${r}-${i}`,o=this.#c.get(e);if(o?.key===a||(o?(o.filter?.remove(),o.key=a,o.url=`none`,o.filter=null):(o={key:a,url:`none`,filter:null},this.#c.set(e,o)),!t||!n))return o.url;let[s,c]=[t,n].map(this.#v.bind(this)),l=Math.round(.2126*s[0]+.7152*s[1]+.0722*s[2]),u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[d,f]=[r,i].map(this.#v.bind(this));u<l&&([l,u,d,f]=[u,l,f,d]),this.#l.style.color=``;let p=(e,t,n)=>{let r=Array(256),i=(u-l)/n,a=e/255,o=(t-e)/(255*n),s=0;for(let e=0;e<=n;e++){let t=Math.round(l+e*i),n=a+e*o;for(let e=s;e<=t;e++)r[e]=n;s=t+1}for(let e=s;e<256;e++)r[e]=r[s-1];return r.join(`,`)},m=`g_${this.#r}_hcm_${e}_filter`,h=o.filter=this.#m(m);return this.#p(h),this.#g(p(d[0],f[0],5),p(d[1],f[1],5),p(d[2],f[2],5),h),o.url=this.#d(m),o.url}destroy(e=!1){e&&this.#a?.size||(this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#o=0)}#f(e){let t=this.#i.createElementNS(El,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0`),e.append(t)}#p(e){let t=this.#i.createElementNS(El,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0`),e.append(t)}#m(e){let t=this.#i.createElementNS(El,`filter`);return t.setAttribute(`color-interpolation-filters`,`sRGB`),t.setAttribute(`id`,e),this.#l.append(t),t}#h(e,t,n){let r=this.#i.createElementNS(El,t);r.setAttribute(`type`,`discrete`),r.setAttribute(`tableValues`,n),e.append(r)}#g(e,t,n,r){let i=this.#i.createElementNS(El,`feComponentTransfer`);r.append(i),this.#h(i,`feFuncR`,e),this.#h(i,`feFuncG`,t),this.#h(i,`feFuncB`,n)}#_(e,t){let n=this.#i.createElementNS(El,`feComponentTransfer`);t.append(n),this.#h(n,`feFuncA`,e)}#v(e){return this.#l.style.color=e,Vl(getComputedStyle(this.#l).getPropertyValue(`color`))}},wu=class{constructor({baseUrl:e=null}){this.baseUrl=e}async fetch({filename:e}){if(!this.baseUrl)throw Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!e)throw Error(`Font filename must be specified.`);let t=`${this.baseUrl}${e}`;return this._fetch(t).catch(e=>{throw Error(`Unable to load font data at: ${t}`)})}async _fetch(e){J("Abstract method `_fetch` called.")}},Tu=class extends wu{async _fetch(e){let t=await Ol(e,`arraybuffer`);return new Uint8Array(t)}};Pc&&q("Please use the `legacy` build in Node.js environments.");async function Eu(e){let t=await process.getBuiltinModule(`fs`).promises.readFile(e);return new Uint8Array(t)}var Du=class extends Su{},Ou=class extends vu{_createCanvas(e,t){return process.getBuiltinModule(`module`).createRequire({}.url)(`@napi-rs/canvas`).createCanvas(e,t)}},ku=class extends bu{async _fetch(e){return Eu(e)}},Au=class extends wu{async _fetch(e){return Eu(e)}},ju={FILL:`Fill`,STROKE:`Stroke`,SHADING:`Shading`};function Mu(e,t){if(!t)return;let n=t[2]-t[0],r=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],n,r),e.clip(i)}var Nu=class{getPattern(){J("Abstract method `getPattern` called.")}},Pu=class extends Nu{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}_createGradient(e){let t;this._type===`axial`?t=e.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type===`radial`&&(t=e.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let e of this._colorStops)t.addColorStop(e[0],e[1]);return t}getPattern(e,t,n,r){let i;if(r===ju.STROKE||r===ju.FILL){let a=t.current.getClippedPathBoundingBox(r,Z(e))||[0,0,0,0],o=Math.ceil(a[2]-a[0])||1,s=Math.ceil(a[3]-a[1])||1,c=t.cachedCanvases.getCanvas(`pattern`,o,s),l=c.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-a[0],-a[1]),n=X.transform(n,[1,0,0,1,a[0],a[1]]),l.transform(...t.baseTransform),this.matrix&&l.transform(...this.matrix),Mu(l,this._bbox),l.fillStyle=this._createGradient(l),l.fill(),i=e.createPattern(c.canvas,`no-repeat`);let u=new DOMMatrix(n);i.setTransform(u)}else Mu(e,this._bbox),i=this._createGradient(e);return i}};function Fu(e,t,n,r,i,a,o,s){let c=t.coords,l=t.colors,u=e.data,d=e.width*4,f;c[n+1]>c[r+1]&&(f=n,n=r,r=f,f=a,a=o,o=f),c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=s,s=f),c[n+1]>c[r+1]&&(f=n,n=r,r=f,f=a,a=o,o=f);let p=(c[n]+t.offsetX)*t.scaleX,m=(c[n+1]+t.offsetY)*t.scaleY,h=(c[r]+t.offsetX)*t.scaleX,g=(c[r+1]+t.offsetY)*t.scaleY,_=(c[i]+t.offsetX)*t.scaleX,v=(c[i+1]+t.offsetY)*t.scaleY;if(m>=v)return;let y=l[a],b=l[a+1],x=l[a+2],S=l[o],C=l[o+1],w=l[o+2],T=l[s],E=l[s+1],D=l[s+2],O=Math.round(m),k=Math.round(v),A,j,M,ee,N,P,F,I;for(let e=O;e<=k;e++){if(e<g){let t=e<m?0:(m-e)/(m-g);A=p-(p-h)*t,j=y-(y-S)*t,M=b-(b-C)*t,ee=x-(x-w)*t}else{let t;t=e>v?1:g===v?0:(g-e)/(g-v),A=h-(h-_)*t,j=S-(S-T)*t,M=C-(C-E)*t,ee=w-(w-D)*t}let t;t=e<m?0:e>v?1:(m-e)/(m-v),N=p-(p-_)*t,P=y-(y-T)*t,F=b-(b-E)*t,I=x-(x-D)*t;let n=Math.round(Math.min(A,N)),r=Math.round(Math.max(A,N)),i=d*e+n*4;for(let e=n;e<=r;e++)t=(A-e)/(A-N),t<0?t=0:t>1&&(t=1),u[i++]=j-(j-P)*t|0,u[i++]=M-(M-F)*t|0,u[i++]=ee-(ee-I)*t|0,u[i++]=255}}function Iu(e,t,n){let r=t.coords,i=t.colors,a,o;switch(t.type){case`lattice`:let s=t.verticesPerRow,c=Math.floor(r.length/s)-1,l=s-1;for(a=0;a<c;a++){let t=a*s;for(let a=0;a<l;a++,t++)Fu(e,n,r[t],r[t+1],r[t+s],i[t],i[t+1],i[t+s]),Fu(e,n,r[t+s+1],r[t+1],r[t+s],i[t+s+1],i[t+1],i[t+s])}break;case`triangles`:for(a=0,o=r.length;a<o;a+=3)Fu(e,n,r[a],r[a+1],r[a+2],i[a],i[a+1],i[a+2]);break;default:throw Error(`illegal figure`)}}var Lu=class extends Nu{constructor(e){super(),this._coords=e[2],this._colors=e[3],this._figures=e[4],this._bounds=e[5],this._bbox=e[7],this._background=e[8],this.matrix=null}_createMeshCanvas(e,t,n){let r=1.1,i=3e3,a=Math.floor(this._bounds[0]),o=Math.floor(this._bounds[1]),s=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-o,l=Math.min(Math.ceil(Math.abs(s*e[0]*r)),i),u=Math.min(Math.ceil(Math.abs(c*e[1]*r)),i),d=s/l,f=c/u,p={coords:this._coords,colors:this._colors,offsetX:-a,offsetY:-o,scaleX:1/d,scaleY:1/f},m=l+4,h=u+4,g=n.getCanvas(`mesh`,m,h),_=g.context,v=_.createImageData(l,u);if(t){let e=v.data;for(let n=0,r=e.length;n<r;n+=4)e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=255}for(let e of this._figures)Iu(v,e,p);return _.putImageData(v,2,2),{canvas:g.canvas,offsetX:a-2*d,offsetY:o-2*f,scaleX:d,scaleY:f}}getPattern(e,t,n,r){Mu(e,this._bbox);let i;if(r===ju.SHADING)i=X.singularValueDecompose2dScale(Z(e));else if(i=X.singularValueDecompose2dScale(t.baseTransform),this.matrix){let e=X.singularValueDecompose2dScale(this.matrix);i=[i[0]*e[0],i[1]*e[1]]}let a=this._createMeshCanvas(i,r===ju.SHADING?null:this._background,t.cachedCanvases);return r!==ju.SHADING&&(e.setTransform(...t.baseTransform),this.matrix&&e.transform(...this.matrix)),e.translate(a.offsetX,a.offsetY),e.scale(a.scaleX,a.scaleY),e.createPattern(a.canvas,`no-repeat`)}},Ru=class extends Nu{getPattern(){return`hotpink`}};function zu(e){switch(e[0]){case`RadialAxial`:return new Pu(e);case`Mesh`:return new Lu(e);case`Dummy`:return new Ru}throw Error(`Unknown IR type: ${e[0]}`)}var Bu={COLORED:1,UNCOLORED:2},Vu=class e{static MAX_PATTERN_SIZE=3e3;constructor(e,t,n,r,i){this.operatorList=e[2],this.matrix=e[3],this.bbox=e[4],this.xstep=e[5],this.ystep=e[6],this.paintType=e[7],this.tilingType=e[8],this.color=t,this.ctx=n,this.canvasGraphicsFactory=r,this.baseTransform=i}createPatternCanvas(e){let{bbox:t,operatorList:n,paintType:r,tilingType:i,color:a,canvasGraphicsFactory:o}=this,{xstep:s,ystep:c}=this;s=Math.abs(s),c=Math.abs(c),$c(`TilingType: `+i);let l=t[0],u=t[1],d=t[2],f=t[3],p=d-l,m=f-u,h=X.singularValueDecompose2dScale(this.matrix),g=X.singularValueDecompose2dScale(this.baseTransform),_=h[0]*g[0],v=h[1]*g[1],y=p,b=m,x=!1,S=!1,C=Math.ceil(s*_),w=Math.ceil(c*v),T=Math.ceil(p*_),E=Math.ceil(m*v);C>=T?y=s:x=!0,w>=E?b=c:S=!0;let D=this.getSizeAndScale(y,this.ctx.canvas.width,_),O=this.getSizeAndScale(b,this.ctx.canvas.height,v),k=e.cachedCanvases.getCanvas(`pattern`,D.size,O.size),A=k.context,j=o.createCanvasGraphics(A);if(j.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(j,r,a),A.translate(-D.scale*l,-O.scale*u),j.transform(D.scale,0,0,O.scale,0,0),A.save(),this.clipBbox(j,l,u,d,f),j.baseTransform=Z(j.ctx),j.executeOperatorList(n),j.endDrawing(),A.restore(),x||S){let t=k.canvas;x&&(y=s),S&&(b=c);let n=this.getSizeAndScale(y,this.ctx.canvas.width,_),r=this.getSizeAndScale(b,this.ctx.canvas.height,v),i=n.size,a=r.size,o=e.cachedCanvases.getCanvas(`pattern-workaround`,i,a),d=o.context,f=x?Math.floor(p/s):0,h=S?Math.floor(m/c):0;for(let e=0;e<=f;e++)for(let n=0;n<=h;n++)d.drawImage(t,i*e,a*n,i,a,0,0,i,a);return{canvas:o.canvas,scaleX:n.scale,scaleY:r.scale,offsetX:l,offsetY:u}}return{canvas:k.canvas,scaleX:D.scale,scaleY:O.scale,offsetX:l,offsetY:u}}getSizeAndScale(t,n,r){let i=Math.max(e.MAX_PATTERN_SIZE,n),a=Math.ceil(t*r);return a>=i?a=i:r=a/t,{scale:r,size:a}}clipBbox(e,t,n,r,i){let a=r-t,o=i-n;e.ctx.rect(t,n,a,o),e.current.updateRectMinMax(Z(e.ctx),[t,n,r,i]),e.clip(),e.endPath()}setFillAndStrokeStyleToContext(e,t,n){let r=e.ctx,i=e.current;switch(t){case Bu.COLORED:let e=this.ctx;r.fillStyle=e.fillStyle,r.strokeStyle=e.strokeStyle,i.fillColor=e.fillStyle,i.strokeColor=e.strokeStyle;break;case Bu.UNCOLORED:let a=X.makeHexColor(n[0],n[1],n[2]);r.fillStyle=a,r.strokeStyle=a,i.fillColor=a,i.strokeColor=a;break;default:throw new ll(`Unsupported paint type: ${t}`)}}getPattern(e,t,n,r){let i=n;r!==ju.SHADING&&(i=X.transform(i,t.baseTransform),this.matrix&&(i=X.transform(i,this.matrix)));let a=this.createPatternCanvas(t),o=new DOMMatrix(i);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);let s=e.createPattern(a.canvas,`repeat`);return s.setTransform(o),s}};function Hu({src:e,srcPos:t=0,dest:n,width:r,height:i,nonBlackColor:a=4294967295,inverseDecode:o=!1}){let s=_l.isLittleEndian?4278190080:255,[c,l]=o?[a,s]:[s,a],u=r>>3,d=r&7,f=e.length;n=new Uint32Array(n.buffer);let p=0;for(let r=0;r<i;r++){for(let r=t+u;t<r;t++){let r=t<f?e[t]:255;n[p++]=r&128?l:c,n[p++]=r&64?l:c,n[p++]=r&32?l:c,n[p++]=r&16?l:c,n[p++]=r&8?l:c,n[p++]=r&4?l:c,n[p++]=r&2?l:c,n[p++]=r&1?l:c}if(d===0)continue;let r=t<f?e[t++]:255;for(let e=0;e<d;e++)n[p++]=r&1<<7-e?l:c}return{srcPos:t,destPos:p}}var Uu=16,Wu=100,Gu=15,Ku=10,qu=1e3,Ju=16;function Yu(e,t){if(e._removeMirroring)throw Error(`Context is already forwarding operations.`);e.__originalSave=e.save,e.__originalRestore=e.restore,e.__originalRotate=e.rotate,e.__originalScale=e.scale,e.__originalTranslate=e.translate,e.__originalTransform=e.transform,e.__originalSetTransform=e.setTransform,e.__originalResetTransform=e.resetTransform,e.__originalClip=e.clip,e.__originalMoveTo=e.moveTo,e.__originalLineTo=e.lineTo,e.__originalBezierCurveTo=e.bezierCurveTo,e.__originalRect=e.rect,e.__originalClosePath=e.closePath,e.__originalBeginPath=e.beginPath,e._removeMirroring=()=>{e.save=e.__originalSave,e.restore=e.__originalRestore,e.rotate=e.__originalRotate,e.scale=e.__originalScale,e.translate=e.__originalTranslate,e.transform=e.__originalTransform,e.setTransform=e.__originalSetTransform,e.resetTransform=e.__originalResetTransform,e.clip=e.__originalClip,e.moveTo=e.__originalMoveTo,e.lineTo=e.__originalLineTo,e.bezierCurveTo=e.__originalBezierCurveTo,e.rect=e.__originalRect,e.closePath=e.__originalClosePath,e.beginPath=e.__originalBeginPath,delete e._removeMirroring},e.save=function(){t.save(),this.__originalSave()},e.restore=function(){t.restore(),this.__originalRestore()},e.translate=function(e,n){t.translate(e,n),this.__originalTranslate(e,n)},e.scale=function(e,n){t.scale(e,n),this.__originalScale(e,n)},e.transform=function(e,n,r,i,a,o){t.transform(e,n,r,i,a,o),this.__originalTransform(e,n,r,i,a,o)},e.setTransform=function(e,n,r,i,a,o){t.setTransform(e,n,r,i,a,o),this.__originalSetTransform(e,n,r,i,a,o)},e.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},e.rotate=function(e){t.rotate(e),this.__originalRotate(e)},e.clip=function(e){t.clip(e),this.__originalClip(e)},e.moveTo=function(e,n){t.moveTo(e,n),this.__originalMoveTo(e,n)},e.lineTo=function(e,n){t.lineTo(e,n),this.__originalLineTo(e,n)},e.bezierCurveTo=function(e,n,r,i,a,o){t.bezierCurveTo(e,n,r,i,a,o),this.__originalBezierCurveTo(e,n,r,i,a,o)},e.rect=function(e,n,r,i){t.rect(e,n,r,i),this.__originalRect(e,n,r,i)},e.closePath=function(){t.closePath(),this.__originalClosePath()},e.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}var Xu=class{constructor(e){this.canvasFactory=e,this.cache=Object.create(null)}getCanvas(e,t,n){let r;return this.cache[e]===void 0?(r=this.canvasFactory.create(t,n),this.cache[e]=r):(r=this.cache[e],this.canvasFactory.reset(r,t,n)),r}delete(e){delete this.cache[e]}clear(){for(let e in this.cache){let t=this.cache[e];this.canvasFactory.destroy(t),delete this.cache[e]}}};function Zu(e,t,n,r,i,a,o,s,c,l){let[u,d,f,p,m,h]=Z(e);if(d===0&&f===0){let g=o*u+m,_=Math.round(g),v=s*p+h,y=Math.round(v),b=(o+c)*u+m,x=Math.abs(Math.round(b)-_)||1,S=(s+l)*p+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(Math.sign(u),0,0,Math.sign(p),_,y),e.drawImage(t,n,r,i,a,0,0,x,C),e.setTransform(u,d,f,p,m,h),[x,C]}if(u===0&&p===0){let g=s*f+m,_=Math.round(g),v=o*d+h,y=Math.round(v),b=(s+l)*f+m,x=Math.abs(Math.round(b)-_)||1,S=(o+c)*d+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(0,Math.sign(d),Math.sign(f),0,_,y),e.drawImage(t,n,r,i,a,0,0,C,x),e.setTransform(u,d,f,p,m,h),[C,x]}e.drawImage(t,n,r,i,a,o,s,c,l);let g=Math.hypot(u,d),_=Math.hypot(f,p);return[g*c,_*l]}function Qu(e){let{width:t,height:n}=e;if(t>qu||n>qu)return null;let r=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),a=t+1,o=new Uint8Array(a*(n+1)),s,c,l,u=t+7&-8,d=new Uint8Array(u*n),f=0;for(let t of e.data){let e=128;for(;e>0;)d[f++]=t&e?0:255,e>>=1}let p=0;for(f=0,d[f]!==0&&(o[0]=1,++p),c=1;c<t;c++)d[f]!==d[f+1]&&(o[c]=d[f]?2:1,++p),f++;for(d[f]!==0&&(o[c]=2,++p),s=1;s<n;s++){f=s*u,l=s*a,d[f-u]!==d[f]&&(o[l]=d[f]?1:8,++p);let e=(d[f]?4:0)+(d[f-u]?8:0);for(c=1;c<t;c++)e=(e>>2)+(d[f+1]?4:0)+(d[f-u+1]?8:0),i[e]&&(o[l+c]=i[e],++p),f++;if(d[f-u]!==d[f]&&(o[l+c]=d[f]?2:4,++p),p>r)return null}for(f=u*(n-1),l=s*a,d[f]!==0&&(o[l]=8,++p),c=1;c<t;c++)d[f]!==d[f+1]&&(o[l+c]=d[f]?4:8,++p),f++;if(d[f]!==0&&(o[l+c]=4,++p),p>r)return null;let m=new Int32Array([0,a,-1,0,-a,0,0,0,1]),h=new Path2D;for(s=0;p&&s<=n;s++){let e=s*a,n=e+t;for(;e<n&&!o[e];)e++;if(e===n)continue;h.moveTo(e%a,s);let r=e,i=o[e];do{let t=m[i];do e+=t;while(!o[e]);let n=o[e];n!==5&&n!==10?(i=n,o[e]=0):(i=n&51*i>>4,o[e]&=i>>2|i<<2),h.lineTo(e%a,e/a|0),o[e]||--p}while(r!==e);--s}return d=null,o=null,function(e){e.save(),e.scale(1/t,-1/n),e.translate(0,-n),e.fill(h),e.beginPath(),e.restore()}}var $u=class{constructor(e,t){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Fc,this.textMatrixScale=1,this.fontMatrix=Ic,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=Uc.FILL,this.textRise=0,this.fillColor=`#000000`,this.strokeColor=`#000000`,this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps=`none`,this.startNewPathAndClipBox([0,0,e,t])}clone(){let e=Object.create(this);return e.clipBox=this.clipBox.slice(),e}setCurrentPoint(e,t){this.x=e,this.y=t}updatePathMinMax(e,t,n){[t,n]=X.applyTransform([t,n],e),this.minX=Math.min(this.minX,t),this.minY=Math.min(this.minY,n),this.maxX=Math.max(this.maxX,t),this.maxY=Math.max(this.maxY,n)}updateRectMinMax(e,t){let n=X.applyTransform(t,e),r=X.applyTransform(t.slice(2),e),i=X.applyTransform([t[0],t[3]],e),a=X.applyTransform([t[2],t[1]],e);this.minX=Math.min(this.minX,n[0],r[0],i[0],a[0]),this.minY=Math.min(this.minY,n[1],r[1],i[1],a[1]),this.maxX=Math.max(this.maxX,n[0],r[0],i[0],a[0]),this.maxY=Math.max(this.maxY,n[1],r[1],i[1],a[1])}updateScalingPathMinMax(e,t){X.scaleMinMax(e,t),this.minX=Math.min(this.minX,t[0]),this.minY=Math.min(this.minY,t[1]),this.maxX=Math.max(this.maxX,t[2]),this.maxY=Math.max(this.maxY,t[3])}updateCurvePathMinMax(e,t,n,r,i,a,o,s,c,l){let u=X.bezierBoundingBox(t,n,r,i,a,o,s,c,l);l||this.updateRectMinMax(e,u)}getPathBoundingBox(e=ju.FILL,t=null){let n=[this.minX,this.minY,this.maxX,this.maxY];if(e===ju.STROKE){t||J(`Stroke bounding box must include transform.`);let e=X.singularValueDecompose2dScale(t),r=e[0]*this.lineWidth/2,i=e[1]*this.lineWidth/2;n[0]-=r,n[1]-=i,n[2]+=r,n[3]+=i}return n}updateClipFromPath(){let e=X.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(e){this.clipBox=e,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(e=ju.FILL,t=null){return X.intersect(this.clipBox,this.getPathBoundingBox(e,t))}};function ed(e,t){if(t instanceof ImageData){e.putImageData(t,0,0);return}let n=t.height,r=t.width,i=n%Ju,a=(n-i)/Ju,o=i===0?a:a+1,s=e.createImageData(r,Ju),c=0,l,u=t.data,d=s.data,f,p,m,h;if(t.kind===Wc.GRAYSCALE_1BPP){let t=u.byteLength,n=new Uint32Array(d.buffer,0,d.byteLength>>2),h=n.length,g=r+7>>3,_=4294967295,v=_l.isLittleEndian?4278190080:255;for(f=0;f<o;f++){for(m=f<a?Ju:i,l=0,p=0;p<m;p++){let e=t-c,i=0,a=e>g?r:e*8-7,o=a&-8,s=0,d=0;for(;i<o;i+=8)d=u[c++],n[l++]=d&128?_:v,n[l++]=d&64?_:v,n[l++]=d&32?_:v,n[l++]=d&16?_:v,n[l++]=d&8?_:v,n[l++]=d&4?_:v,n[l++]=d&2?_:v,n[l++]=d&1?_:v;for(;i<a;i++)s===0&&(d=u[c++],s=128),n[l++]=d&s?_:v,s>>=1}for(;l<h;)n[l++]=0;e.putImageData(s,0,f*Ju)}}else if(t.kind===Wc.RGBA_32BPP){for(p=0,h=r*Ju*4,f=0;f<a;f++)d.set(u.subarray(c,c+h)),c+=h,e.putImageData(s,0,p),p+=Ju;f<o&&(h=r*i*4,d.set(u.subarray(c,c+h)),e.putImageData(s,0,p))}else if(t.kind===Wc.RGB_24BPP)for(m=Ju,h=r*m,f=0;f<o;f++){for(f>=a&&(m=i,h=r*m),l=0,p=h;p--;)d[l++]=u[c++],d[l++]=u[c++],d[l++]=u[c++],d[l++]=255;e.putImageData(s,0,f*Ju)}else throw Error(`bad image kind: ${t.kind}`)}function td(e,t){if(t.bitmap){e.drawImage(t.bitmap,0,0);return}let n=t.height,r=t.width,i=n%Ju,a=(n-i)/Ju,o=i===0?a:a+1,s=e.createImageData(r,Ju),c=0,l=t.data,u=s.data;for(let t=0;t<o;t++){let n=t<a?Ju:i;({srcPos:c}=Hu({src:l,srcPos:c,dest:u,width:r,height:n,nonBlackColor:0})),e.putImageData(s,0,t*Ju)}}function nd(e,t){for(let n of[`strokeStyle`,`fillStyle`,`fillRule`,`globalAlpha`,`lineWidth`,`lineCap`,`lineJoin`,`miterLimit`,`globalCompositeOperation`,`font`,`filter`])e[n]!==void 0&&(t[n]=e[n]);e.setLineDash!==void 0&&(t.setLineDash(e.getLineDash()),t.lineDashOffset=e.lineDashOffset)}function rd(e){if(e.strokeStyle=e.fillStyle=`#000000`,e.fillRule=`nonzero`,e.globalAlpha=1,e.lineWidth=1,e.lineCap=`butt`,e.lineJoin=`miter`,e.miterLimit=10,e.globalCompositeOperation=`source-over`,e.font=`10px sans-serif`,e.setLineDash!==void 0&&(e.setLineDash([]),e.lineDashOffset=0),!Pc){let{filter:t}=e;t!==`none`&&t!==``&&(e.filter=`none`)}}function id(e,t){if(t)return!0;let n=X.singularValueDecompose2dScale(e);n[0]=Math.fround(n[0]),n[1]=Math.fround(n[1]);let r=Math.fround((globalThis.devicePixelRatio||1)*Dl.PDF_TO_CSS_UNITS);return n[0]<=r&&n[1]<=r}var ad=[`butt`,`round`,`square`],od=[`miter`,`round`,`bevel`],sd={},cd={},ld=class e{constructor(e,t,n,r,i,{optionalContentConfig:a,markedContentStack:o=null},s,c){this.ctx=e,this.current=new $u(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=t,this.objs=n,this.canvasFactory=r,this.filterFactory=i,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=a,this.cachedCanvases=new Xu(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=s,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(e,t=null){return typeof e==`string`?e.startsWith(`g_`)?this.commonObjs.get(e):this.objs.get(e):t}beginDrawing({transform:e,viewport:t,transparency:n=!1,background:r=null}){let i=this.ctx.canvas.width,a=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=r||`#ffffff`,this.ctx.fillRect(0,0,i,a),this.ctx.fillStyle=o,n){let e=this.cachedCanvases.getCanvas(`transparent`,i,a);this.compositeCtx=this.ctx,this.transparentCanvas=e.canvas,this.ctx=e.context,this.ctx.save(),this.ctx.transform(...Z(this.compositeCtx))}this.ctx.save(),rd(this.ctx),e&&(this.ctx.transform(...e),this.outputScaleX=e[0],this.outputScaleY=e[0]),this.ctx.transform(...t.transform),this.viewportScale=t.scale,this.baseTransform=Z(this.ctx)}executeOperatorList(e,t,n,r){let i=e.argsArray,a=e.fnArray,o=t||0,s=i.length;if(s===o)return o;let c=s-o>Ku&&typeof n==`function`,l=c?Date.now()+Gu:0,u=0,d=this.commonObjs,f=this.objs,p;for(;;){if(r!==void 0&&o===r.nextBreakPoint)return r.breakIt(o,n),o;if(p=a[o],p!==Jc.dependency)this[p].apply(this,i[o]);else for(let e of i[o]){let t=e.startsWith(`g_`)?d:f;if(!t.has(e))return t.get(e,n),o}if(o++,o===s)return o;if(c&&++u>Ku){if(Date.now()>l)return n(),o;u=0}}}#e(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&=(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),null)}endDrawing(){this.#e(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let e of this._cachedBitmapsMap.values()){for(let t of e.values())typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),this.#t()}#t(){if(this.pageColors){let e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!==`none`){let t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}}_scaleImage(e,t){let n=e.width??e.displayWidth,r=e.height??e.displayHeight,i=Math.max(Math.hypot(t[0],t[1]),1),a=Math.max(Math.hypot(t[2],t[3]),1),o=n,s=r,c=`prescale1`,l,u;for(;i>2&&o>1||a>2&&s>1;){let t=o,n=s;i>2&&o>1&&(t=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/t),a>2&&s>1&&(n=s>=16384?Math.floor(s/2)-1||1:Math.ceil(s)/2,a/=s/n),l=this.cachedCanvases.getCanvas(c,t,n),u=l.context,u.clearRect(0,0,t,n),u.drawImage(e,0,0,o,s,0,0,t,n),e=l.canvas,o=t,s=n,c=c===`prescale1`?`prescale2`:`prescale1`}return{img:e,paintWidth:o,paintHeight:s}}_createMaskCanvas(e){let t=this.ctx,{width:n,height:r}=e,i=this.current.fillColor,a=this.current.patternFill,o=Z(t),s,c,l,u;if((e.bitmap||e.data)&&e.count>1){let t=e.bitmap||e.data.buffer;c=JSON.stringify(a?o:[o.slice(0,4),i]),s=this._cachedBitmapsMap.get(t),s||(s=new Map,this._cachedBitmapsMap.set(t,s));let n=s.get(c);if(n&&!a)return{canvas:n,offsetX:Math.round(Math.min(o[0],o[2])+o[4]),offsetY:Math.round(Math.min(o[1],o[3])+o[5])};l=n}l||(u=this.cachedCanvases.getCanvas(`maskCanvas`,n,r),td(u.context,e));let d=X.transform(o,[1/n,0,0,-1/r,0,0]);d=X.transform(d,[1,0,0,1,0,-r]);let[f,p,m,h]=X.getAxialAlignedBoundingBox([0,0,n,r],d),g=Math.round(m-f)||1,_=Math.round(h-p)||1,v=this.cachedCanvases.getCanvas(`fillCanvas`,g,_),y=v.context,b=f,x=p;y.translate(-b,-x),y.transform(...d),l||(l=this._scaleImage(u.canvas,Ul(y)),l=l.img,s&&a&&s.set(c,l)),y.imageSmoothingEnabled=id(Z(y),e.interpolate),Zu(y,l,0,0,l.width,l.height,0,0,n,r),y.globalCompositeOperation=`source-in`;let S=X.transform(Ul(y),[1,0,0,1,-b,-x]);return y.fillStyle=a?i.getPattern(t,this,S,ju.FILL):i,y.fillRect(0,0,n,r),s&&!a&&(this.cachedCanvases.delete(`fillCanvas`),s.set(c,v.canvas)),{canvas:v.canvas,offsetX:Math.round(b),offsetY:Math.round(x)}}setLineWidth(e){e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(e){this.ctx.lineCap=ad[e]}setLineJoin(e){this.ctx.lineJoin=od[e]}setMiterLimit(e){this.ctx.miterLimit=e}setDash(e,t){let n=this.ctx;n.setLineDash!==void 0&&(n.setLineDash(e),n.lineDashOffset=t)}setRenderingIntent(e){}setFlatness(e){}setGState(e){for(let[t,n]of e)switch(t){case`LW`:this.setLineWidth(n);break;case`LC`:this.setLineCap(n);break;case`LJ`:this.setLineJoin(n);break;case`ML`:this.setMiterLimit(n);break;case`D`:this.setDash(n[0],n[1]);break;case`RI`:this.setRenderingIntent(n);break;case`FL`:this.setFlatness(n);break;case`Font`:this.setFont(n[0],n[1]);break;case`CA`:this.current.strokeAlpha=n;break;case`ca`:this.current.fillAlpha=n,this.ctx.globalAlpha=n;break;case`BM`:this.ctx.globalCompositeOperation=n;break;case`SMask`:this.current.activeSMask=n?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case`TR`:this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode():!this.current.activeSMask&&e&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw Error(`beginSMaskMode called while already in smask mode`);let e=this.ctx.canvas.width,t=this.ctx.canvas.height,n=`smaskGroupAt`+this.groupLevel,r=this.cachedCanvases.getCanvas(n,e,t);this.suspendedCtx=this.ctx,this.ctx=r.context;let i=this.ctx;i.setTransform(...Z(this.suspendedCtx)),nd(this.suspendedCtx,i),Yu(i,this.suspendedCtx),this.setGState([[`BM`,`source-over`],[`ca`,1],[`CA`,1]])}endSMaskMode(){if(!this.inSMaskMode)throw Error(`endSMaskMode called while not in smask mode`);this.ctx._removeMirroring(),nd(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(e){if(!this.current.activeSMask)return;e?(e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])):e=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let t=this.current.activeSMask,n=this.suspendedCtx;this.composeSMask(n,t,this.ctx,e),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(e,t,n,r){let i=r[0],a=r[1],o=r[2]-i,s=r[3]-a;o===0||s===0||(this.genericComposeSMask(t.context,n,o,s,t.subtype,t.backdrop,t.transferMap,i,a,t.offsetX,t.offsetY),e.save(),e.globalAlpha=1,e.globalCompositeOperation=`source-over`,e.setTransform(1,0,0,1,0,0),e.drawImage(n.canvas,0,0),e.restore())}genericComposeSMask(e,t,n,r,i,a,o,s,c,l,u){let d=e.canvas,f=s-l,p=c-u;if(a){let t=X.makeHexColor(...a);if(f<0||p<0||f+n>d.width||p+r>d.height){let e=this.cachedCanvases.getCanvas(`maskExtension`,n,r),i=e.context;i.drawImage(d,-f,-p),i.globalCompositeOperation=`destination-atop`,i.fillStyle=t,i.fillRect(0,0,n,r),i.globalCompositeOperation=`source-over`,d=e.canvas,f=p=0}else{e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);let i=new Path2D;i.rect(f,p,n,r),e.clip(i),e.globalCompositeOperation=`destination-atop`,e.fillStyle=t,e.fillRect(f,p,n,r),e.restore()}}t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0),i===`Alpha`&&o?t.filter=this.filterFactory.addAlphaFilter(o):i===`Luminosity`&&(t.filter=this.filterFactory.addLuminosityFilter(o));let m=new Path2D;m.rect(s,c,n,r),t.clip(m),t.globalCompositeOperation=`destination-in`,t.drawImage(d,f,p,n,r,s,c,n,r),t.restore()}save(){this.inSMaskMode?(nd(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let e=this.current;this.stateStack.push(e),this.current=e.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),nd(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(e,t,n,r,i,a){this.ctx.transform(e,t,n,r,i,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,n){let r=this.ctx,i=this.current,a=i.x,o=i.y,s,c,l=Z(r),u=l[0]===0&&l[3]===0||l[1]===0&&l[2]===0,d=u?n.slice(0):null;for(let n=0,f=0,p=e.length;n<p;n++)switch(e[n]|0){case Jc.rectangle:a=t[f++],o=t[f++];let e=t[f++],n=t[f++],p=a+e,m=o+n;r.moveTo(a,o),e===0||n===0?r.lineTo(p,m):(r.lineTo(p,o),r.lineTo(p,m),r.lineTo(a,m)),u||i.updateRectMinMax(l,[a,o,p,m]),r.closePath();break;case Jc.moveTo:a=t[f++],o=t[f++],r.moveTo(a,o),u||i.updatePathMinMax(l,a,o);break;case Jc.lineTo:a=t[f++],o=t[f++],r.lineTo(a,o),u||i.updatePathMinMax(l,a,o);break;case Jc.curveTo:s=a,c=o,a=t[f+4],o=t[f+5],r.bezierCurveTo(t[f],t[f+1],t[f+2],t[f+3],a,o),i.updateCurvePathMinMax(l,s,c,t[f],t[f+1],t[f+2],t[f+3],a,o,d),f+=6;break;case Jc.curveTo2:s=a,c=o,r.bezierCurveTo(a,o,t[f],t[f+1],t[f+2],t[f+3]),i.updateCurvePathMinMax(l,s,c,a,o,t[f],t[f+1],t[f+2],t[f+3],d),a=t[f+2],o=t[f+3],f+=4;break;case Jc.curveTo3:s=a,c=o,a=t[f+2],o=t[f+3],r.bezierCurveTo(t[f],t[f+1],a,o,a,o),i.updateCurvePathMinMax(l,s,c,t[f],t[f+1],a,o,a,o,d),f+=4;break;case Jc.closePath:r.closePath();break}u&&i.updateScalingPathMinMax(l,d),i.setCurrentPoint(a,o)}closePath(){this.ctx.closePath()}stroke(e=!0){let t=this.ctx,n=this.current.strokeColor;t.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof n==`object`&&n?.getPattern?(t.save(),t.strokeStyle=n.getPattern(t,this,Ul(t),ju.STROKE),this.rescaleAndStroke(!1),t.restore()):this.rescaleAndStroke(!0)),e&&this.consumePath(this.current.getClippedPathBoundingBox()),t.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(e=!0){let t=this.ctx,n=this.current.fillColor,r=this.current.patternFill,i=!1;r&&(t.save(),t.fillStyle=n.getPattern(t,this,Ul(t),ju.FILL),i=!0);let a=this.current.getClippedPathBoundingBox();this.contentVisible&&a!==null&&(this.pendingEOFill?(t.fill(`evenodd`),this.pendingEOFill=!1):t.fill()),i&&t.restore(),e&&this.consumePath(a)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=sd}eoClip(){this.pendingClip=cd}beginText(){this.current.textMatrix=Fc,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let e=this.pendingTextPaths,t=this.ctx;if(e===void 0){t.beginPath();return}let n=new Path2D,r=t.getTransform().invertSelf();for(let{transform:t,x:i,y:a,fontSize:o,path:s}of e)n.addPath(s,new DOMMatrix(t).preMultiplySelf(r).translate(i,a).scale(o,-o));t.clip(n),t.beginPath(),delete this.pendingTextPaths}setCharSpacing(e){this.current.charSpacing=e}setWordSpacing(e){this.current.wordSpacing=e}setHScale(e){this.current.textHScale=e/100}setLeading(e){this.current.leading=-e}setFont(e,t){let n=this.commonObjs.get(e),r=this.current;if(!n)throw Error(`Can't find font for ${e}`);if(r.fontMatrix=n.fontMatrix||Ic,(r.fontMatrix[0]===0||r.fontMatrix[3]===0)&&q(`Invalid font matrix for font `+e),t<0?(t=-t,r.fontDirection=-1):r.fontDirection=1,this.current.font=n,this.current.fontSize=t,n.isType3Font)return;let i=n.loadedName||`sans-serif`,a=n.systemFontInfo?.css||`"${i}", ${n.fallbackName}`,o=`normal`;n.black?o=`900`:n.bold&&(o=`bold`);let s=n.italic?`italic`:`normal`,c=t;t<Uu?c=Uu:t>Wu&&(c=Wu),this.current.fontSizeScale=t/c,this.ctx.font=`${s} ${o} ${c}px ${a}`}setTextRenderingMode(e){this.current.textRenderingMode=e}setTextRise(e){this.current.textRise=e}moveText(e,t){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=t}setLeadingMoveText(e,t){this.setLeading(-t),this.moveText(e,t)}setTextMatrix(e,t,n,r,i,a){this.current.textMatrix=[e,t,n,r,i,a],this.current.textMatrixScale=Math.hypot(e,t),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#n(e,t,n){let r=new Path2D;return r.addPath(e,new DOMMatrix(n).invertSelf().multiplySelf(t)),r}paintChar(e,t,n,r,i){let a=this.ctx,o=this.current,s=o.font,c=o.textRenderingMode,l=o.fontSize/o.fontSizeScale,u=c&Uc.FILL_STROKE_MASK,d=!!(c&Uc.ADD_TO_PATH_FLAG),f=o.patternFill&&!s.missingFile,p=o.patternStroke&&!s.missingFile,m;if((s.disableFontFace||d||f||p)&&(m=s.getPathGenerator(this.commonObjs,e)),s.disableFontFace||f||p){if(a.save(),a.translate(t,n),a.scale(l,-l),u===Uc.FILL||u===Uc.FILL_STROKE)if(r){let e=a.getTransform();a.setTransform(...r),a.fill(this.#n(m,e,r))}else a.fill(m);if(u===Uc.STROKE||u===Uc.FILL_STROKE)if(i){let e=a.getTransform();a.setTransform(...i),a.stroke(this.#n(m,e,i))}else a.lineWidth/=l,a.stroke(m);a.restore()}else(u===Uc.FILL||u===Uc.FILL_STROKE)&&a.fillText(e,t,n),(u===Uc.STROKE||u===Uc.FILL_STROKE)&&a.strokeText(e,t,n);d&&(this.pendingTextPaths||=[]).push({transform:Z(a),x:t,y:n,fontSize:l,path:m})}get isFontSubpixelAAEnabled(){let{context:e}=this.cachedCanvases.getCanvas(`isFontSubpixelAAEnabled`,10,10);e.scale(1.5,1),e.fillText(`I`,0,10);let t=e.getImageData(0,0,10,10).data,n=!1;for(let e=3;e<t.length;e+=4)if(t[e]>0&&t[e]<255){n=!0;break}return Y(this,`isFontSubpixelAAEnabled`,n)}showText(e){let t=this.current,n=t.font;if(n.isType3Font)return this.showType3Text(e);let r=t.fontSize;if(r===0)return;let i=this.ctx,a=t.fontSizeScale,o=t.charSpacing,s=t.wordSpacing,c=t.fontDirection,l=t.textHScale*c,u=e.length,d=n.vertical,f=d?1:-1,p=n.defaultVMetrics,m=r*t.fontMatrix[0],h=t.textRenderingMode===Uc.FILL&&!n.disableFontFace&&!t.patternFill;i.save(),i.transform(...t.textMatrix),i.translate(t.x,t.y+t.textRise),c>0?i.scale(l,-1):i.scale(l,1);let g,_;if(t.patternFill){i.save();let e=t.fillColor.getPattern(i,this,Ul(i),ju.FILL);g=Z(i),i.restore(),i.fillStyle=e}if(t.patternStroke){i.save();let e=t.strokeColor.getPattern(i,this,Ul(i),ju.STROKE);_=Z(i),i.restore(),i.strokeStyle=e}let v=t.lineWidth,y=t.textMatrixScale;if(y===0||v===0){let e=t.textRenderingMode&Uc.FILL_STROKE_MASK;(e===Uc.STROKE||e===Uc.FILL_STROKE)&&(v=this.getSinglePixelWidth())}else v/=y;if(a!==1&&(i.scale(a,a),v/=a),i.lineWidth=v,n.isInvalidPDFjsFont){let n=[],r=0;for(let t of e)n.push(t.unicode),r+=t.width;i.fillText(n.join(``),0,0),t.x+=r*m*l,i.restore(),this.compose();return}let b=0,x;for(x=0;x<u;++x){let t=e[x];if(typeof t==`number`){b+=f*t*r/1e3;continue}let l=!1,u=(t.isSpace?s:0)+o,v=t.fontChar,y=t.accent,S,C,w=t.width;if(d){let e=t.vmetric||p,n=-(t.vmetric?e[1]:w*.5)*m,r=e[2]*m;w=e?-e[0]:w,S=n/a,C=(b+r)/a}else S=b/a,C=0;if(n.remeasure&&w>0){let e=i.measureText(v).width*1e3/r*a;if(w<e&&this.isFontSubpixelAAEnabled){let t=w/e;l=!0,i.save(),i.scale(t,1),S/=t}else w!==e&&(S+=(w-e)/2e3*r/a)}if(this.contentVisible&&(t.isInFont||n.missingFile)){if(h&&!y)i.fillText(v,S,C);else if(this.paintChar(v,S,C,g,_),y){let e=S+r*y.offset.x/a,t=C-r*y.offset.y/a;this.paintChar(y.fontChar,e,t,g,_)}}let T=d?w*m-u*c:w*m+u*c;b+=T,l&&i.restore()}d?t.y-=b:t.x+=b*l,i.restore(),this.compose()}showType3Text(e){let t=this.ctx,n=this.current,r=n.font,i=n.fontSize,a=n.fontDirection,o=r.vertical?1:-1,s=n.charSpacing,c=n.wordSpacing,l=n.textHScale*a,u=n.fontMatrix||Ic,d=e.length,f=n.textRenderingMode===Uc.INVISIBLE,p,m,h,g;if(!(f||i===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,t.save(),t.transform(...n.textMatrix),t.translate(n.x,n.y),t.scale(l,a),p=0;p<d;++p){if(m=e[p],typeof m==`number`){g=o*m*i/1e3,this.ctx.translate(g,0),n.x+=g*l;continue}let a=(m.isSpace?c:0)+s,d=r.charProcOperatorList[m.operatorListId];if(!d){q(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),t.scale(i,i),t.transform(...u),this.executeOperatorList(d),this.restore()),h=X.applyTransform([m.width,0],u)[0]*i+a,t.translate(h,0),n.x+=h*l}t.restore(),this.processingType3=null}}setCharWidth(e,t){}setCharWidthAndBounds(e,t,n,r,i,a){this.ctx.rect(n,r,i-n,a-r),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let n;if(t[0]===`TilingPattern`){let r=t[1],i=this.baseTransform||Z(this.ctx);n=new Vu(t,r,this.ctx,{createCanvasGraphics:t=>new e(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})},i)}else n=this._getPattern(t[1],t[2]);return n}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(e,t,n){this.ctx.strokeStyle=this.current.strokeColor=X.makeHexColor(e,t,n),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor=`transparent`,this.current.patternStroke=!1}setFillRGBColor(e,t,n){this.ctx.fillStyle=this.current.fillColor=X.makeHexColor(e,t,n),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor=`transparent`,this.current.patternFill=!1}_getPattern(e,t=null){let n;return this.cachedPatterns.has(e)?n=this.cachedPatterns.get(e):(n=zu(this.getObject(e)),this.cachedPatterns.set(e,n)),t&&(n.matrix=t),n}shadingFill(e){if(!this.contentVisible)return;let t=this.ctx;this.save(),t.fillStyle=this._getPattern(e).getPattern(t,this,Ul(t),ju.SHADING);let n=Ul(t);if(n){let{width:e,height:r}=t.canvas,[i,a,o,s]=X.getAxialAlignedBoundingBox([0,0,e,r],n);this.ctx.fillRect(i,a,o-i,s-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){J(`Should not call beginInlineImage`)}beginImageData(){J(`Should not call beginImageData`)}paintFormXObjectBegin(e,t){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),e&&this.transform(...e),this.baseTransform=Z(this.ctx),t)){let e=t[2]-t[0],n=t[3]-t[1];this.ctx.rect(t[0],t[1],e,n),this.current.updateRectMinMax(Z(this.ctx),t),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let t=this.ctx;e.isolated||$c(`TODO: Support non-isolated groups.`),e.knockout&&q(`Knockout groups not supported.`);let n=Z(t);if(e.matrix&&t.transform(...e.matrix),!e.bbox)throw Error(`Bounding box is required.`);let r=X.getAxialAlignedBoundingBox(e.bbox,Z(t)),i=[0,0,t.canvas.width,t.canvas.height];r=X.intersect(r,i)||[0,0,0,0];let a=Math.floor(r[0]),o=Math.floor(r[1]),s=Math.max(Math.ceil(r[2])-a,1),c=Math.max(Math.ceil(r[3])-o,1);this.current.startNewPathAndClipBox([0,0,s,c]);let l=`groupAt`+this.groupLevel;e.smask&&(l+=`_smask_`+this.smaskCounter++%2);let u=this.cachedCanvases.getCanvas(l,s,c),d=u.context;d.translate(-a,-o),d.transform(...n),e.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(t.setTransform(1,0,0,1,0,0),t.translate(a,o),t.save()),nd(t,d),this.ctx=d,this.setGState([[`BM`,`source-over`],[`ca`,1],[`CA`,1]]),this.groupStack.push(t),this.groupLevel++}endGroup(e){if(!this.contentVisible)return;this.groupLevel--;let t=this.ctx,n=this.groupStack.pop();if(this.ctx=n,this.ctx.imageSmoothingEnabled=!1,e.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let e=Z(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...e);let n=X.getAxialAlignedBoundingBox([0,0,t.canvas.width,t.canvas.height],e);this.ctx.drawImage(t.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(e,t,n,r,i){if(this.#e(),rd(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),t){let r=t[2]-t[0],a=t[3]-t[1];if(i&&this.annotationCanvasMap){n=n.slice(),n[4]-=t[0],n[5]-=t[1],t=t.slice(),t[0]=t[1]=0,t[2]=r,t[3]=a;let[i,o]=X.singularValueDecompose2dScale(Z(this.ctx)),{viewportScale:s}=this,c=Math.ceil(r*this.outputScaleX*s),l=Math.ceil(a*this.outputScaleY*s);this.annotationCanvas=this.canvasFactory.create(c,l);let{canvas:u,context:d}=this.annotationCanvas;this.annotationCanvasMap.set(e,u),this.annotationCanvas.savedCtx=this.ctx,this.ctx=d,this.ctx.save(),this.ctx.setTransform(i,0,0,-o,0,a*o),rd(this.ctx)}else rd(this.ctx),this.endPath(),this.ctx.rect(t[0],t[1],r,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new $u(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...n),this.transform(...r)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#t(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(e){if(!this.contentVisible)return;let t=e.count;e=this.getObject(e.data,e),e.count=t;let n=this.ctx,r=this.processingType3;if(r&&(r.compiled===void 0&&(r.compiled=Qu(e)),r.compiled)){r.compiled(n);return}let i=this._createMaskCanvas(e),a=i.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(a,i.offsetX,i.offsetY),n.restore(),this.compose()}paintImageMaskXObjectRepeat(e,t,n=0,r=0,i,a){if(!this.contentVisible)return;e=this.getObject(e.data,e);let o=this.ctx;o.save();let s=Z(o);o.transform(t,n,r,i,0,0);let c=this._createMaskCanvas(e);o.setTransform(1,0,0,1,c.offsetX-s[4],c.offsetY-s[5]);for(let e=0,l=a.length;e<l;e+=2){let l=X.transform(s,[t,n,r,i,a[e],a[e+1]]),[u,d]=X.applyTransform([0,0],l);o.drawImage(c.canvas,u,d)}o.restore(),this.compose()}paintImageMaskXObjectGroup(e){if(!this.contentVisible)return;let t=this.ctx,n=this.current.fillColor,r=this.current.patternFill;for(let i of e){let{data:e,width:a,height:o,transform:s}=i,c=this.cachedCanvases.getCanvas(`maskCanvas`,a,o),l=c.context;l.save(),td(l,this.getObject(e,i)),l.globalCompositeOperation=`source-in`,l.fillStyle=r?n.getPattern(l,this,Ul(t),ju.FILL):n,l.fillRect(0,0,a,o),l.restore(),t.save(),t.transform(...s),t.scale(1,-1),Zu(t,c.canvas,0,0,a,o,0,-1,1,1),t.restore()}this.compose()}paintImageXObject(e){if(!this.contentVisible)return;let t=this.getObject(e);if(!t){q(`Dependent image isn't ready yet`);return}this.paintInlineImageXObject(t)}paintImageXObjectRepeat(e,t,n,r){if(!this.contentVisible)return;let i=this.getObject(e);if(!i){q(`Dependent image isn't ready yet`);return}let a=i.width,o=i.height,s=[];for(let e=0,i=r.length;e<i;e+=2)s.push({transform:[t,0,0,n,r[e],r[e+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(i,s)}applyTransferMapsToCanvas(e){return this.current.transferMaps!==`none`&&(e.filter=this.current.transferMaps,e.drawImage(e.canvas,0,0),e.filter=`none`),e.canvas}applyTransferMapsToBitmap(e){if(this.current.transferMaps===`none`)return e.bitmap;let{bitmap:t,width:n,height:r}=e,i=this.cachedCanvases.getCanvas(`inlineImage`,n,r),a=i.context;return a.filter=this.current.transferMaps,a.drawImage(t,0,0),a.filter=`none`,i.canvas}paintInlineImageXObject(e){if(!this.contentVisible)return;let t=e.width,n=e.height,r=this.ctx;if(this.save(),!Pc){let{filter:e}=r;e!==`none`&&e!==``&&(r.filter=`none`)}r.scale(1/t,-1/n);let i;if(e.bitmap)i=this.applyTransferMapsToBitmap(e);else if(typeof HTMLElement==`function`&&e instanceof HTMLElement||!e.data)i=e;else{let r=this.cachedCanvases.getCanvas(`inlineImage`,t,n).context;ed(r,e),i=this.applyTransferMapsToCanvas(r)}let a=this._scaleImage(i,Ul(r));r.imageSmoothingEnabled=id(Z(r),e.interpolate),Zu(r,a.img,0,0,a.paintWidth,a.paintHeight,0,-n,t,n),this.compose(),this.restore()}paintInlineImageXObjectGroup(e,t){if(!this.contentVisible)return;let n=this.ctx,r;if(e.bitmap)r=e.bitmap;else{let t=e.width,n=e.height,i=this.cachedCanvases.getCanvas(`inlineImage`,t,n).context;ed(i,e),r=this.applyTransferMapsToCanvas(i)}for(let e of t)n.save(),n.transform(...e.transform),n.scale(1,-1),Zu(n,r,e.x,e.y,e.w,e.h,0,-1,1,1),n.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(e){}markPointProps(e,t){}beginMarkedContent(e){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(e,t){e===`OC`?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(t)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(e){let t=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(e);let n=this.ctx;this.pendingClip&&=(t||(this.pendingClip===cd?n.clip(`evenodd`):n.clip()),null),this.current.startNewPathAndClipBox(this.current.clipBox),n.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let e=Z(this.ctx);if(e[1]===0&&e[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(e[0]),Math.abs(e[3]));else{let t=Math.abs(e[0]*e[3]-e[2]*e[1]),n=Math.hypot(e[0],e[2]),r=Math.hypot(e[1],e[3]);this._cachedGetSinglePixelWidth=Math.max(n,r)/t}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:e}=this.current,{a:t,b:n,c:r,d:i}=this.ctx.getTransform(),a,o;if(n===0&&r===0){let n=Math.abs(t),r=Math.abs(i);if(n===r)if(e===0)a=o=1/n;else{let t=n*e;a=o=t<1?1/t:1}else if(e===0)a=1/n,o=1/r;else{let t=n*e,i=r*e;a=t<1?1/t:1,o=i<1?1/i:1}}else{let s=Math.abs(t*i-n*r),c=Math.hypot(t,n),l=Math.hypot(r,i);if(e===0)a=l/s,o=c/s;else{let t=e*s;a=l>t?l/t:1,o=c>t?c/t:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(e){let{ctx:t}=this,{lineWidth:n}=this.current,[r,i]=this.getScaleForStroking();if(t.lineWidth=n||1,r===1&&i===1){t.stroke();return}let a=t.getLineDash();if(e&&t.save(),t.scale(r,i),a.length>0){let e=Math.max(r,i);t.setLineDash(a.map(t=>t/e)),t.lineDashOffset/=e}t.stroke(),e&&t.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};for(let e in Jc)ld.prototype[e]!==void 0&&(ld.prototype[Jc[e]]=ld.prototype[e]);var ud=class{static#e=null;static#t=``;static get workerPort(){return this.#e}static set workerPort(e){if(!(typeof Worker<`u`&&e instanceof Worker)&&e!==null)throw Error("Invalid `workerPort` type.");this.#e=e}static get workerSrc(){return this.#t}static set workerSrc(e){if(typeof e!=`string`)throw Error("Invalid `workerSrc` type.");this.#t=e}},dd=class{#e;#t;constructor({parsedData:e,rawData:t}){this.#e=e,this.#t=t}getRaw(){return this.#t}get(e){return this.#e.get(e)??null}getAll(){return ml(this.#e)}has(e){return this.#e.has(e)}},fd=Symbol(`INTERNAL`),pd=class{#e=!1;#t=!1;#n=!1;#r=!0;constructor(e,{name:t,intent:n,usage:r,rbGroups:i}){this.#e=!!(e&zc.DISPLAY),this.#t=!!(e&zc.PRINT),this.name=t,this.intent=n,this.usage=r,this.rbGroups=i}get visible(){if(this.#n)return this.#r;if(!this.#r)return!1;let{print:e,view:t}=this.usage;return this.#e?t?.viewState!==`OFF`:!this.#t||e?.printState!==`OFF`}_setVisible(e,t,n=!1){e!==fd&&J("Internal method `_setVisible` called."),this.#n=n,this.#r=t}},md=class{#e=null;#t=new Map;#n=null;#r=null;constructor(e,t=zc.DISPLAY){if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,this.#r=e.order;for(let n of e.groups)this.#t.set(n.id,new pd(t,n));if(e.baseState===`OFF`)for(let e of this.#t.values())e._setVisible(fd,!1);for(let t of e.on)this.#t.get(t)._setVisible(fd,!0);for(let t of e.off)this.#t.get(t)._setVisible(fd,!1);this.#n=this.getHash()}}#i(e){let t=e.length;if(t<2)return!0;let n=e[0];for(let r=1;r<t;r++){let t=e[r],i;if(Array.isArray(t))i=this.#i(t);else if(this.#t.has(t))i=this.#t.get(t).visible;else return q(`Optional content group not found: ${t}`),!0;switch(n){case`And`:if(!i)return!1;break;case`Or`:if(i)return!0;break;case`Not`:return!i;default:return!0}}return n===`And`}isVisible(e){if(this.#t.size===0)return!0;if(!e)return $c(`Optional content group not defined.`),!0;if(e.type===`OCG`)return this.#t.has(e.id)?this.#t.get(e.id).visible:(q(`Optional content group not found: ${e.id}`),!0);if(e.type===`OCMD`){if(e.expression)return this.#i(e.expression);if(!e.policy||e.policy===`AnyOn`){for(let t of e.ids){if(!this.#t.has(t))return q(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!0}return!1}else if(e.policy===`AllOn`){for(let t of e.ids){if(!this.#t.has(t))return q(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!1}return!0}else if(e.policy===`AnyOff`){for(let t of e.ids){if(!this.#t.has(t))return q(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!0}return!1}else if(e.policy===`AllOff`){for(let t of e.ids){if(!this.#t.has(t))return q(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!1}return!0}return q(`Unknown optional content policy ${e.policy}.`),!0}return q(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,n=!0){let r=this.#t.get(e);if(!r){q(`Optional content group not found: ${e}`);return}if(n&&t&&r.rbGroups.length)for(let t of r.rbGroups)for(let n of t)n!==e&&this.#t.get(n)?._setVisible(fd,!1,!0);r._setVisible(fd,!!t,!0),this.#e=null}setOCGState({state:e,preserveRB:t}){let n;for(let r of e){switch(r){case`ON`:case`OFF`:case`Toggle`:n=r;continue}let e=this.#t.get(r);if(e)switch(n){case`ON`:this.setVisibility(r,!0,t);break;case`OFF`:this.setVisibility(r,!1,t);break;case`Toggle`:this.setVisibility(r,!e.visible,t);break}}this.#e=null}get hasInitialVisibility(){return this.#n===null||this.getHash()===this.#n}getOrder(){return this.#t.size?this.#r?this.#r.slice():[...this.#t.keys()]:null}getGroups(){return this.#t.size>0?ml(this.#t):null}getGroup(e){return this.#t.get(e)||null}getHash(){if(this.#e!==null)return this.#e;let e=new su;for(let[t,n]of this.#t)e.update(`${t}:${n.visible}`);return this.#e=e.hexdigest()}},hd=class{constructor(e,{disableRange:t=!1,disableStream:n=!1}){el(e,`PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.`);let{length:r,initialData:i,progressiveDone:a,contentDispositionFilename:o}=e;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=o,i?.length>0){let e=i instanceof Uint8Array&&i.byteLength===i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer;this._queuedChunks.push(e)}this._pdfDataRangeTransport=e,this._isStreamingSupported=!n,this._isRangeSupported=!t,this._contentLength=r,this._fullRequestReader=null,this._rangeReaders=[],e.addRangeListener((e,t)=>{this._onReceiveData({begin:e,chunk:t})}),e.addProgressListener((e,t)=>{this._onProgress({loaded:e,total:t})}),e.addProgressiveReadListener(e=>{this._onReceiveData({chunk:e})}),e.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),e.transportReady()}_onReceiveData({begin:e,chunk:t}){let n=t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer;e===void 0?this._fullRequestReader?this._fullRequestReader._enqueue(n):this._queuedChunks.push(n):el(this._rangeReaders.some(function(t){return t._begin===e?(t._enqueue(n),!0):!1}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(e){e.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:e.loaded}):this._fullRequestReader?.onProgress?.({loaded:e.loaded,total:e.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(e){let t=this._rangeReaders.indexOf(e);t>=0&&this._rangeReaders.splice(t,1)}getFullReader(){el(!this._fullRequestReader,`PDFDataTransportStream.getFullReader can only be called once.`);let e=this._queuedChunks;return this._queuedChunks=null,new gd(this,e,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new _d(this,e,t);return this._pdfDataRangeTransport.requestDataRange(e,t),this._rangeReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeReaders.slice(0))t.cancel(e);this._pdfDataRangeTransport.abort()}},gd=class{constructor(e,t,n=!1,r=null){this._stream=e,this._done=n||!1,this._filename=Ml(r)?r:null,this._queuedChunks=t||[],this._loaded=0;for(let e of this._queuedChunks)this._loaded+=e.byteLength;this._requests=[],this._headersReady=Promise.resolve(),e._fullRequestReader=this,this.onProgress=null}_enqueue(e){this._done||(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunks.push(e),this._loaded+=e.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||=!0}},_d=class{constructor(e,t,n){this._stream=e,this._begin=t,this._end=n,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(e){if(!this._done){if(this._requests.length===0)this._queuedChunk=e;else{this._requests.shift().resolve({value:e,done:!1});for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}};function vd(e){let t=!0,n=r(`filename\\*`,`i`).exec(e);if(n){n=n[1];let e=s(n);return e=unescape(e),e=c(e),e=l(e),a(e)}if(n=o(e),n)return a(l(n));if(n=r(`filename`,`i`).exec(e),n){n=n[1];let e=s(n);return e=l(e),a(e)}function r(e,t){return RegExp(`(?:^|;)\\s*`+e+`\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)`,t)}function i(e,n){if(e){if(!/^[\x00-\xFF]+$/.test(n))return n;try{let r=new TextDecoder(e,{fatal:!0}),i=fl(n);n=r.decode(i),t=!1}catch{}}return n}function a(e){return t&&/[\x80-\xff]/.test(e)&&(e=i(`utf-8`,e),t&&(e=i(`iso-8859-1`,e))),e}function o(e){let t=[],n,i=r(`filename\\*((?!0\\d)\\d+)(\\*?)`,`ig`);for(;(n=i.exec(e))!==null;){let[,e,r,i]=n;if(e=parseInt(e,10),e in t){if(e===0)break;continue}t[e]=[r,i]}let a=[];for(let e=0;e<t.length&&e in t;++e){let[n,r]=t[e];r=s(r),n&&(r=unescape(r),e===0&&(r=c(r))),a.push(r)}return a.join(``)}function s(e){if(e.startsWith(`"`)){let t=e.slice(1).split(`\\"`);for(let e=0;e<t.length;++e){let n=t[e].indexOf(`"`);n!==-1&&(t[e]=t[e].slice(0,n),t.length=e+1),t[e]=t[e].replaceAll(/\\(.)/g,`$1`)}e=t.join(`"`)}return e}function c(e){let t=e.indexOf(`'`);return t===-1?e:i(e.slice(0,t),e.slice(t+1).replace(/^[^']*'/,``))}function l(e){return!e.startsWith(`=?`)||/[\x00-\x19\x80-\xff]/.test(e)?e:e.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(e,t,n,r){if(n===`q`||n===`Q`)return r=r.replaceAll(`_`,` `),r=r.replaceAll(/=([0-9a-fA-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))}),i(t,r);try{r=atob(r)}catch{}return i(t,r)})}return``}function yd(e,t){let n=new Headers;if(!e||!t||typeof t!=`object`)return n;for(let e in t){let r=t[e];r!==void 0&&n.append(e,r)}return n}function bd(e){try{return new URL(e).origin}catch{}return null}function xd({responseHeaders:e,isHttp:t,rangeChunkSize:n,disableRange:r}){let i={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(e.get(`Content-Length`),10);return!Number.isInteger(a)||(i.suggestedLength=a,a<=2*n)||r||!t||e.get(`Accept-Ranges`)!==`bytes`||(e.get(`Content-Encoding`)||`identity`)!==`identity`||(i.allowRangeRequests=!0),i}function Sd(e){let t=e.get(`Content-Disposition`);if(t){let e=vd(t);if(e.includes(`%`))try{e=decodeURIComponent(e)}catch{}if(Ml(e))return e}return null}function Cd(e,t){return e===404||e===0&&t.startsWith(`file:`)?new sl(`Missing PDF "`+t+`".`):new cl(`Unexpected server response (${e}) while retrieving PDF "${t}".`,e)}function wd(e){return e===200||e===206}function Td(e,t,n){return{method:`GET`,headers:e,signal:n.signal,mode:`cors`,credentials:t?`include`:`same-origin`,redirect:`follow`}}function Ed(e){return e instanceof Uint8Array?e.buffer:e instanceof ArrayBuffer?e:(q(`getArrayBuffer - unexpected data format: ${e}`),new Uint8Array(e).buffer)}var Dd=class{_responseOrigin=null;constructor(e){this.source=e,this.isHttp=/^https?:/i.test(e.url),this.headers=yd(this.isHttp,e.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return el(!this._fullRequestReader,`PDFFetchStream.getFullReader can only be called once.`),this._fullRequestReader=new Od(this),this._fullRequestReader}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new kd(this,e,t);return this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Od=class{constructor(e){this._stream=e,this._reader=null,this._loaded=0,this._filename=null;let t=e.source;this._withCredentials=t.withCredentials||!1,this._contentLength=t.length,this._headersCapability=Promise.withResolvers(),this._disableRange=t.disableRange||!1,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!t.disableStream,this._isRangeSupported=!t.disableRange;let n=new Headers(e.headers),r=t.url;fetch(r,Td(n,this._withCredentials,this._abortController)).then(t=>{if(e._responseOrigin=bd(t.url),!wd(t.status))throw Cd(t.status,r);this._reader=t.body.getReader(),this._headersCapability.resolve();let n=t.headers,{allowRangeRequests:i,suggestedLength:a}=xd({responseHeaders:n,isHttp:e.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=i,this._contentLength=a||this._contentLength,this._filename=Sd(n),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ul(`Streaming is disabled.`))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Ed(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},kd=class{constructor(e,t,n){this._stream=e,this._reader=null,this._loaded=0;let r=e.source;this._withCredentials=r.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!r.disableStream,this._abortController=new AbortController;let i=new Headers(e.headers);i.append(`Range`,`bytes=${t}-${n-1}`);let a=r.url;fetch(a,Td(i,this._withCredentials,this._abortController)).then(t=>{let n=bd(t.url);if(n!==e._responseOrigin)throw Error(`Expected range response-origin "${n}" to match "${e._responseOrigin}".`);if(!wd(t.status))throw Cd(t.status,a);this._readCapability.resolve(),this._reader=t.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Ed(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},Ad=200,jd=206;function Md(e){let t=e.response;return typeof t==`string`?fl(t).buffer:t}var Nd=class{_responseOrigin=null;constructor({url:e,httpHeaders:t,withCredentials:n}){this.url=e,this.isHttp=/^https?:/i.test(e),this.headers=yd(this.isHttp,t),this.withCredentials=n||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(e){let t=new XMLHttpRequest,n=this.currXhrId++,r=this.pendingRequests[n]={xhr:t};t.open(`GET`,this.url),t.withCredentials=this.withCredentials;for(let[e,n]of this.headers)t.setRequestHeader(e,n);return this.isHttp&&`begin`in e&&`end`in e?(t.setRequestHeader(`Range`,`bytes=${e.begin}-${e.end-1}`),r.expectedStatus=jd):r.expectedStatus=Ad,t.responseType=`arraybuffer`,el(e.onError,"Expected `onError` callback to be provided."),t.onerror=()=>{e.onError(t.status)},t.onreadystatechange=this.onStateChange.bind(this,n),t.onprogress=this.onProgress.bind(this,n),r.onHeadersReceived=e.onHeadersReceived,r.onDone=e.onDone,r.onError=e.onError,r.onProgress=e.onProgress,t.send(null),n}onProgress(e,t){let n=this.pendingRequests[e];n&&n.onProgress?.(t)}onStateChange(e,t){let n=this.pendingRequests[e];if(!n)return;let r=n.xhr;if(r.readyState>=2&&n.onHeadersReceived&&(n.onHeadersReceived(),delete n.onHeadersReceived),r.readyState!==4||!(e in this.pendingRequests))return;if(delete this.pendingRequests[e],r.status===0&&this.isHttp){n.onError(r.status);return}let i=r.status||Ad;if(!(i===Ad&&n.expectedStatus===jd)&&i!==n.expectedStatus){n.onError(r.status);return}let a=Md(r);if(i===jd){let e=r.getResponseHeader(`Content-Range`),t=/bytes (\d+)-(\d+)\/(\d+)/.exec(e);t?n.onDone({begin:parseInt(t[1],10),chunk:a}):(q(`Missing or invalid "Content-Range" header.`),n.onError(0))}else a?n.onDone({begin:0,chunk:a}):n.onError(r.status)}getRequestXhr(e){return this.pendingRequests[e].xhr}isPendingRequest(e){return e in this.pendingRequests}abortRequest(e){let t=this.pendingRequests[e].xhr;delete this.pendingRequests[e],t.abort()}},Pd=class{constructor(e){this._source=e,this._manager=new Nd(e),this._rangeChunkSize=e.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(e){let t=this._rangeRequestReaders.indexOf(e);t>=0&&this._rangeRequestReaders.splice(t,1)}getFullReader(){return el(!this._fullRequestReader,`PDFNetworkStream.getFullReader can only be called once.`),this._fullRequestReader=new Fd(this._manager,this._source),this._fullRequestReader}getRangeReader(e,t){let n=new Id(this._manager,e,t);return n.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Fd=class{constructor(e,t){this._manager=e,this._url=t.url,this._fullRequestId=e.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=t.disableRange||!1,this._contentLength=t.length,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let e=this._fullRequestId,t=this._manager.getRequestXhr(e);this._manager._responseOrigin=bd(t.responseURL);let n=t.getAllResponseHeaders(),r=new Headers(n?n.trimStart().replace(/[^\S ]+$/,``).split(/[\r\n]+/).map(e=>{let[t,...n]=e.split(`: `);return[t,n.join(`: `)]}):[]),{allowRangeRequests:i,suggestedLength:a}=xd({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=a||this._contentLength,this._filename=Sd(r),this._isRangeSupported&&this._manager.abortRequest(e),this._headersCapability.resolve()}_onDone(e){if(e&&(this._requests.length>0?this._requests.shift().resolve({value:e.chunk,done:!1}):this._cachedChunks.push(e.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(e){this._storedError=Cd(e,this._url),this._headersCapability.reject(this._storedError);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(e){this.onProgress?.({loaded:e.loaded,total:e.lengthComputable?e.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e);for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}},Id=class{constructor(e,t,n){this._manager=e,this._url=e.url,this._requestId=e.request({begin:t,end:n,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){let e=bd(this._manager.getRequestXhr(this._requestId)?.responseURL);e!==this._manager._responseOrigin&&(this._storedError=Error(`Expected range response-origin "${e}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(e){let t=e.chunk;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(e){this._storedError??=Cd(e,this._url);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(e){this.isStreamingSupported||this.onProgress?.({loaded:e.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}},Ld=/^[a-z][a-z0-9\-+.]+:/i;function Rd(e){if(Ld.test(e))return new URL(e);let t=process.getBuiltinModule(`url`);return new URL(t.pathToFileURL(e))}var zd=class{constructor(e){this.source=e,this.url=Rd(e.url),el(this.url.protocol===`file:`,`PDFNodeStream only supports file:// URLs.`),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return el(!this._fullRequestReader,`PDFNodeStream.getFullReader can only be called once.`),this._fullRequestReader=new Bd(this),this._fullRequestReader}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new Vd(this,e,t);return this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Bd=class{constructor(e){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null;let t=e.source;this._contentLength=t.length,this._loaded=0,this._filename=null,this._disableRange=t.disableRange||!1,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!t.disableStream,this._isRangeSupported=!t.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();let n=process.getBuiltinModule(`fs`);n.promises.lstat(this._url).then(e=>{this._contentLength=e.size,this._setReadableStream(n.createReadStream(this._url)),this._headersCapability.resolve()},e=>{e.code===`ENOENT`&&(e=new sl(`Missing PDF "${this._url}".`)),this._storedError=e,this._headersCapability.reject(e)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on(`readable`,()=>{this._readCapability.resolve()}),e.on(`end`,()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on(`error`,e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new ul(`streaming is disabled`)),this._storedError&&this._readableStream.destroy(this._storedError)}},Vd=class{constructor(e,t,n){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let r=e.source;this._isStreamingSupported=!r.disableStream;let i=process.getBuiltinModule(`fs`);this._setReadableStream(i.createReadStream(this._url,{start:t,end:n-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on(`readable`,()=>{this._readCapability.resolve()}),e.on(`end`,()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on(`error`,e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}},Hd=1e5,Ud=30,Wd=.8,Gd=class e{#e=Promise.withResolvers();#t=null;#n=!1;#r=!!globalThis.FontInspector?.enabled;#i=null;#a=null;#o=0;#s=0;#c=null;#l=null;#u=0;#d=0;#f=Object.create(null);#p=[];#m=null;#h=[];#g=new WeakMap;#_=null;static#v=new Map;static#y=new Map;static#b=new WeakMap;static#x=null;static#S=new Set;constructor({textContentSource:t,container:n,viewport:r}){if(t instanceof ReadableStream)this.#m=t;else if(typeof t==`object`)this.#m=new ReadableStream({start(e){e.enqueue(t),e.close()}});else throw Error(`No "textContentSource" parameter specified.`);this.#t=this.#l=n,this.#d=r.scale*(globalThis.devicePixelRatio||1),this.#u=r.rotation,this.#a={div:null,properties:null,ctx:null};let{pageWidth:i,pageHeight:a,pageX:o,pageY:s}=r.rawDims;this.#_=[1,0,0,-1,-o,s+a],this.#s=i,this.#o=a,e.#O(),Wl(n,r),this.#e.promise.finally(()=>{e.#S.delete(this),this.#a=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:e,isFirefox:t}=_l.platform;return Y(this,`fontFamilyMap`,new Map([[`sans-serif`,`${e&&t?`Calibri, `:``}sans-serif`],[`monospace`,`${e&&t?`Lucida Console, `:``}monospace`]]))}render(){let t=()=>{this.#c.read().then(({value:e,done:n})=>{if(n){this.#e.resolve();return}this.#i??=e.lang,Object.assign(this.#f,e.styles),this.#C(e.items),t()},this.#e.reject)};return this.#c=this.#m.getReader(),e.#S.add(this),t(),this.#e.promise}update({viewport:t,onBefore:n=null}){let r=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#u&&(n?.(),this.#u=i,Wl(this.#l,{rotation:i})),r!==this.#d){n?.(),this.#d=r;let t={div:null,properties:null,ctx:e.#E(this.#i)};for(let e of this.#h)t.properties=this.#g.get(e),t.div=e,this.#T(t)}}cancel(){let e=new ul(`TextLayer task cancelled.`);this.#c?.cancel(e).catch(()=>{}),this.#c=null,this.#e.reject(e)}get textDivs(){return this.#h}get textContentItemsStr(){return this.#p}#C(t){if(this.#n)return;this.#a.ctx??=e.#E(this.#i);let n=this.#h,r=this.#p;for(let e of t){if(n.length>Hd){q(`Ignoring additional textDivs for performance reasons.`),this.#n=!0;return}if(e.str===void 0){if(e.type===`beginMarkedContentProps`||e.type===`beginMarkedContent`){let t=this.#t;this.#t=document.createElement(`span`),this.#t.classList.add(`markedContent`),e.id!==null&&this.#t.setAttribute(`id`,`${e.id}`),t.append(this.#t)}else e.type===`endMarkedContent`&&(this.#t=this.#t.parentNode);continue}r.push(e.str),this.#w(e)}}#w(t){let n=document.createElement(`span`),r={angle:0,canvasWidth:0,hasText:t.str!==``,hasEOL:t.hasEOL,fontSize:0};this.#h.push(n);let i=X.transform(this.#_,t.transform),a=Math.atan2(i[1],i[0]),o=this.#f[t.fontName];o.vertical&&(a+=Math.PI/2);let s=this.#r&&o.fontSubstitution||o.fontFamily;s=e.fontFamilyMap.get(s)||s;let c=Math.hypot(i[2],i[3]),l=c*e.#k(s,this.#i),u,d;a===0?(u=i[4],d=i[5]-l):(u=i[4]+l*Math.sin(a),d=i[5]-l*Math.cos(a));let f=`calc(var(--scale-factor)*`,p=n.style;this.#t===this.#l?(p.left=`${(100*u/this.#s).toFixed(2)}%`,p.top=`${(100*d/this.#o).toFixed(2)}%`):(p.left=`${f}${u.toFixed(2)}px)`,p.top=`${f}${d.toFixed(2)}px)`),p.fontSize=`${f}${(e.#x*c).toFixed(2)}px)`,p.fontFamily=s,r.fontSize=c,n.setAttribute(`role`,`presentation`),n.textContent=t.str,n.dir=t.dir,this.#r&&(n.dataset.fontName=o.fontSubstitutionLoadedName||t.fontName),a!==0&&(r.angle=180/Math.PI*a);let m=!1;if(t.str.length>1)m=!0;else if(t.str!==` `&&t.transform[0]!==t.transform[3]){let e=Math.abs(t.transform[0]),n=Math.abs(t.transform[3]);e!==n&&Math.max(e,n)/Math.min(e,n)>1.5&&(m=!0)}if(m&&(r.canvasWidth=o.vertical?t.height:t.width),this.#g.set(n,r),this.#a.div=n,this.#a.properties=r,this.#T(this.#a),r.hasText&&this.#t.append(n),r.hasEOL){let e=document.createElement(`br`);e.setAttribute(`role`,`presentation`),this.#t.append(e)}}#T(t){let{div:n,properties:r,ctx:i}=t,{style:a}=n,o=``;if(e.#x>1&&(o=`scale(${1/e.#x})`),r.canvasWidth!==0&&r.hasText){let{fontFamily:t}=a,{canvasWidth:s,fontSize:c}=r;e.#D(i,c*this.#d,t);let{width:l}=i.measureText(n.textContent);l>0&&(o=`scaleX(${s*this.#d/l}) ${o}`)}r.angle!==0&&(o=`rotate(${r.angle}deg) ${o}`),o.length>0&&(a.transform=o)}static cleanup(){if(!(this.#S.size>0)){this.#v.clear();for(let{canvas:e}of this.#y.values())e.remove();this.#y.clear()}}static#E(e=null){let t=this.#y.get(e||=``);if(!t){let n=document.createElement(`canvas`);n.className=`hiddenCanvasElement`,n.lang=e,document.body.append(n),t=n.getContext(`2d`,{alpha:!1,willReadFrequently:!0}),this.#y.set(e,t),this.#b.set(t,{size:0,family:``})}return t}static#D(e,t,n){let r=this.#b.get(e);t===r.size&&n===r.family||(e.font=`${t}px ${n}`,r.size=t,r.family=n)}static#O(){if(this.#x!==null)return;let e=document.createElement(`div`);e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize=`1px`,e.style.position=`absolute`,e.textContent=`X`,document.body.append(e),this.#x=e.getBoundingClientRect().height,e.remove()}static#k(e,t){let n=this.#v.get(e);if(n)return n;let r=this.#E(t);r.canvas.width=r.canvas.height=Ud,this.#D(r,Ud,e);let i=r.measureText(``),a=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(a){let t=a/(a+o);return this.#v.set(e,t),r.canvas.width=r.canvas.height=0,t}r.strokeStyle=`red`,r.clearRect(0,0,Ud,Ud),r.strokeText(`g`,0,0);let s=r.getImageData(0,0,Ud,Ud).data;o=0;for(let e=s.length-1-3;e>=0;e-=4)if(s[e]>0){o=Math.ceil(e/4/Ud);break}r.clearRect(0,0,Ud,Ud),r.strokeText(`A`,0,Ud),s=r.getImageData(0,0,Ud,Ud).data,a=0;for(let e=0,t=s.length;e<t;e+=4)if(s[e]>0){a=Ud-Math.floor(e/4/Ud);break}r.canvas.width=r.canvas.height=0;let c=a?a/(a+o):Wd;return this.#v.set(e,c),c}},Kd=class e{static textContent(t){let n=[],r={items:n,styles:Object.create(null)};function i(t){if(!t)return;let r=null,a=t.name;if(a===`#text`)r=t.value;else if(e.shouldBuildText(a))t?.attributes?.textContent?r=t.attributes.textContent:t.value&&(r=t.value);else return;if(r!==null&&n.push({str:r}),t.children)for(let e of t.children)i(e)}return i(t),r}static shouldBuildText(e){return!(e===`textarea`||e===`input`||e===`option`||e===`select`)}},qd=65536,Jd=100,Yd=5e3,Xd=Pc?Ou:yu,Zd=Pc?ku:xu,Qd=Pc?Du:Cu,$d=Pc?Au:Tu;function ef(e={}){typeof e==`string`||e instanceof URL?e={url:e}:(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});let t=new af,{docId:n}=t,r=e.url?tf(e.url):null,i=e.data?nf(e.data):null,a=e.httpHeaders||null,o=e.withCredentials===!0,s=e.password??null,c=e.range instanceof of?e.range:null,l=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:qd,u=e.worker instanceof uf?e.worker:null,d=e.verbosity,f=typeof e.docBaseUrl==`string`&&!jl(e.docBaseUrl)?e.docBaseUrl:null,p=typeof e.cMapUrl==`string`?e.cMapUrl:null,m=e.cMapPacked!==!1,h=e.CMapReaderFactory||Zd,g=typeof e.standardFontDataUrl==`string`?e.standardFontDataUrl:null,_=e.StandardFontDataFactory||$d,v=e.stopAtErrors!==!0,y=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,b=e.isEvalSupported!==!1,x=typeof e.isOffscreenCanvasSupported==`boolean`?e.isOffscreenCanvasSupported:!Pc,S=typeof e.isImageDecoderSupported==`boolean`?e.isImageDecoderSupported:!Pc&&(_l.platform.isFirefox||!globalThis.chrome),C=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,w=typeof e.disableFontFace==`boolean`?e.disableFontFace:Pc,T=e.fontExtraProperties===!0,E=e.enableXfa===!0,D=e.ownerDocument||globalThis.document,O=e.disableRange===!0,k=e.disableStream===!0,A=e.disableAutoFetch===!0,j=e.pdfBug===!0,M=e.CanvasFactory||Xd,ee=e.FilterFactory||Qd,N=e.enableHWA===!0,P=c?c.length:e.length??NaN,F=typeof e.useSystemFonts==`boolean`?e.useSystemFonts:!Pc&&!w,I=typeof e.useWorkerFetch==`boolean`?e.useWorkerFetch:h===xu&&_===Tu&&p&&g&&Il(p,document.baseURI)&&Il(g,document.baseURI);Zc(d);let te={canvasFactory:new M({ownerDocument:D,enableHWA:N}),filterFactory:new ee({docId:n,ownerDocument:D}),cMapReaderFactory:I?null:new h({baseUrl:p,isCompressed:m}),standardFontDataFactory:I?null:new _({baseUrl:g})};if(!u){let e={verbosity:d,port:ud.workerPort};u=e.port?uf.fromPort(e):new uf(e),t._worker=u}let ne={docId:n,apiVersion:`4.10.38`,data:i,password:s,disableAutoFetch:A,rangeChunkSize:l,length:P,docBaseUrl:f,enableXfa:E,evaluatorOptions:{maxImageSize:y,disableFontFace:w,ignoreErrors:v,isEvalSupported:b,isOffscreenCanvasSupported:x,isImageDecoderSupported:S,canvasMaxAreaInBytes:C,fontExtraProperties:T,useSystemFonts:F,cMapUrl:I?p:null,standardFontDataUrl:I?g:null}},re={disableFontFace:w,fontExtraProperties:T,ownerDocument:D,pdfBug:j,styleElement:null,loadingParams:{disableAutoFetch:A,enableXfa:E}};return u.promise.then(function(){if(t.destroyed)throw Error(`Loading aborted`);if(u.destroyed)throw Error(`Worker was destroyed`);let e=u.messageHandler.sendWithPromise(`GetDocRequest`,ne,i?[i.buffer]:null),s;if(c)s=new hd(c,{disableRange:O,disableStream:k});else if(!i){if(!r)throw Error("getDocument - no `url` parameter provided.");let e;if(Pc)if(Il(r)){if(typeof fetch>`u`||typeof Response>`u`||!(`body`in Response.prototype))throw Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");e=Dd}else e=zd;else e=Il(r)?Dd:Pd;s=new e({url:r,length:P,httpHeaders:a,withCredentials:o,rangeChunkSize:l,disableRange:O,disableStream:k})}return e.then(e=>{if(t.destroyed)throw Error(`Loading aborted`);if(u.destroyed)throw Error(`Worker was destroyed`);let r=new _u(n,e,u.port),i=new df(r,t,s,re,te);t._transport=i,r.send(`Ready`,null)})}).catch(t._capability.reject),t}function tf(e){if(e instanceof URL)return e.href;try{return new URL(e,window.location).href}catch{if(Pc&&typeof e==`string`)return e}throw Error(`Invalid PDF url data: either string or URL-object is expected in the url property.`)}function nf(e){if(Pc&&typeof Buffer<`u`&&e instanceof Buffer)throw Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if(typeof e==`string`)return fl(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`object`&&!isNaN(e?.length))return new Uint8Array(e);throw Error(`Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.`)}function rf(e){return typeof e==`object`&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0}var af=class e{static#e=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${e.#e++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(e){throw this._worker?.port&&delete this._worker._pendingDestroy,e}this._transport=null,this._worker?.destroy(),this._worker=null}},of=class{constructor(e,t,n=!1,r=null){this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=r,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(e){this._rangeListeners.push(e)}addProgressListener(e){this._progressListeners.push(e)}addProgressiveReadListener(e){this._progressiveReadListeners.push(e)}addProgressiveDoneListener(e){this._progressiveDoneListeners.push(e)}onDataRange(e,t){for(let n of this._rangeListeners)n(e,t)}onDataProgress(e,t){this._readyCapability.promise.then(()=>{for(let n of this._progressListeners)n(e,t)})}onDataProgressiveRead(e){this._readyCapability.promise.then(()=>{for(let t of this._progressiveReadListeners)t(e)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(let e of this._progressiveDoneListeners)e()})}transportReady(){this._readyCapability.resolve()}requestDataRange(e,t){J(`Abstract method PDFDataRangeTransport.requestDataRange`)}abort(){}},sf=class{constructor(e,t){this._pdfInfo=e,this._transport=t}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Y(this,`isPureXfa`,!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}},cf=class{#e=null;#t=!1;constructor(e,t,n,r=!1){this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=r?new Fl:null,this._pdfBug=r,this.commonObjs=n.commonObjs,this.objs=new pf,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:n=0,offsetY:r=0,dontFlip:i=!1}={}){return new kl({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:r,dontFlip:i})}getAnnotations({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Y(this,`isPureXfa`,!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:e,viewport:t,intent:n=`display`,annotationMode:r=Bc.ENABLE,transform:i=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:s=null,pageColors:c=null,printAnnotationStorage:l=null,isEditing:u=!1}){this._stats?.time(`Overall`);let d=this._transport.getRenderingIntent(n,r,l,u),{renderingIntent:f,cacheKey:p}=d;this.#t=!1,this.#r(),o||=this._transport.getOptionalContentConfig(f);let m=this._intentStates.get(p);m||(m=Object.create(null),this._intentStates.set(p,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);let h=!!(f&zc.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(d));let g=e=>{m.renderTasks.delete(_),(this._maybeCleanupAfterRender||h)&&(this.#t=!0),this.#n(!h),e?(_.capability.reject(e),this._abortOperatorList({intentState:m,reason:e instanceof Error?e:Error(e)})):_.capability.resolve(),this._stats&&(this._stats.timeEnd(`Rendering`),this._stats.timeEnd(`Overall`),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},_=new hf({callback:g,params:{canvasContext:e,viewport:t,transform:i,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:s,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!h,pdfBug:this._pdfBug,pageColors:c});(m.renderTasks||=new Set).add(_);let v=_.task;return Promise.all([m.displayReadyCapability.promise,o]).then(([e,t])=>{if(this.destroyed){g();return}if(this._stats?.time(`Rendering`),!(t.renderingIntent&f))throw Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");_.initializeGraphics({transparency:e,optionalContentConfig:t}),_.operatorListChanged()}).catch(g),v}getOperatorList({intent:e=`display`,annotationMode:t=Bc.ENABLE,printAnnotationStorage:n=null,isEditing:r=!1}={}){function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(s))}let a=this._transport.getRenderingIntent(e,t,n,r,!0),o=this._intentStates.get(a.cacheKey);o||(o=Object.create(null),this._intentStates.set(a.cacheKey,o));let s;return o.opListReadCapability||(s=Object.create(null),s.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(s),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(a)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream(`GetTextContent`,{pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(e){return e.items.length}})}getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(e=>Kd.textContent(e));let t=this.streamTextContent(e);return new Promise(function(e,n){function r(){i.read().then(function({value:t,done:n}){if(n){e(a);return}a.lang??=t.lang,Object.assign(a.styles,t.styles),a.items.push(...t.items),r()},n)}let i=t.getReader(),a={items:[],styles:Object.create(null),lang:null};r()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let e=[];for(let t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:Error(`Page was destroyed.`),force:!0}),!t.opListReadCapability)for(let n of t.renderTasks)e.push(n.completed),n.cancel();return this.objs.clear(),this.#t=!1,this.#r(),Promise.all(e)}cleanup(e=!1){this.#t=!0;let t=this.#n(!1);return e&&t&&(this._stats&&=new Fl),t}#n(e=!1){if(this.#r(),!this.#t||this.destroyed)return!1;if(e)return this.#e=setTimeout(()=>{this.#e=null,this.#n(!1)},Yd),!1;for(let{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#t=!1,!0}#r(){this.#e&&=(clearTimeout(this.#e),null)}_startRenderPage(e,t){let n=this._intentStates.get(t);n&&(this._stats?.timeEnd(`Page Request`),n.displayReadyCapability?.resolve(e))}_renderPageChunk(e,t){for(let n=0,r=e.length;n<r;n++)t.operatorList.fnArray.push(e.fnArray[n]),t.operatorList.argsArray.push(e.argsArray[n]);t.operatorList.lastChunk=e.lastChunk,t.operatorList.separateAnnots=e.separateAnnots;for(let e of t.renderTasks)e.operatorListChanged();e.lastChunk&&this.#n(!0)}_pumpOperatorList({renderingIntent:e,cacheKey:t,annotationStorageSerializable:n,modifiedIds:r}){let{map:i,transfer:a}=n,o=this._transport.messageHandler.sendWithStream(`GetOperatorList`,{pageIndex:this._pageIndex,intent:e,cacheKey:t,annotationStorage:i,modifiedIds:r},a).getReader(),s=this._intentStates.get(t);s.streamReader=o;let c=()=>{o.read().then(({value:e,done:t})=>{if(t){s.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(e,s),c())},e=>{if(s.streamReader=null,!this._transport.destroyed){if(s.operatorList){s.operatorList.lastChunk=!0;for(let e of s.renderTasks)e.operatorListChanged();this.#n(!0)}if(s.displayReadyCapability)s.displayReadyCapability.reject(e);else if(s.opListReadCapability)s.opListReadCapability.reject(e);else throw e}})};c()}_abortOperatorList({intentState:e,reason:t,force:n=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&=(clearTimeout(e.streamReaderCancelTimeout),null),!n){if(e.renderTasks.size>0)return;if(t instanceof Al){let n=Jd;t.extraDelay>0&&t.extraDelay<1e3&&(n+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},n);return}}if(e.streamReader.cancel(new ul(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(let[t,n]of this._intentStates)if(n===e){this._intentStates.delete(t);break}this.cleanup()}}}get stats(){return this._stats}},lf=class{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[e]of this.#e)e.call(this,n)})}addEventListener(e,t,n=null){let r=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){q("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,t);r=()=>i.removeEventListener(`abort`,a),i.addEventListener(`abort`,a)}this.#e.set(t,r)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},uf=class e{static#e=0;static#t=!1;static#n;static{Pc&&(this.#t=!0,ud.workerSrc||=`./pdf.worker.mjs`),this._isSameOrigin=(e,t)=>{let n;try{if(n=new URL(e),!n.origin||n.origin===`null`)return!1}catch{return!1}let r=new URL(t,n);return n.origin===r.origin},this._createCDNWrapper=e=>{let t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:`text/javascript`}))}}constructor({name:t=null,port:n=null,verbosity:r=Qc()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if(e.#n?.has(n))throw Error(`Cannot use more than one PDFWorker per port.`);(e.#n||=new WeakMap).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return this._readyCapability.promise}#r(){this._readyCapability.resolve(),this._messageHandler.send(`configure`,{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(e){this._port=e,this._messageHandler=new _u(`main`,`worker`,e),this._messageHandler.on(`ready`,function(){}),this.#r()}_initialize(){if(e.#t||e.#i){this._setupFakeWorker();return}let{workerSrc:t}=e;try{e._isSameOrigin(window.location.href,t)||(t=e._createCDNWrapper(new URL(t,window.location).href));let n=new Worker(t,{type:`module`}),r=new _u(`main`,`worker`,n),i=()=>{a.abort(),r.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(Error(`Worker was destroyed`)):this._setupFakeWorker()},a=new AbortController;n.addEventListener(`error`,()=>{this._webWorker||i()},{signal:a.signal}),r.on(`test`,e=>{if(a.abort(),this.destroyed||!e){i();return}this._messageHandler=r,this._port=n,this._webWorker=n,this.#r()}),r.on(`ready`,e=>{if(a.abort(),this.destroyed){i();return}try{o()}catch{this._setupFakeWorker()}});let o=()=>{let e=new Uint8Array;r.send(`test`,e,[e.buffer])};o();return}catch{$c(`The worker has been disabled.`)}this._setupFakeWorker()}_setupFakeWorker(){e.#t||=(q(`Setting up fake worker.`),!0),e._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(Error(`Worker was destroyed`));return}let n=new lf;this._port=n;let r=`fake${e.#e++}`,i=new _u(r+`_worker`,r,n);t.setup(i,n),this._messageHandler=new _u(r,r+`_worker`,n),this.#r()}).catch(e=>{this._readyCapability.reject(Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,e.#n?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw Error(`PDFWorker.fromPort - invalid method signature.`);let n=this.#n?.get(t.port);if(n){if(n._pendingDestroy)throw Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new e(t)}static get workerSrc(){if(ud.workerSrc)return ud.workerSrc;throw Error(`No "GlobalWorkerOptions.workerSrc" specified.`)}static get#i(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return Y(this,`_setupFakeWorkerGlobal`,(async()=>this.#i?this.#i:(await import(this.workerSrc)).WorkerMessageHandler)())}},df=class{#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=null;constructor(e,t,n,r,i){this.messageHandler=e,this.loadingTask=t,this.commonObjs=new pf,this.fontLoader=new du({ownerDocument:r.ownerDocument,styleElement:r.styleElement}),this.loadingParams=r.loadingParams,this._params=r,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.cMapReaderFactory=i.cMapReaderFactory,this.standardFontDataFactory=i.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=n,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#a(e,t=null){let n=this.#e.get(e);if(n)return n;let r=this.messageHandler.sendWithPromise(e,t);return this.#e.set(e,r),r}get annotationStorage(){return Y(this,`annotationStorage`,new lu)}getRenderingIntent(e,t=Bc.ENABLE,n=null,r=!1,i=!1){let a=zc.DISPLAY,o=cu;switch(e){case`any`:a=zc.ANY;break;case`display`:break;case`print`:a=zc.PRINT;break;default:q(`getRenderingIntent - invalid intent: ${e}`)}let s=a&zc.PRINT&&n instanceof uu?n:this.annotationStorage;switch(t){case Bc.DISABLE:a+=zc.ANNOTATIONS_DISABLE;break;case Bc.ENABLE:break;case Bc.ENABLE_FORMS:a+=zc.ANNOTATIONS_FORMS;break;case Bc.ENABLE_STORAGE:a+=zc.ANNOTATIONS_STORAGE,o=s.serializable;break;default:q(`getRenderingIntent - invalid annotationMode: ${t}`)}r&&(a+=zc.IS_EDITING),i&&(a+=zc.OPLIST);let{ids:c,hash:l}=s.modifiedIds,u=[a,o.hash,l];return{renderingIntent:a,cacheKey:u.join(`_`),annotationStorageSerializable:o,modifiedIds:c}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#i?.reject(Error(`Worker was destroyed during onPassword callback`));let e=[];for(let t of this.#t.values())e.push(t._destroy());this.#t.clear(),this.#n.clear(),this.#r.clear(),this.hasOwnProperty(`annotationStorage`)&&this.annotationStorage.resetModified();let t=this.messageHandler.sendWithPromise(`Terminate`,null);return e.push(t),Promise.all(e).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(),Gd.cleanup(),this._networkStream?.cancelAllRequests(new ul(`Worker was terminated.`)),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:e,loadingTask:t}=this;e.on(`GetReader`,(e,t)=>{el(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=e=>{this._lastProgress={loaded:e.loaded,total:e.total}},t.onPull=()=>{this._fullReader.read().then(function({value:e,done:n}){if(n){t.close();return}el(e instanceof ArrayBuffer,`GetReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{this._fullReader.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`ReaderHeadersReady`,async e=>{await this._fullReader.headersReady;let{isStreamingSupported:n,isRangeSupported:r,contentLength:i}=this._fullReader;return(!n||!r)&&(this._lastProgress&&t.onProgress?.(this._lastProgress),this._fullReader.onProgress=e=>{t.onProgress?.({loaded:e.loaded,total:e.total})}),{isStreamingSupported:n,isRangeSupported:r,contentLength:i}}),e.on(`GetRangeReader`,(e,t)=>{el(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let n=this._networkStream.getRangeReader(e.begin,e.end);if(!n){t.close();return}t.onPull=()=>{n.read().then(function({value:e,done:n}){if(n){t.close();return}el(e instanceof ArrayBuffer,`GetRangeReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{n.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`GetDoc`,({pdfInfo:e})=>{this._numPages=e.numPages,this._htmlForXfa=e.htmlForXfa,delete e.htmlForXfa,t._capability.resolve(new sf(e,this))}),e.on(`DocException`,e=>{t._capability.reject(gu(e))}),e.on(`PasswordRequest`,e=>{this.#i=Promise.withResolvers();try{if(!t.onPassword)throw gu(e);t.onPassword(e=>{e instanceof Error?this.#i.reject(e):this.#i.resolve({password:e})},e.code)}catch(e){this.#i.reject(e)}return this.#i.promise}),e.on(`DataLoaded`,e=>{t.onProgress?.({loaded:e.length,total:e.length}),this.downloadInfoCapability.resolve(e)}),e.on(`StartRenderPage`,e=>{this.destroyed||this.#t.get(e.pageIndex)._startRenderPage(e.transparency,e.cacheKey)}),e.on(`commonobj`,([t,n,r])=>{if(this.destroyed||this.commonObjs.has(t))return null;switch(n){case`Font`:let{disableFontFace:i,fontExtraProperties:a,pdfBug:o}=this._params;if(`error`in r){let e=r.error;q(`Error during font loading: ${e}`),this.commonObjs.resolve(t,e);break}let s=new fu(r,{disableFontFace:i,fontExtraProperties:a,inspectFont:o&&globalThis.FontInspector?.enabled?(e,t)=>globalThis.FontInspector.fontAdded(e,t):null});this.fontLoader.bind(s).catch(()=>e.sendWithPromise(`FontFallback`,{id:t})).finally(()=>{!a&&s.data&&(s.data=null),this.commonObjs.resolve(t,s)});break;case`CopyLocalImage`:let{imageRef:c}=r;el(c,`The imageRef must be defined.`);for(let e of this.#t.values())for(let[,n]of e.objs)if(n?.ref===c)return n.dataLen?(this.commonObjs.resolve(t,structuredClone(n)),n.dataLen):null;break;case`FontPath`:case`Image`:case`Pattern`:this.commonObjs.resolve(t,r);break;default:throw Error(`Got unknown common object type ${n}`)}return null}),e.on(`obj`,([e,t,n,r])=>{if(this.destroyed)return;let i=this.#t.get(t);if(!i.objs.has(e)){if(i._intentStates.size===0){r?.bitmap?.close();return}switch(n){case`Image`:i.objs.resolve(e,r),r?.dataLen>Lc&&(i._maybeCleanupAfterRender=!0);break;case`Pattern`:i.objs.resolve(e,r);break;default:throw Error(`Got unknown object type ${n}`)}}}),e.on(`DocProgress`,e=>{this.destroyed||t.onProgress?.({loaded:e.loaded,total:e.total})}),e.on(`FetchBuiltInCMap`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.cMapReaderFactory)throw Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(e)}),e.on(`FetchStandardFontData`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.standardFontDataFactory)throw Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(e)})}getData(){return this.messageHandler.sendWithPromise(`GetData`,null)}saveDocument(){this.annotationStorage.size<=0&&q("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise(`SaveDocument`,{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:this._fullReader?.filename??null},t).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this._numPages)return Promise.reject(Error(`Invalid page request.`));let t=e-1,n=this.#n.get(t);if(n)return n;let r=this.messageHandler.sendWithPromise(`GetPage`,{pageIndex:t}).then(n=>{if(this.destroyed)throw Error(`Transport destroyed`);n.refStr&&this.#r.set(n.refStr,e);let r=new cf(t,n,this,this._params.pdfBug);return this.#t.set(t,r),r});return this.#n.set(t,r),r}getPageIndex(e){return rf(e)?this.messageHandler.sendWithPromise(`GetPageIndex`,{num:e.num,gen:e.gen}):Promise.reject(Error(`Invalid pageIndex request.`))}getAnnotations(e,t){return this.messageHandler.sendWithPromise(`GetAnnotations`,{pageIndex:e,intent:t})}getFieldObjects(){return this.#a(`GetFieldObjects`)}hasJSActions(){return this.#a(`HasJSActions`)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise(`GetCalculationOrderIds`,null)}getDestinations(){return this.messageHandler.sendWithPromise(`GetDestinations`,null)}getDestination(e){return typeof e==`string`?this.messageHandler.sendWithPromise(`GetDestination`,{id:e}):Promise.reject(Error(`Invalid destination request.`))}getPageLabels(){return this.messageHandler.sendWithPromise(`GetPageLabels`,null)}getPageLayout(){return this.messageHandler.sendWithPromise(`GetPageLayout`,null)}getPageMode(){return this.messageHandler.sendWithPromise(`GetPageMode`,null)}getViewerPreferences(){return this.messageHandler.sendWithPromise(`GetViewerPreferences`,null)}getOpenAction(){return this.messageHandler.sendWithPromise(`GetOpenAction`,null)}getAttachments(){return this.messageHandler.sendWithPromise(`GetAttachments`,null)}getDocJSActions(){return this.#a(`GetDocJSActions`)}getPageJSActions(e){return this.messageHandler.sendWithPromise(`GetPageJSActions`,{pageIndex:e})}getStructTree(e){return this.messageHandler.sendWithPromise(`GetStructTree`,{pageIndex:e})}getOutline(){return this.messageHandler.sendWithPromise(`GetOutline`,null)}getOptionalContentConfig(e){return this.#a(`GetOptionalContentConfig`).then(t=>new md(t,e))}getPermissions(){return this.messageHandler.sendWithPromise(`GetPermissions`,null)}getMetadata(){let e=`GetMetadata`,t=this.#e.get(e);if(t)return t;let n=this.messageHandler.sendWithPromise(e,null).then(e=>({info:e[0],metadata:e[1]?new dd(e[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#e.set(e,n),n}getMarkInfo(){return this.messageHandler.sendWithPromise(`GetMarkInfo`,null)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise(`Cleanup`,null);for(let e of this.#t.values())if(!e.cleanup())throw Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(!0),Gd.cleanup()}}cachedPageNumber(e){if(!rf(e))return null;let t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`;return this.#r.get(t)??null}},ff=Symbol(`INITIAL_DATA`),pf=class{#e=Object.create(null);#t(e){return this.#e[e]||={...Promise.withResolvers(),data:ff}}get(e,t=null){if(t){let n=this.#t(e);return n.promise.then(()=>t(n.data)),null}let n=this.#e[e];if(!n||n.data===ff)throw Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){let t=this.#e[e];return!!t&&t.data!==ff}delete(e){let t=this.#e[e];return!t||t.data===ff?!1:(delete this.#e[e],!0)}resolve(e,t=null){let n=this.#t(e);n.data=t,n.resolve()}clear(){for(let e in this.#e){let{data:t}=this.#e[e];t?.bitmap?.close()}this.#e=Object.create(null)}*[Symbol.iterator](){for(let e in this.#e){let{data:t}=this.#e[e];t!==ff&&(yield[e,t])}}},mf=class{#e=null;constructor(e){this.#e=e,this.onContinue=null}get promise(){return this.#e.capability.promise}cancel(e=0){this.#e.cancel(null,e)}get separateAnnots(){let{separateAnnots:e}=this.#e.operatorList;if(!e)return!1;let{annotationCanvasMap:t}=this.#e;return e.form||e.canvas&&t?.size>0}},hf=class e{#e=null;static#t=new WeakSet;constructor({callback:e,params:t,objs:n,commonObjs:r,annotationCanvasMap:i,operatorList:a,pageIndex:o,canvasFactory:s,filterFactory:c,useRequestAnimationFrame:l=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=e,this.params=t,this.objs=n,this.commonObjs=r,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=o,this.canvasFactory=s,this.filterFactory=c,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=l===!0&&typeof window<`u`,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new mf(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){if(this.cancelled)return;if(this._canvas){if(e.#t.has(this._canvas))throw Error(`Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.`);e.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:r,viewport:i,transform:a,background:o}=this.params;this.gfx=new ld(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:a,viewport:i,transparency:t,background:o}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,n=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#e&&=(window.cancelAnimationFrame(this.#e),null),e.#t.delete(this._canvas),this.callback(t||new Al(`Rendering cancelled, page ${this._pageIndex+1}`,n))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#e=window.requestAnimationFrame(()=>{this.#e=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),e.#t.delete(this._canvas),this.callback())))}},gf=`4.10.38`,_f=`f9bea397f`;function vf(e){return Math.floor(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`)}function yf(e){return Math.max(0,Math.min(255,255*e))}var bf=class{static CMYK_G([e,t,n,r]){return[`G`,1-Math.min(1,.3*e+.59*n+.11*t+r)]}static G_CMYK([e]){return[`CMYK`,0,0,0,1-e]}static G_RGB([e]){return[`RGB`,e,e,e]}static G_rgb([e]){return e=yf(e),[e,e,e]}static G_HTML([e]){let t=vf(e);return`#${t}${t}${t}`}static RGB_G([e,t,n]){return[`G`,.3*e+.59*t+.11*n]}static RGB_rgb(e){return e.map(yf)}static RGB_HTML(e){return`#${e.map(vf).join(``)}`}static T_HTML(){return`#00000000`}static T_rgb(){return[null]}static CMYK_RGB([e,t,n,r]){return[`RGB`,1-Math.min(1,e+r),1-Math.min(1,n+r),1-Math.min(1,t+r)]}static CMYK_rgb([e,t,n,r]){return[yf(1-Math.min(1,e+r)),yf(1-Math.min(1,n+r)),yf(1-Math.min(1,t+r))]}static CMYK_HTML(e){let t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,n]){let r=1-e,i=1-t,a=1-n;return[`CMYK`,r,i,a,Math.min(r,i,a)]}},xf=class{create(e,t,n=!1){if(e<=0||t<=0)throw Error(`Invalid SVG dimensions`);let r=this._createSVG(`svg:svg`);return r.setAttribute(`version`,`1.1`),n||(r.setAttribute(`width`,`${e}px`),r.setAttribute(`height`,`${t}px`)),r.setAttribute(`preserveAspectRatio`,`none`),r.setAttribute(`viewBox`,`0 0 ${e} ${t}`),r}createElement(e){if(typeof e!=`string`)throw Error(`Invalid SVG element type`);return this._createSVG(e)}_createSVG(e){J("Abstract method `_createSVG` called.")}},Sf=class extends xf{_createSVG(e){return document.createElementNS(El,e)}},Cf=class{static setupStorage(e,t,n,r,i){let a=r.getValue(t,{value:null});switch(n.name){case`textarea`:if(a.value!==null&&(e.textContent=a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})});break;case`input`:if(n.attributes.type===`radio`||n.attributes.type===`checkbox`){if(a.value===n.attributes.xfaOn?e.setAttribute(`checked`,!0):a.value===n.attributes.xfaOff&&e.removeAttribute(`checked`),i===`print`)break;e.addEventListener(`change`,e=>{r.setValue(t,{value:e.target.checked?e.target.getAttribute(`xfaOn`):e.target.getAttribute(`xfaOff`)})})}else{if(a.value!==null&&e.setAttribute(`value`,a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})})}break;case`select`:if(a.value!==null){e.setAttribute(`value`,a.value);for(let e of n.children)e.attributes.value===a.value?e.attributes.selected=!0:e.attributes.hasOwnProperty(`selected`)&&delete e.attributes.selected}e.addEventListener(`input`,e=>{let n=e.target.options,i=n.selectedIndex===-1?``:n[n.selectedIndex].value;r.setValue(t,{value:i})});break}}static setAttributes({html:e,element:t,storage:n=null,intent:r,linkService:i}){let{attributes:a}=t,o=e instanceof HTMLAnchorElement;a.type===`radio`&&(a.name=`${a.name}-${r}`);for(let[t,n]of Object.entries(a))if(n!=null)switch(t){case`class`:n.length&&e.setAttribute(t,n.join(` `));break;case`dataId`:break;case`id`:e.setAttribute(`data-element-id`,n);break;case`style`:Object.assign(e.style,n);break;case`textContent`:e.textContent=n;break;default:(!o||t!==`href`&&t!==`newWindow`)&&e.setAttribute(t,n)}o&&i.addLinkAttributes(e,a.href,a.newWindow),n&&a.dataId&&this.setupStorage(e,a.dataId,t,n)}static render(e){let t=e.annotationStorage,n=e.linkService,r=e.xfaHtml,i=e.intent||`display`,a=document.createElement(r.name);r.attributes&&this.setAttributes({html:a,element:r,intent:i,linkService:n});let o=i!==`richText`,s=e.div;if(s.append(a),e.viewport){let t=`matrix(${e.viewport.transform.join(`,`)})`;s.style.transform=t}o&&s.setAttribute(`class`,`xfaLayer xfaFont`);let c=[];if(r.children.length===0){if(r.value){let e=document.createTextNode(r.value);a.append(e),o&&Kd.shouldBuildText(r.name)&&c.push(e)}return{textDivs:c}}let l=[[r,-1,a]];for(;l.length>0;){let[e,r,a]=l.at(-1);if(r+1===e.children.length){l.pop();continue}let s=e.children[++l.at(-1)[1]];if(s===null)continue;let{name:u}=s;if(u===`#text`){let e=document.createTextNode(s.value);c.push(e),a.append(e);continue}let d=s?.attributes?.xmlns?document.createElementNS(s.attributes.xmlns,u):document.createElement(u);if(a.append(d),s.attributes&&this.setAttributes({html:d,element:s,storage:t,intent:i,linkService:n}),s.children?.length>0)l.push([s,-1,d]);else if(s.value){let e=document.createTextNode(s.value);o&&Kd.shouldBuildText(u)&&c.push(e),d.append(e)}}for(let e of s.querySelectorAll(`.xfaNonInteractive input, .xfaNonInteractive textarea`))e.setAttribute(`readOnly`,!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(`,`)})`;e.div.style.transform=t,e.div.hidden=!1}},wf=1e3,Tf=9,Ef=new WeakSet;function Df(e){return{width:e[2]-e[0],height:e[3]-e[1]}}var Of=class{static create(e){switch(e.data.annotationType){case Gc.LINK:return new Af(e);case Gc.TEXT:return new jf(e);case Gc.WIDGET:switch(e.data.fieldType){case`Tx`:return new Nf(e);case`Btn`:return e.data.radioButton?new If(e):e.data.checkBox?new Ff(e):new Lf(e);case`Ch`:return new Rf(e);case`Sig`:return new Pf(e)}return new Mf(e);case Gc.POPUP:return new zf(e);case Gc.FREETEXT:return new Vf(e);case Gc.LINE:return new Hf(e);case Gc.SQUARE:return new Uf(e);case Gc.CIRCLE:return new Wf(e);case Gc.POLYLINE:return new Gf(e);case Gc.CARET:return new qf(e);case Gc.INK:return new Jf(e);case Gc.POLYGON:return new Kf(e);case Gc.HIGHLIGHT:return new Yf(e);case Gc.UNDERLINE:return new Xf(e);case Gc.SQUIGGLY:return new Zf(e);case Gc.STRIKEOUT:return new Qf(e);case Gc.STAMP:return new $f(e);case Gc.FILEATTACHMENT:return new ep(e);default:return new kf(e)}}},kf=class e{#e=null;#t=!1;#n=null;constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:r=!1}={}){this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,t&&(this.container=this._createContainer(n)),r&&this._createQuadrilaterals()}static _hasPopupData({titleObj:e,contentsObj:t,richText:n}){return!!(e?.str||t?.str||n?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return e._hasPopupData(this.data)}updateEdited(e){if(!this.container)return;this.#e||={rect:this.data.rect.slice(0)};let{rect:t}=e;t&&this.#r(t),this.#n?.popup.updateEdited(e)}resetEdited(){this.#e&&=(this.#r(this.#e.rect),this.#n?.popup.resetEdited(),null)}#r(e){let{container:{style:t},data:{rect:n,rotation:r},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:a,pageX:o,pageY:s}}}}=this;n?.splice(0,4,...e);let{width:c,height:l}=Df(e);t.left=`${100*(e[0]-o)/i}%`,t.top=`${100*(a-e[3]+s)/a}%`,r===0?(t.width=`${100*c/i}%`,t.height=`${100*l/a}%`):this.setRotation(r)}_createContainer(e){let{data:t,parent:{page:n,viewport:r}}=this,i=document.createElement(`section`);i.setAttribute(`data-annotation-id`,t.id),this instanceof Mf||(i.tabIndex=wf);let{style:a}=i;if(a.zIndex=this.parent.zIndex++,t.alternativeText&&(i.title=t.alternativeText),t.noRotate&&i.classList.add(`norotate`),!t.rect||this instanceof zf){let{rotation:e}=t;return!t.hasOwnCanvas&&e!==0&&this.setRotation(e,i),i}let{width:o,height:s}=Df(t.rect);if(!e&&t.borderStyle.width>0){a.borderWidth=`${t.borderStyle.width}px`;let e=t.borderStyle.horizontalCornerRadius,n=t.borderStyle.verticalCornerRadius;switch(e>0||n>0?a.borderRadius=`calc(${e}px * var(--scale-factor)) / calc(${n}px * var(--scale-factor))`:this instanceof If&&(a.borderRadius=`calc(${o}px * var(--scale-factor)) / calc(${s}px * var(--scale-factor))`),t.borderStyle.style){case Kc.SOLID:a.borderStyle=`solid`;break;case Kc.DASHED:a.borderStyle=`dashed`;break;case Kc.BEVELED:q(`Unimplemented border style: beveled`);break;case Kc.INSET:q(`Unimplemented border style: inset`);break;case Kc.UNDERLINE:a.borderBottomStyle=`solid`;break;default:break}let r=t.borderColor||null;r?(this.#t=!0,a.borderColor=X.makeHexColor(r[0]|0,r[1]|0,r[2]|0)):a.borderWidth=0}let c=X.normalizeRect([t.rect[0],n.view[3]-t.rect[1]+n.view[1],t.rect[2],n.view[3]-t.rect[3]+n.view[1]]),{pageWidth:l,pageHeight:u,pageX:d,pageY:f}=r.rawDims;a.left=`${100*(c[0]-d)/l}%`,a.top=`${100*(c[1]-f)/u}%`;let{rotation:p}=t;return t.hasOwnCanvas||p===0?(a.width=`${100*o/l}%`,a.height=`${100*s/u}%`):this.setRotation(p,i),i}setRotation(e,t=this.container){if(!this.data.rect)return;let{pageWidth:n,pageHeight:r}=this.parent.viewport.rawDims,{width:i,height:a}=Df(this.data.rect),o,s;e%180==0?(o=100*i/n,s=100*a/r):(o=100*a/n,s=100*i/r),t.style.width=`${o}%`,t.style.height=`${s}%`,t.setAttribute(`data-main-rotation`,(360-e)%360)}get _commonActions(){let e=(e,t,n)=>{let r=n.detail[e],i=r[0],a=r.slice(1);n.target.style[t]=bf[`${i}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[t]:bf[`${i}_rgb`](a)})};return Y(this,`_commonActions`,{display:e=>{let{display:t}=e.detail,n=t%2==1;this.container.style.visibility=n?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noView:n,noPrint:t===1||t===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{let{hidden:t}=e.detail;this.container.style.visibility=t?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noPrint:t,noView:t})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:t=>{e(`bgColor`,`backgroundColor`,t)},fillColor:t=>{e(`fillColor`,`backgroundColor`,t)},fgColor:t=>{e(`fgColor`,`color`,t)},textColor:t=>{e(`textColor`,`color`,t)},borderColor:t=>{e(`borderColor`,`borderColor`,t)},strokeColor:t=>{e(`strokeColor`,`borderColor`,t)},rotation:e=>{let t=e.detail.rotation;this.setRotation(t),this.annotationStorage.setValue(this.data.id,{rotation:t})}})}_dispatchEventFromSandbox(e,t){let n=this._commonActions;for(let r of Object.keys(t.detail))(e[r]||n[r])?.(t)}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;let t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;let n=this._commonActions;for(let[r,i]of Object.entries(t)){let a=n[r];a&&(a({detail:{[r]:i},target:e}),delete t[r])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[t,n,r,i]=this.data.rect.map(e=>Math.fround(e));if(e.length===8){let[a,o,s,c]=e.subarray(2,6);if(r===a&&i===o&&t===s&&n===c)return}let{style:a}=this.container,o;if(this.#t){let{borderColor:e,borderWidth:t}=a;a.borderWidth=0,o=[`url('data:image/svg+xml;utf8,`,`<svg xmlns="http://www.w3.org/2000/svg"`,` preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${e}" stroke-width="${t}">`],this.container.classList.add(`hasBorder`)}let s=r-t,c=i-n,{svgFactory:l}=this,u=l.createElement(`svg`);u.classList.add(`quadrilateralsContainer`),u.setAttribute(`width`,0),u.setAttribute(`height`,0);let d=l.createElement(`defs`);u.append(d);let f=l.createElement(`clipPath`),p=`clippath_${this.data.id}`;f.setAttribute(`id`,p),f.setAttribute(`clipPathUnits`,`objectBoundingBox`),d.append(f);for(let n=2,r=e.length;n<r;n+=8){let r=e[n],a=e[n+1],u=e[n+2],d=e[n+3],p=l.createElement(`rect`),m=(u-t)/s,h=(i-a)/c,g=(r-u)/s,_=(a-d)/c;p.setAttribute(`x`,m),p.setAttribute(`y`,h),p.setAttribute(`width`,g),p.setAttribute(`height`,_),f.append(p),o?.push(`<rect vector-effect="non-scaling-stroke" x="${m}" y="${h}" width="${g}" height="${_}"/>`)}this.#t&&(o.push(`</g></svg>')`),a.backgroundImage=o.join(``)),this.container.append(u),this.container.style.clipPath=`url(#${p})`}_createPopup(){let{data:e}=this,t=this.#n=new zf({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(t.render())}render(){J("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){let n=[];if(this._fieldObjects){let r=this._fieldObjects[e];if(r)for(let{page:e,id:i,exportValues:a}of r){if(e===-1||i===t)continue;let r=typeof a==`string`?a:null,o=document.querySelector(`[data-element-id="${i}"]`);if(o&&!Ef.has(o)){q(`_getElementsByName - element not allowed: ${i}`);continue}n.push({id:i,exportValue:r,domElement:o})}return n}for(let r of document.getElementsByName(e)){let{exportValue:e}=r,i=r.getAttribute(`data-element-id`);i!==t&&Ef.has(r)&&n.push({id:i,exportValue:e,domElement:r})}return n}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(let t of e)t.classList.add(`highlightArea`);else e.classList.add(`highlightArea`)}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener(`dblclick`,()=>{this.linkService.eventBus?.dispatch(`switchannotationeditormode`,{source:this,mode:e,editId:t})})}},Af=class extends kf{constructor(e,t=null){super(e,{isRenderable:!0,ignoreBorder:!!t?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=e.data.isTooltipOnly}render(){let{data:e,linkService:t}=this,n=document.createElement(`a`);n.setAttribute(`data-element-id`,e.id);let r=!1;return e.url?(t.addLinkAttributes(n,e.url,e.newWindow),r=!0):e.action?(this._bindNamedAction(n,e.action),r=!0):e.attachment?(this.#t(n,e.attachment,e.attachmentDest),r=!0):e.setOCGState?(this.#n(n,e.setOCGState),r=!0):e.dest?(this._bindLink(n,e.dest),r=!0):(e.actions&&(e.actions.Action||e.actions[`Mouse Up`]||e.actions[`Mouse Down`])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(n,e),r=!0),e.resetForm?(this._bindResetFormAction(n,e.resetForm),r=!0):this.isTooltipOnly&&!r&&(this._bindLink(n,``),r=!0)),this.container.classList.add(`linkAnnotation`),r&&this.container.append(n),this.container}#e(){this.container.setAttribute(`data-internal-link`,``)}_bindLink(e,t){e.href=this.linkService.getDestinationHash(t),e.onclick=()=>(t&&this.linkService.goToDestination(t),!1),(t||t===``)&&this.#e()}_bindNamedAction(e,t){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeNamedAction(t),!1),this.#e()}#t(e,t,n=null){e.href=this.linkService.getAnchorUrl(``),t.description&&(e.title=t.description),e.onclick=()=>(this.downloadManager?.openOrDownloadData(t.content,t.filename,n),!1),this.#e()}#n(e,t){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeSetOCGState(t),!1),this.#e()}_bindJSAction(e,t){e.href=this.linkService.getAnchorUrl(``);let n=new Map([[`Action`,`onclick`],[`Mouse Up`,`onmouseup`],[`Mouse Down`,`onmousedown`]]);for(let r of Object.keys(t.actions)){let i=n.get(r);i&&(e[i]=()=>(this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t.id,name:r}}),!1))}e.onclick||=()=>!1,this.#e()}_bindResetFormAction(e,t){let n=e.onclick;if(n||(e.href=this.linkService.getAnchorUrl(``)),this.#e(),!this._fieldObjects){q('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),n||(e.onclick=()=>!1);return}e.onclick=()=>{n?.();let{fields:e,refs:r,include:i}=t,a=[];if(e.length!==0||r.length!==0){let t=new Set(r);for(let n of e){let e=this._fieldObjects[n]||[];for(let{id:n}of e)t.add(n)}for(let e of Object.values(this._fieldObjects))for(let n of e)t.has(n.id)===i&&a.push(n)}else for(let e of Object.values(this._fieldObjects))a.push(...e);let o=this.annotationStorage,s=[];for(let e of a){let{id:t}=e;switch(s.push(t),e.type){case`text`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}case`checkbox`:case`radiobutton`:{let n=e.defaultValue===e.exportValues;o.setValue(t,{value:n});break}case`combobox`:case`listbox`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}default:continue}let n=document.querySelector(`[data-element-id="${t}"]`);if(n){if(!Ef.has(n)){q(`_bindResetFormAction - element not allowed: ${t}`);continue}n.dispatchEvent(new Event(`resetform`))}}return this.enableScripting&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:`app`,ids:s,name:`ResetForm`}}),!1}}},jf=class extends kf{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add(`textAnnotation`);let e=document.createElement(`img`);return e.src=this.imageResourcesPath+`annotation-`+this.data.name.toLowerCase()+`.svg`,e.setAttribute(`data-l10n-id`,`pdfjs-text-annotation-type`),e.setAttribute(`data-l10n-args`,JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(e),this.container}},Mf=class extends kf{render(){return this.container}showElementAndHideCanvas(e){this.data.hasOwnCanvas&&(e.previousSibling?.nodeName===`CANVAS`&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return _l.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,n,r,i){n.includes(`mouse`)?e.addEventListener(n,e=>{this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e),shift:e.shiftKey,modifier:this._getKeyModifier(e)}})}):e.addEventListener(n,e=>{if(n===`blur`){if(!t.focused||!e.relatedTarget)return;t.focused=!1}else if(n===`focus`){if(t.focused)return;t.focused=!0}i&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e)}})})}_setEventListeners(e,t,n,r){for(let[i,a]of n)(a===`Action`||this.data.actions?.[a])&&((a===`Focus`||a===`Blur`)&&(t||={focused:!1}),this._setEventListener(e,t,i,a,r),a===`Focus`&&!this.data.actions?.Blur?this._setEventListener(e,t,`blur`,`Blur`,null):a===`Blur`&&!this.data.actions?.Focus&&this._setEventListener(e,t,`focus`,`Focus`,null))}_setBackgroundColor(e){let t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?`transparent`:X.makeHexColor(t[0],t[1],t[2])}_setTextStyle(e){let t=[`left`,`center`,`right`],{fontColor:n}=this.data.defaultAppearanceData,r=this.data.defaultAppearanceData.fontSize||Tf,i=e.style,a,o=e=>Math.round(10*e)/10;if(this.data.multiLine){let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2),t=e/(Math.round(e/(Rc*r))||1);a=Math.min(r,o(t/Rc))}else{let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(r,o(e/Rc))}i.fontSize=`calc(${a}px * var(--scale-factor))`,i.color=X.makeHexColor(n[0],n[1],n[2]),this.data.textAlignment!==null&&(i.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute(`required`,!0):e.removeAttribute(`required`),e.setAttribute(`aria-required`,t)}},Nf=class extends Mf{constructor(e){let t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,n,r){let i=this.annotationStorage;for(let a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[t]=n),i.setValue(a.id,{[r]:n})}render(){let e=this.annotationStorage,t=this.data.id;this.container.classList.add(`textWidgetAnnotation`);let n=null;if(this.renderForms){let r=e.getValue(t,{value:this.data.fieldValue}),i=r.value||``,a=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;a&&i.length>a&&(i=i.slice(0,a));let o=r.formattedValue||this.data.textContent?.join(`
|
|
440
|
-
`)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,``));let s={userValue:i,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(n=document.createElement(`textarea`),n.textContent=o??i,this.data.doNotScroll&&(n.style.overflowY=`hidden`)):(n=document.createElement(`input`),n.type=`text`,n.setAttribute(`value`,o??i),this.data.doNotScroll&&(n.style.overflowX=`hidden`)),this.data.hasOwnCanvas&&(n.hidden=!0),Ef.add(n),n.setAttribute(`data-element-id`,t),n.disabled=this.data.readOnly,n.name=this.data.fieldName,n.tabIndex=wf,this._setRequired(n,this.data.required),a&&(n.maxLength=a),n.addEventListener(`input`,r=>{e.setValue(t,{value:r.target.value}),this.setPropertyOnSiblings(n,`value`,r.target.value,`value`),s.formattedValue=null}),n.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue??``;n.value=s.userValue=t,s.formattedValue=null});let c=e=>{let{formattedValue:t}=s;t!=null&&(e.target.value=t),e.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener(`focus`,e=>{if(s.focused)return;let{target:t}=e;s.userValue&&(t.value=s.userValue),s.lastCommittedValue=t.value,s.commitKey=1,this.data.actions?.Focus||(s.focused=!0)}),n.addEventListener(`updatefromsandbox`,n=>{this.showElementAndHideCanvas(n.target),this._dispatchEventFromSandbox({value(n){s.userValue=n.detail.value??``,e.setValue(t,{value:s.userValue.toString()}),n.target.value=s.userValue},formattedValue(n){let{formattedValue:r}=n.detail;s.formattedValue=r,r!=null&&n.target!==document.activeElement&&(n.target.value=r),e.setValue(t,{formattedValue:r})},selRange(e){e.target.setSelectionRange(...e.detail.selRange)},charLimit:n=>{let{charLimit:r}=n.detail,{target:i}=n;if(r===0){i.removeAttribute(`maxLength`);return}i.setAttribute(`maxLength`,r);let a=s.userValue;!a||a.length<=r||(a=a.slice(0,r),i.value=s.userValue=a,e.setValue(t,{value:a}),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:a,willCommit:!0,commitKey:1,selStart:i.selectionStart,selEnd:i.selectionEnd}}))}},n)}),n.addEventListener(`keydown`,e=>{s.commitKey=1;let n=-1;if(e.key===`Escape`?n=0:e.key===`Enter`&&!this.data.multiLine?n=2:e.key===`Tab`&&(s.commitKey=3),n===-1)return;let{value:r}=e.target;s.lastCommittedValue!==r&&(s.lastCommittedValue=r,s.userValue=r,this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:r,willCommit:!0,commitKey:n,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}))});let r=c;c=null,n.addEventListener(`blur`,e=>{if(!s.focused||!e.relatedTarget)return;this.data.actions?.Blur||(s.focused=!1);let{value:n}=e.target;s.userValue=n,s.lastCommittedValue!==n&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:n,willCommit:!0,commitKey:s.commitKey,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}),r(e)}),this.data.actions?.Keystroke&&n.addEventListener(`beforeinput`,e=>{s.lastCommittedValue=null;let{data:n,target:r}=e,{value:i,selectionStart:a,selectionEnd:o}=r,c=a,l=o;switch(e.inputType){case`deleteWordBackward`:{let e=i.substring(0,a).match(/\w*[^\w]*$/);e&&(c-=e[0].length);break}case`deleteWordForward`:{let e=i.substring(a).match(/^[^\w]*\w*/);e&&(l+=e[0].length);break}case`deleteContentBackward`:a===o&&--c;break;case`deleteContentForward`:a===o&&(l+=1);break}e.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:i,change:n||``,willCommit:!1,selStart:c,selEnd:l}})}),this._setEventListeners(n,s,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.value)}if(c&&n.addEventListener(`blur`,c),this.data.comb){let e=(this.data.rect[2]-this.data.rect[0])/a;n.classList.add(`comb`),n.style.letterSpacing=`calc(${e}px * var(--scale-factor) - 1ch)`}}else n=document.createElement(`div`),n.textContent=this.data.fieldValue,n.style.verticalAlign=`middle`,n.style.display=`table-cell`,this.data.hasOwnCanvas&&(n.hidden=!0);return this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}},Pf=class extends Mf{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}},Ff=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.exportValue===t.fieldValue}).value;typeof r==`string`&&(r=r!==`Off`,e.setValue(n,{value:r})),this.container.classList.add(`buttonWidgetAnnotation`,`checkBox`);let i=document.createElement(`input`);return Ef.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`checkbox`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.setAttribute(`exportValue`,t.exportValue),i.tabIndex=wf,i.addEventListener(`change`,r=>{let{name:i,checked:a}=r.target;for(let r of this._getElementsByName(i,n)){let n=a&&r.exportValue===t.exportValue;r.domElement&&(r.domElement.checked=n),e.setValue(r.id,{value:n})}e.setValue(n,{value:a})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue||`Off`;e.target.checked=n===t.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value(t){t.target.checked=t.detail.value!==`Off`,e.setValue(n,{value:t.target.checked})}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},If=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`buttonWidgetAnnotation`,`radioButton`);let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.fieldValue===t.buttonValue}).value;if(typeof r==`string`&&(r=r!==t.buttonValue,e.setValue(n,{value:r})),r)for(let r of this._getElementsByName(t.fieldName,n))e.setValue(r.id,{value:!1});let i=document.createElement(`input`);if(Ef.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`radio`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.tabIndex=wf,i.addEventListener(`change`,t=>{let{name:r,checked:i}=t.target;for(let t of this._getElementsByName(r,n))e.setValue(t.id,{value:!1});e.setValue(n,{value:i})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue;e.target.checked=n!=null&&n===t.buttonValue}),this.enableScripting&&this.hasJSActions){let r=t.buttonValue;i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value:t=>{let i=r===t.detail.value;for(let r of this._getElementsByName(t.target.name)){let t=i&&r.id===n;r.domElement&&(r.domElement.checked=t),e.setValue(r.id,{value:t})}}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)}return this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},Lf=class extends Af{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){let e=super.render();e.classList.add(`buttonWidgetAnnotation`,`pushButton`);let t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener(`updatefromsandbox`,e=>{this._dispatchEventFromSandbox({},e)})),e}},Rf=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`choiceWidgetAnnotation`);let e=this.annotationStorage,t=this.data.id,n=e.getValue(t,{value:this.data.fieldValue}),r=document.createElement(`select`);Ef.add(r),r.setAttribute(`data-element-id`,t),r.disabled=this.data.readOnly,this._setRequired(r,this.data.required),r.name=this.data.fieldName,r.tabIndex=wf;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(r.size=this.data.options.length,this.data.multiSelect&&(r.multiple=!0)),r.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue;for(let e of r.options)e.selected=e.value===t});for(let e of this.data.options){let t=document.createElement(`option`);t.textContent=e.displayValue,t.value=e.exportValue,n.value.includes(e.exportValue)&&(t.setAttribute(`selected`,!0),i=!1),r.append(t)}let a=null;if(i){let e=document.createElement(`option`);e.value=` `,e.setAttribute(`hidden`,!0),e.setAttribute(`selected`,!0),r.prepend(e),a=()=>{e.remove(),r.removeEventListener(`input`,a),a=null},r.addEventListener(`input`,a)}let o=e=>{let t=e?`value`:`textContent`,{options:n,multiple:i}=r;return i?Array.prototype.filter.call(n,e=>e.selected).map(e=>e[t]):n.selectedIndex===-1?null:n[n.selectedIndex][t]},s=o(!1),c=e=>{let t=e.target.options;return Array.prototype.map.call(t,e=>({displayValue:e.textContent,exportValue:e.value}))};return this.enableScripting&&this.hasJSActions?(r.addEventListener(`updatefromsandbox`,n=>{this._dispatchEventFromSandbox({value(n){a?.();let i=n.detail.value,c=new Set(Array.isArray(i)?i:[i]);for(let e of r.options)e.selected=c.has(e.value);e.setValue(t,{value:o(!0)}),s=o(!1)},multipleSelection(e){r.multiple=!0},remove(n){let i=r.options,a=n.detail.remove;i[a].selected=!1,r.remove(a),i.length>0&&Array.prototype.findIndex.call(i,e=>e.selected)===-1&&(i[0].selected=!0),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},clear(n){for(;r.length!==0;)r.remove(0);e.setValue(t,{value:null,items:[]}),s=o(!1)},insert(n){let{index:i,displayValue:a,exportValue:l}=n.detail.insert,u=r.children[i],d=document.createElement(`option`);d.textContent=a,d.value=l,u?u.before(d):r.append(d),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},items(n){let{items:i}=n.detail;for(;r.length!==0;)r.remove(0);for(let e of i){let{displayValue:t,exportValue:n}=e,i=document.createElement(`option`);i.textContent=t,i.value=n,r.append(i)}r.options.length>0&&(r.options[0].selected=!0),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},indices(n){let r=new Set(n.detail.indices);for(let e of n.target.options)e.selected=r.has(e.index);e.setValue(t,{value:o(!0)}),s=o(!1)},editable(e){e.target.disabled=!e.detail.editable}},n)}),r.addEventListener(`input`,n=>{let r=o(!0),i=o(!1);e.setValue(t,{value:r}),n.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:s,change:i,changeEx:r,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(r,null,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`],[`input`,`Action`],[`input`,`Validate`]],e=>e.target.value)):r.addEventListener(`input`,function(n){e.setValue(t,{value:o(!0)})}),this.data.combo&&this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},zf=class extends kf{constructor(e){let{data:t,elements:n}=e;super(e,{isRenderable:kf._hasPopupData(t)}),this.elements=n,this.popup=null}render(){this.container.classList.add(`popupAnnotation`);let e=this.popup=new Bf({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),t=[];for(let n of this.elements)n.popup=e,n.container.ariaHasPopup=`dialog`,t.push(n.data.id),n.addHighlightArea();return this.container.setAttribute(`aria-controls`,t.map(e=>`${wl}${e}`).join(`,`)),this.container}},Bf=class{#e=this.#C.bind(this);#t=this.#D.bind(this);#n=this.#E.bind(this);#r=this.#T.bind(this);#i=null;#a=null;#o=null;#s=null;#c=null;#l=null;#u=null;#d=!1;#f=null;#p=null;#m=null;#h=null;#g=null;#_=null;#v=!1;constructor({container:e,color:t,elements:n,titleObj:r,modificationDate:i,contentsObj:a,richText:o,parent:s,rect:c,parentRect:l,open:u}){this.#a=e,this.#g=r,this.#o=a,this.#h=o,this.#l=s,this.#i=t,this.#m=c,this.#u=l,this.#c=n,this.#s=zl.toDateObject(i),this.trigger=n.flatMap(e=>e.getElementsToTriggerPopup());for(let e of this.trigger)e.addEventListener(`click`,this.#r),e.addEventListener(`mouseenter`,this.#n),e.addEventListener(`mouseleave`,this.#t),e.classList.add(`popupTriggerArea`);for(let e of n)e.container?.addEventListener(`keydown`,this.#e);this.#a.hidden=!0,u&&this.#T()}render(){if(this.#f)return;let e=this.#f=document.createElement(`div`);if(e.className=`popup`,this.#i){let t=e.style.outlineColor=X.makeHexColor(...this.#i);CSS.supports(`background-color`,`color-mix(in srgb, red 30%, white)`)?e.style.backgroundColor=`color-mix(in srgb, ${t} 30%, white)`:e.style.backgroundColor=X.makeHexColor(...this.#i.map(e=>Math.floor(.7*(255-e)+e)))}let t=document.createElement(`span`);t.className=`header`;let n=document.createElement(`h1`);if(t.append(n),{dir:n.dir,str:n.textContent}=this.#g,e.append(t),this.#s){let e=document.createElement(`span`);e.classList.add(`popupDate`),e.setAttribute(`data-l10n-id`,`pdfjs-annotation-date-time-string`),e.setAttribute(`data-l10n-args`,JSON.stringify({dateObj:this.#s.valueOf()})),t.append(e)}let r=this.#y;if(r)Cf.render({xfaHtml:r,intent:`richText`,div:e}),e.lastChild.classList.add(`richText`,`popupContent`);else{let t=this._formatContents(this.#o);e.append(t)}this.#a.append(e)}get#y(){let e=this.#h,t=this.#o;return e?.str&&(!t?.str||t.str===e.str)&&this.#h.html||null}get#b(){return this.#y?.attributes?.style?.fontSize||0}get#x(){return this.#y?.attributes?.style?.color||null}#S(e){let t=[],n={str:e,html:{name:`div`,attributes:{dir:`auto`},children:[{name:`p`,children:t}]}},r={style:{color:this.#x,fontSize:this.#b?`calc(${this.#b}px * var(--scale-factor))`:``}};for(let n of e.split(`
|
|
441
|
-
`))t.push({name:`span`,value:n,attributes:r});return n}_formatContents({str:e,dir:t}){let n=document.createElement(`p`);n.classList.add(`popupContent`),n.dir=t;let r=e.split(/(?:\r\n?|\n)/);for(let e=0,t=r.length;e<t;++e){let i=r[e];n.append(document.createTextNode(i)),e<t-1&&n.append(document.createElement(`br`))}return n}#C(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key===`Enter`||e.key===`Escape`&&this.#d)&&this.#T()}updateEdited({rect:e,popupContent:t}){this.#_||={contentsObj:this.#o,richText:this.#h},e&&(this.#p=null),t&&(this.#h=this.#S(t),this.#o=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#_&&({contentsObj:this.#o,richText:this.#h}=this.#_,this.#_=null,this.#f?.remove(),this.#f=null,this.#p=null)}#w(){if(this.#p!==null)return;let{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:r,pageY:i}}}=this.#l,a=!!this.#u,o=a?this.#u:this.#m;for(let e of this.#c)if(!o||X.intersect(e.data.rect,o)!==null){o=e.data.rect,a=!0;break}let s=X.normalizeRect([o[0],e[3]-o[1]+e[1],o[2],e[3]-o[3]+e[1]]),c=a?o[2]-o[0]+5:0,l=s[0]+c,u=s[1];this.#p=[100*(l-r)/t,100*(u-i)/n];let{style:d}=this.#a;d.left=`${this.#p[0]}%`,d.top=`${this.#p[1]}%`}#T(){this.#d=!this.#d,this.#d?(this.#E(),this.#a.addEventListener(`click`,this.#r),this.#a.addEventListener(`keydown`,this.#e)):(this.#D(),this.#a.removeEventListener(`click`,this.#r),this.#a.removeEventListener(`keydown`,this.#e))}#E(){this.#f||this.render(),this.isVisible?this.#d&&this.#a.classList.add(`focused`):(this.#w(),this.#a.hidden=!1,this.#a.style.zIndex=parseInt(this.#a.style.zIndex)+1e3)}#D(){this.#a.classList.remove(`focused`),!(this.#d||!this.isVisible)&&(this.#a.hidden=!0,this.#a.style.zIndex=parseInt(this.#a.style.zIndex)-1e3)}forceHide(){this.#v=this.isVisible,this.#v&&(this.#a.hidden=!0)}maybeShow(){this.#v&&(this.#f||this.#E(),this.#v=!1,this.#a.hidden=!1)}get isVisible(){return this.#a.hidden===!1}},Vf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=G.FREETEXT}render(){if(this.container.classList.add(`freeTextAnnotation`),this.textContent){let e=document.createElement(`div`);e.classList.add(`annotationTextContent`),e.setAttribute(`role`,`comment`);for(let t of this.textContent){let n=document.createElement(`span`);n.textContent=t,e.append(n)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},Hf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`lineAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=this.#e=this.svgFactory.createElement(`svg:line`);return i.setAttribute(`x1`,e.rect[2]-e.lineCoordinates[0]),i.setAttribute(`y1`,e.rect[3]-e.lineCoordinates[1]),i.setAttribute(`x2`,e.rect[2]-e.lineCoordinates[2]),i.setAttribute(`y2`,e.rect[3]-e.lineCoordinates[3]),i.setAttribute(`stroke-width`,e.borderStyle.width||1),i.setAttribute(`stroke`,`transparent`),i.setAttribute(`fill`,`transparent`),r.append(i),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Uf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`squareAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:rect`);return a.setAttribute(`x`,i/2),a.setAttribute(`y`,i/2),a.setAttribute(`width`,t-i),a.setAttribute(`height`,n-i),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Wf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`circleAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:ellipse`);return a.setAttribute(`cx`,t/2),a.setAttribute(`cy`,n/2),a.setAttribute(`rx`,t/2-i/2),a.setAttribute(`ry`,n/2-i/2),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Gf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`polylineAnnotation`,this.svgElementName=`svg:polyline`}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,vertices:t,borderStyle:n,popupRef:r}}=this;if(!t)return this.container;let{width:i,height:a}=Df(e),o=this.svgFactory.create(i,a,!0),s=[];for(let n=0,r=t.length;n<r;n+=2){let r=t[n]-e[0],i=e[3]-t[n+1];s.push(`${r},${i}`)}s=s.join(` `);let c=this.#e=this.svgFactory.createElement(this.svgElementName);return c.setAttribute(`points`,s),c.setAttribute(`stroke-width`,n.width||1),c.setAttribute(`stroke`,`transparent`),c.setAttribute(`fill`,`transparent`),o.append(c),this.container.append(o),!r&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Kf=class extends Gf{constructor(e){super(e),this.containerClassName=`polygonAnnotation`,this.svgElementName=`svg:polygon`}},qf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add(`caretAnnotation`),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}},Jf=class extends kf{#e=null;#t=[];constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`inkAnnotation`,this.svgElementName=`svg:polyline`,this.annotationEditorType=this.data.it===`InkHighlight`?G.HIGHLIGHT:G.INK}#n(e,t){switch(e){case 90:return{transform:`rotate(90) translate(${-t[0]},${t[1]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};case 180:return{transform:`rotate(180) translate(${-t[2]},${t[1]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]};case 270:return{transform:`rotate(270) translate(${-t[2]},${t[3]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};default:return{transform:`translate(${-t[0]},${t[3]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]}}}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,rotation:t,inkLists:n,borderStyle:r,popupRef:i}}=this,{transform:a,width:o,height:s}=this.#n(t,e),c=this.svgFactory.create(o,s,!0),l=this.#e=this.svgFactory.createElement(`svg:g`);c.append(l),l.setAttribute(`stroke-width`,r.width||1),l.setAttribute(`stroke-linecap`,`round`),l.setAttribute(`stroke-linejoin`,`round`),l.setAttribute(`stroke-miterlimit`,10),l.setAttribute(`stroke`,`transparent`),l.setAttribute(`fill`,`transparent`),l.setAttribute(`transform`,a);for(let e=0,t=n.length;e<t;e++){let t=this.svgFactory.createElement(this.svgElementName);this.#t.push(t),t.setAttribute(`points`,n[e].join(`,`)),l.append(t)}return!i&&this.hasPopupData&&this._createPopup(),this.container.append(c),this._editOnDoubleClick(),this.container}updateEdited(e){super.updateEdited(e);let{thickness:t,points:n,rect:r}=e,i=this.#e;if(t>=0&&i.setAttribute(`stroke-width`,t||1),n)for(let e=0,t=this.#t.length;e<t;e++)this.#t[e].setAttribute(`points`,n[e].join(`,`));if(r){let{transform:e,width:t,height:n}=this.#n(this.data.rotation,r);i.parentElement.setAttribute(`viewBox`,`0 0 ${t} ${n}`),i.setAttribute(`transform`,e)}}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Yf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=G.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`highlightAnnotation`),this._editOnDoubleClick(),this.container}},Xf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`underlineAnnotation`),this.container}},Zf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`squigglyAnnotation`),this.container}},Qf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`strikeoutAnnotation`),this.container}},$f=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=G.STAMP}render(){return this.container.classList.add(`stampAnnotation`),this.container.setAttribute(`role`,`img`),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},ep=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0});let{file:t}=this.data;this.filename=t.filename,this.content=t.content,this.linkService.eventBus?.dispatch(`fileattachmentannotation`,{source:this,...t})}render(){this.container.classList.add(`fileAttachmentAnnotation`);let{container:e,data:t}=this,n;t.hasAppearance||t.fillAlpha===0?n=document.createElement(`div`):(n=document.createElement(`img`),n.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(t.name)?`paperclip`:`pushpin`}.svg`,t.fillAlpha&&t.fillAlpha<1&&(n.style=`filter: opacity(${Math.round(t.fillAlpha*100)}%);`)),n.addEventListener(`dblclick`,this.#t.bind(this)),this.#e=n;let{isMac:r}=_l.platform;return e.addEventListener(`keydown`,e=>{e.key===`Enter`&&(r?e.metaKey:e.ctrlKey)&&this.#t()}),!t.popupRef&&this.hasPopupData?this._createPopup():n.classList.add(`popupTriggerArea`),e.append(n),e}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}#t(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}},tp=class{#e=null;#t=null;#n=new Map;#r=null;constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:r,page:i,viewport:a,structTreeLayer:o}){this.div=e,this.#e=t,this.#t=n,this.#r=o||null,this.page=i,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=r}hasEditableAnnotations(){return this.#n.size>0}async#i(e,t){let n=e.firstChild||e,r=n.id=`${wl}${t}`,i=await this.#r?.getAriaAttributes(r);if(i)for(let[e,t]of i)n.setAttribute(e,t);this.div.append(e),this.#e?.moveElementInDOM(this.div,e,n,!1)}async render(e){let{annotations:t}=e,n=this.div;Wl(n,this.viewport);let r=new Map,i={data:null,layer:n,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||``,renderForms:e.renderForms!==!1,svgFactory:new Sf,annotationStorage:e.annotationStorage||new lu,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(let e of t){if(e.noHTML)continue;let t=e.annotationType===Gc.POPUP;if(t){let t=r.get(e.id);if(!t)continue;i.elements=t}else{let{width:t,height:n}=Df(e.rect);if(t<=0||n<=0)continue}i.data=e;let n=Of.create(i);if(!n.isRenderable)continue;if(!t&&e.popupRef){let t=r.get(e.popupRef);t?t.push(n):r.set(e.popupRef,[n])}let a=n.render();e.hidden&&(a.style.visibility=`hidden`),await this.#i(a,e.id),n._isEditable&&(this.#n.set(n.data.id,n),this._annotationEditorUIManager?.renderAnnotationElement(n))}this.#a()}update({viewport:e}){let t=this.div;this.viewport=e,Wl(t,{rotation:e.rotation}),this.#a(),t.hidden=!1}#a(){if(!this.#t)return;let e=this.div;for(let[t,n]of this.#t){let r=e.querySelector(`[data-annotation-id="${t}"]`);if(!r)continue;n.className=`annotationContent`;let{firstChild:i}=r;i?i.nodeName===`CANVAS`?i.replaceWith(n):i.classList.contains(`annotationContent`)?i.after(n):i.before(n):r.append(n)}this.#t.clear()}getEditableAnnotations(){return Array.from(this.#n.values())}getEditableAnnotation(e){return this.#n.get(e)}},np=/\r\n?|\n/g,rp=class e extends Q{#e;#t=``;#n=`${this.id}-editor`;#r=null;#i;static _freeTextDefaultContent=``;static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.isEmpty(),r=eu.TRANSLATE_SMALL,i=eu.TRANSLATE_BIG;return Y(this,`_keyboardManager`,new Ql([[[`ctrl+s`,`mac+meta+s`,`ctrl+p`,`mac+meta+p`],t.commitOrRemove,{bubbles:!0}],[[`ctrl+Enter`,`mac+meta+Enter`,`Escape`,`mac+Escape`],t.commitOrRemove],[[`ArrowLeft`,`mac+ArrowLeft`],t._translateEmpty,{args:[-r,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t._translateEmpty,{args:[-i,0],checker:n}],[[`ArrowRight`,`mac+ArrowRight`],t._translateEmpty,{args:[r,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t._translateEmpty,{args:[i,0],checker:n}],[[`ArrowUp`,`mac+ArrowUp`],t._translateEmpty,{args:[0,-r],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t._translateEmpty,{args:[0,-i],checker:n}],[[`ArrowDown`,`mac+ArrowDown`],t._translateEmpty,{args:[0,r],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t._translateEmpty,{args:[0,i],checker:n}]]))}static _type=`freetext`;static _editorType=G.FREETEXT;constructor(t){super({...t,name:`freeTextEditor`}),this.#e=t.color||e._defaultColor||Q._defaultLineColor,this.#i=t.fontSize||e._defaultFontSize}static initialize(e,t){Q.initialize(e,t);let n=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(n.getPropertyValue(`--freetext-padding`))}static updateDefaultParams(t,n){switch(t){case K.FREETEXT_SIZE:e._defaultFontSize=n;break;case K.FREETEXT_COLOR:e._defaultColor=n;break}}updateParams(e,t){switch(e){case K.FREETEXT_SIZE:this.#a(t);break;case K.FREETEXT_COLOR:this.#o(t);break}}static get defaultPropertiesToUpdate(){return[[K.FREETEXT_SIZE,e._defaultFontSize],[K.FREETEXT_COLOR,e._defaultColor||Q._defaultLineColor]]}get propertiesToUpdate(){return[[K.FREETEXT_SIZE,this.#i],[K.FREETEXT_COLOR,this.#e]]}#a(e){let t=e=>{this.editorDiv.style.fontSize=`calc(${e}px * var(--scale-factor))`,this.translate(0,-(e-this.#i)*this.parentScale),this.#i=e,this.#c()},n=this.#i;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#o(e){let t=e=>{this.#e=this.editorDiv.style.color=e},n=this.#e;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(e,t){this._uiManager.translateSelectedEditors(e,t,!0)}getInitialTranslation(){let t=this.parentScale;return[-e._internalPadding*t,-(e._internalPadding+this.#i)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(G.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove(`enabled`),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute(`aria-activedescendant`),this.#r=new AbortController;let e=this._uiManager.combinedSignal(this.#r);this.editorDiv.addEventListener(`keydown`,this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener(`focus`,this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener(`blur`,this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener(`input`,this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener(`paste`,this.editorDivPaste.bind(this),{signal:e})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add(`enabled`),this.editorDiv.contentEditable=!1,this.div.setAttribute(`aria-activedescendant`,this.#n),this._isDraggable=!0,this.#r?.abort(),this.#r=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add(`freetextEditing`))}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(e){this.width||(this.enableEditMode(),e&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===``}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add(`freetextEditing`)),super.remove()}#s(){let t=[];this.editorDiv.normalize();let n=null;for(let r of this.editorDiv.childNodes)n?.nodeType===Node.TEXT_NODE&&r.nodeName===`BR`||(t.push(e.#l(r)),n=r);return t.join(`
|
|
442
|
-
`)}#c(){let[e,t]=this.parentDimensions,n;if(this.isAttachedToDOM)n=this.div.getBoundingClientRect();else{let{currentLayer:e,div:t}=this,r=t.style.display,i=t.classList.contains(`hidden`);t.classList.remove(`hidden`),t.style.display=`hidden`,e.div.append(this.div),n=t.getBoundingClientRect(),t.remove(),t.style.display=r,t.classList.toggle(`hidden`,i)}this.rotation%180==this.parentRotation%180?(this.width=n.width/e,this.height=n.height/t):(this.width=n.height/e,this.height=n.width/t),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let e=this.#t,t=this.#t=this.#s().trimEnd();if(e===t)return;let n=e=>{if(this.#t=e,!e){this.remove();return}this.#u(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{n(t)},undo:()=>{n(e)},mustExec:!1}),this.#c()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(e){this.enterInEditMode()}keydown(e){e.target===this.div&&e.key===`Enter`&&(this.enterInEditMode(),e.preventDefault())}editorDivKeydown(t){e._keyboardManager.exec(this,t)}editorDivFocus(e){this.isEditing=!0}editorDivBlur(e){this.isEditing=!1}editorDivInput(e){this.parent.div.classList.toggle(`freetextEditing`,this.isEmpty())}disableEditing(){this.editorDiv.setAttribute(`role`,`comment`),this.editorDiv.removeAttribute(`aria-multiline`)}enableEditing(){this.editorDiv.setAttribute(`role`,`textbox`),this.editorDiv.setAttribute(`aria-multiline`,!0)}render(){if(this.div)return this.div;let e,t;this.width&&(e=this.x,t=this.y),super.render(),this.editorDiv=document.createElement(`div`),this.editorDiv.className=`internal`,this.editorDiv.setAttribute(`id`,this.#n),this.editorDiv.setAttribute(`data-l10n-id`,`pdfjs-free-text2`),this.editorDiv.setAttribute(`data-l10n-attrs`,`default-content`),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:n}=this.editorDiv;if(n.fontSize=`calc(${this.#i}px * var(--scale-factor))`,n.color=this.#e,this.div.append(this.editorDiv),this.overlayDiv=document.createElement(`div`),this.overlayDiv.classList.add(`overlay`,`enabled`),this.div.append(this.overlayDiv),Jl(this,this.div,[`dblclick`,`keydown`]),this.width){let[n,r]=this.parentDimensions;if(this.annotationElementId){let{position:i}=this._initialData,[a,o]=this.getInitialTranslation();[a,o]=this.pageTranslationToScreen(a,o);let[s,c]=this.pageDimensions,[l,u]=this.pageTranslation,d,f;switch(this.rotation){case 0:d=e+(i[0]-l)/s,f=t+this.height-(i[1]-u)/c;break;case 90:d=e+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[o,-a];break;case 180:d=e-this.width+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[-a,-o];break;case 270:d=e+(i[0]-l-this.height*c)/s,f=t+(i[1]-u-this.width*s)/c,[a,o]=[-o,a]
|
|
439
|
+
`}applyTo2d({imageData:{data:e}}){let t=-this.vibrance;for(let n=0;n<e.length;n+=4){let r=e[n],i=e[n+1],a=e[n+2],o=Math.max(r,i,a),s=(r+i+a)/3,c=2*Math.abs(o-s)/255*t;e[n]+=o===r?0:(o-r)*c,e[n+1]+=o===i?0:(o-i)*c,e[n+2]+=o===a?0:(o-a)*c}}sendUniformData(e,t){e.uniform1f(t.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}};p(Nc,`type`,`Vibrance`),p(Nc,`defaults`,{vibrance:0}),p(Nc,`uniformLocations`,[`uVibrance`]),L.setClass(Nc),u({BaseFilter:()=>ec,BlackWhite:()=>gc,BlendColor:()=>nc,BlendImage:()=>ic,Blur:()=>ac,Brightness:()=>oc,Brownie:()=>uc,ColorMatrix:()=>cc,Composed:()=>_c,Contrast:()=>vc,Convolute:()=>bc,Gamma:()=>Sc,Grayscale:()=>wc,HueRotation:()=>Ec,Invert:()=>Dc,Kodachrome:()=>fc,Noise:()=>Oc,Pixelate:()=>kc,Polaroid:()=>mc,RemoveColor:()=>Ac,Resize:()=>jc,Saturation:()=>Mc,Sepia:()=>hc,Technicolor:()=>pc,Vibrance:()=>Nc,Vintage:()=>dc});var Pc={};Pc.d=(e,t)=>{for(var n in t)Pc.o(t,n)&&!Pc.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},Pc.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var U=globalThis.pdfjsLib={};Pc.d(U,{AbortException:()=>ul,AnnotationEditorLayer:()=>yp,AnnotationEditorParamsType:()=>G,AnnotationEditorType:()=>W,AnnotationEditorUIManager:()=>eu,AnnotationLayer:()=>tp,AnnotationMode:()=>Vc,ColorPicker:()=>up,DOMSVGFactory:()=>Sf,DrawLayer:()=>bp,FeatureTest:()=>_l,GlobalWorkerOptions:()=>ud,ImageKind:()=>Gc,InvalidPDFException:()=>ol,MissingPDFException:()=>sl,OPS:()=>Yc,OutputScale:()=>Gl,PDFDataRangeTransport:()=>of,PDFDateString:()=>zl,PDFWorker:()=>uf,PasswordResponses:()=>Xc,PermissionFlag:()=>Uc,PixelsPerInch:()=>Dl,RenderingCancelledException:()=>Al,TextLayer:()=>Gd,TouchManager:()=>nu,UnexpectedResponseException:()=>cl,Util:()=>X,VerbosityLevel:()=>Jc,XfaLayer:()=>Cf,build:()=>_f,createValidAbsoluteUrl:()=>nl,fetchData:()=>Ol,getDocument:()=>ef,getFilenameFromUrl:()=>Nl,getPdfFilenameFromUrl:()=>Pl,getXfaPageViewport:()=>Bl,isDataScheme:()=>jl,isPdfFile:()=>Ml,noContextMenu:()=>Ll,normalizeUnicode:()=>Sl,setLayerDimensions:()=>Wl,shadow:()=>Y,stopEvent:()=>Rl,version:()=>gf});var Fc=typeof process==`object`&&process+``==`[object process]`&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!==`browser`),Ic=[1,0,0,1,0,0],Lc=[.001,0,0,.001,0,0],Rc=1e7,zc=1.35,Bc={ANY:1,DISPLAY:2,PRINT:4,SAVE:8,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Vc={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Hc=`pdfjs_internal_editor_`,W={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},G={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},Uc={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Wc={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_ADD_TO_PATH:4,STROKE_ADD_TO_PATH:5,FILL_STROKE_ADD_TO_PATH:6,ADD_TO_PATH:7,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Gc={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Kc={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,SOUND:18,MOVIE:19,WIDGET:20,SCREEN:21,PRINTERMARK:22,TRAPNET:23,WATERMARK:24,THREED:25,REDACT:26},qc={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Jc={ERRORS:0,WARNINGS:1,INFOS:5},Yc={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},Xc={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},Zc=Jc.WARNINGS;function Qc(e){Number.isInteger(e)&&(Zc=e)}function $c(){return Zc}function el(e){Zc>=Jc.INFOS&&console.log(`Info: ${e}`)}function K(e){Zc>=Jc.WARNINGS&&console.log(`Warning: ${e}`)}function q(e){throw Error(e)}function J(e,t){e||q(t)}function tl(e){switch(e?.protocol){case`http:`:case`https:`:case`ftp:`:case`mailto:`:case`tel:`:return!0;default:return!1}}function nl(e,t=null,n=null){if(!e)return null;try{if(n&&typeof e==`string`&&(n.addDefaultProtocol&&e.startsWith(`www.`)&&e.match(/\./g)?.length>=2&&(e=`http://${e}`),n.tryConvertEncoding))try{e=yl(e)}catch{}let r=t?new URL(e,t):new URL(e);if(tl(r))return r}catch{}return null}function Y(e,t,n,r=!1){return Object.defineProperty(e,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}var rl=function(){function e(e,t){this.message=e,this.name=t}return e.prototype=Error(),e.constructor=e,e}(),il=class extends rl{constructor(e,t){super(e,`PasswordException`),this.code=t}},al=class extends rl{constructor(e,t){super(e,`UnknownErrorException`),this.details=t}},ol=class extends rl{constructor(e){super(e,`InvalidPDFException`)}},sl=class extends rl{constructor(e){super(e,`MissingPDFException`)}},cl=class extends rl{constructor(e,t){super(e,`UnexpectedResponseException`),this.status=t}},ll=class extends rl{constructor(e){super(e,`FormatError`)}},ul=class extends rl{constructor(e){super(e,`AbortException`)}};function dl(e){(typeof e!=`object`||e?.length===void 0)&&q(`Invalid argument for bytesToString`);let t=e.length,n=8192;if(t<n)return String.fromCharCode.apply(null,e);let r=[];for(let i=0;i<t;i+=n){let a=Math.min(i+n,t),o=e.subarray(i,a);r.push(String.fromCharCode.apply(null,o))}return r.join(``)}function fl(e){typeof e!=`string`&&q(`Invalid argument for stringToBytes`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;++r)n[r]=e.charCodeAt(r)&255;return n}function pl(e){return String.fromCharCode(e>>24&255,e>>16&255,e>>8&255,e&255)}function ml(e){let t=Object.create(null);for(let[n,r]of e)t[n]=r;return t}function hl(){let e=new Uint8Array(4);return e[0]=1,new Uint32Array(e.buffer,0,1)[0]===1}function gl(){try{return Function(``),!0}catch{return!1}}var _l=class{static get isLittleEndian(){return Y(this,`isLittleEndian`,hl())}static get isEvalSupported(){return Y(this,`isEvalSupported`,gl())}static get isOffscreenCanvasSupported(){return Y(this,`isOffscreenCanvasSupported`,typeof OffscreenCanvas<`u`)}static get isImageDecoderSupported(){return Y(this,`isImageDecoderSupported`,typeof ImageDecoder<`u`)}static get platform(){return typeof navigator<`u`&&typeof navigator?.platform==`string`?Y(this,`platform`,{isMac:navigator.platform.includes(`Mac`),isWindows:navigator.platform.includes(`Win`),isFirefox:typeof navigator?.userAgent==`string`&&navigator.userAgent.includes(`Firefox`)}):Y(this,`platform`,{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return Y(this,`isCSSRoundSupported`,globalThis.CSS?.supports?.(`width: round(1.5px, 1px)`))}},vl=Array.from(Array(256).keys(),e=>e.toString(16).padStart(2,`0`)),X=class{static makeHexColor(e,t,n){return`#${vl[e]}${vl[t]}${vl[n]}`}static scaleMinMax(e,t){let n;e[0]?(e[0]<0&&(n=t[0],t[0]=t[2],t[2]=n),t[0]*=e[0],t[2]*=e[0],e[3]<0&&(n=t[1],t[1]=t[3],t[3]=n),t[1]*=e[3],t[3]*=e[3]):(n=t[0],t[0]=t[1],t[1]=n,n=t[2],t[2]=t[3],t[3]=n,e[1]<0&&(n=t[1],t[1]=t[3],t[3]=n),t[1]*=e[1],t[3]*=e[1],e[2]<0&&(n=t[0],t[0]=t[2],t[2]=n),t[0]*=e[2],t[2]*=e[2]),t[0]+=e[4],t[1]+=e[5],t[2]+=e[4],t[3]+=e[5]}static transform(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}static applyTransform(e,t){return[e[0]*t[0]+e[1]*t[2]+t[4],e[0]*t[1]+e[1]*t[3]+t[5]]}static applyInverseTransform(e,t){let n=t[0]*t[3]-t[1]*t[2];return[(e[0]*t[3]-e[1]*t[2]+t[2]*t[5]-t[4]*t[3])/n,(-e[0]*t[1]+e[1]*t[0]+t[4]*t[1]-t[5]*t[0])/n]}static getAxialAlignedBoundingBox(e,t){let n=this.applyTransform(e,t),r=this.applyTransform(e.slice(2,4),t),i=this.applyTransform([e[0],e[3]],t),a=this.applyTransform([e[2],e[1]],t);return[Math.min(n[0],r[0],i[0],a[0]),Math.min(n[1],r[1],i[1],a[1]),Math.max(n[0],r[0],i[0],a[0]),Math.max(n[1],r[1],i[1],a[1])]}static inverseTransform(e){let t=e[0]*e[3]-e[1]*e[2];return[e[3]/t,-e[1]/t,-e[2]/t,e[0]/t,(e[2]*e[5]-e[4]*e[3])/t,(e[4]*e[1]-e[5]*e[0])/t]}static singularValueDecompose2dScale(e){let t=[e[0],e[2],e[1],e[3]],n=e[0]*t[0]+e[1]*t[2],r=e[0]*t[1]+e[1]*t[3],i=e[2]*t[0]+e[3]*t[2],a=e[2]*t[1]+e[3]*t[3],o=(n+a)/2,s=Math.sqrt((n+a)**2-4*(n*a-i*r))/2,c=o+s||1,l=o-s||1;return[Math.sqrt(c),Math.sqrt(l)]}static normalizeRect(e){let t=e.slice(0);return e[0]>e[2]&&(t[0]=e[2],t[2]=e[0]),e[1]>e[3]&&(t[1]=e[3],t[3]=e[1]),t}static intersect(e,t){let n=Math.max(Math.min(e[0],e[2]),Math.min(t[0],t[2])),r=Math.min(Math.max(e[0],e[2]),Math.max(t[0],t[2]));if(n>r)return null;let i=Math.max(Math.min(e[1],e[3]),Math.min(t[1],t[3])),a=Math.min(Math.max(e[1],e[3]),Math.max(t[1],t[3]));return i>a?null:[n,i,r,a]}static#e(e,t,n,r,i,a,o,s,c,l){if(c<=0||c>=1)return;let u=1-c,d=c*c,f=d*c,p=u*(u*(u*e+3*c*t)+3*d*n)+f*r,m=u*(u*(u*i+3*c*a)+3*d*o)+f*s;l[0]=Math.min(l[0],p),l[1]=Math.min(l[1],m),l[2]=Math.max(l[2],p),l[3]=Math.max(l[3],m)}static#t(e,t,n,r,i,a,o,s,c,l,u,d){if(Math.abs(c)<1e-12){Math.abs(l)>=1e-12&&this.#e(e,t,n,r,i,a,o,s,-u/l,d);return}let f=l**2-4*u*c;if(f<0)return;let p=Math.sqrt(f),m=2*c;this.#e(e,t,n,r,i,a,o,s,(-l+p)/m,d),this.#e(e,t,n,r,i,a,o,s,(-l-p)/m,d)}static bezierBoundingBox(e,t,n,r,i,a,o,s,c){return c?(c[0]=Math.min(c[0],e,o),c[1]=Math.min(c[1],t,s),c[2]=Math.max(c[2],e,o),c[3]=Math.max(c[3],t,s)):c=[Math.min(e,o),Math.min(t,s),Math.max(e,o),Math.max(t,s)],this.#t(e,n,i,o,t,r,a,s,3*(-e+3*(n-i)+o),6*(e-2*n+i),3*(n-e),c),this.#t(e,n,i,o,t,r,a,s,3*(-t+3*(r-a)+s),6*(t-2*r+a),3*(r-t),c),c}};function yl(e){return decodeURIComponent(escape(e))}var bl=null,xl=null;function Sl(e){return bl||(bl=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,xl=new Map([[`ſt`,`ſt`]])),e.replaceAll(bl,(e,t,n)=>t?t.normalize(`NFKC`):xl.get(n))}function Cl(){if(typeof crypto.randomUUID==`function`)return crypto.randomUUID();let e=new Uint8Array(32);return crypto.getRandomValues(e),dl(e)}var wl=`pdfjs_internal_id_`;function Tl(e){return Uint8Array.prototype.toBase64?e.toBase64():btoa(dl(e))}typeof Promise.try!=`function`&&(Promise.try=function(e,...t){return new Promise(n=>{n(e(...t))})});var El=`http://www.w3.org/2000/svg`,Dl=class{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF};async function Ol(e,t=`text`){if(Il(e,document.baseURI)){let n=await fetch(e);if(!n.ok)throw Error(n.statusText);switch(t){case`arraybuffer`:return n.arrayBuffer();case`blob`:return n.blob();case`json`:return n.json()}return n.text()}return new Promise((n,r)=>{let i=new XMLHttpRequest;i.open(`GET`,e,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case`arraybuffer`:case`blob`:case`json`:n(i.response);return}n(i.responseText);return}r(Error(i.statusText))}},i.send(null)})}var kl=class e{constructor({viewBox:e,userUnit:t,scale:n,rotation:r,offsetX:i=0,offsetY:a=0,dontFlip:o=!1}){this.viewBox=e,this.userUnit=t,this.scale=n,this.rotation=r,this.offsetX=i,this.offsetY=a,n*=t;let s=(e[2]+e[0])/2,c=(e[3]+e[1])/2,l,u,d,f;switch(r%=360,r<0&&(r+=360),r){case 180:l=-1,u=0,d=0,f=1;break;case 90:l=0,u=1,d=1,f=0;break;case 270:l=0,u=-1,d=-1,f=0;break;case 0:l=1,u=0,d=0,f=-1;break;default:throw Error(`PageViewport: Invalid rotation, must be a multiple of 90 degrees.`)}o&&(d=-d,f=-f);let p,m,h,g;l===0?(p=Math.abs(c-e[1])*n+i,m=Math.abs(s-e[0])*n+a,h=(e[3]-e[1])*n,g=(e[2]-e[0])*n):(p=Math.abs(s-e[0])*n+i,m=Math.abs(c-e[1])*n+a,h=(e[2]-e[0])*n,g=(e[3]-e[1])*n),this.transform=[l*n,u*n,d*n,f*n,p-l*n*s-d*n*c,m-u*n*s-f*n*c],this.width=h,this.height=g}get rawDims(){let{userUnit:e,viewBox:t}=this,n=t.map(t=>t*e);return Y(this,`rawDims`,{pageWidth:n[2]-n[0],pageHeight:n[3]-n[1],pageX:n[0],pageY:n[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:i=this.offsetY,dontFlip:a=!1}={}){return new e({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:n,offsetX:r,offsetY:i,dontFlip:a})}convertToViewportPoint(e,t){return X.applyTransform([e,t],this.transform)}convertToViewportRectangle(e){let t=X.applyTransform([e[0],e[1]],this.transform),n=X.applyTransform([e[2],e[3]],this.transform);return[t[0],t[1],n[0],n[1]]}convertToPdfPoint(e,t){return X.applyInverseTransform([e,t],this.transform)}},Al=class extends rl{constructor(e,t=0){super(e,`RenderingCancelledException`),this.extraDelay=t}};function jl(e){let t=e.length,n=0;for(;n<t&&e[n].trim()===``;)n++;return e.substring(n,n+5).toLowerCase()===`data:`}function Ml(e){return typeof e==`string`&&/\.pdf$/i.test(e)}function Nl(e){return[e]=e.split(/[#?]/,1),e.substring(e.lastIndexOf(`/`)+1)}function Pl(e,t=`document.pdf`){if(typeof e!=`string`)return t;if(jl(e))return K(`getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.`),t;let n=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,r=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=n.exec(e),a=r.exec(i[1])||r.exec(i[2])||r.exec(i[3]);if(a&&(a=a[0],a.includes(`%`)))try{a=r.exec(decodeURIComponent(a))[0]}catch{}return a||t}var Fl=class{started=Object.create(null);times=[];time(e){e in this.started&&K(`Timer is already running for ${e}`),this.started[e]=Date.now()}timeEnd(e){e in this.started||K(`Timer has not been started for ${e}`),this.times.push({name:e,start:this.started[e],end:Date.now()}),delete this.started[e]}toString(){let e=[],t=0;for(let{name:e}of this.times)t=Math.max(e.length,t);for(let{name:n,start:r,end:i}of this.times)e.push(`${n.padEnd(t)} ${i-r}ms\n`);return e.join(``)}};function Il(e,t){try{let{protocol:n}=t?new URL(e,t):new URL(e);return n===`http:`||n===`https:`}catch{return!1}}function Ll(e){e.preventDefault()}function Rl(e){e.preventDefault(),e.stopPropagation()}var zl=class{static#e;static toDateObject(e){if(!e||typeof e!=`string`)return null;this.#e||=RegExp(`^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?`);let t=this.#e.exec(e);if(!t)return null;let n=parseInt(t[1],10),r=parseInt(t[2],10);r=r>=1&&r<=12?r-1:0;let i=parseInt(t[3],10);i=i>=1&&i<=31?i:1;let a=parseInt(t[4],10);a=a>=0&&a<=23?a:0;let o=parseInt(t[5],10);o=o>=0&&o<=59?o:0;let s=parseInt(t[6],10);s=s>=0&&s<=59?s:0;let c=t[7]||`Z`,l=parseInt(t[8],10);l=l>=0&&l<=23?l:0;let u=parseInt(t[9],10)||0;return u=u>=0&&u<=59?u:0,c===`-`?(a+=l,o+=u):c===`+`&&(a-=l,o-=u),new Date(Date.UTC(n,r,i,a,o,s))}};function Bl(e,{scale:t=1,rotation:n=0}){let{width:r,height:i}=e.attributes.style;return new kl({viewBox:[0,0,parseInt(r),parseInt(i)],userUnit:1,scale:t,rotation:n})}function Vl(e){if(e.startsWith(`#`)){let t=parseInt(e.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return e.startsWith(`rgb(`)?e.slice(4,-1).split(`,`).map(e=>parseInt(e)):e.startsWith(`rgba(`)?e.slice(5,-1).split(`,`).map(e=>parseInt(e)).slice(0,3):(K(`Not a valid color format: "${e}"`),[0,0,0])}function Hl(e){let t=document.createElement(`span`);t.style.visibility=`hidden`,document.body.append(t);for(let n of e.keys()){t.style.color=n;let r=window.getComputedStyle(t).color;e.set(n,Vl(r))}t.remove()}function Z(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform();return[t,n,r,i,a,o]}function Ul(e){let{a:t,b:n,c:r,d:i,e:a,f:o}=e.getTransform().invertSelf();return[t,n,r,i,a,o]}function Wl(e,t,n=!1,r=!0){if(t instanceof kl){let{pageWidth:r,pageHeight:i}=t.rawDims,{style:a}=e,o=_l.isCSSRoundSupported,s=`var(--scale-factor) * ${r}px`,c=`var(--scale-factor) * ${i}px`,l=o?`round(down, ${s}, var(--scale-round-x, 1px))`:`calc(${s})`,u=o?`round(down, ${c}, var(--scale-round-y, 1px))`:`calc(${c})`;!n||t.rotation%180==0?(a.width=l,a.height=u):(a.width=u,a.height=l)}r&&e.setAttribute(`data-main-rotation`,t.rotation)}var Gl=class{constructor(){let e=window.devicePixelRatio||1;this.sx=e,this.sy=e}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}},Kl=class e{#e=null;#t=null;#n;#r=null;#i=null;static#a=null;constructor(t){this.#n=t,e.#a||=Object.freeze({freetext:`pdfjs-editor-remove-freetext-button`,highlight:`pdfjs-editor-remove-highlight-button`,ink:`pdfjs-editor-remove-ink-button`,stamp:`pdfjs-editor-remove-stamp-button`})}render(){let t=this.#e=document.createElement(`div`);t.classList.add(`editToolbar`,`hidden`),t.setAttribute(`role`,`toolbar`);let n=this.#n._uiManager._signal;t.addEventListener(`contextmenu`,Ll,{signal:n}),t.addEventListener(`pointerdown`,e.#o,{signal:n});let r=this.#r=document.createElement(`div`);r.className=`buttons`,t.append(r);let i=this.#n.toolbarPosition;if(i){let{style:e}=t;e.insetInlineEnd=`${100*(this.#n._uiManager.direction===`ltr`?1-i[0]:i[0])}%`,e.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#u(),t}get div(){return this.#e}static#o(e){e.stopPropagation()}#s(e){this.#n._focusEventsAllowed=!1,Rl(e)}#c(e){this.#n._focusEventsAllowed=!0,Rl(e)}#l(e){let t=this.#n._uiManager._signal;e.addEventListener(`focusin`,this.#s.bind(this),{capture:!0,signal:t}),e.addEventListener(`focusout`,this.#c.bind(this),{capture:!0,signal:t}),e.addEventListener(`contextmenu`,Ll,{signal:t})}hide(){this.#e.classList.add(`hidden`),this.#t?.hideDropdown()}show(){this.#e.classList.remove(`hidden`),this.#i?.shown()}#u(){let{editorType:t,_uiManager:n}=this.#n,r=document.createElement(`button`);r.className=`delete`,r.tabIndex=0,r.setAttribute(`data-l10n-id`,e.#a[t]),this.#l(r),r.addEventListener(`click`,e=>{n.delete()},{signal:n._signal}),this.#r.append(r)}get#d(){let e=document.createElement(`div`);return e.className=`divider`,e}async addAltText(e){let t=await e.render();this.#l(t),this.#r.prepend(t,this.#d),this.#i=e}addColorPicker(e){this.#t=e;let t=e.renderButton();this.#l(t),this.#r.prepend(t,this.#d)}remove(){this.#e.remove(),this.#t?.destroy(),this.#t=null}},ql=class{#e=null;#t=null;#n;constructor(e){this.#n=e}#r(){let e=this.#t=document.createElement(`div`);e.className=`editToolbar`,e.setAttribute(`role`,`toolbar`),e.addEventListener(`contextmenu`,Ll,{signal:this.#n._signal});let t=this.#e=document.createElement(`div`);return t.className=`buttons`,e.append(t),this.#a(),e}#i(e,t){let n=0,r=0;for(let i of e){let e=i.y+i.height;if(e<n)continue;let a=i.x+(t?i.width:0);if(e>n){r=a,n=e;continue}t?a>r&&(r=a):a<r&&(r=a)}return[t?1-r:r,n]}show(e,t,n){let[r,i]=this.#i(t,n),{style:a}=this.#t||=this.#r();e.append(this.#t),a.insetInlineEnd=`${100*r}%`,a.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){this.#t.remove()}#a(){let e=document.createElement(`button`);e.className=`highlightButton`,e.tabIndex=0,e.setAttribute(`data-l10n-id`,`pdfjs-highlight-floating-button1`);let t=document.createElement(`span`);e.append(t),t.className=`visuallyHidden`,t.setAttribute(`data-l10n-id`,`pdfjs-highlight-floating-button-label`);let n=this.#n._signal;e.addEventListener(`contextmenu`,Ll,{signal:n}),e.addEventListener(`click`,()=>{this.#n.highlightSelection(`floating_button`)},{signal:n}),this.#e.append(e)}};function Jl(e,t,n){for(let r of n)t.addEventListener(r,e[r].bind(e))}var Yl=class{#e=0;get id(){return`${Hc}${this.#e++}`}},Xl=class e{#e=Cl();#t=0;#n=null;static get _isSVGFittingCanvas(){let e=new OffscreenCanvas(1,3).getContext(`2d`,{willReadFrequently:!0}),t=new Image;t.src=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>`;let n=t.decode().then(()=>(e.drawImage(t,0,0,1,1,0,0,1,3),new Uint32Array(e.getImageData(0,0,1,1).data.buffer)[0]===0));return Y(this,`_isSVGFittingCanvas`,n)}async#r(t,n){this.#n||=new Map;let r=this.#n.get(t);if(r===null)return null;if(r?.bitmap)return r.refCounter+=1,r;try{r||={bitmap:null,id:`image_${this.#e}_${this.#t++}`,refCounter:0,isSvg:!1};let t;if(typeof n==`string`?(r.url=n,t=await Ol(n,`blob`)):n instanceof File?t=r.file=n:n instanceof Blob&&(t=n),t.type===`image/svg+xml`){let n=e._isSVGFittingCanvas,i=new FileReader,a=new Image,o=new Promise((e,t)=>{a.onload=()=>{r.bitmap=a,r.isSvg=!0,e()},i.onload=async()=>{let e=r.svgUrl=i.result;a.src=await n?`${e}#svgView(preserveAspectRatio(none))`:e},a.onerror=i.onerror=t});i.readAsDataURL(t),await o}else r.bitmap=await createImageBitmap(t);r.refCounter=1}catch(e){K(e),r=null}return this.#n.set(t,r),r&&this.#n.set(r.id,r),r}async getFromFile(e){let{lastModified:t,name:n,size:r,type:i}=e;return this.#r(`${t}_${n}_${r}_${i}`,e)}async getFromUrl(e){return this.#r(e,e)}async getFromBlob(e,t){let n=await t;return this.#r(e,n)}async getFromId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t)return null;if(t.bitmap)return t.refCounter+=1,t;if(t.file)return this.getFromFile(t.file);if(t.blobPromise){let{blobPromise:e}=t;return delete t.blobPromise,this.getFromBlob(t.id,e)}return this.getFromUrl(t.url)}getFromCanvas(e,t){this.#n||=new Map;let n=this.#n.get(e);if(n?.bitmap)return n.refCounter+=1,n;let r=new OffscreenCanvas(t.width,t.height);return r.getContext(`2d`).drawImage(t,0,0),n={bitmap:r.transferToImageBitmap(),id:`image_${this.#e}_${this.#t++}`,refCounter:1,isSvg:!1},this.#n.set(e,n),this.#n.set(n.id,n),n}getSvgUrl(e){let t=this.#n.get(e);return t?.isSvg?t.svgUrl:null}deleteId(e){this.#n||=new Map;let t=this.#n.get(e);if(!t||(--t.refCounter,t.refCounter!==0))return;let{bitmap:n}=t;if(!t.url&&!t.file){let e=new OffscreenCanvas(n.width,n.height);e.getContext(`bitmaprenderer`).transferFromImageBitmap(n),t.blobPromise=e.convertToBlob()}n.close?.(),t.bitmap=null}isValidId(e){return e.startsWith(`image_${this.#e}_`)}},Zl=class{#e=[];#t=!1;#n;#r=-1;constructor(e=128){this.#n=e}add({cmd:e,undo:t,post:n,mustExec:r,type:i=NaN,overwriteIfSameType:a=!1,keepUndo:o=!1}){if(r&&e(),this.#t)return;let s={cmd:e,undo:t,post:n,type:i};if(this.#r===-1){this.#e.length>0&&(this.#e.length=0),this.#r=0,this.#e.push(s);return}if(a&&this.#e[this.#r].type===i){o&&(s.undo=this.#e[this.#r].undo),this.#e[this.#r]=s;return}let c=this.#r+1;c===this.#n?this.#e.splice(0,1):(this.#r=c,c<this.#e.length&&this.#e.splice(c)),this.#e.push(s)}undo(){if(this.#r===-1)return;this.#t=!0;let{undo:e,post:t}=this.#e[this.#r];e(),t?.(),this.#t=!1,--this.#r}redo(){if(this.#r<this.#e.length-1){this.#r+=1,this.#t=!0;let{cmd:e,post:t}=this.#e[this.#r];e(),t?.(),this.#t=!1}}hasSomethingToUndo(){return this.#r!==-1}hasSomethingToRedo(){return this.#r<this.#e.length-1}cleanType(e){if(this.#r!==-1){for(let t=this.#r;t>=0;t--)if(this.#e[t].type!==e){this.#e.splice(t+1,this.#r-t),this.#r=t;return}this.#e.length=0,this.#r=-1}}destroy(){this.#e=null}},Ql=class{constructor(e){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:t}=_l.platform;for(let[n,r,i={}]of e)for(let e of n){let n=e.startsWith(`mac+`);t&&n?(this.callbacks.set(e.slice(4),{callback:r,options:i}),this.allKeys.add(e.split(`+`).at(-1))):!t&&!n&&(this.callbacks.set(e,{callback:r,options:i}),this.allKeys.add(e.split(`+`).at(-1)))}}#e(e){e.altKey&&this.buffer.push(`alt`),e.ctrlKey&&this.buffer.push(`ctrl`),e.metaKey&&this.buffer.push(`meta`),e.shiftKey&&this.buffer.push(`shift`),this.buffer.push(e.key);let t=this.buffer.join(`+`);return this.buffer.length=0,t}exec(e,t){if(!this.allKeys.has(t.key))return;let n=this.callbacks.get(this.#e(t));if(!n)return;let{callback:r,options:{bubbles:i=!1,args:a=[],checker:o=null}}=n;o&&!o(e,t)||(r.bind(e,...a,t)(),i||Rl(t))}},$l=class e{static _colorsMapping=new Map([[`CanvasText`,[0,0,0]],[`Canvas`,[255,255,255]]]);get _colors(){let e=new Map([[`CanvasText`,null],[`Canvas`,null]]);return Hl(e),Y(this,`_colors`,e)}convert(t){let n=Vl(t);if(!window.matchMedia(`(forced-colors: active)`).matches)return n;for(let[t,r]of this._colors)if(r.every((e,t)=>e===n[t]))return e._colorsMapping.get(t);return n}getHexCode(e){let t=this._colors.get(e);return t?X.makeHexColor(...t):e}},eu=class e{#e=new AbortController;#t=null;#n=new Map;#r=new Map;#i=null;#a=null;#o=null;#s=new Zl;#c=null;#l=null;#u=0;#d=new Set;#f=null;#p=null;#m=new Set;_editorUndoBar=null;#h=!1;#g=!1;#_=!1;#v=null;#y=null;#b=null;#x=null;#S=!1;#C=null;#w=new Yl;#T=!1;#E=!1;#D=null;#O=null;#k=null;#A=null;#j=W.NONE;#M=new Set;#N=null;#P=null;#F=null;#I={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#L=[0,0];#R=null;#z=null;#B=null;#V=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.#z.contains(document.activeElement)&&document.activeElement.tagName!==`BUTTON`&&e.hasSomethingToControl(),r=(e,{target:t})=>{if(t instanceof HTMLInputElement){let{type:e}=t;return e!==`text`&&e!==`number`}return!0},i=this.TRANSLATE_SMALL,a=this.TRANSLATE_BIG;return Y(this,`_keyboardManager`,new Ql([[[`ctrl+a`,`mac+meta+a`],t.selectAll,{checker:r}],[[`ctrl+z`,`mac+meta+z`],t.undo,{checker:r}],[[`ctrl+y`,`ctrl+shift+z`,`mac+meta+shift+z`,`ctrl+shift+Z`,`mac+meta+shift+Z`],t.redo,{checker:r}],[[`Backspace`,`alt+Backspace`,`ctrl+Backspace`,`shift+Backspace`,`mac+Backspace`,`mac+alt+Backspace`,`mac+ctrl+Backspace`,`Delete`,`ctrl+Delete`,`shift+Delete`,`mac+Delete`],t.delete,{checker:r}],[[`Enter`,`mac+Enter`],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#z.contains(t)&&!e.isEnterHandled}],[[` `,`mac+ `],t.addNewEditorFromKeyboard,{checker:(e,{target:t})=>!(t instanceof HTMLButtonElement)&&e.#z.contains(document.activeElement)}],[[`Escape`,`mac+Escape`],t.unselectAll],[[`ArrowLeft`,`mac+ArrowLeft`],t.translateSelectedEditors,{args:[-i,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t.translateSelectedEditors,{args:[-a,0],checker:n}],[[`ArrowRight`,`mac+ArrowRight`],t.translateSelectedEditors,{args:[i,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t.translateSelectedEditors,{args:[a,0],checker:n}],[[`ArrowUp`,`mac+ArrowUp`],t.translateSelectedEditors,{args:[0,-i],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t.translateSelectedEditors,{args:[0,-a],checker:n}],[[`ArrowDown`,`mac+ArrowDown`],t.translateSelectedEditors,{args:[0,i],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t.translateSelectedEditors,{args:[0,a],checker:n}]]))}constructor(e,t,n,r,i,a,o,s,c,l,u,d,f){let p=this._signal=this.#e.signal;this.#z=e,this.#B=t,this.#i=n,this._eventBus=r,r._on(`editingaction`,this.onEditingAction.bind(this),{signal:p}),r._on(`pagechanging`,this.onPageChanging.bind(this),{signal:p}),r._on(`scalechanging`,this.onScaleChanging.bind(this),{signal:p}),r._on(`rotationchanging`,this.onRotationChanging.bind(this),{signal:p}),r._on(`setpreference`,this.onSetPreference.bind(this),{signal:p}),r._on(`switchannotationeditorparams`,e=>this.updateParams(e.type,e.value),{signal:p}),this.#q(),this.#ee(),this.#X(),this.#a=i.annotationStorage,this.#v=i.filterFactory,this.#P=a,this.#x=o||null,this.#h=s,this.#g=c,this.#_=l,this.#A=u||null,this.viewParameters={realScale:Dl.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#V?.resolve(),this.#V=null,this.#e?.abort(),this.#e=null,this._signal=null;for(let e of this.#r.values())e.destroy();this.#r.clear(),this.#n.clear(),this.#m.clear(),this.#t=null,this.#M.clear(),this.#s.destroy(),this.#i?.destroy(),this.#C?.hide(),this.#C=null,this.#y&&=(clearTimeout(this.#y),null),this.#R&&=(clearTimeout(this.#R),null),this._editorUndoBar?.destroy()}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return this.#A}get useNewAltTextFlow(){return this.#g}get useNewAltTextWhenAddingImage(){return this.#_}get hcmFilter(){return Y(this,`hcmFilter`,this.#P?this.#v.addHCMFilter(this.#P.foreground,this.#P.background):`none`)}get direction(){return Y(this,`direction`,getComputedStyle(this.#z).direction)}get highlightColors(){return Y(this,`highlightColors`,this.#x?new Map(this.#x.split(`,`).map(e=>e.split(`=`).map(e=>e.trim()))):null)}get highlightColorNames(){return Y(this,`highlightColorNames`,this.highlightColors?new Map(Array.from(this.highlightColors,e=>e.reverse())):null)}setCurrentDrawingSession(e){e?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#l=e}setMainHighlightColorPicker(e){this.#k=e}editAltText(e,t=!1){this.#i?.editAltText(this,e,t)}switchToMode(e,t){this._eventBus.on(`annotationeditormodechanged`,t,{once:!0,signal:this._signal}),this._eventBus.dispatch(`showannotationeditorui`,{source:this,mode:e})}setPreference(e,t){this._eventBus.dispatch(`setpreference`,{source:this,name:e,value:t})}onSetPreference({name:e,value:t}){e===`enableNewAltTextWhenAddingImage`&&(this.#_=t)}onPageChanging({pageNumber:e}){this.#u=e-1}focusMainContainer(){this.#z.focus()}findParent(e,t){for(let n of this.#r.values()){let{x:r,y:i,width:a,height:o}=n.div.getBoundingClientRect();if(e>=r&&e<=r+a&&t>=i&&t<=i+o)return n}return null}disableUserSelect(e=!1){this.#B.classList.toggle(`noUserSelect`,e)}addShouldRescale(e){this.#m.add(e)}removeShouldRescale(e){this.#m.delete(e)}onScaleChanging({scale:e}){this.commitOrRemove(),this.viewParameters.realScale=e*Dl.PDF_TO_CSS_UNITS;for(let e of this.#m)e.onScaleChanging();this.#l?.onScaleChanging()}onRotationChanging({pagesRotation:e}){this.commitOrRemove(),this.viewParameters.rotation=e}#H({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e}#U(e){let{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(let t of this.#r.values())if(t.hasTextLayer(e))return t;return null}highlightSelection(e=``){let t=document.getSelection();if(!t||t.isCollapsed)return;let{anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a}=t,o=t.toString(),s=this.#H(t).closest(`.textLayer`),c=this.getSelectionBoxes(s);if(!c)return;t.empty();let l=this.#U(s),u=this.#j===W.NONE,d=()=>{l?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:c,anchorNode:n,anchorOffset:r,focusNode:i,focusOffset:a,text:o}),u&&this.showAllEditors(`highlight`,!0,!0)};if(u){this.switchToMode(W.HIGHLIGHT,d);return}d()}#W(){let e=document.getSelection();if(!e||e.isCollapsed)return;let t=this.#H(e).closest(`.textLayer`),n=this.getSelectionBoxes(t);n&&(this.#C||=new ql(this),this.#C.show(t,n,this.direction===`ltr`))}addToAnnotationStorage(e){!e.isEmpty()&&this.#a&&!this.#a.has(e.id)&&this.#a.setValue(e.id,e)}#G(){let e=document.getSelection();if(!e||e.isCollapsed){this.#N&&(this.#C?.hide(),this.#N=null,this.#te({hasSelectedText:!1}));return}let{anchorNode:t}=e;if(t===this.#N)return;let n=this.#H(e).closest(`.textLayer`);if(!n){this.#N&&(this.#C?.hide(),this.#N=null,this.#te({hasSelectedText:!1}));return}if(this.#C?.hide(),this.#N=t,this.#te({hasSelectedText:!0}),(this.#j===W.HIGHLIGHT||this.#j===W.NONE)&&(this.#j===W.HIGHLIGHT&&this.showAllEditors(`highlight`,!0,!0),this.#S=this.isShiftKeyDown,!this.isShiftKeyDown)){let e=this.#j===W.HIGHLIGHT?this.#U(n):null;e?.toggleDrawing();let t=new AbortController,r=this.combinedSignal(t),i=n=>{(n.type!==`pointerup`||n.button===0)&&(t.abort(),e?.toggleDrawing(!0),n.type===`pointerup`&&this.#K(`main_toolbar`))};window.addEventListener(`pointerup`,i,{signal:r}),window.addEventListener(`blur`,i,{signal:r})}}#K(e=``){this.#j===W.HIGHLIGHT?this.highlightSelection(e):this.#h&&this.#W()}#q(){document.addEventListener(`selectionchange`,this.#G.bind(this),{signal:this._signal})}#J(){if(this.#b)return;this.#b=new AbortController;let e=this.combinedSignal(this.#b);window.addEventListener(`focus`,this.focus.bind(this),{signal:e}),window.addEventListener(`blur`,this.blur.bind(this),{signal:e})}#Y(){this.#b?.abort(),this.#b=null}blur(){if(this.isShiftKeyDown=!1,this.#S&&(this.#S=!1,this.#K(`main_toolbar`)),!this.hasSelection)return;let{activeElement:e}=document;for(let t of this.#M)if(t.div.contains(e)){this.#O=[t,e],t._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;let[e,t]=this.#O;this.#O=null,t.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}#X(){if(this.#D)return;this.#D=new AbortController;let e=this.combinedSignal(this.#D);window.addEventListener(`keydown`,this.keydown.bind(this),{signal:e}),window.addEventListener(`keyup`,this.keyup.bind(this),{signal:e})}#Z(){this.#D?.abort(),this.#D=null}#Q(){if(this.#c)return;this.#c=new AbortController;let e=this.combinedSignal(this.#c);document.addEventListener(`copy`,this.copy.bind(this),{signal:e}),document.addEventListener(`cut`,this.cut.bind(this),{signal:e}),document.addEventListener(`paste`,this.paste.bind(this),{signal:e})}#$(){this.#c?.abort(),this.#c=null}#ee(){let e=this._signal;document.addEventListener(`dragover`,this.dragOver.bind(this),{signal:e}),document.addEventListener(`drop`,this.drop.bind(this),{signal:e})}addEditListeners(){this.#X(),this.#Q()}removeEditListeners(){this.#Z(),this.#$()}dragOver(e){for(let{type:t}of e.dataTransfer.items)for(let n of this.#p)if(n.isHandlingMimeForPasting(t)){e.dataTransfer.dropEffect=`copy`,e.preventDefault();return}}drop(e){for(let t of e.dataTransfer.items)for(let n of this.#p)if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){if(e.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let t=[];for(let e of this.#M){let n=e.serialize(!0);n&&t.push(n)}t.length!==0&&e.clipboardData.setData(`application/pdfjs`,JSON.stringify(t))}cut(e){this.copy(e),this.delete()}async paste(e){e.preventDefault();let{clipboardData:t}=e;for(let e of t.items)for(let t of this.#p)if(t.isHandlingMimeForPasting(e.type)){t.paste(e,this.currentLayer);return}let n=t.getData(`application/pdfjs`);if(!n)return;try{n=JSON.parse(n)}catch(e){K(`paste: "${e.message}".`);return}if(!Array.isArray(n))return;this.unselectAll();let r=this.currentLayer;try{let e=[];for(let t of n){let n=await r.deserialize(t);if(!n)return;e.push(n)}this.addCommands({cmd:()=>{for(let t of e)this.#ae(t);this.#ce(e)},undo:()=>{for(let t of e)t.remove()},mustExec:!0})}catch(e){K(`paste: "${e.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key===`Shift`&&(this.isShiftKeyDown=!0),this.#j!==W.NONE&&!this.isEditorHandlingKeyboard&&e._keyboardManager.exec(this,t)}keyup(e){this.isShiftKeyDown&&e.key===`Shift`&&(this.isShiftKeyDown=!1,this.#S&&(this.#S=!1,this.#K(`main_toolbar`)))}onEditingAction({name:e}){switch(e){case`undo`:case`redo`:case`delete`:case`selectAll`:this[e]();break;case`highlightSelection`:this.highlightSelection(`context_menu`)}}#te(e){Object.entries(e).some(([e,t])=>this.#I[e]!==t)&&(this._eventBus.dispatch(`annotationeditorstateschanged`,{source:this,details:Object.assign(this.#I,e)}),this.#j===W.HIGHLIGHT&&e.hasSelectedEditor===!1&&this.#ne([[G.HIGHLIGHT_FREE,!0]]))}#ne(e){this._eventBus.dispatch(`annotationeditorparamschanged`,{source:this,details:e})}setEditingState(e){e?(this.#J(),this.#Q(),this.#te({isEditing:this.#j!==W.NONE,isEmpty:this.#se(),hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:this.#s.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#Y(),this.#$(),this.#te({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!this.#p){this.#p=e;for(let e of this.#p)this.#ne(e.defaultPropertiesToUpdate)}}getId(){return this.#w.id}get currentLayer(){return this.#r.get(this.#u)}getLayer(e){return this.#r.get(e)}get currentPageIndex(){return this.#u}addLayer(e){this.#r.set(e.pageIndex,e),this.#T?e.enable():e.disable()}removeLayer(e){this.#r.delete(e.pageIndex)}async updateMode(e,t=null,n=!1){if(this.#j!==e&&!(this.#V&&(await this.#V.promise,!this.#V))){if(this.#V=Promise.withResolvers(),this.#j=e,e===W.NONE){this.setEditingState(!1),this.#ie(),this._editorUndoBar?.hide(),this.#V.resolve();return}this.setEditingState(!0),await this.#re(),this.unselectAll();for(let t of this.#r.values())t.updateMode(e);if(!t){n&&this.addNewEditorFromKeyboard(),this.#V.resolve();return}for(let e of this.#n.values())e.annotationElementId===t?(this.setSelected(e),e.enterInEditMode()):e.unselect();this.#V.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e!==this.#j&&this._eventBus.dispatch(`switchannotationeditormode`,{source:this,mode:e})}updateParams(e,t){if(this.#p){switch(e){case G.CREATE:this.currentLayer.addNewEditor();return;case G.HIGHLIGHT_DEFAULT_COLOR:this.#k?.updateColor(t);break;case G.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:{type:`highlight`,action:`toggle_visibility`}}}),(this.#F||=new Map).set(e,t),this.showAllEditors(`highlight`,t)}for(let n of this.#M)n.updateParams(e,t);for(let n of this.#p)n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){for(let n of this.#n.values())n.editorType===e&&n.show(t);(this.#F?.get(G.HIGHLIGHT_SHOW_ALL)??!0)!==t&&this.#ne([[G.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(this.#E!==e){this.#E=e;for(let t of this.#r.values())e?t.disableClick():t.enableClick(),t.div.classList.toggle(`waiting`,e)}}async#re(){if(!this.#T){this.#T=!0;let e=[];for(let t of this.#r.values())e.push(t.enable());await Promise.all(e);for(let e of this.#n.values())e.enable()}}#ie(){if(this.unselectAll(),this.#T){this.#T=!1;for(let e of this.#r.values())e.disable();for(let e of this.#n.values())e.disable()}}getEditors(e){let t=[];for(let n of this.#n.values())n.pageIndex===e&&t.push(n);return t}getEditor(e){return this.#n.get(e)}addEditor(e){this.#n.set(e.id,e)}removeEditor(e){e.div.contains(document.activeElement)&&(this.#y&&clearTimeout(this.#y),this.#y=setTimeout(()=>{this.focusMainContainer(),this.#y=null},0)),this.#n.delete(e.id),this.unselect(e),(!e.annotationElementId||!this.#d.has(e.annotationElementId))&&this.#a?.remove(e.id)}addDeletedAnnotationElement(e){this.#d.add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return this.#d.has(e)}removeDeletedAnnotationElement(e){this.#d.delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}#ae(e){let t=this.#r.get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))}setActiveEditor(e){this.#t!==e&&(this.#t=e,e&&this.#ne(e.propertiesToUpdate))}get#oe(){let e=null;for(e of this.#M);return e}updateUI(e){this.#oe===e&&this.#ne(e.propertiesToUpdate)}updateUIForDefaultProperties(e){this.#ne(e.defaultPropertiesToUpdate)}toggleSelected(e){if(this.#M.has(e)){this.#M.delete(e),e.unselect(),this.#te({hasSelectedEditor:this.hasSelection});return}this.#M.add(e),e.select(),this.#ne(e.propertiesToUpdate),this.#te({hasSelectedEditor:!0})}setSelected(e){this.#l?.commitOrRemove();for(let t of this.#M)t!==e&&t.unselect();this.#M.clear(),this.#M.add(e),e.select(),this.#ne(e.propertiesToUpdate),this.#te({hasSelectedEditor:!0})}isSelected(e){return this.#M.has(e)}get firstSelectedEditor(){return this.#M.values().next().value}unselect(e){e.unselect(),this.#M.delete(e),this.#te({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#M.size!==0}get isEnterHandled(){return this.#M.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#s.undo(),this.#te({hasSomethingToUndo:this.#s.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#se()}),this._editorUndoBar?.hide()}redo(){this.#s.redo(),this.#te({hasSomethingToUndo:!0,hasSomethingToRedo:this.#s.hasSomethingToRedo(),isEmpty:this.#se()})}addCommands(e){this.#s.add(e),this.#te({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#se()})}cleanUndoStack(e){this.#s.cleanType(e)}#se(){if(this.#n.size===0)return!0;if(this.#n.size===1)for(let e of this.#n.values())return e.isEmpty();return!1}delete(){this.commitOrRemove();let e=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!e)return;let t=e?[e]:[...this.#M],n=()=>{this._editorUndoBar?.show(r,t.length===1?t[0].editorType:t.length);for(let e of t)e.remove()},r=()=>{for(let e of t)this.#ae(e)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#ce(e){for(let e of this.#M)e.unselect();this.#M.clear();for(let t of e)t.isEmpty()||(this.#M.add(t),t.select());this.#te({hasSelectedEditor:this.hasSelection})}selectAll(){for(let e of this.#M)e.commit();this.#ce(this.#n.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#j!==W.NONE))&&!this.#l?.commitOrRemove()&&this.hasSelection){for(let e of this.#M)e.unselect();this.#M.clear(),this.#te({hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;this.#L[0]+=e,this.#L[1]+=t;let[r,i]=this.#L,a=[...this.#M];this.#R&&clearTimeout(this.#R),this.#R=setTimeout(()=>{this.#R=null,this.#L[0]=this.#L[1]=0,this.addCommands({cmd:()=>{for(let e of a)this.#n.has(e.id)&&e.translateInPage(r,i)},undo:()=>{for(let e of a)this.#n.has(e.id)&&e.translateInPage(-r,-i)},mustExec:!1})},1e3);for(let n of a)n.translateInPage(e,t)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(let e of this.#M)this.#f.set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);let e=this.#f;this.#f=null;let t=!1;for(let[{x:n,y:r,pageIndex:i},a]of e)a.newX=n,a.newY=r,a.newPageIndex=i,t||=n!==a.savedX||r!==a.savedY||i!==a.savedPageIndex;if(!t)return!1;let n=(e,t,n,r)=>{if(this.#n.has(e.id)){let i=this.#r.get(r);i?e._setParentAndPosition(i,t,n):(e.pageIndex=r,e.x=t,e.y=n)}};return this.addCommands({cmd:()=>{for(let[t,{newX:r,newY:i,newPageIndex:a}]of e)n(t,r,i,a)},undo:()=>{for(let[t,{savedX:r,savedY:i,savedPageIndex:a}]of e)n(t,r,i,a)},mustExec:!0}),!0}dragSelectedEditors(e,t){if(this.#f)for(let n of this.#f.keys())n.drag(e,t)}rebuild(e){if(e.parent===null){let t=this.getLayer(e.pageIndex);t?(t.changeParent(e),t.addOrRebuild(e)):(this.addEditor(e),this.addToAnnotationStorage(e),e.rebuild())}else e.parent.addOrRebuild(e)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#M.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return this.#t===e}getActive(){return this.#t}getMode(){return this.#j}get imageManager(){return Y(this,`imageManager`,new Xl)}getSelectionBoxes(e){if(!e)return null;let t=document.getSelection();for(let n=0,r=t.rangeCount;n<r;n++)if(!e.contains(t.getRangeAt(n).commonAncestorContainer))return null;let{x:n,y:r,width:i,height:a}=e.getBoundingClientRect(),o;switch(e.getAttribute(`data-main-rotation`)){case`90`:o=(e,t,o,s)=>({x:(t-r)/a,y:1-(e+o-n)/i,width:s/a,height:o/i});break;case`180`:o=(e,t,o,s)=>({x:1-(e+o-n)/i,y:1-(t+s-r)/a,width:o/i,height:s/a});break;case`270`:o=(e,t,o,s)=>({x:1-(t+s-r)/a,y:(e-n)/i,width:s/a,height:o/i});break;default:o=(e,t,o,s)=>({x:(e-n)/i,y:(t-r)/a,width:o/i,height:s/a})}let s=[];for(let e=0,n=t.rangeCount;e<n;e++){let n=t.getRangeAt(e);if(!n.collapsed)for(let{x:e,y:t,width:r,height:i}of n.getClientRects())r!==0&&i!==0&&s.push(o(e,t,r,i))}return s.length===0?null:s}addChangedExistingAnnotation({annotationElementId:e,id:t}){(this.#o||=new Map).set(e,t)}removeChangedExistingAnnotation({annotationElementId:e}){this.#o?.delete(e)}renderAnnotationElement(e){let t=this.#o?.get(e.data.id);if(!t)return;let n=this.#a.getRawValue(t);n&&(this.#j===W.NONE&&!n.hasBeenModified||n.renderAnnotationElement(e))}},tu=class e{#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=!1;#s=null;#c=null;#l=null;#u=null;#d=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#d=t._uiManager.useNewAltTextFlow,e.#f||=Object.freeze({added:`pdfjs-editor-new-alt-text-added-button`,"added-label":`pdfjs-editor-new-alt-text-added-button-label`,missing:`pdfjs-editor-new-alt-text-missing-button`,"missing-label":`pdfjs-editor-new-alt-text-missing-button-label`,review:`pdfjs-editor-new-alt-text-to-review-button`,"review-label":`pdfjs-editor-new-alt-text-to-review-button-label`})}static initialize(t){e._l10n??=t}async render(){let t=this.#n=document.createElement(`button`);t.className=`altText`,t.tabIndex=`0`;let n=this.#r=document.createElement(`span`);t.append(n),this.#d?(t.classList.add(`new`),t.setAttribute(`data-l10n-id`,e.#f.missing),n.setAttribute(`data-l10n-id`,e.#f[`missing-label`])):(t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-button`),n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-button-label`));let r=this.#c._uiManager._signal;t.addEventListener(`contextmenu`,Ll,{signal:r}),t.addEventListener(`pointerdown`,e=>e.stopPropagation(),{signal:r});let i=e=>{e.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#d&&this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_clicked`,data:{label:this.#p}})};return t.addEventListener(`click`,i,{capture:!0,signal:r}),t.addEventListener(`keydown`,e=>{e.target===t&&e.key===`Enter`&&(this.#o=!0,i(e))},{signal:r}),await this.#m(),t}get#p(){return this.#e&&`added`||this.#e===null&&this.guessedText&&`review`||`missing`}finish(){this.#n&&(this.#n.focus({focusVisible:this.#o}),this.#o=!1)}isEmpty(){return this.#d?this.#e===null:!this.#e&&!this.#t}hasData(){return this.#d?this.#e!==null||!!this.#l:this.isEmpty()}get guessedText(){return this.#l}async setGuessedText(t){this.#e===null&&(this.#l=t,this.#u=await e._l10n.get(`pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer`,{generatedAltText:t}),this.#m())}toggleAltTextBadge(e=!1){if(!this.#d||this.#e){this.#s?.remove(),this.#s=null;return}if(!this.#s){let e=this.#s=document.createElement(`div`);e.className=`noAltTextBadge`,this.#c.div.append(e)}this.#s.classList.toggle(`hidden`,!e)}serialize(e){let t=this.#e;return!e&&this.#l===t&&(t=this.#u),{altText:t,decorative:this.#t,guessedText:this.#l,textWithDisclaimer:this.#u}}get data(){return{altText:this.#e,decorative:this.#t}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:r,cancel:i=!1}){n&&(this.#l=n,this.#u=r),(this.#e!==e||this.#t!==t)&&(i||(this.#e=e,this.#t=t),this.#m())}toggle(e=!1){this.#n&&(!e&&this.#a&&(clearTimeout(this.#a),this.#a=null),this.#n.disabled=!e)}shown(){this.#c._reportTelemetry({action:`pdfjs.image.alt_text.image_status_label_displayed`,data:{label:this.#p}})}destroy(){this.#n?.remove(),this.#n=null,this.#r=null,this.#i=null,this.#s?.remove(),this.#s=null}async#m(){let t=this.#n;if(!t)return;if(this.#d){if(t.classList.toggle(`done`,!!this.#e),t.setAttribute(`data-l10n-id`,e.#f[this.#p]),this.#r?.setAttribute(`data-l10n-id`,e.#f[`${this.#p}-label`]),!this.#e){this.#i?.remove();return}}else{if(!this.#e&&!this.#t){t.classList.remove(`done`),this.#i?.remove();return}t.classList.add(`done`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-edit-button`)}let n=this.#i;if(!n){this.#i=n=document.createElement(`span`),n.className=`tooltip`,n.setAttribute(`role`,`tooltip`),n.id=`alt-text-tooltip-${this.#c.id}`;let e=this.#c._uiManager._signal;e.addEventListener(`abort`,()=>{clearTimeout(this.#a),this.#a=null},{once:!0}),t.addEventListener(`mouseenter`,()=>{this.#a=setTimeout(()=>{this.#a=null,this.#i.classList.add(`show`),this.#c._reportTelemetry({action:`alt_text_tooltip`})},100)},{signal:e}),t.addEventListener(`mouseleave`,()=>{this.#a&&=(clearTimeout(this.#a),null),this.#i?.classList.remove(`show`)},{signal:e})}this.#t?n.setAttribute(`data-l10n-id`,`pdfjs-editor-alt-text-decorative-tooltip`):(n.removeAttribute(`data-l10n-id`),n.textContent=this.#e),n.parentNode||t.append(n),this.#c.getImageForAltText()?.setAttribute(`aria-describedby`,n.id)}},nu=class e{#e;#t=!1;#n=null;#r;#i;#a;#o;#s;#c=null;#l;#u=null;constructor({container:e,isPinchingDisabled:t=null,isPinchingStopped:n=null,onPinchStart:r=null,onPinching:i=null,onPinchEnd:a=null,signal:o}){this.#e=e,this.#n=n,this.#r=t,this.#i=r,this.#a=i,this.#o=a,this.#l=new AbortController,this.#s=AbortSignal.any([o,this.#l.signal]),e.addEventListener(`touchstart`,this.#d.bind(this),{passive:!1,signal:this.#s})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return Y(this,`MIN_TOUCH_DISTANCE_TO_PINCH`,35/(window.devicePixelRatio||1))}#d(e){if(this.#r?.()||e.touches.length<2)return;if(!this.#u){this.#u=new AbortController;let e=AbortSignal.any([this.#s,this.#u.signal]),t=this.#e,n={signal:e,passive:!1};t.addEventListener(`touchmove`,this.#f.bind(this),n),t.addEventListener(`touchend`,this.#p.bind(this),n),t.addEventListener(`touchcancel`,this.#p.bind(this),n),this.#i?.()}if(Rl(e),e.touches.length!==2||this.#n?.()){this.#c=null;return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),this.#c={touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[n,r]=t.touches;n.identifier>r.identifier&&([n,r]=[r,n]);let{screenX:i,screenY:a}=n,{screenX:o,screenY:s}=r,c=this.#c,{touch0X:l,touch0Y:u,touch1X:d,touch1Y:f}=c,p=d-l,m=f-u,h=o-i,g=s-a,_=Math.hypot(h,g)||1,v=Math.hypot(p,m)||1;if(!this.#t&&Math.abs(v-_)<=e.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=a,c.touch1X=o,c.touch1Y=s,t.preventDefault(),!this.#t){this.#t=!0;return}let y=[(i+o)/2,(a+s)/2];this.#a?.(y,v,_)}#p(e){this.#u.abort(),this.#u=null,this.#o?.(),this.#c&&(e.preventDefault(),this.#c=null,this.#t=!1)}destroy(){this.#l?.abort(),this.#l=null}},Q=class e{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=``;#o=!1;#s=null;#c=null;#l=null;#u=null;#d=``;#f=!1;#p=null;#m=!1;#h=!1;#g=!1;#_=null;#v=0;#y=0;#b=null;#x=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#S=!1;#C=e._zIndex++;static _borderLineWidth=-1;static _colorManager=new $l;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let t=e.prototype._resizeWithKeyboard,n=eu.TRANSLATE_SMALL,r=eu.TRANSLATE_BIG;return Y(this,`_resizerKeyboardManager`,new Ql([[[`ArrowLeft`,`mac+ArrowLeft`],t,{args:[-n,0]}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t,{args:[-r,0]}],[[`ArrowRight`,`mac+ArrowRight`],t,{args:[n,0]}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t,{args:[r,0]}],[[`ArrowUp`,`mac+ArrowUp`],t,{args:[0,-n]}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t,{args:[0,-r]}],[[`ArrowDown`,`mac+ArrowDown`],t,{args:[0,n]}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t,{args:[0,r]}],[[`Escape`,`mac+Escape`],e.prototype._stopResizingWithKeyboard]]))}constructor(e){this.parent=e.parent,this.id=e.id,this.width=this.height=null,this.pageIndex=e.parent.pageIndex,this.name=e.name,this.div=null,this._uiManager=e.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=e.isCentered,this._structTreeParentId=null;let{rotation:t,rawDims:{pageWidth:n,pageHeight:r,pageX:i,pageY:a}}=this.parent.viewport;this.rotation=t,this.pageRotation=(360+t-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[n,r],this.pageTranslation=[i,a];let[o,s]=this.parentDimensions;this.x=e.x/o,this.y=e.y/s,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return Y(this,`_defaultLineColor`,this._colorManager.getHexCode(`CanvasText`))}static deleteAnnotationElement(e){let t=new ru({id:e.parent.getNextId(),parent:e.parent,uiManager:e._uiManager});t.annotationElementId=e.annotationElementId,t.deleted=!0,t._uiManager.addToAnnotationStorage(t)}static initialize(t,n){if(e._l10n??=t,e._l10nResizer||=Object.freeze({topLeft:`pdfjs-editor-resizer-top-left`,topMiddle:`pdfjs-editor-resizer-top-middle`,topRight:`pdfjs-editor-resizer-top-right`,middleRight:`pdfjs-editor-resizer-middle-right`,bottomRight:`pdfjs-editor-resizer-bottom-right`,bottomMiddle:`pdfjs-editor-resizer-bottom-middle`,bottomLeft:`pdfjs-editor-resizer-bottom-left`,middleLeft:`pdfjs-editor-resizer-middle-left`}),e._borderLineWidth!==-1)return;let r=getComputedStyle(document.documentElement);e._borderLineWidth=parseFloat(r.getPropertyValue(`--outline-width`))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){q(`Not implemented`)}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(e){this.#S=e,this.div?.classList.toggle(`draggable`,e)}get isEnterHandled(){return!0}center(){let[e,t]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*t/(e*2),this.y+=this.width*e/(t*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*t/(e*2),this.y-=this.width*e/(t*2);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(e){this._uiManager.addCommands(e)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#C}setParent(e){e===null?this.#H():(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions),this.parent=e}focusin(e){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(e){this._focusEventsAllowed&&this.isAttachedToDOM&&(e.relatedTarget?.closest(`#${this.id}`)||(e.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove()))}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(e,t,n,r){let[i,a]=this.parentDimensions;[n,r]=this.screenToPageTranslation(n,r),this.x=(e+n)/i,this.y=(t+r)/a,this.fixAndSetPosition()}#w([e,t],n,r){[n,r]=this.screenToPageTranslation(n,r),this.x+=n/e,this.y+=r/t,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(e,t){this.#w(this.parentDimensions,e,t)}translateInPage(e,t){this.#p||=[this.x,this.y,this.width,this.height],this.#w(this.pageDimensions,e,t),this.div.scrollIntoView({block:`nearest`})}drag(e,t){this.#p||=[this.x,this.y,this.width,this.height];let{div:n,parentDimensions:[r,i]}=this;if(this.x+=e/r,this.y+=t/i,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:e,y:t}=this.div.getBoundingClientRect();this.parent.findNewParent(this,e,t)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:a,y:o}=this,[s,c]=this.getBaseTranslation();a+=s,o+=c;let{style:l}=n;l.left=`${(100*a).toFixed(2)}%`,l.top=`${(100*o).toFixed(2)}%`,this._onTranslating(a,o),n.scrollIntoView({block:`nearest`})}_onTranslating(e,t){}_onTranslated(e,t){}get _hasBeenMoved(){return!!this.#p&&(this.#p[0]!==this.x||this.#p[1]!==this.y)}get _hasBeenResized(){return!!this.#p&&(this.#p[2]!==this.width||this.#p[3]!==this.height)}getBaseTranslation(){let[t,n]=this.parentDimensions,{_borderLineWidth:r}=e,i=r/t,a=r/n;switch(this.rotation){case 90:return[-i,a];case 180:return[i,a];case 270:return[i,-a];default:return[-i,-a]}}get _mustFixPosition(){return!0}fixAndSetPosition(e=this.rotation){let{div:{style:t},pageDimensions:[n,r]}=this,{x:i,y:a,width:o,height:s}=this;if(o*=n,s*=r,i*=n,a*=r,this._mustFixPosition)switch(e){case 0:i=Math.max(0,Math.min(n-o,i)),a=Math.max(0,Math.min(r-s,a));break;case 90:i=Math.max(0,Math.min(n-s,i)),a=Math.min(r,Math.max(o,a));break;case 180:i=Math.min(n,Math.max(o,i)),a=Math.min(r,Math.max(s,a));break;case 270:i=Math.min(n,Math.max(s,i)),a=Math.max(0,Math.min(r-o,a))}this.x=i/=n,this.y=a/=r;let[c,l]=this.getBaseTranslation();i+=c,a+=l,t.left=`${(100*i).toFixed(2)}%`,t.top=`${(100*a).toFixed(2)}%`,this.moveInDOM()}static#T(e,t,n){switch(n){case 90:return[t,-e];case 180:return[-e,-t];case 270:return[-t,e];default:return[e,t]}}screenToPageTranslation(t,n){return e.#T(t,n,this.parentRotation)}pageTranslationToScreen(t,n){return e.#T(t,n,360-this.parentRotation)}#E(e){switch(e){case 90:{let[e,t]=this.pageDimensions;return[0,-e/t,t/e,0]}case 180:return[-1,0,0,-1];case 270:{let[e,t]=this.pageDimensions;return[0,e/t,-t/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:e,pageDimensions:[t,n]}=this;return[t*e,n*e]}setDims(e,t){let[n,r]=this.parentDimensions,{style:i}=this.div;i.width=`${(100*e/n).toFixed(2)}%`,this.#o||(i.height=`${(100*t/r).toFixed(2)}%`)}fixDims(){let{style:e}=this.div,{height:t,width:n}=e,r=n.endsWith(`%`),i=!this.#o&&t.endsWith(`%`);if(r&&i)return;let[a,o]=this.parentDimensions;r||(e.width=`${(100*parseFloat(n)/a).toFixed(2)}%`),!this.#o&&!i&&(e.height=`${(100*parseFloat(t)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#D(){if(this.#s)return;this.#s=document.createElement(`div`),this.#s.classList.add(`resizers`);let e=this._willKeepAspectRatio?[`topLeft`,`topRight`,`bottomRight`,`bottomLeft`]:[`topLeft`,`topMiddle`,`topRight`,`middleRight`,`bottomRight`,`bottomMiddle`,`bottomLeft`,`middleLeft`],t=this._uiManager._signal;for(let n of e){let e=document.createElement(`div`);this.#s.append(e),e.classList.add(`resizer`,n),e.setAttribute(`data-resizer-name`,n),e.addEventListener(`pointerdown`,this.#O.bind(this,n),{signal:t}),e.addEventListener(`contextmenu`,Ll,{signal:t}),e.tabIndex=-1}this.div.prepend(this.#s)}#O(e,t){t.preventDefault();let{isMac:n}=_l.platform;if(t.button!==0||t.ctrlKey&&n)return;this.#n?.toggle(!1);let r=this._isDraggable;this._isDraggable=!1,this.#c=[t.screenX,t.screenY];let i=new AbortController,a=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener(`pointermove`,this.#j.bind(this,e),{passive:!0,capture:!0,signal:a}),window.addEventListener(`touchmove`,Rl,{passive:!1,signal:a}),window.addEventListener(`contextmenu`,Ll,{signal:a}),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let o=this.parent.div.style.cursor,s=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(t.target).cursor;let c=()=>{i.abort(),this.parent.togglePointerEvents(!0),this.#n?.toggle(!0),this._isDraggable=r,this.parent.div.style.cursor=o,this.div.style.cursor=s,this.#A()};window.addEventListener(`pointerup`,c,{signal:a}),window.addEventListener(`blur`,c,{signal:a})}#k(e,t,n,r){this.width=n,this.height=r,this.x=e,this.y=t;let[i,a]=this.parentDimensions;this.setDims(i*n,a*r),this.fixAndSetPosition(),this._onResized()}_onResized(){}#A(){if(!this.#l)return;let{savedX:e,savedY:t,savedWidth:n,savedHeight:r}=this.#l;this.#l=null;let i=this.x,a=this.y,o=this.width,s=this.height;(i!==e||a!==t||o!==n||s!==r)&&this.addCommands({cmd:this.#k.bind(this,i,a,o,s),undo:this.#k.bind(this,e,t,n,r),mustExec:!0})}static _round(e){return Math.round(e*1e4)/1e4}#j(t,n){let[r,i]=this.parentDimensions,a=this.x,o=this.y,s=this.width,c=this.height,l=e.MIN_SIZE/r,u=e.MIN_SIZE/i,d=this.#E(this.rotation),f=(e,t)=>[d[0]*e+d[2]*t,d[1]*e+d[3]*t],p=this.#E(360-this.rotation),m=(e,t)=>[p[0]*e+p[2]*t,p[1]*e+p[3]*t],h,g,_=!1,v=!1;switch(t){case`topLeft`:_=!0,h=(e,t)=>[0,0],g=(e,t)=>[e,t];break;case`topMiddle`:h=(e,t)=>[e/2,0],g=(e,t)=>[e/2,t];break;case`topRight`:_=!0,h=(e,t)=>[e,0],g=(e,t)=>[0,t];break;case`middleRight`:v=!0,h=(e,t)=>[e,t/2],g=(e,t)=>[0,t/2];break;case`bottomRight`:_=!0,h=(e,t)=>[e,t],g=(e,t)=>[0,0];break;case`bottomMiddle`:h=(e,t)=>[e/2,t],g=(e,t)=>[e/2,0];break;case`bottomLeft`:_=!0,h=(e,t)=>[0,t],g=(e,t)=>[e,0];break;case`middleLeft`:v=!0,h=(e,t)=>[0,t/2],g=(e,t)=>[e,t/2]}let y=h(s,c),b=g(s,c),x=f(...b),S=e._round(a+x[0]),C=e._round(o+x[1]),w=1,T=1,E,D;if(n.fromKeyboard)({deltaX:E,deltaY:D}=n);else{let{screenX:e,screenY:t}=n,[r,i]=this.#c;[E,D]=this.screenToPageTranslation(e-r,t-i),this.#c[0]=e,this.#c[1]=t}if([E,D]=m(E/r,D/i),_){let e=Math.hypot(s,c);w=T=Math.max(Math.min(Math.hypot(b[0]-y[0]-E,b[1]-y[1]-D)/e,1/s,1/c),l/s,u/c)}else v?w=Math.max(l,Math.min(1,Math.abs(b[0]-y[0]-E)))/s:T=Math.max(u,Math.min(1,Math.abs(b[1]-y[1]-D)))/c;let O=e._round(s*w),k=e._round(c*T);x=f(...g(O,k));let A=S-x[0],j=C-x[1];this.#p||=[this.x,this.y,this.width,this.height],this.width=O,this.height=k,this.x=A,this.y=j,this.setDims(r*O,i*k),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#n?.finish()}async addEditToolbar(){return this._editToolbar||this.#h?this._editToolbar:(this._editToolbar=new Kl(this),this.div.append(this._editToolbar.render()),this.#n&&await this._editToolbar.addAltText(this.#n),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#n?.destroy())}addContainer(e){let t=this._editToolbar?.div;t?t.before(e):this.div.append(e)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#n||(tu.initialize(e._l10n),this.#n=new tu(this),this.#e&&=(this.#n.data=this.#e,null),await this.addEditToolbar())}get altTextData(){return this.#n?.data}set altTextData(e){this.#n&&(this.#n.data=e)}get guessedAltText(){return this.#n?.guessedText}async setGuessedAltText(e){await this.#n?.setGuessedText(e)}serializeAltText(e){return this.#n?.serialize(e)}hasAltText(){return!!this.#n&&!this.#n.isEmpty()}hasAltTextData(){return this.#n?.hasData()??!1}render(){this.div=document.createElement(`div`),this.div.setAttribute(`data-editor-rotation`,(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute(`id`,this.id),this.div.tabIndex=this.#r?-1:0,this._isVisible||this.div.classList.add(`hidden`),this.setInForeground(),this.#L();let[e,t]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*t/e).toFixed(2)}%`,this.div.style.maxHeight=`${(100*e/t).toFixed(2)}%`);let[n,r]=this.getInitialTranslation();return this.translate(n,r),Jl(this,this.div,[`pointerdown`]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#x||=new nu({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#M.bind(this),onPinching:this.#N.bind(this),onPinchEnd:this.#P.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#M(){this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#n?.toggle(!1),this.parent.togglePointerEvents(!1)}#N(t,n,r){let i=.7,a=r/n*i+1-i;if(a===1)return;let o=this.#E(this.rotation),s=(e,t)=>[o[0]*e+o[2]*t,o[1]*e+o[3]*t],[c,l]=this.parentDimensions,u=this.x,d=this.y,f=this.width,p=this.height,m=e.MIN_SIZE/c,h=e.MIN_SIZE/l;a=Math.max(Math.min(a,1/f,1/p),m/f,h/p);let g=e._round(f*a),_=e._round(p*a);if(g===f&&_===p)return;this.#p||=[u,d,f,p];let v=s(f/2,p/2),y=e._round(u+v[0]),b=e._round(d+v[1]),x=s(g/2,_/2);this.x=y-x[0],this.y=b-x[1],this.width=g,this.height=_,this.setDims(c*g,l*_),this.fixAndSetPosition(),this._onResizing()}#P(){this.#n?.toggle(!0),this.parent.togglePointerEvents(!0),this.#A()}pointerdown(e){let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#I(e);return}this.#F(e)}get isSelected(){return this._uiManager.isSelected(this)}#F(e){let{isMac:t}=_l.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)}#I(e){let{isSelected:t}=this;this._uiManager.setUpDragSession();let n=!1,r=new AbortController,i=this._uiManager.combinedSignal(r),a={capture:!0,passive:!1,signal:i},o=e=>{r.abort(),this.#i=null,this.#f=!1,this._uiManager.endDragSession()||this.#F(e),n&&this._onStopDragging()};t&&(this.#v=e.clientX,this.#y=e.clientY,this.#i=e.pointerId,this.#a=e.pointerType,window.addEventListener(`pointermove`,e=>{n||(n=!0,this._onStartDragging());let{clientX:t,clientY:r,pointerId:i}=e;if(i!==this.#i){Rl(e);return}let[a,o]=this.screenToPageTranslation(t-this.#v,r-this.#y);this.#v=t,this.#y=r,this._uiManager.dragSelectedEditors(a,o)},a),window.addEventListener(`touchmove`,Rl,a),window.addEventListener(`pointerdown`,e=>{e.pointerType===this.#a&&(this.#x||e.isPrimary)&&o(e),Rl(e)},a));let s=e=>{if(!this.#i||this.#i===e.pointerId){o(e);return}Rl(e)};window.addEventListener(`pointerup`,s,{signal:i}),window.addEventListener(`blur`,s,{signal:i})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#_&&clearTimeout(this.#_),this.#_=setTimeout(()=>{this.#_=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(e,t,n){e.changeParent(this),this.x=t,this.y=n,this.fixAndSetPosition(),this._onTranslated()}getRect(e,t,n=this.rotation){let r=this.parentScale,[i,a]=this.pageDimensions,[o,s]=this.pageTranslation,c=e/r,l=t/r,u=this.x*i,d=this.y*a,f=this.width*i,p=this.height*a;switch(n){case 0:return[u+c+o,a-d-l-p+s,u+c+f+o,a-d-l+s];case 90:return[u+l+o,a-d+c+s,u+l+p+o,a-d+c+f+s];case 180:return[u-c-f+o,a-d+l+s,u-c+o,a-d+l+p+s];case 270:return[u-l-p+o,a-d-c-f+s,u-l+o,a-d-c+s];default:throw Error(`Invalid rotation`)}}getRectInCurrentCoords(e,t){let[n,r,i,a]=e,o=i-n,s=a-r;switch(this.rotation){case 0:return[n,t-a,o,s];case 90:return[n,t-r,s,o];case 180:return[i,t-r,o,s];case 270:return[i,t-a,s,o];default:throw Error(`Invalid rotation`)}}onceAdded(e){}isEmpty(){return!1}enableEditMode(){this.#h=!0}disableEditMode(){this.#h=!1}isInEditMode(){return this.#h}shouldGetKeyboardEvents(){return this.#g}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){let{top:e,left:t,bottom:n,right:r}=this.getClientDimensions(),{innerHeight:i,innerWidth:a}=window;return t<a&&r>0&&e<i&&n>0}#L(){if(this.#u||!this.div)return;this.#u=new AbortController;let e=this._uiManager.combinedSignal(this.#u);this.div.addEventListener(`focusin`,this.focusin.bind(this),{signal:e}),this.div.addEventListener(`focusout`,this.focusout.bind(this),{signal:e})}rebuild(){this.#L()}rotate(e){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||``}}serialize(e=!1,t=null){q(`An editor must be serializable`)}static async deserialize(e,t,n){let r=new this.prototype.constructor({parent:t,id:t.getNextId(),uiManager:n});r.rotation=e.rotation,r.#e=e.accessibilityData;let[i,a]=r.pageDimensions,[o,s,c,l]=r.getRectInCurrentCoords(e.rect,a);return r.x=o/i,r.y=s/a,r.width=c/i,r.height=l/a,r}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#u?.abort(),this.#u=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#_&&=(clearTimeout(this.#_),null),this.#H(),this.removeEditToolbar(),this.#b){for(let e of this.#b.values())clearTimeout(e);this.#b=null}this.parent=null,this.#x?.destroy(),this.#x=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#D(),this.#s.classList.remove(`hidden`),Jl(this,this.div,[`keydown`]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!==`Enter`)return;this._uiManager.setSelected(this),this.#l={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let n=this.#s.children;if(!this.#t){this.#t=Array.from(n);let t=this.#R.bind(this),r=this.#z.bind(this),i=this._uiManager._signal;for(let n of this.#t){let a=n.getAttribute(`data-resizer-name`);n.setAttribute(`role`,`spinbutton`),n.addEventListener(`keydown`,t,{signal:i}),n.addEventListener(`blur`,r,{signal:i}),n.addEventListener(`focus`,this.#B.bind(this,a),{signal:i}),n.setAttribute(`data-l10n-id`,e._l10nResizer[a])}}let r=this.#t[0],i=0;for(let e of n){if(e===r)break;i++}let a=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(a!==i){if(a<i)for(let e=0;e<i-a;e++)this.#s.append(this.#s.firstChild);else if(a>i)for(let e=0;e<a-i;e++)this.#s.firstChild.before(this.#s.lastChild);let t=0;for(let r of n){let n=this.#t[t++].getAttribute(`data-resizer-name`);r.setAttribute(`data-l10n-id`,e._l10nResizer[n])}}this.#V(0),this.#g=!0,this.#s.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#R(t){e._resizerKeyboardManager.exec(this,t)}#z(e){this.#g&&e.relatedTarget?.parentNode!==this.#s&&this.#H()}#B(e){this.#d=this.#g?e:``}#V(e){if(this.#t)for(let t of this.#t)t.tabIndex=e}_resizeWithKeyboard(e,t){this.#g&&this.#j(this.#d,{deltaX:e,deltaY:t,fromKeyboard:!0})}#H(){this.#g=!1,this.#V(-1),this.#A()}_stopResizingWithKeyboard(){this.#H(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add(`selectedEditor`),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains(`selectedEditor`)&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#n?.toggleAltTextBadge(!1)}unselect(){this.#s?.classList.add(`hidden`),this.div?.classList.remove(`selectedEditor`),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#n?.toggleAltTextBadge(!0)}updateParams(e,t){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#m}set isEditing(e){this.#m=e,this.parent&&(e?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(e,t){this.#o=!0;let n=e/t,{style:r}=this.div;r.aspectRatio=n,r.height=`auto`}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:`added`}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){this.#b||=new Map;let{action:n}=t,r=this.#b.get(n);r&&clearTimeout(r),r=setTimeout(()=>{this._reportTelemetry(t),this.#b.delete(n),this.#b.size===0&&(this.#b=null)},e._telemetryTimeout),this.#b.set(n,r);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch(`reporttelemetry`,{source:this,details:{type:`editing`,data:t}})}show(e=this._isVisible){this.div.classList.toggle(`hidden`,!e),this._isVisible=e}enable(){this.div&&(this.div.tabIndex=0),this.#r=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#r=!0}renderAnnotationElement(e){let t=e.container.querySelector(`.annotationContent`);if(!t)t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.container.prepend(t);else if(t.nodeName===`CANVAS`){let e=t;t=document.createElement(`div`),t.classList.add(`annotationContent`,this.editorType),e.before(t)}return t}resetAnnotationElement(e){let{firstChild:t}=e.container;t?.nodeName===`DIV`&&t.classList.contains(`annotationContent`)&&t.remove()}},ru=class extends Q{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}},iu=3285377520,au=4294901760,ou=65535,su=class{constructor(e){this.h1=e?e&4294967295:iu,this.h2=e?e&4294967295:iu}update(e){let t,n;if(typeof e==`string`){t=new Uint8Array(e.length*2),n=0;for(let r=0,i=e.length;r<i;r++){let i=e.charCodeAt(r);i<=255?t[n++]=i:(t[n++]=i>>>8,t[n++]=i&255)}}else if(ArrayBuffer.isView(e))t=e.slice(),n=t.byteLength;else throw Error(`Invalid data format, must be a string or TypedArray.`);let r=n>>2,i=n-r*4,a=new Uint32Array(t.buffer,0,r),o=0,s=0,c=this.h1,l=this.h2,u=3432918353,d=461845907,f=11601,p=13715;for(let e=0;e<r;e++)e&1?(o=a[e],o=o*u&au|o*f&ou,o=o<<15|o>>>17,o=o*d&au|o*p&ou,c^=o,c=c<<13|c>>>19,c=c*5+3864292196):(s=a[e],s=s*u&au|s*f&ou,s=s<<15|s>>>17,s=s*d&au|s*p&ou,l^=s,l=l<<13|l>>>19,l=l*5+3864292196);switch(o=0,i){case 3:o^=t[r*4+2]<<16;case 2:o^=t[r*4+1]<<8;case 1:o^=t[r*4],o=o*u&au|o*f&ou,o=o<<15|o>>>17,o=o*d&au|o*p&ou,r&1?c^=o:l^=o}this.h1=c,this.h2=l}hexdigest(){let e=this.h1,t=this.h2;return e^=t>>>1,e=e*3981806797&au|e*36045&ou,t=t*4283543511&au|((t<<16|e>>>16)*2950163797&au)>>>16,e^=t>>>1,e=e*444984403&au|e*60499&ou,t=t*3301882366&au|((t<<16|e>>>16)*3120437893&au)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,`0`)+(t>>>0).toString(16).padStart(8,`0`)}},cu=Object.freeze({map:null,hash:``,transfer:void 0}),lu=class{#e=!1;#t=null;#n=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(e,t){let n=this.#n.get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return this.#n.get(e)}remove(e){if(this.#n.delete(e),this.#n.size===0&&this.resetModified(),typeof this.onAnnotationEditor==`function`){for(let e of this.#n.values())if(e instanceof Q)return;this.onAnnotationEditor(null)}}setValue(e,t){let n=this.#n.get(e),r=!1;if(n!==void 0)for(let[e,i]of Object.entries(t))n[e]!==i&&(r=!0,n[e]=i);else r=!0,this.#n.set(e,t);r&&this.#r(),t instanceof Q&&typeof this.onAnnotationEditor==`function`&&this.onAnnotationEditor(t.constructor._type)}has(e){return this.#n.has(e)}getAll(){return this.#n.size>0?ml(this.#n):null}setAll(e){for(let[t,n]of Object.entries(e))this.setValue(t,n)}get size(){return this.#n.size}#r(){this.#e||(this.#e=!0,typeof this.onSetModified==`function`&&this.onSetModified())}resetModified(){this.#e&&(this.#e=!1,typeof this.onResetModified==`function`&&this.onResetModified())}get print(){return new uu(this)}get serializable(){if(this.#n.size===0)return cu;let e=new Map,t=new su,n=[],r=Object.create(null),i=!1;for(let[n,a]of this.#n){let o=a instanceof Q?a.serialize(!1,r):a;o&&(e.set(n,o),t.update(`${n}:${JSON.stringify(o)}`),i||=!!o.bitmap)}if(i)for(let t of e.values())t.bitmap&&n.push(t.bitmap);return e.size>0?{map:e,hash:t.hexdigest(),transfer:n}:cu}get editorStats(){let e=null,t=new Map;for(let n of this.#n.values()){if(!(n instanceof Q))continue;let r=n.telemetryFinalData;if(!r)continue;let{type:i}=r;t.has(i)||t.set(i,Object.getPrototypeOf(n).constructor),e||=Object.create(null);let a=e[i]||=new Map;for(let[e,t]of Object.entries(r)){if(e===`type`)continue;let n=a.get(e);n||(n=new Map,a.set(e,n));let r=n.get(t)??0;n.set(t,r+1)}}for(let[n,r]of t)e[n]=r.computeTelemetryFinalData(e[n]);return e}resetModifiedIds(){this.#t=null}get modifiedIds(){if(this.#t)return this.#t;let e=[];for(let t of this.#n.values())!(t instanceof Q)||!t.annotationElementId||!t.serialize()||e.push(t.annotationElementId);return this.#t={ids:new Set(e),hash:e.join(`,`)}}},uu=class extends lu{#e;constructor(e){super();let{map:t,hash:n,transfer:r}=e.serializable,i=structuredClone(t,r?{transfer:r}:null);this.#e={map:i,hash:n,transfer:r}}get print(){q(`Should not call PrintAnnotationStorage.print`)}get serializable(){return this.#e}get modifiedIds(){return Y(this,`modifiedIds`,{ids:new Set,hash:``})}},du=class{#e=new Set;constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){this._document=e,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(e){this.nativeFontFaces.add(e),this._document.fonts.add(e)}removeNativeFontFace(e){this.nativeFontFaces.delete(e),this._document.fonts.delete(e)}insertRule(e){this.styleElement||(this.styleElement=this._document.createElement(`style`),this._document.documentElement.getElementsByTagName(`head`)[0].append(this.styleElement));let t=this.styleElement.sheet;t.insertRule(e,t.cssRules.length)}clear(){for(let e of this.nativeFontFaces)this._document.fonts.delete(e);this.nativeFontFaces.clear(),this.#e.clear(),this.styleElement&&=(this.styleElement.remove(),null)}async loadSystemFont({systemFontInfo:e,_inspectFont:t}){if(!(!e||this.#e.has(e.loadedName))){if(J(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){let{loadedName:n,src:r,style:i}=e,a=new FontFace(n,r,i);this.addNativeFontFace(a);try{await a.load(),this.#e.add(n),t?.(e)}catch{K(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}q(`Not implemented: loadSystemFont without the Font Loading API.`)}}async bind(e){if(e.attached||e.missingFile&&!e.systemFontInfo)return;if(e.attached=!0,e.systemFontInfo){await this.loadSystemFont(e);return}if(this.isFontLoadingAPISupported){let t=e.createNativeFontFace();if(t){this.addNativeFontFace(t);try{await t.loaded}catch(n){throw K(`Failed to load font '${t.family}': '${n}'.`),e.disableFontFace=!0,n}}return}let t=e.createFontFaceRule();if(t){if(this.insertRule(t),this.isSyncFontLoadingSupported)return;await new Promise(t=>{let n=this._queueLoadingCallback(t);this._prepareFontLoadEvent(e,n)})}}get isFontLoadingAPISupported(){let e=!!this._document?.fonts;return Y(this,`isFontLoadingAPISupported`,e)}get isSyncFontLoadingSupported(){let e=!1;return(Fc||typeof navigator<`u`&&typeof navigator?.userAgent==`string`&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(e=!0),Y(this,`isSyncFontLoadingSupported`,e)}_queueLoadingCallback(e){function t(){for(J(!r.done,`completeRequest() cannot be called twice.`),r.done=!0;n.length>0&&n[0].done;){let e=n.shift();setTimeout(e.callback,0)}}let{loadingRequests:n}=this,r={done:!1,complete:t,callback:e};return n.push(r),r}get _loadTestFont(){let e=atob(`T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==`);return Y(this,`_loadTestFont`,e)}_prepareFontLoadEvent(e,t){function n(e,t){return e.charCodeAt(t)<<24|e.charCodeAt(t+1)<<16|e.charCodeAt(t+2)<<8|e.charCodeAt(t+3)&255}function r(e,t,n,r){let i=e.substring(0,t),a=e.substring(t+n);return i+r+a}let i,a,o=this._document.createElement(`canvas`);o.width=1,o.height=1;let s=o.getContext(`2d`),c=0;function l(e,t){if(++c>30){K(`Load test font never loaded.`),t();return}if(s.font=`30px `+e,s.fillText(`.`,0,20),s.getImageData(0,0,1,1).data[3]>0){t();return}setTimeout(l.bind(null,e,t))}let u=`lt${Date.now()}${this.loadTestFontId++}`,d=this._loadTestFont;d=r(d,976,u.length,u);let f=1482184792,p=n(d,16);for(i=0,a=u.length-3;i<a;i+=4)p=p-f+n(u,i)|0;i<u.length&&(p=p-f+n(u+`XXX`,i)|0),d=r(d,16,4,pl(p));let m=`@font-face {font-family:"${u}";src:${`url(data:font/opentype;base64,${btoa(d)});`}}`;this.insertRule(m);let h=this._document.createElement(`div`);h.style.visibility=`hidden`,h.style.width=h.style.height=`10px`,h.style.position=`absolute`,h.style.top=h.style.left=`0px`;for(let t of[e.loadedName,u]){let e=this._document.createElement(`span`);e.textContent=`Hi`,e.style.fontFamily=t,h.append(e)}this._document.body.append(h),l(u,()=>{h.remove(),t.complete()})}},fu=class{constructor(e,{disableFontFace:t=!1,fontExtraProperties:n=!1,inspectFont:r=null}){this.compiledGlyphs=Object.create(null);for(let t in e)this[t]=e[t];this.disableFontFace=t===!0,this.fontExtraProperties=n===!0,this._inspectFont=r}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let e;if(!this.cssFontInfo)e=new FontFace(this.loadedName,this.data,{});else{let t={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(t.style=`oblique ${this.cssFontInfo.italicAngle}deg`),e=new FontFace(this.cssFontInfo.fontFamily,this.data,t)}return this._inspectFont?.(this),e}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;let e=`url(data:${this.mimetype};base64,${Tl(this.data)});`,t;if(!this.cssFontInfo)t=`@font-face {font-family:"${this.loadedName}";src:${e}}`;else{let n=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(n+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),t=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${n}src:${e}}`}return this._inspectFont?.(this,e),t}getPathGenerator(e,t){if(this.compiledGlyphs[t]!==void 0)return this.compiledGlyphs[t];let n=this.loadedName+`_path_`+t,r;try{r=e.get(n)}catch(e){K(`getPathGenerator - ignoring character: "${e}".`)}let i=new Path2D(r||``);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=i}},pu={DATA:1,ERROR:2},mu={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function hu(){}function gu(e){if(e instanceof ul||e instanceof ol||e instanceof sl||e instanceof il||e instanceof cl||e instanceof al)return e;switch(e instanceof Error||typeof e==`object`&&e||q(`wrapReason: Expected "reason" to be a (possibly cloned) Error.`),e.name){case`AbortException`:return new ul(e.message);case`InvalidPDFException`:return new ol(e.message);case`MissingPDFException`:return new sl(e.message);case`PasswordException`:return new il(e.message,e.code);case`UnexpectedResponseException`:return new cl(e.message,e.status);case`UnknownErrorException`:return new al(e.message,e.details)}return new al(e.message,e.toString())}var _u=class{#e=new AbortController;constructor(e,t,n){this.sourceName=e,this.targetName=t,this.comObj=n,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),n.addEventListener(`message`,this.#t.bind(this),{signal:this.#e.signal})}#t({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){this.#r(e);return}if(e.callback){let t=e.callbackId,n=this.callbackCapabilities[t];if(!n)throw Error(`Cannot resolve callback ${t}`);if(delete this.callbackCapabilities[t],e.callback===pu.DATA)n.resolve(e.data);else if(e.callback===pu.ERROR)n.reject(gu(e.reason));else throw Error(`Unexpected callback case`);return}let t=this.actionHandler[e.action];if(!t)throw Error(`Unknown action from worker: ${e.action}`);if(e.callbackId){let n=this.sourceName,r=e.sourceName,i=this.comObj;Promise.try(t,e.data).then(function(t){i.postMessage({sourceName:n,targetName:r,callback:pu.DATA,callbackId:e.callbackId,data:t})},function(t){i.postMessage({sourceName:n,targetName:r,callback:pu.ERROR,callbackId:e.callbackId,reason:gu(t)})});return}if(e.streamId){this.#n(e);return}t(e.data)}on(e,t){let n=this.actionHandler;if(n[e])throw Error(`There is already an actionName called "${e}"`);n[e]=t}send(e,t,n){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,data:t},n)}sendWithPromise(e,t,n){let r=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[r]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:e,callbackId:r,data:t},n)}catch(e){i.reject(e)}return i.promise}sendWithStream(e,t,n,r){let i=this.streamId++,a=this.sourceName,o=this.targetName,s=this.comObj;return new ReadableStream({start:n=>{let c=Promise.withResolvers();return this.streamControllers[i]={controller:n,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},s.postMessage({sourceName:a,targetName:o,action:e,streamId:i,data:t,desiredSize:n.desiredSize},r),c.promise},pull:e=>{let t=Promise.withResolvers();return this.streamControllers[i].pullCall=t,s.postMessage({sourceName:a,targetName:o,stream:mu.PULL,streamId:i,desiredSize:e.desiredSize}),t.promise},cancel:e=>{J(e instanceof Error,`cancel must have a valid reason`);let t=Promise.withResolvers();return this.streamControllers[i].cancelCall=t,this.streamControllers[i].isClosed=!0,s.postMessage({sourceName:a,targetName:o,stream:mu.CANCEL,streamId:i,reason:gu(e)}),t.promise}},n)}#n(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this,o=this.actionHandler[e.action],s={enqueue(e,a=1,o){if(this.isCancelled)return;let s=this.desiredSize;this.desiredSize-=a,s>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:n,targetName:r,stream:mu.ENQUEUE,streamId:t,chunk:e},o)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:mu.CLOSE,streamId:t}),delete a.streamSinks[t])},error(e){J(e instanceof Error,`error must have a valid reason`),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:n,targetName:r,stream:mu.ERROR,streamId:t,reason:gu(e)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:e.desiredSize,ready:null};s.sinkCapability.resolve(),s.ready=s.sinkCapability.promise,this.streamSinks[t]=s,Promise.try(o,e.data,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.START_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.START_COMPLETE,streamId:t,reason:gu(e)})})}#r(e){let t=e.streamId,n=this.sourceName,r=e.sourceName,i=this.comObj,a=this.streamControllers[t],o=this.streamSinks[t];switch(e.stream){case mu.START_COMPLETE:e.success?a.startCall.resolve():a.startCall.reject(gu(e.reason));break;case mu.PULL_COMPLETE:e.success?a.pullCall.resolve():a.pullCall.reject(gu(e.reason));break;case mu.PULL:if(!o){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,success:!0});break}o.desiredSize<=0&&e.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=e.desiredSize,Promise.try(o.onPull||hu).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.PULL_COMPLETE,streamId:t,reason:gu(e)})});break;case mu.ENQUEUE:if(J(a,`enqueue should have stream controller`),a.isClosed)break;a.controller.enqueue(e.chunk);break;case mu.CLOSE:if(J(a,`close should have stream controller`),a.isClosed)break;a.isClosed=!0,a.controller.close(),this.#i(a,t);break;case mu.ERROR:J(a,`error should have stream controller`),a.controller.error(gu(e.reason)),this.#i(a,t);break;case mu.CANCEL_COMPLETE:e.success?a.cancelCall.resolve():a.cancelCall.reject(gu(e.reason)),this.#i(a,t);break;case mu.CANCEL:if(!o)break;let s=gu(e.reason);Promise.try(o.onCancel||hu,s).then(function(){i.postMessage({sourceName:n,targetName:r,stream:mu.CANCEL_COMPLETE,streamId:t,success:!0})},function(e){i.postMessage({sourceName:n,targetName:r,stream:mu.CANCEL_COMPLETE,streamId:t,reason:gu(e)})}),o.sinkCapability.reject(s),o.isCancelled=!0,delete this.streamSinks[t];break;default:throw Error(`Unexpected stream case`)}}async#i(e,t){await Promise.allSettled([e.startCall?.promise,e.pullCall?.promise,e.cancelCall?.promise]),delete this.streamControllers[t]}destroy(){this.#e?.abort(),this.#e=null}},vu=class{#e=!1;constructor({enableHWA:e=!1}){this.#e=e}create(e,t){if(e<=0||t<=0)throw Error(`Invalid canvas size`);let n=this._createCanvas(e,t);return{canvas:n,context:n.getContext(`2d`,{willReadFrequently:!this.#e})}}reset(e,t,n){if(!e.canvas)throw Error(`Canvas is not specified`);if(t<=0||n<=0)throw Error(`Invalid canvas size`);e.canvas.width=t,e.canvas.height=n}destroy(e){if(!e.canvas)throw Error(`Canvas is not specified`);e.canvas.width=0,e.canvas.height=0,e.canvas=null,e.context=null}_createCanvas(e,t){q("Abstract method `_createCanvas` called.")}},yu=class extends vu{constructor({ownerDocument:e=globalThis.document,enableHWA:t=!1}){super({enableHWA:t}),this._document=e}_createCanvas(e,t){let n=this._document.createElement(`canvas`);return n.width=e,n.height=t,n}},bu=class{constructor({baseUrl:e=null,isCompressed:t=!0}){this.baseUrl=e,this.isCompressed=t}async fetch({name:e}){if(!this.baseUrl)throw Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!e)throw Error(`CMap name must be specified.`);let t=this.baseUrl+e+(this.isCompressed?`.bcmap`:``);return this._fetch(t).then(e=>({cMapData:e,isCompressed:this.isCompressed})).catch(e=>{throw Error(`Unable to load ${this.isCompressed?`binary `:``}CMap at: ${t}`)})}async _fetch(e){q("Abstract method `_fetch` called.")}},xu=class extends bu{async _fetch(e){let t=await Ol(e,this.isCompressed?`arraybuffer`:`text`);return t instanceof ArrayBuffer?new Uint8Array(t):fl(t)}},Su=class{addFilter(e){return`none`}addHCMFilter(e,t){return`none`}addAlphaFilter(e){return`none`}addLuminosityFilter(e){return`none`}addHighlightHCMFilter(e,t,n,r,i){return`none`}destroy(e=!1){}},Cu=class extends Su{#e;#t;#n;#r;#i;#a;#o=0;constructor({docId:e,ownerDocument:t=globalThis.document}){super(),this.#r=e,this.#i=t}get#s(){return this.#t||=new Map}get#c(){return this.#a||=new Map}get#l(){if(!this.#n){let e=this.#i.createElement(`div`),{style:t}=e;t.visibility=`hidden`,t.contain=`strict`,t.width=t.height=0,t.position=`absolute`,t.top=t.left=0,t.zIndex=-1;let n=this.#i.createElementNS(El,`svg`);n.setAttribute(`width`,0),n.setAttribute(`height`,0),this.#n=this.#i.createElementNS(El,`defs`),e.append(n),n.append(this.#n),this.#i.body.append(e)}return this.#n}#u(e){if(e.length===1){let t=e[0],n=Array(256);for(let e=0;e<256;e++)n[e]=t[e]/255;let r=n.join(`,`);return[r,r,r]}let[t,n,r]=e,i=Array(256),a=Array(256),o=Array(256);for(let e=0;e<256;e++)i[e]=t[e]/255,a[e]=n[e]/255,o[e]=r[e]/255;return[i.join(`,`),a.join(`,`),o.join(`,`)]}#d(e){if(this.#e===void 0){this.#e=``;let e=this.#i.URL;e!==this.#i.baseURI&&(jl(e)?K(`#createUrl: ignore "data:"-URL for performance reasons.`):this.#e=e.split(`#`,1)[0])}return`url(${this.#e}#${e})`}addFilter(e){if(!e)return`none`;let t=this.#s.get(e);if(t)return t;let[n,r,i]=this.#u(e),a=e.length===1?n:`${n}${r}${i}`;if(t=this.#s.get(a),t)return this.#s.set(e,t),t;let o=`g_${this.#r}_transfer_map_${this.#o++}`,s=this.#d(o);this.#s.set(e,s),this.#s.set(a,s);let c=this.#m(o);return this.#g(n,r,i,c),s}addHCMFilter(e,t){let n=`${e}-${t}`,r=`base`,i=this.#c.get(r);if(i?.key===n||(i?(i.filter?.remove(),i.key=n,i.url=`none`,i.filter=null):(i={key:n,url:`none`,filter:null},this.#c.set(r,i)),!e||!t))return i.url;let a=this.#v(e);e=X.makeHexColor(...a);let o=this.#v(t);if(t=X.makeHexColor(...o),this.#l.style.color=``,e===`#000000`&&t===`#ffffff`||e===t)return i.url;let s=Array(256);for(let e=0;e<=255;e++){let t=e/255;s[e]=t<=.03928?t/12.92:((t+.055)/1.055)**2.4}let c=s.join(`,`),l=`g_${this.#r}_hcm_filter`,u=i.filter=this.#m(l);this.#g(c,c,c,u),this.#p(u);let d=(e,t)=>{let n=a[e]/255,r=o[e]/255,i=Array(t+1);for(let e=0;e<=t;e++)i[e]=n+e/t*(r-n);return i.join(`,`)};return this.#g(d(0,5),d(1,5),d(2,5),u),i.url=this.#d(l),i.url}addAlphaFilter(e){let t=this.#s.get(e);if(t)return t;let[n]=this.#u([e]),r=`alpha_${n}`;if(t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_alpha_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#_(n,o),a}addLuminosityFilter(e){let t=this.#s.get(e||`luminosity`);if(t)return t;let n,r;if(e?([n]=this.#u([e]),r=`luminosity_${n}`):r=`luminosity`,t=this.#s.get(r),t)return this.#s.set(e,t),t;let i=`g_${this.#r}_luminosity_map_${this.#o++}`,a=this.#d(i);this.#s.set(e,a),this.#s.set(r,a);let o=this.#m(i);return this.#f(o),e&&this.#_(n,o),a}addHighlightHCMFilter(e,t,n,r,i){let a=`${t}-${n}-${r}-${i}`,o=this.#c.get(e);if(o?.key===a||(o?(o.filter?.remove(),o.key=a,o.url=`none`,o.filter=null):(o={key:a,url:`none`,filter:null},this.#c.set(e,o)),!t||!n))return o.url;let[s,c]=[t,n].map(this.#v.bind(this)),l=Math.round(.2126*s[0]+.7152*s[1]+.0722*s[2]),u=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),[d,f]=[r,i].map(this.#v.bind(this));u<l&&([l,u,d,f]=[u,l,f,d]),this.#l.style.color=``;let p=(e,t,n)=>{let r=Array(256),i=(u-l)/n,a=e/255,o=(t-e)/(255*n),s=0;for(let e=0;e<=n;e++){let t=Math.round(l+e*i),n=a+e*o;for(let e=s;e<=t;e++)r[e]=n;s=t+1}for(let e=s;e<256;e++)r[e]=r[s-1];return r.join(`,`)},m=`g_${this.#r}_hcm_${e}_filter`,h=o.filter=this.#m(m);return this.#p(h),this.#g(p(d[0],f[0],5),p(d[1],f[1],5),p(d[2],f[2],5),h),o.url=this.#d(m),o.url}destroy(e=!1){e&&this.#a?.size||(this.#n?.parentNode.parentNode.remove(),this.#n=null,this.#t?.clear(),this.#t=null,this.#a?.clear(),this.#a=null,this.#o=0)}#f(e){let t=this.#i.createElementNS(El,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0`),e.append(t)}#p(e){let t=this.#i.createElementNS(El,`feColorMatrix`);t.setAttribute(`type`,`matrix`),t.setAttribute(`values`,`0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0`),e.append(t)}#m(e){let t=this.#i.createElementNS(El,`filter`);return t.setAttribute(`color-interpolation-filters`,`sRGB`),t.setAttribute(`id`,e),this.#l.append(t),t}#h(e,t,n){let r=this.#i.createElementNS(El,t);r.setAttribute(`type`,`discrete`),r.setAttribute(`tableValues`,n),e.append(r)}#g(e,t,n,r){let i=this.#i.createElementNS(El,`feComponentTransfer`);r.append(i),this.#h(i,`feFuncR`,e),this.#h(i,`feFuncG`,t),this.#h(i,`feFuncB`,n)}#_(e,t){let n=this.#i.createElementNS(El,`feComponentTransfer`);t.append(n),this.#h(n,`feFuncA`,e)}#v(e){return this.#l.style.color=e,Vl(getComputedStyle(this.#l).getPropertyValue(`color`))}},wu=class{constructor({baseUrl:e=null}){this.baseUrl=e}async fetch({filename:e}){if(!this.baseUrl)throw Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!e)throw Error(`Font filename must be specified.`);let t=`${this.baseUrl}${e}`;return this._fetch(t).catch(e=>{throw Error(`Unable to load font data at: ${t}`)})}async _fetch(e){q("Abstract method `_fetch` called.")}},Tu=class extends wu{async _fetch(e){let t=await Ol(e,`arraybuffer`);return new Uint8Array(t)}};Fc&&K("Please use the `legacy` build in Node.js environments.");async function Eu(e){let t=await process.getBuiltinModule(`fs`).promises.readFile(e);return new Uint8Array(t)}var Du=class extends Su{},Ou=class extends vu{_createCanvas(e,t){return process.getBuiltinModule(`module`).createRequire({}.url)(`@napi-rs/canvas`).createCanvas(e,t)}},ku=class extends bu{async _fetch(e){return Eu(e)}},Au=class extends wu{async _fetch(e){return Eu(e)}},ju={FILL:`Fill`,STROKE:`Stroke`,SHADING:`Shading`};function Mu(e,t){if(!t)return;let n=t[2]-t[0],r=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],n,r),e.clip(i)}var Nu=class{getPattern(){q("Abstract method `getPattern` called.")}},Pu=class extends Nu{constructor(e){super(),this._type=e[1],this._bbox=e[2],this._colorStops=e[3],this._p0=e[4],this._p1=e[5],this._r0=e[6],this._r1=e[7],this.matrix=null}_createGradient(e){let t;this._type===`axial`?t=e.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type===`radial`&&(t=e.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(let e of this._colorStops)t.addColorStop(e[0],e[1]);return t}getPattern(e,t,n,r){let i;if(r===ju.STROKE||r===ju.FILL){let a=t.current.getClippedPathBoundingBox(r,Z(e))||[0,0,0,0],o=Math.ceil(a[2]-a[0])||1,s=Math.ceil(a[3]-a[1])||1,c=t.cachedCanvases.getCanvas(`pattern`,o,s),l=c.context;l.clearRect(0,0,l.canvas.width,l.canvas.height),l.beginPath(),l.rect(0,0,l.canvas.width,l.canvas.height),l.translate(-a[0],-a[1]),n=X.transform(n,[1,0,0,1,a[0],a[1]]),l.transform(...t.baseTransform),this.matrix&&l.transform(...this.matrix),Mu(l,this._bbox),l.fillStyle=this._createGradient(l),l.fill(),i=e.createPattern(c.canvas,`no-repeat`);let u=new DOMMatrix(n);i.setTransform(u)}else Mu(e,this._bbox),i=this._createGradient(e);return i}};function Fu(e,t,n,r,i,a,o,s){let c=t.coords,l=t.colors,u=e.data,d=e.width*4,f;c[n+1]>c[r+1]&&(f=n,n=r,r=f,f=a,a=o,o=f),c[r+1]>c[i+1]&&(f=r,r=i,i=f,f=o,o=s,s=f),c[n+1]>c[r+1]&&(f=n,n=r,r=f,f=a,a=o,o=f);let p=(c[n]+t.offsetX)*t.scaleX,m=(c[n+1]+t.offsetY)*t.scaleY,h=(c[r]+t.offsetX)*t.scaleX,g=(c[r+1]+t.offsetY)*t.scaleY,_=(c[i]+t.offsetX)*t.scaleX,v=(c[i+1]+t.offsetY)*t.scaleY;if(m>=v)return;let y=l[a],b=l[a+1],x=l[a+2],S=l[o],C=l[o+1],w=l[o+2],T=l[s],E=l[s+1],D=l[s+2],O=Math.round(m),k=Math.round(v),A,j,M,ee,N,P,F,I;for(let e=O;e<=k;e++){if(e<g){let t=e<m?0:(m-e)/(m-g);A=p-(p-h)*t,j=y-(y-S)*t,M=b-(b-C)*t,ee=x-(x-w)*t}else{let t;t=e>v?1:g===v?0:(g-e)/(g-v),A=h-(h-_)*t,j=S-(S-T)*t,M=C-(C-E)*t,ee=w-(w-D)*t}let t;t=e<m?0:e>v?1:(m-e)/(m-v),N=p-(p-_)*t,P=y-(y-T)*t,F=b-(b-E)*t,I=x-(x-D)*t;let n=Math.round(Math.min(A,N)),r=Math.round(Math.max(A,N)),i=d*e+n*4;for(let e=n;e<=r;e++)t=(A-e)/(A-N),t<0?t=0:t>1&&(t=1),u[i++]=j-(j-P)*t|0,u[i++]=M-(M-F)*t|0,u[i++]=ee-(ee-I)*t|0,u[i++]=255}}function Iu(e,t,n){let r=t.coords,i=t.colors,a,o;switch(t.type){case`lattice`:let s=t.verticesPerRow,c=Math.floor(r.length/s)-1,l=s-1;for(a=0;a<c;a++){let t=a*s;for(let a=0;a<l;a++,t++)Fu(e,n,r[t],r[t+1],r[t+s],i[t],i[t+1],i[t+s]),Fu(e,n,r[t+s+1],r[t+1],r[t+s],i[t+s+1],i[t+1],i[t+s])}break;case`triangles`:for(a=0,o=r.length;a<o;a+=3)Fu(e,n,r[a],r[a+1],r[a+2],i[a],i[a+1],i[a+2]);break;default:throw Error(`illegal figure`)}}var Lu=class extends Nu{constructor(e){super(),this._coords=e[2],this._colors=e[3],this._figures=e[4],this._bounds=e[5],this._bbox=e[7],this._background=e[8],this.matrix=null}_createMeshCanvas(e,t,n){let r=1.1,i=3e3,a=Math.floor(this._bounds[0]),o=Math.floor(this._bounds[1]),s=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-o,l=Math.min(Math.ceil(Math.abs(s*e[0]*r)),i),u=Math.min(Math.ceil(Math.abs(c*e[1]*r)),i),d=s/l,f=c/u,p={coords:this._coords,colors:this._colors,offsetX:-a,offsetY:-o,scaleX:1/d,scaleY:1/f},m=l+4,h=u+4,g=n.getCanvas(`mesh`,m,h),_=g.context,v=_.createImageData(l,u);if(t){let e=v.data;for(let n=0,r=e.length;n<r;n+=4)e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=255}for(let e of this._figures)Iu(v,e,p);return _.putImageData(v,2,2),{canvas:g.canvas,offsetX:a-2*d,offsetY:o-2*f,scaleX:d,scaleY:f}}getPattern(e,t,n,r){Mu(e,this._bbox);let i;if(r===ju.SHADING)i=X.singularValueDecompose2dScale(Z(e));else if(i=X.singularValueDecompose2dScale(t.baseTransform),this.matrix){let e=X.singularValueDecompose2dScale(this.matrix);i=[i[0]*e[0],i[1]*e[1]]}let a=this._createMeshCanvas(i,r===ju.SHADING?null:this._background,t.cachedCanvases);return r!==ju.SHADING&&(e.setTransform(...t.baseTransform),this.matrix&&e.transform(...this.matrix)),e.translate(a.offsetX,a.offsetY),e.scale(a.scaleX,a.scaleY),e.createPattern(a.canvas,`no-repeat`)}},Ru=class extends Nu{getPattern(){return`hotpink`}};function zu(e){switch(e[0]){case`RadialAxial`:return new Pu(e);case`Mesh`:return new Lu(e);case`Dummy`:return new Ru}throw Error(`Unknown IR type: ${e[0]}`)}var Bu={COLORED:1,UNCOLORED:2},Vu=class e{static MAX_PATTERN_SIZE=3e3;constructor(e,t,n,r,i){this.operatorList=e[2],this.matrix=e[3],this.bbox=e[4],this.xstep=e[5],this.ystep=e[6],this.paintType=e[7],this.tilingType=e[8],this.color=t,this.ctx=n,this.canvasGraphicsFactory=r,this.baseTransform=i}createPatternCanvas(e){let{bbox:t,operatorList:n,paintType:r,tilingType:i,color:a,canvasGraphicsFactory:o}=this,{xstep:s,ystep:c}=this;s=Math.abs(s),c=Math.abs(c),el(`TilingType: `+i);let l=t[0],u=t[1],d=t[2],f=t[3],p=d-l,m=f-u,h=X.singularValueDecompose2dScale(this.matrix),g=X.singularValueDecompose2dScale(this.baseTransform),_=h[0]*g[0],v=h[1]*g[1],y=p,b=m,x=!1,S=!1,C=Math.ceil(s*_),w=Math.ceil(c*v),T=Math.ceil(p*_),E=Math.ceil(m*v);C>=T?y=s:x=!0,w>=E?b=c:S=!0;let D=this.getSizeAndScale(y,this.ctx.canvas.width,_),O=this.getSizeAndScale(b,this.ctx.canvas.height,v),k=e.cachedCanvases.getCanvas(`pattern`,D.size,O.size),A=k.context,j=o.createCanvasGraphics(A);if(j.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(j,r,a),A.translate(-D.scale*l,-O.scale*u),j.transform(D.scale,0,0,O.scale,0,0),A.save(),this.clipBbox(j,l,u,d,f),j.baseTransform=Z(j.ctx),j.executeOperatorList(n),j.endDrawing(),A.restore(),x||S){let t=k.canvas;x&&(y=s),S&&(b=c);let n=this.getSizeAndScale(y,this.ctx.canvas.width,_),r=this.getSizeAndScale(b,this.ctx.canvas.height,v),i=n.size,a=r.size,o=e.cachedCanvases.getCanvas(`pattern-workaround`,i,a),d=o.context,f=x?Math.floor(p/s):0,h=S?Math.floor(m/c):0;for(let e=0;e<=f;e++)for(let n=0;n<=h;n++)d.drawImage(t,i*e,a*n,i,a,0,0,i,a);return{canvas:o.canvas,scaleX:n.scale,scaleY:r.scale,offsetX:l,offsetY:u}}return{canvas:k.canvas,scaleX:D.scale,scaleY:O.scale,offsetX:l,offsetY:u}}getSizeAndScale(t,n,r){let i=Math.max(e.MAX_PATTERN_SIZE,n),a=Math.ceil(t*r);return a>=i?a=i:r=a/t,{scale:r,size:a}}clipBbox(e,t,n,r,i){let a=r-t,o=i-n;e.ctx.rect(t,n,a,o),e.current.updateRectMinMax(Z(e.ctx),[t,n,r,i]),e.clip(),e.endPath()}setFillAndStrokeStyleToContext(e,t,n){let r=e.ctx,i=e.current;switch(t){case Bu.COLORED:let e=this.ctx;r.fillStyle=e.fillStyle,r.strokeStyle=e.strokeStyle,i.fillColor=e.fillStyle,i.strokeColor=e.strokeStyle;break;case Bu.UNCOLORED:let a=X.makeHexColor(n[0],n[1],n[2]);r.fillStyle=a,r.strokeStyle=a,i.fillColor=a,i.strokeColor=a;break;default:throw new ll(`Unsupported paint type: ${t}`)}}getPattern(e,t,n,r){let i=n;r!==ju.SHADING&&(i=X.transform(i,t.baseTransform),this.matrix&&(i=X.transform(i,this.matrix)));let a=this.createPatternCanvas(t),o=new DOMMatrix(i);o=o.translate(a.offsetX,a.offsetY),o=o.scale(1/a.scaleX,1/a.scaleY);let s=e.createPattern(a.canvas,`repeat`);return s.setTransform(o),s}};function Hu({src:e,srcPos:t=0,dest:n,width:r,height:i,nonBlackColor:a=4294967295,inverseDecode:o=!1}){let s=_l.isLittleEndian?4278190080:255,[c,l]=o?[a,s]:[s,a],u=r>>3,d=r&7,f=e.length;n=new Uint32Array(n.buffer);let p=0;for(let r=0;r<i;r++){for(let r=t+u;t<r;t++){let r=t<f?e[t]:255;n[p++]=r&128?l:c,n[p++]=r&64?l:c,n[p++]=r&32?l:c,n[p++]=r&16?l:c,n[p++]=r&8?l:c,n[p++]=r&4?l:c,n[p++]=r&2?l:c,n[p++]=r&1?l:c}if(d===0)continue;let r=t<f?e[t++]:255;for(let e=0;e<d;e++)n[p++]=r&1<<7-e?l:c}return{srcPos:t,destPos:p}}var Uu=16,Wu=100,Gu=15,Ku=10,qu=1e3,Ju=16;function Yu(e,t){if(e._removeMirroring)throw Error(`Context is already forwarding operations.`);e.__originalSave=e.save,e.__originalRestore=e.restore,e.__originalRotate=e.rotate,e.__originalScale=e.scale,e.__originalTranslate=e.translate,e.__originalTransform=e.transform,e.__originalSetTransform=e.setTransform,e.__originalResetTransform=e.resetTransform,e.__originalClip=e.clip,e.__originalMoveTo=e.moveTo,e.__originalLineTo=e.lineTo,e.__originalBezierCurveTo=e.bezierCurveTo,e.__originalRect=e.rect,e.__originalClosePath=e.closePath,e.__originalBeginPath=e.beginPath,e._removeMirroring=()=>{e.save=e.__originalSave,e.restore=e.__originalRestore,e.rotate=e.__originalRotate,e.scale=e.__originalScale,e.translate=e.__originalTranslate,e.transform=e.__originalTransform,e.setTransform=e.__originalSetTransform,e.resetTransform=e.__originalResetTransform,e.clip=e.__originalClip,e.moveTo=e.__originalMoveTo,e.lineTo=e.__originalLineTo,e.bezierCurveTo=e.__originalBezierCurveTo,e.rect=e.__originalRect,e.closePath=e.__originalClosePath,e.beginPath=e.__originalBeginPath,delete e._removeMirroring},e.save=function(){t.save(),this.__originalSave()},e.restore=function(){t.restore(),this.__originalRestore()},e.translate=function(e,n){t.translate(e,n),this.__originalTranslate(e,n)},e.scale=function(e,n){t.scale(e,n),this.__originalScale(e,n)},e.transform=function(e,n,r,i,a,o){t.transform(e,n,r,i,a,o),this.__originalTransform(e,n,r,i,a,o)},e.setTransform=function(e,n,r,i,a,o){t.setTransform(e,n,r,i,a,o),this.__originalSetTransform(e,n,r,i,a,o)},e.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},e.rotate=function(e){t.rotate(e),this.__originalRotate(e)},e.clip=function(e){t.clip(e),this.__originalClip(e)},e.moveTo=function(e,n){t.moveTo(e,n),this.__originalMoveTo(e,n)},e.lineTo=function(e,n){t.lineTo(e,n),this.__originalLineTo(e,n)},e.bezierCurveTo=function(e,n,r,i,a,o){t.bezierCurveTo(e,n,r,i,a,o),this.__originalBezierCurveTo(e,n,r,i,a,o)},e.rect=function(e,n,r,i){t.rect(e,n,r,i),this.__originalRect(e,n,r,i)},e.closePath=function(){t.closePath(),this.__originalClosePath()},e.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}var Xu=class{constructor(e){this.canvasFactory=e,this.cache=Object.create(null)}getCanvas(e,t,n){let r;return this.cache[e]===void 0?(r=this.canvasFactory.create(t,n),this.cache[e]=r):(r=this.cache[e],this.canvasFactory.reset(r,t,n)),r}delete(e){delete this.cache[e]}clear(){for(let e in this.cache){let t=this.cache[e];this.canvasFactory.destroy(t),delete this.cache[e]}}};function Zu(e,t,n,r,i,a,o,s,c,l){let[u,d,f,p,m,h]=Z(e);if(d===0&&f===0){let g=o*u+m,_=Math.round(g),v=s*p+h,y=Math.round(v),b=(o+c)*u+m,x=Math.abs(Math.round(b)-_)||1,S=(s+l)*p+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(Math.sign(u),0,0,Math.sign(p),_,y),e.drawImage(t,n,r,i,a,0,0,x,C),e.setTransform(u,d,f,p,m,h),[x,C]}if(u===0&&p===0){let g=s*f+m,_=Math.round(g),v=o*d+h,y=Math.round(v),b=(s+l)*f+m,x=Math.abs(Math.round(b)-_)||1,S=(o+c)*d+h,C=Math.abs(Math.round(S)-y)||1;return e.setTransform(0,Math.sign(d),Math.sign(f),0,_,y),e.drawImage(t,n,r,i,a,0,0,C,x),e.setTransform(u,d,f,p,m,h),[C,x]}e.drawImage(t,n,r,i,a,o,s,c,l);let g=Math.hypot(u,d),_=Math.hypot(f,p);return[g*c,_*l]}function Qu(e){let{width:t,height:n}=e;if(t>qu||n>qu)return null;let r=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),a=t+1,o=new Uint8Array(a*(n+1)),s,c,l,u=t+7&-8,d=new Uint8Array(u*n),f=0;for(let t of e.data){let e=128;for(;e>0;)d[f++]=t&e?0:255,e>>=1}let p=0;for(f=0,d[f]!==0&&(o[0]=1,++p),c=1;c<t;c++)d[f]!==d[f+1]&&(o[c]=d[f]?2:1,++p),f++;for(d[f]!==0&&(o[c]=2,++p),s=1;s<n;s++){f=s*u,l=s*a,d[f-u]!==d[f]&&(o[l]=d[f]?1:8,++p);let e=(d[f]?4:0)+(d[f-u]?8:0);for(c=1;c<t;c++)e=(e>>2)+(d[f+1]?4:0)+(d[f-u+1]?8:0),i[e]&&(o[l+c]=i[e],++p),f++;if(d[f-u]!==d[f]&&(o[l+c]=d[f]?2:4,++p),p>r)return null}for(f=u*(n-1),l=s*a,d[f]!==0&&(o[l]=8,++p),c=1;c<t;c++)d[f]!==d[f+1]&&(o[l+c]=d[f]?4:8,++p),f++;if(d[f]!==0&&(o[l+c]=4,++p),p>r)return null;let m=new Int32Array([0,a,-1,0,-a,0,0,0,1]),h=new Path2D;for(s=0;p&&s<=n;s++){let e=s*a,n=e+t;for(;e<n&&!o[e];)e++;if(e===n)continue;h.moveTo(e%a,s);let r=e,i=o[e];do{let t=m[i];do e+=t;while(!o[e]);let n=o[e];n!==5&&n!==10?(i=n,o[e]=0):(i=n&51*i>>4,o[e]&=i>>2|i<<2),h.lineTo(e%a,e/a|0),o[e]||--p}while(r!==e);--s}return d=null,o=null,function(e){e.save(),e.scale(1/t,-1/n),e.translate(0,-n),e.fill(h),e.beginPath(),e.restore()}}var $u=class{constructor(e,t){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Ic,this.textMatrixScale=1,this.fontMatrix=Lc,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Wc.FILL,this.textRise=0,this.fillColor=`#000000`,this.strokeColor=`#000000`,this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps=`none`,this.startNewPathAndClipBox([0,0,e,t])}clone(){let e=Object.create(this);return e.clipBox=this.clipBox.slice(),e}setCurrentPoint(e,t){this.x=e,this.y=t}updatePathMinMax(e,t,n){[t,n]=X.applyTransform([t,n],e),this.minX=Math.min(this.minX,t),this.minY=Math.min(this.minY,n),this.maxX=Math.max(this.maxX,t),this.maxY=Math.max(this.maxY,n)}updateRectMinMax(e,t){let n=X.applyTransform(t,e),r=X.applyTransform(t.slice(2),e),i=X.applyTransform([t[0],t[3]],e),a=X.applyTransform([t[2],t[1]],e);this.minX=Math.min(this.minX,n[0],r[0],i[0],a[0]),this.minY=Math.min(this.minY,n[1],r[1],i[1],a[1]),this.maxX=Math.max(this.maxX,n[0],r[0],i[0],a[0]),this.maxY=Math.max(this.maxY,n[1],r[1],i[1],a[1])}updateScalingPathMinMax(e,t){X.scaleMinMax(e,t),this.minX=Math.min(this.minX,t[0]),this.minY=Math.min(this.minY,t[1]),this.maxX=Math.max(this.maxX,t[2]),this.maxY=Math.max(this.maxY,t[3])}updateCurvePathMinMax(e,t,n,r,i,a,o,s,c,l){let u=X.bezierBoundingBox(t,n,r,i,a,o,s,c,l);l||this.updateRectMinMax(e,u)}getPathBoundingBox(e=ju.FILL,t=null){let n=[this.minX,this.minY,this.maxX,this.maxY];if(e===ju.STROKE){t||q(`Stroke bounding box must include transform.`);let e=X.singularValueDecompose2dScale(t),r=e[0]*this.lineWidth/2,i=e[1]*this.lineWidth/2;n[0]-=r,n[1]-=i,n[2]+=r,n[3]+=i}return n}updateClipFromPath(){let e=X.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(e||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(e){this.clipBox=e,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(e=ju.FILL,t=null){return X.intersect(this.clipBox,this.getPathBoundingBox(e,t))}};function ed(e,t){if(t instanceof ImageData){e.putImageData(t,0,0);return}let n=t.height,r=t.width,i=n%Ju,a=(n-i)/Ju,o=i===0?a:a+1,s=e.createImageData(r,Ju),c=0,l,u=t.data,d=s.data,f,p,m,h;if(t.kind===Gc.GRAYSCALE_1BPP){let t=u.byteLength,n=new Uint32Array(d.buffer,0,d.byteLength>>2),h=n.length,g=r+7>>3,_=4294967295,v=_l.isLittleEndian?4278190080:255;for(f=0;f<o;f++){for(m=f<a?Ju:i,l=0,p=0;p<m;p++){let e=t-c,i=0,a=e>g?r:e*8-7,o=a&-8,s=0,d=0;for(;i<o;i+=8)d=u[c++],n[l++]=d&128?_:v,n[l++]=d&64?_:v,n[l++]=d&32?_:v,n[l++]=d&16?_:v,n[l++]=d&8?_:v,n[l++]=d&4?_:v,n[l++]=d&2?_:v,n[l++]=d&1?_:v;for(;i<a;i++)s===0&&(d=u[c++],s=128),n[l++]=d&s?_:v,s>>=1}for(;l<h;)n[l++]=0;e.putImageData(s,0,f*Ju)}}else if(t.kind===Gc.RGBA_32BPP){for(p=0,h=r*Ju*4,f=0;f<a;f++)d.set(u.subarray(c,c+h)),c+=h,e.putImageData(s,0,p),p+=Ju;f<o&&(h=r*i*4,d.set(u.subarray(c,c+h)),e.putImageData(s,0,p))}else if(t.kind===Gc.RGB_24BPP)for(m=Ju,h=r*m,f=0;f<o;f++){for(f>=a&&(m=i,h=r*m),l=0,p=h;p--;)d[l++]=u[c++],d[l++]=u[c++],d[l++]=u[c++],d[l++]=255;e.putImageData(s,0,f*Ju)}else throw Error(`bad image kind: ${t.kind}`)}function td(e,t){if(t.bitmap){e.drawImage(t.bitmap,0,0);return}let n=t.height,r=t.width,i=n%Ju,a=(n-i)/Ju,o=i===0?a:a+1,s=e.createImageData(r,Ju),c=0,l=t.data,u=s.data;for(let t=0;t<o;t++){let n=t<a?Ju:i;({srcPos:c}=Hu({src:l,srcPos:c,dest:u,width:r,height:n,nonBlackColor:0})),e.putImageData(s,0,t*Ju)}}function nd(e,t){for(let n of[`strokeStyle`,`fillStyle`,`fillRule`,`globalAlpha`,`lineWidth`,`lineCap`,`lineJoin`,`miterLimit`,`globalCompositeOperation`,`font`,`filter`])e[n]!==void 0&&(t[n]=e[n]);e.setLineDash!==void 0&&(t.setLineDash(e.getLineDash()),t.lineDashOffset=e.lineDashOffset)}function rd(e){if(e.strokeStyle=e.fillStyle=`#000000`,e.fillRule=`nonzero`,e.globalAlpha=1,e.lineWidth=1,e.lineCap=`butt`,e.lineJoin=`miter`,e.miterLimit=10,e.globalCompositeOperation=`source-over`,e.font=`10px sans-serif`,e.setLineDash!==void 0&&(e.setLineDash([]),e.lineDashOffset=0),!Fc){let{filter:t}=e;t!==`none`&&t!==``&&(e.filter=`none`)}}function id(e,t){if(t)return!0;let n=X.singularValueDecompose2dScale(e);n[0]=Math.fround(n[0]),n[1]=Math.fround(n[1]);let r=Math.fround((globalThis.devicePixelRatio||1)*Dl.PDF_TO_CSS_UNITS);return n[0]<=r&&n[1]<=r}var ad=[`butt`,`round`,`square`],od=[`miter`,`round`,`bevel`],sd={},cd={},ld=class e{constructor(e,t,n,r,i,{optionalContentConfig:a,markedContentStack:o=null},s,c){this.ctx=e,this.current=new $u(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=t,this.objs=n,this.canvasFactory=r,this.filterFactory=i,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=o||[],this.optionalContentConfig=a,this.cachedCanvases=new Xu(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=s,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(e,t=null){return typeof e==`string`?e.startsWith(`g_`)?this.commonObjs.get(e):this.objs.get(e):t}beginDrawing({transform:e,viewport:t,transparency:n=!1,background:r=null}){let i=this.ctx.canvas.width,a=this.ctx.canvas.height,o=this.ctx.fillStyle;if(this.ctx.fillStyle=r||`#ffffff`,this.ctx.fillRect(0,0,i,a),this.ctx.fillStyle=o,n){let e=this.cachedCanvases.getCanvas(`transparent`,i,a);this.compositeCtx=this.ctx,this.transparentCanvas=e.canvas,this.ctx=e.context,this.ctx.save(),this.ctx.transform(...Z(this.compositeCtx))}this.ctx.save(),rd(this.ctx),e&&(this.ctx.transform(...e),this.outputScaleX=e[0],this.outputScaleY=e[0]),this.ctx.transform(...t.transform),this.viewportScale=t.scale,this.baseTransform=Z(this.ctx)}executeOperatorList(e,t,n,r){let i=e.argsArray,a=e.fnArray,o=t||0,s=i.length;if(s===o)return o;let c=s-o>Ku&&typeof n==`function`,l=c?Date.now()+Gu:0,u=0,d=this.commonObjs,f=this.objs,p;for(;;){if(r!==void 0&&o===r.nextBreakPoint)return r.breakIt(o,n),o;if(p=a[o],p!==Yc.dependency)this[p].apply(this,i[o]);else for(let e of i[o]){let t=e.startsWith(`g_`)?d:f;if(!t.has(e))return t.get(e,n),o}if(o++,o===s)return o;if(c&&++u>Ku){if(Date.now()>l)return n(),o;u=0}}}#e(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&=(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),null)}endDrawing(){this.#e(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(let e of this._cachedBitmapsMap.values()){for(let t of e.values())typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement&&(t.width=t.height=0);e.clear()}this._cachedBitmapsMap.clear(),this.#t()}#t(){if(this.pageColors){let e=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(e!==`none`){let t=this.ctx.filter;this.ctx.filter=e,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=t}}}_scaleImage(e,t){let n=e.width??e.displayWidth,r=e.height??e.displayHeight,i=Math.max(Math.hypot(t[0],t[1]),1),a=Math.max(Math.hypot(t[2],t[3]),1),o=n,s=r,c=`prescale1`,l,u;for(;i>2&&o>1||a>2&&s>1;){let t=o,n=s;i>2&&o>1&&(t=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/t),a>2&&s>1&&(n=s>=16384?Math.floor(s/2)-1||1:Math.ceil(s)/2,a/=s/n),l=this.cachedCanvases.getCanvas(c,t,n),u=l.context,u.clearRect(0,0,t,n),u.drawImage(e,0,0,o,s,0,0,t,n),e=l.canvas,o=t,s=n,c=c===`prescale1`?`prescale2`:`prescale1`}return{img:e,paintWidth:o,paintHeight:s}}_createMaskCanvas(e){let t=this.ctx,{width:n,height:r}=e,i=this.current.fillColor,a=this.current.patternFill,o=Z(t),s,c,l,u;if((e.bitmap||e.data)&&e.count>1){let t=e.bitmap||e.data.buffer;c=JSON.stringify(a?o:[o.slice(0,4),i]),s=this._cachedBitmapsMap.get(t),s||(s=new Map,this._cachedBitmapsMap.set(t,s));let n=s.get(c);if(n&&!a)return{canvas:n,offsetX:Math.round(Math.min(o[0],o[2])+o[4]),offsetY:Math.round(Math.min(o[1],o[3])+o[5])};l=n}l||(u=this.cachedCanvases.getCanvas(`maskCanvas`,n,r),td(u.context,e));let d=X.transform(o,[1/n,0,0,-1/r,0,0]);d=X.transform(d,[1,0,0,1,0,-r]);let[f,p,m,h]=X.getAxialAlignedBoundingBox([0,0,n,r],d),g=Math.round(m-f)||1,_=Math.round(h-p)||1,v=this.cachedCanvases.getCanvas(`fillCanvas`,g,_),y=v.context,b=f,x=p;y.translate(-b,-x),y.transform(...d),l||(l=this._scaleImage(u.canvas,Ul(y)),l=l.img,s&&a&&s.set(c,l)),y.imageSmoothingEnabled=id(Z(y),e.interpolate),Zu(y,l,0,0,l.width,l.height,0,0,n,r),y.globalCompositeOperation=`source-in`;let S=X.transform(Ul(y),[1,0,0,1,-b,-x]);return y.fillStyle=a?i.getPattern(t,this,S,ju.FILL):i,y.fillRect(0,0,n,r),s&&!a&&(this.cachedCanvases.delete(`fillCanvas`),s.set(c,v.canvas)),{canvas:v.canvas,offsetX:Math.round(b),offsetY:Math.round(x)}}setLineWidth(e){e!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=e,this.ctx.lineWidth=e}setLineCap(e){this.ctx.lineCap=ad[e]}setLineJoin(e){this.ctx.lineJoin=od[e]}setMiterLimit(e){this.ctx.miterLimit=e}setDash(e,t){let n=this.ctx;n.setLineDash!==void 0&&(n.setLineDash(e),n.lineDashOffset=t)}setRenderingIntent(e){}setFlatness(e){}setGState(e){for(let[t,n]of e)switch(t){case`LW`:this.setLineWidth(n);break;case`LC`:this.setLineCap(n);break;case`LJ`:this.setLineJoin(n);break;case`ML`:this.setMiterLimit(n);break;case`D`:this.setDash(n[0],n[1]);break;case`RI`:this.setRenderingIntent(n);break;case`FL`:this.setFlatness(n);break;case`Font`:this.setFont(n[0],n[1]);break;case`CA`:this.current.strokeAlpha=n;break;case`ca`:this.current.fillAlpha=n,this.ctx.globalAlpha=n;break;case`BM`:this.ctx.globalCompositeOperation=n;break;case`SMask`:this.current.activeSMask=n?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case`TR`:this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(n)}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){let e=this.inSMaskMode;this.current.activeSMask&&!e?this.beginSMaskMode():!this.current.activeSMask&&e&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw Error(`beginSMaskMode called while already in smask mode`);let e=this.ctx.canvas.width,t=this.ctx.canvas.height,n=`smaskGroupAt`+this.groupLevel,r=this.cachedCanvases.getCanvas(n,e,t);this.suspendedCtx=this.ctx,this.ctx=r.context;let i=this.ctx;i.setTransform(...Z(this.suspendedCtx)),nd(this.suspendedCtx,i),Yu(i,this.suspendedCtx),this.setGState([[`BM`,`source-over`],[`ca`,1],[`CA`,1]])}endSMaskMode(){if(!this.inSMaskMode)throw Error(`endSMaskMode called while not in smask mode`);this.ctx._removeMirroring(),nd(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(e){if(!this.current.activeSMask)return;e?(e[0]=Math.floor(e[0]),e[1]=Math.floor(e[1]),e[2]=Math.ceil(e[2]),e[3]=Math.ceil(e[3])):e=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];let t=this.current.activeSMask,n=this.suspendedCtx;this.composeSMask(n,t,this.ctx,e),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(e,t,n,r){let i=r[0],a=r[1],o=r[2]-i,s=r[3]-a;o!==0&&s!==0&&(this.genericComposeSMask(t.context,n,o,s,t.subtype,t.backdrop,t.transferMap,i,a,t.offsetX,t.offsetY),e.save(),e.globalAlpha=1,e.globalCompositeOperation=`source-over`,e.setTransform(1,0,0,1,0,0),e.drawImage(n.canvas,0,0),e.restore())}genericComposeSMask(e,t,n,r,i,a,o,s,c,l,u){let d=e.canvas,f=s-l,p=c-u;if(a){let t=X.makeHexColor(...a);if(f<0||p<0||f+n>d.width||p+r>d.height){let e=this.cachedCanvases.getCanvas(`maskExtension`,n,r),i=e.context;i.drawImage(d,-f,-p),i.globalCompositeOperation=`destination-atop`,i.fillStyle=t,i.fillRect(0,0,n,r),i.globalCompositeOperation=`source-over`,d=e.canvas,f=p=0}else{e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0);let i=new Path2D;i.rect(f,p,n,r),e.clip(i),e.globalCompositeOperation=`destination-atop`,e.fillStyle=t,e.fillRect(f,p,n,r),e.restore()}}t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0),i===`Alpha`&&o?t.filter=this.filterFactory.addAlphaFilter(o):i===`Luminosity`&&(t.filter=this.filterFactory.addLuminosityFilter(o));let m=new Path2D;m.rect(s,c,n,r),t.clip(m),t.globalCompositeOperation=`destination-in`,t.drawImage(d,f,p,n,r,s,c,n,r),t.restore()}save(){this.inSMaskMode?(nd(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();let e=this.current;this.stateStack.push(e),this.current=e.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),nd(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(e,t,n,r,i,a){this.ctx.transform(e,t,n,r,i,a),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(e,t,n){let r=this.ctx,i=this.current,a=i.x,o=i.y,s,c,l=Z(r),u=l[0]===0&&l[3]===0||l[1]===0&&l[2]===0,d=u?n.slice(0):null;for(let n=0,f=0,p=e.length;n<p;n++)switch(e[n]|0){case Yc.rectangle:a=t[f++],o=t[f++];let e=t[f++],n=t[f++],p=a+e,m=o+n;r.moveTo(a,o),e===0||n===0?r.lineTo(p,m):(r.lineTo(p,o),r.lineTo(p,m),r.lineTo(a,m)),u||i.updateRectMinMax(l,[a,o,p,m]),r.closePath();break;case Yc.moveTo:a=t[f++],o=t[f++],r.moveTo(a,o),u||i.updatePathMinMax(l,a,o);break;case Yc.lineTo:a=t[f++],o=t[f++],r.lineTo(a,o),u||i.updatePathMinMax(l,a,o);break;case Yc.curveTo:s=a,c=o,a=t[f+4],o=t[f+5],r.bezierCurveTo(t[f],t[f+1],t[f+2],t[f+3],a,o),i.updateCurvePathMinMax(l,s,c,t[f],t[f+1],t[f+2],t[f+3],a,o,d),f+=6;break;case Yc.curveTo2:s=a,c=o,r.bezierCurveTo(a,o,t[f],t[f+1],t[f+2],t[f+3]),i.updateCurvePathMinMax(l,s,c,a,o,t[f],t[f+1],t[f+2],t[f+3],d),a=t[f+2],o=t[f+3],f+=4;break;case Yc.curveTo3:s=a,c=o,a=t[f+2],o=t[f+3],r.bezierCurveTo(t[f],t[f+1],a,o,a,o),i.updateCurvePathMinMax(l,s,c,t[f],t[f+1],a,o,a,o,d),f+=4;break;case Yc.closePath:r.closePath()}u&&i.updateScalingPathMinMax(l,d),i.setCurrentPoint(a,o)}closePath(){this.ctx.closePath()}stroke(e=!0){let t=this.ctx,n=this.current.strokeColor;t.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof n==`object`&&n?.getPattern?(t.save(),t.strokeStyle=n.getPattern(t,this,Ul(t),ju.STROKE),this.rescaleAndStroke(!1),t.restore()):this.rescaleAndStroke(!0)),e&&this.consumePath(this.current.getClippedPathBoundingBox()),t.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(e=!0){let t=this.ctx,n=this.current.fillColor,r=this.current.patternFill,i=!1;r&&(t.save(),t.fillStyle=n.getPattern(t,this,Ul(t),ju.FILL),i=!0);let a=this.current.getClippedPathBoundingBox();this.contentVisible&&a!==null&&(this.pendingEOFill?(t.fill(`evenodd`),this.pendingEOFill=!1):t.fill()),i&&t.restore(),e&&this.consumePath(a)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=sd}eoClip(){this.pendingClip=cd}beginText(){this.current.textMatrix=Ic,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){let e=this.pendingTextPaths,t=this.ctx;if(e===void 0){t.beginPath();return}let n=new Path2D,r=t.getTransform().invertSelf();for(let{transform:t,x:i,y:a,fontSize:o,path:s}of e)n.addPath(s,new DOMMatrix(t).preMultiplySelf(r).translate(i,a).scale(o,-o));t.clip(n),t.beginPath(),delete this.pendingTextPaths}setCharSpacing(e){this.current.charSpacing=e}setWordSpacing(e){this.current.wordSpacing=e}setHScale(e){this.current.textHScale=e/100}setLeading(e){this.current.leading=-e}setFont(e,t){let n=this.commonObjs.get(e),r=this.current;if(!n)throw Error(`Can't find font for ${e}`);if(r.fontMatrix=n.fontMatrix||Lc,(r.fontMatrix[0]===0||r.fontMatrix[3]===0)&&K(`Invalid font matrix for font `+e),t<0?(t=-t,r.fontDirection=-1):r.fontDirection=1,this.current.font=n,this.current.fontSize=t,n.isType3Font)return;let i=n.loadedName||`sans-serif`,a=n.systemFontInfo?.css||`"${i}", ${n.fallbackName}`,o=`normal`;n.black?o=`900`:n.bold&&(o=`bold`);let s=n.italic?`italic`:`normal`,c=t;t<Uu?c=Uu:t>Wu&&(c=Wu),this.current.fontSizeScale=t/c,this.ctx.font=`${s} ${o} ${c}px ${a}`}setTextRenderingMode(e){this.current.textRenderingMode=e}setTextRise(e){this.current.textRise=e}moveText(e,t){this.current.x=this.current.lineX+=e,this.current.y=this.current.lineY+=t}setLeadingMoveText(e,t){this.setLeading(-t),this.moveText(e,t)}setTextMatrix(e,t,n,r,i,a){this.current.textMatrix=[e,t,n,r,i,a],this.current.textMatrixScale=Math.hypot(e,t),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#n(e,t,n){let r=new Path2D;return r.addPath(e,new DOMMatrix(n).invertSelf().multiplySelf(t)),r}paintChar(e,t,n,r,i){let a=this.ctx,o=this.current,s=o.font,c=o.textRenderingMode,l=o.fontSize/o.fontSizeScale,u=c&Wc.FILL_STROKE_MASK,d=!!(c&Wc.ADD_TO_PATH_FLAG),f=o.patternFill&&!s.missingFile,p=o.patternStroke&&!s.missingFile,m;if((s.disableFontFace||d||f||p)&&(m=s.getPathGenerator(this.commonObjs,e)),s.disableFontFace||f||p){if(a.save(),a.translate(t,n),a.scale(l,-l),u===Wc.FILL||u===Wc.FILL_STROKE){if(r){let e=a.getTransform();a.setTransform(...r),a.fill(this.#n(m,e,r))}else a.fill(m)}if(u===Wc.STROKE||u===Wc.FILL_STROKE){if(i){let e=a.getTransform();a.setTransform(...i),a.stroke(this.#n(m,e,i))}else a.lineWidth/=l,a.stroke(m)}a.restore()}else(u===Wc.FILL||u===Wc.FILL_STROKE)&&a.fillText(e,t,n),(u===Wc.STROKE||u===Wc.FILL_STROKE)&&a.strokeText(e,t,n);d&&(this.pendingTextPaths||=[]).push({transform:Z(a),x:t,y:n,fontSize:l,path:m})}get isFontSubpixelAAEnabled(){let{context:e}=this.cachedCanvases.getCanvas(`isFontSubpixelAAEnabled`,10,10);e.scale(1.5,1),e.fillText(`I`,0,10);let t=e.getImageData(0,0,10,10).data,n=!1;for(let e=3;e<t.length;e+=4)if(t[e]>0&&t[e]<255){n=!0;break}return Y(this,`isFontSubpixelAAEnabled`,n)}showText(e){let t=this.current,n=t.font;if(n.isType3Font)return this.showType3Text(e);let r=t.fontSize;if(r===0)return;let i=this.ctx,a=t.fontSizeScale,o=t.charSpacing,s=t.wordSpacing,c=t.fontDirection,l=t.textHScale*c,u=e.length,d=n.vertical,f=d?1:-1,p=n.defaultVMetrics,m=r*t.fontMatrix[0],h=t.textRenderingMode===Wc.FILL&&!n.disableFontFace&&!t.patternFill;i.save(),i.transform(...t.textMatrix),i.translate(t.x,t.y+t.textRise),c>0?i.scale(l,-1):i.scale(l,1);let g,_;if(t.patternFill){i.save();let e=t.fillColor.getPattern(i,this,Ul(i),ju.FILL);g=Z(i),i.restore(),i.fillStyle=e}if(t.patternStroke){i.save();let e=t.strokeColor.getPattern(i,this,Ul(i),ju.STROKE);_=Z(i),i.restore(),i.strokeStyle=e}let v=t.lineWidth,y=t.textMatrixScale;if(y===0||v===0){let e=t.textRenderingMode&Wc.FILL_STROKE_MASK;(e===Wc.STROKE||e===Wc.FILL_STROKE)&&(v=this.getSinglePixelWidth())}else v/=y;if(a!==1&&(i.scale(a,a),v/=a),i.lineWidth=v,n.isInvalidPDFjsFont){let n=[],r=0;for(let t of e)n.push(t.unicode),r+=t.width;i.fillText(n.join(``),0,0),t.x+=r*m*l,i.restore(),this.compose();return}let b=0,x;for(x=0;x<u;++x){let t=e[x];if(typeof t==`number`){b+=f*t*r/1e3;continue}let l=!1,u=(t.isSpace?s:0)+o,v=t.fontChar,y=t.accent,S,C,w=t.width;if(d){let e=t.vmetric||p,n=-(t.vmetric?e[1]:w*.5)*m,r=e[2]*m;w=e?-e[0]:w,S=n/a,C=(b+r)/a}else S=b/a,C=0;if(n.remeasure&&w>0){let e=i.measureText(v).width*1e3/r*a;if(w<e&&this.isFontSubpixelAAEnabled){let t=w/e;l=!0,i.save(),i.scale(t,1),S/=t}else w!==e&&(S+=(w-e)/2e3*r/a)}if(this.contentVisible&&(t.isInFont||n.missingFile)){if(h&&!y)i.fillText(v,S,C);else if(this.paintChar(v,S,C,g,_),y){let e=S+r*y.offset.x/a,t=C-r*y.offset.y/a;this.paintChar(y.fontChar,e,t,g,_)}}let T=d?w*m-u*c:w*m+u*c;b+=T,l&&i.restore()}d?t.y-=b:t.x+=b*l,i.restore(),this.compose()}showType3Text(e){let t=this.ctx,n=this.current,r=n.font,i=n.fontSize,a=n.fontDirection,o=r.vertical?1:-1,s=n.charSpacing,c=n.wordSpacing,l=n.textHScale*a,u=n.fontMatrix||Lc,d=e.length,f=n.textRenderingMode===Wc.INVISIBLE,p,m,h,g;if(!(f||i===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,t.save(),t.transform(...n.textMatrix),t.translate(n.x,n.y),t.scale(l,a),p=0;p<d;++p){if(m=e[p],typeof m==`number`){g=o*m*i/1e3,this.ctx.translate(g,0),n.x+=g*l;continue}let a=(m.isSpace?c:0)+s,d=r.charProcOperatorList[m.operatorListId];if(!d){K(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),t.scale(i,i),t.transform(...u),this.executeOperatorList(d),this.restore()),h=X.applyTransform([m.width,0],u)[0]*i+a,t.translate(h,0),n.x+=h*l}t.restore(),this.processingType3=null}}setCharWidth(e,t){}setCharWidthAndBounds(e,t,n,r,i,a){this.ctx.rect(n,r,i-n,a-r),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let n;if(t[0]===`TilingPattern`){let r=t[1],i=this.baseTransform||Z(this.ctx);n=new Vu(t,r,this.ctx,{createCanvasGraphics:t=>new e(t,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})},i)}else n=this._getPattern(t[1],t[2]);return n}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(e,t,n){this.ctx.strokeStyle=this.current.strokeColor=X.makeHexColor(e,t,n),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor=`transparent`,this.current.patternStroke=!1}setFillRGBColor(e,t,n){this.ctx.fillStyle=this.current.fillColor=X.makeHexColor(e,t,n),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor=`transparent`,this.current.patternFill=!1}_getPattern(e,t=null){let n;return this.cachedPatterns.has(e)?n=this.cachedPatterns.get(e):(n=zu(this.getObject(e)),this.cachedPatterns.set(e,n)),t&&(n.matrix=t),n}shadingFill(e){if(!this.contentVisible)return;let t=this.ctx;this.save(),t.fillStyle=this._getPattern(e).getPattern(t,this,Ul(t),ju.SHADING);let n=Ul(t);if(n){let{width:e,height:r}=t.canvas,[i,a,o,s]=X.getAxialAlignedBoundingBox([0,0,e,r],n);this.ctx.fillRect(i,a,o-i,s-a)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){q(`Should not call beginInlineImage`)}beginImageData(){q(`Should not call beginImageData`)}paintFormXObjectBegin(e,t){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),e&&this.transform(...e),this.baseTransform=Z(this.ctx),t)){let e=t[2]-t[0],n=t[3]-t[1];this.ctx.rect(t[0],t[1],e,n),this.current.updateRectMinMax(Z(this.ctx),t),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(e){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);let t=this.ctx;e.isolated||el(`TODO: Support non-isolated groups.`),e.knockout&&K(`Knockout groups not supported.`);let n=Z(t);if(e.matrix&&t.transform(...e.matrix),!e.bbox)throw Error(`Bounding box is required.`);let r=X.getAxialAlignedBoundingBox(e.bbox,Z(t)),i=[0,0,t.canvas.width,t.canvas.height];r=X.intersect(r,i)||[0,0,0,0];let a=Math.floor(r[0]),o=Math.floor(r[1]),s=Math.max(Math.ceil(r[2])-a,1),c=Math.max(Math.ceil(r[3])-o,1);this.current.startNewPathAndClipBox([0,0,s,c]);let l=`groupAt`+this.groupLevel;e.smask&&(l+=`_smask_`+this.smaskCounter++%2);let u=this.cachedCanvases.getCanvas(l,s,c),d=u.context;d.translate(-a,-o),d.transform(...n),e.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:a,offsetY:o,subtype:e.smask.subtype,backdrop:e.smask.backdrop,transferMap:e.smask.transferMap||null,startTransformInverse:null}):(t.setTransform(1,0,0,1,0,0),t.translate(a,o),t.save()),nd(t,d),this.ctx=d,this.setGState([[`BM`,`source-over`],[`ca`,1],[`CA`,1]]),this.groupStack.push(t),this.groupLevel++}endGroup(e){if(!this.contentVisible)return;this.groupLevel--;let t=this.ctx,n=this.groupStack.pop();if(this.ctx=n,this.ctx.imageSmoothingEnabled=!1,e.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();let e=Z(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...e);let n=X.getAxialAlignedBoundingBox([0,0,t.canvas.width,t.canvas.height],e);this.ctx.drawImage(t.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(e,t,n,r,i){if(this.#e(),rd(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),t){let r=t[2]-t[0],a=t[3]-t[1];if(i&&this.annotationCanvasMap){n=n.slice(),n[4]-=t[0],n[5]-=t[1],t=t.slice(),t[0]=t[1]=0,t[2]=r,t[3]=a;let[i,o]=X.singularValueDecompose2dScale(Z(this.ctx)),{viewportScale:s}=this,c=Math.ceil(r*this.outputScaleX*s),l=Math.ceil(a*this.outputScaleY*s);this.annotationCanvas=this.canvasFactory.create(c,l);let{canvas:u,context:d}=this.annotationCanvas;this.annotationCanvasMap.set(e,u),this.annotationCanvas.savedCtx=this.ctx,this.ctx=d,this.ctx.save(),this.ctx.setTransform(i,0,0,-o,0,a*o),rd(this.ctx)}else rd(this.ctx),this.endPath(),this.ctx.rect(t[0],t[1],r,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new $u(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...n),this.transform(...r)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#t(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(e){if(!this.contentVisible)return;let t=e.count;e=this.getObject(e.data,e),e.count=t;let n=this.ctx,r=this.processingType3;if(r&&(r.compiled===void 0&&(r.compiled=Qu(e)),r.compiled)){r.compiled(n);return}let i=this._createMaskCanvas(e),a=i.canvas;n.save(),n.setTransform(1,0,0,1,0,0),n.drawImage(a,i.offsetX,i.offsetY),n.restore(),this.compose()}paintImageMaskXObjectRepeat(e,t,n=0,r=0,i,a){if(!this.contentVisible)return;e=this.getObject(e.data,e);let o=this.ctx;o.save();let s=Z(o);o.transform(t,n,r,i,0,0);let c=this._createMaskCanvas(e);o.setTransform(1,0,0,1,c.offsetX-s[4],c.offsetY-s[5]);for(let e=0,l=a.length;e<l;e+=2){let l=X.transform(s,[t,n,r,i,a[e],a[e+1]]),[u,d]=X.applyTransform([0,0],l);o.drawImage(c.canvas,u,d)}o.restore(),this.compose()}paintImageMaskXObjectGroup(e){if(!this.contentVisible)return;let t=this.ctx,n=this.current.fillColor,r=this.current.patternFill;for(let i of e){let{data:e,width:a,height:o,transform:s}=i,c=this.cachedCanvases.getCanvas(`maskCanvas`,a,o),l=c.context;l.save(),td(l,this.getObject(e,i)),l.globalCompositeOperation=`source-in`,l.fillStyle=r?n.getPattern(l,this,Ul(t),ju.FILL):n,l.fillRect(0,0,a,o),l.restore(),t.save(),t.transform(...s),t.scale(1,-1),Zu(t,c.canvas,0,0,a,o,0,-1,1,1),t.restore()}this.compose()}paintImageXObject(e){if(!this.contentVisible)return;let t=this.getObject(e);if(!t){K(`Dependent image isn't ready yet`);return}this.paintInlineImageXObject(t)}paintImageXObjectRepeat(e,t,n,r){if(!this.contentVisible)return;let i=this.getObject(e);if(!i){K(`Dependent image isn't ready yet`);return}let a=i.width,o=i.height,s=[];for(let e=0,i=r.length;e<i;e+=2)s.push({transform:[t,0,0,n,r[e],r[e+1]],x:0,y:0,w:a,h:o});this.paintInlineImageXObjectGroup(i,s)}applyTransferMapsToCanvas(e){return this.current.transferMaps!==`none`&&(e.filter=this.current.transferMaps,e.drawImage(e.canvas,0,0),e.filter=`none`),e.canvas}applyTransferMapsToBitmap(e){if(this.current.transferMaps===`none`)return e.bitmap;let{bitmap:t,width:n,height:r}=e,i=this.cachedCanvases.getCanvas(`inlineImage`,n,r),a=i.context;return a.filter=this.current.transferMaps,a.drawImage(t,0,0),a.filter=`none`,i.canvas}paintInlineImageXObject(e){if(!this.contentVisible)return;let t=e.width,n=e.height,r=this.ctx;if(this.save(),!Fc){let{filter:e}=r;e!==`none`&&e!==``&&(r.filter=`none`)}r.scale(1/t,-1/n);let i;if(e.bitmap)i=this.applyTransferMapsToBitmap(e);else if(typeof HTMLElement==`function`&&e instanceof HTMLElement||!e.data)i=e;else{let r=this.cachedCanvases.getCanvas(`inlineImage`,t,n).context;ed(r,e),i=this.applyTransferMapsToCanvas(r)}let a=this._scaleImage(i,Ul(r));r.imageSmoothingEnabled=id(Z(r),e.interpolate),Zu(r,a.img,0,0,a.paintWidth,a.paintHeight,0,-n,t,n),this.compose(),this.restore()}paintInlineImageXObjectGroup(e,t){if(!this.contentVisible)return;let n=this.ctx,r;if(e.bitmap)r=e.bitmap;else{let t=e.width,n=e.height,i=this.cachedCanvases.getCanvas(`inlineImage`,t,n).context;ed(i,e),r=this.applyTransferMapsToCanvas(i)}for(let e of t)n.save(),n.transform(...e.transform),n.scale(1,-1),Zu(n,r,e.x,e.y,e.w,e.h,0,-1,1,1),n.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(e){}markPointProps(e,t){}beginMarkedContent(e){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(e,t){e===`OC`?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(t)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(e){let t=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(e);let n=this.ctx;this.pendingClip&&=(t||(this.pendingClip===cd?n.clip(`evenodd`):n.clip()),null),this.current.startNewPathAndClipBox(this.current.clipBox),n.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){let e=Z(this.ctx);if(e[1]===0&&e[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(e[0]),Math.abs(e[3]));else{let t=Math.abs(e[0]*e[3]-e[2]*e[1]),n=Math.hypot(e[0],e[2]),r=Math.hypot(e[1],e[3]);this._cachedGetSinglePixelWidth=Math.max(n,r)/t}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:e}=this.current,{a:t,b:n,c:r,d:i}=this.ctx.getTransform(),a,o;if(n===0&&r===0){let n=Math.abs(t),r=Math.abs(i);if(n===r){if(e===0)a=o=1/n;else{let t=n*e;a=o=t<1?1/t:1}}else if(e===0)a=1/n,o=1/r;else{let t=n*e,i=r*e;a=t<1?1/t:1,o=i<1?1/i:1}}else{let s=Math.abs(t*i-n*r),c=Math.hypot(t,n),l=Math.hypot(r,i);if(e===0)a=l/s,o=c/s;else{let t=e*s;a=l>t?l/t:1,o=c>t?c/t:1}}this._cachedScaleForStroking[0]=a,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(e){let{ctx:t}=this,{lineWidth:n}=this.current,[r,i]=this.getScaleForStroking();if(t.lineWidth=n||1,r===1&&i===1){t.stroke();return}let a=t.getLineDash();if(e&&t.save(),t.scale(r,i),a.length>0){let e=Math.max(r,i);t.setLineDash(a.map(t=>t/e)),t.lineDashOffset/=e}t.stroke(),e&&t.restore()}isContentVisible(){for(let e=this.markedContentStack.length-1;e>=0;e--)if(!this.markedContentStack[e].visible)return!1;return!0}};for(let e in Yc)ld.prototype[e]!==void 0&&(ld.prototype[Yc[e]]=ld.prototype[e]);var ud=class{static#e=null;static#t=``;static get workerPort(){return this.#e}static set workerPort(e){if(!(typeof Worker<`u`&&e instanceof Worker)&&e!==null)throw Error("Invalid `workerPort` type.");this.#e=e}static get workerSrc(){return this.#t}static set workerSrc(e){if(typeof e!=`string`)throw Error("Invalid `workerSrc` type.");this.#t=e}},dd=class{#e;#t;constructor({parsedData:e,rawData:t}){this.#e=e,this.#t=t}getRaw(){return this.#t}get(e){return this.#e.get(e)??null}getAll(){return ml(this.#e)}has(e){return this.#e.has(e)}},fd=Symbol(`INTERNAL`),pd=class{#e=!1;#t=!1;#n=!1;#r=!0;constructor(e,{name:t,intent:n,usage:r,rbGroups:i}){this.#e=!!(e&Bc.DISPLAY),this.#t=!!(e&Bc.PRINT),this.name=t,this.intent=n,this.usage=r,this.rbGroups=i}get visible(){if(this.#n)return this.#r;if(!this.#r)return!1;let{print:e,view:t}=this.usage;return this.#e?t?.viewState!==`OFF`:!this.#t||e?.printState!==`OFF`}_setVisible(e,t,n=!1){e!==fd&&q("Internal method `_setVisible` called."),this.#n=n,this.#r=t}},md=class{#e=null;#t=new Map;#n=null;#r=null;constructor(e,t=Bc.DISPLAY){if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,this.#r=e.order;for(let n of e.groups)this.#t.set(n.id,new pd(t,n));if(e.baseState===`OFF`)for(let e of this.#t.values())e._setVisible(fd,!1);for(let t of e.on)this.#t.get(t)._setVisible(fd,!0);for(let t of e.off)this.#t.get(t)._setVisible(fd,!1);this.#n=this.getHash()}}#i(e){let t=e.length;if(t<2)return!0;let n=e[0];for(let r=1;r<t;r++){let t=e[r],i;if(Array.isArray(t))i=this.#i(t);else if(this.#t.has(t))i=this.#t.get(t).visible;else return K(`Optional content group not found: ${t}`),!0;switch(n){case`And`:if(!i)return!1;break;case`Or`:if(i)return!0;break;case`Not`:return!i;default:return!0}}return n===`And`}isVisible(e){if(this.#t.size===0)return!0;if(!e)return el(`Optional content group not defined.`),!0;if(e.type===`OCG`)return this.#t.has(e.id)?this.#t.get(e.id).visible:(K(`Optional content group not found: ${e.id}`),!0);if(e.type===`OCMD`){if(e.expression)return this.#i(e.expression);if(!e.policy||e.policy===`AnyOn`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!0}return!1}if(e.policy===`AllOn`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!1}return!0}if(e.policy===`AnyOff`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(!this.#t.get(t).visible)return!0}return!1}if(e.policy===`AllOff`){for(let t of e.ids){if(!this.#t.has(t))return K(`Optional content group not found: ${t}`),!0;if(this.#t.get(t).visible)return!1}return!0}return K(`Unknown optional content policy ${e.policy}.`),!0}return K(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,n=!0){let r=this.#t.get(e);if(!r){K(`Optional content group not found: ${e}`);return}if(n&&t&&r.rbGroups.length)for(let t of r.rbGroups)for(let n of t)n!==e&&this.#t.get(n)?._setVisible(fd,!1,!0);r._setVisible(fd,!!t,!0),this.#e=null}setOCGState({state:e,preserveRB:t}){let n;for(let r of e){switch(r){case`ON`:case`OFF`:case`Toggle`:n=r;continue}let e=this.#t.get(r);if(e)switch(n){case`ON`:this.setVisibility(r,!0,t);break;case`OFF`:this.setVisibility(r,!1,t);break;case`Toggle`:this.setVisibility(r,!e.visible,t)}}this.#e=null}get hasInitialVisibility(){return this.#n===null||this.getHash()===this.#n}getOrder(){return this.#t.size?this.#r?this.#r.slice():[...this.#t.keys()]:null}getGroups(){return this.#t.size>0?ml(this.#t):null}getGroup(e){return this.#t.get(e)||null}getHash(){if(this.#e!==null)return this.#e;let e=new su;for(let[t,n]of this.#t)e.update(`${t}:${n.visible}`);return this.#e=e.hexdigest()}},hd=class{constructor(e,{disableRange:t=!1,disableStream:n=!1}){J(e,`PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.`);let{length:r,initialData:i,progressiveDone:a,contentDispositionFilename:o}=e;if(this._queuedChunks=[],this._progressiveDone=a,this._contentDispositionFilename=o,i?.length>0){let e=i instanceof Uint8Array&&i.byteLength===i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer;this._queuedChunks.push(e)}this._pdfDataRangeTransport=e,this._isStreamingSupported=!n,this._isRangeSupported=!t,this._contentLength=r,this._fullRequestReader=null,this._rangeReaders=[],e.addRangeListener((e,t)=>{this._onReceiveData({begin:e,chunk:t})}),e.addProgressListener((e,t)=>{this._onProgress({loaded:e,total:t})}),e.addProgressiveReadListener(e=>{this._onReceiveData({chunk:e})}),e.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),e.transportReady()}_onReceiveData({begin:e,chunk:t}){let n=t instanceof Uint8Array&&t.byteLength===t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer;e===void 0?this._fullRequestReader?this._fullRequestReader._enqueue(n):this._queuedChunks.push(n):J(this._rangeReaders.some(function(t){return t._begin===e&&(t._enqueue(n),!0)}),"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(e){e.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:e.loaded}):this._fullRequestReader?.onProgress?.({loaded:e.loaded,total:e.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(e){let t=this._rangeReaders.indexOf(e);t>=0&&this._rangeReaders.splice(t,1)}getFullReader(){J(!this._fullRequestReader,`PDFDataTransportStream.getFullReader can only be called once.`);let e=this._queuedChunks;return this._queuedChunks=null,new gd(this,e,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new _d(this,e,t);return this._pdfDataRangeTransport.requestDataRange(e,t),this._rangeReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeReaders.slice(0))t.cancel(e);this._pdfDataRangeTransport.abort()}},gd=class{constructor(e,t,n=!1,r=null){this._stream=e,this._done=n||!1,this._filename=Ml(r)?r:null,this._queuedChunks=t||[],this._loaded=0;for(let e of this._queuedChunks)this._loaded+=e.byteLength;this._requests=[],this._headersReady=Promise.resolve(),e._fullRequestReader=this,this.onProgress=null}_enqueue(e){this._done||(this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunks.push(e),this._loaded+=e.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||=!0}},_d=class{constructor(e,t,n){this._stream=e,this._begin=t,this._end=n,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(e){if(!this._done){if(this._requests.length===0)this._queuedChunk=e;else{this._requests.shift().resolve({value:e,done:!1});for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}};function vd(e){let t=!0,n=r(`filename\\*`,`i`).exec(e);if(n){n=n[1];let e=s(n);return e=unescape(e),e=c(e),e=l(e),a(e)}if(n=o(e),n)return a(l(n));if(n=r(`filename`,`i`).exec(e),n){n=n[1];let e=s(n);return e=l(e),a(e)}function r(e,t){return RegExp(`(?:^|;)\\s*`+e+`\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)`,t)}function i(e,n){if(e){if(!/^[\x00-\xFF]+$/.test(n))return n;try{let r=new TextDecoder(e,{fatal:!0}),i=fl(n);n=r.decode(i),t=!1}catch{}}return n}function a(e){return t&&/[\x80-\xff]/.test(e)&&(e=i(`utf-8`,e),t&&(e=i(`iso-8859-1`,e))),e}function o(e){let t=[],n,i=r(`filename\\*((?!0\\d)\\d+)(\\*?)`,`ig`);for(;(n=i.exec(e))!==null;){let[,e,r,i]=n;if(e=parseInt(e,10),e in t){if(e===0)break;continue}t[e]=[r,i]}let a=[];for(let e=0;e<t.length&&e in t;++e){let[n,r]=t[e];r=s(r),n&&(r=unescape(r),e===0&&(r=c(r))),a.push(r)}return a.join(``)}function s(e){if(e.startsWith(`"`)){let t=e.slice(1).split(`\\"`);for(let e=0;e<t.length;++e){let n=t[e].indexOf(`"`);n!==-1&&(t[e]=t[e].slice(0,n),t.length=e+1),t[e]=t[e].replaceAll(/\\(.)/g,`$1`)}e=t.join(`"`)}return e}function c(e){let t=e.indexOf(`'`);return t===-1?e:i(e.slice(0,t),e.slice(t+1).replace(/^[^']*'/,``))}function l(e){return!e.startsWith(`=?`)||/[\x00-\x19\x80-\xff]/.test(e)?e:e.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(e,t,n,r){if(n===`q`||n===`Q`)return r=r.replaceAll(`_`,` `),r=r.replaceAll(/=([0-9a-fA-F]{2})/g,function(e,t){return String.fromCharCode(parseInt(t,16))}),i(t,r);try{r=atob(r)}catch{}return i(t,r)})}return``}function yd(e,t){let n=new Headers;if(!e||!t||typeof t!=`object`)return n;for(let e in t){let r=t[e];r!==void 0&&n.append(e,r)}return n}function bd(e){try{return new URL(e).origin}catch{}return null}function xd({responseHeaders:e,isHttp:t,rangeChunkSize:n,disableRange:r}){let i={allowRangeRequests:!1,suggestedLength:void 0},a=parseInt(e.get(`Content-Length`),10);return!Number.isInteger(a)||(i.suggestedLength=a,a<=2*n)||r||!t||e.get(`Accept-Ranges`)!==`bytes`||(e.get(`Content-Encoding`)||`identity`)!==`identity`||(i.allowRangeRequests=!0),i}function Sd(e){let t=e.get(`Content-Disposition`);if(t){let e=vd(t);if(e.includes(`%`))try{e=decodeURIComponent(e)}catch{}if(Ml(e))return e}return null}function Cd(e,t){return e===404||e===0&&t.startsWith(`file:`)?new sl(`Missing PDF "`+t+`".`):new cl(`Unexpected server response (${e}) while retrieving PDF "${t}".`,e)}function wd(e){return e===200||e===206}function Td(e,t,n){return{method:`GET`,headers:e,signal:n.signal,mode:`cors`,credentials:t?`include`:`same-origin`,redirect:`follow`}}function Ed(e){return e instanceof Uint8Array?e.buffer:e instanceof ArrayBuffer?e:(K(`getArrayBuffer - unexpected data format: ${e}`),new Uint8Array(e).buffer)}var Dd=class{_responseOrigin=null;constructor(e){this.source=e,this.isHttp=/^https?:/i.test(e.url),this.headers=yd(this.isHttp,e.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return J(!this._fullRequestReader,`PDFFetchStream.getFullReader can only be called once.`),this._fullRequestReader=new Od(this),this._fullRequestReader}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new kd(this,e,t);return this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Od=class{constructor(e){this._stream=e,this._reader=null,this._loaded=0,this._filename=null;let t=e.source;this._withCredentials=t.withCredentials||!1,this._contentLength=t.length,this._headersCapability=Promise.withResolvers(),this._disableRange=t.disableRange||!1,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!t.disableStream,this._isRangeSupported=!t.disableRange;let n=new Headers(e.headers),r=t.url;fetch(r,Td(n,this._withCredentials,this._abortController)).then(t=>{if(e._responseOrigin=bd(t.url),!wd(t.status))throw Cd(t.status,r);this._reader=t.body.getReader(),this._headersCapability.resolve();let n=t.headers,{allowRangeRequests:i,suggestedLength:a}=xd({responseHeaders:n,isHttp:e.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=i,this._contentLength=a||this._contentLength,this._filename=Sd(n),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ul(`Streaming is disabled.`))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Ed(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},kd=class{constructor(e,t,n){this._stream=e,this._reader=null,this._loaded=0;let r=e.source;this._withCredentials=r.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!r.disableStream,this._abortController=new AbortController;let i=new Headers(e.headers);i.append(`Range`,`bytes=${t}-${n-1}`);let a=r.url;fetch(a,Td(i,this._withCredentials,this._abortController)).then(t=>{let n=bd(t.url);if(n!==e._responseOrigin)throw Error(`Expected range response-origin "${n}" to match "${e._responseOrigin}".`);if(!wd(t.status))throw Cd(t.status,a);this._readCapability.resolve(),this._reader=t.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;let{value:e,done:t}=await this._reader.read();return t?{value:e,done:t}:(this._loaded+=e.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Ed(e),done:!1})}cancel(e){this._reader?.cancel(e),this._abortController.abort()}},Ad=200,jd=206;function Md(e){let t=e.response;return typeof t==`string`?fl(t).buffer:t}var Nd=class{_responseOrigin=null;constructor({url:e,httpHeaders:t,withCredentials:n}){this.url=e,this.isHttp=/^https?:/i.test(e),this.headers=yd(this.isHttp,t),this.withCredentials=n||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(e){let t=new XMLHttpRequest,n=this.currXhrId++,r=this.pendingRequests[n]={xhr:t};t.open(`GET`,this.url),t.withCredentials=this.withCredentials;for(let[e,n]of this.headers)t.setRequestHeader(e,n);return this.isHttp&&`begin`in e&&`end`in e?(t.setRequestHeader(`Range`,`bytes=${e.begin}-${e.end-1}`),r.expectedStatus=jd):r.expectedStatus=Ad,t.responseType=`arraybuffer`,J(e.onError,"Expected `onError` callback to be provided."),t.onerror=()=>{e.onError(t.status)},t.onreadystatechange=this.onStateChange.bind(this,n),t.onprogress=this.onProgress.bind(this,n),r.onHeadersReceived=e.onHeadersReceived,r.onDone=e.onDone,r.onError=e.onError,r.onProgress=e.onProgress,t.send(null),n}onProgress(e,t){let n=this.pendingRequests[e];n&&n.onProgress?.(t)}onStateChange(e,t){let n=this.pendingRequests[e];if(!n)return;let r=n.xhr;if(r.readyState>=2&&n.onHeadersReceived&&(n.onHeadersReceived(),delete n.onHeadersReceived),r.readyState!==4||!(e in this.pendingRequests))return;if(delete this.pendingRequests[e],r.status===0&&this.isHttp){n.onError(r.status);return}let i=r.status||Ad;if((i!==Ad||n.expectedStatus!==jd)&&i!==n.expectedStatus){n.onError(r.status);return}let a=Md(r);if(i===jd){let e=r.getResponseHeader(`Content-Range`),t=/bytes (\d+)-(\d+)\/(\d+)/.exec(e);t?n.onDone({begin:parseInt(t[1],10),chunk:a}):(K(`Missing or invalid "Content-Range" header.`),n.onError(0))}else a?n.onDone({begin:0,chunk:a}):n.onError(r.status)}getRequestXhr(e){return this.pendingRequests[e].xhr}isPendingRequest(e){return e in this.pendingRequests}abortRequest(e){let t=this.pendingRequests[e].xhr;delete this.pendingRequests[e],t.abort()}},Pd=class{constructor(e){this._source=e,this._manager=new Nd(e),this._rangeChunkSize=e.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(e){let t=this._rangeRequestReaders.indexOf(e);t>=0&&this._rangeRequestReaders.splice(t,1)}getFullReader(){return J(!this._fullRequestReader,`PDFNetworkStream.getFullReader can only be called once.`),this._fullRequestReader=new Fd(this._manager,this._source),this._fullRequestReader}getRangeReader(e,t){let n=new Id(this._manager,e,t);return n.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Fd=class{constructor(e,t){this._manager=e,this._url=t.url,this._fullRequestId=e.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=t.disableRange||!1,this._contentLength=t.length,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){let e=this._fullRequestId,t=this._manager.getRequestXhr(e);this._manager._responseOrigin=bd(t.responseURL);let n=t.getAllResponseHeaders(),r=new Headers(n?n.trimStart().replace(/[^\S ]+$/,``).split(/[\r\n]+/).map(e=>{let[t,...n]=e.split(`: `);return[t,n.join(`: `)]}):[]),{allowRangeRequests:i,suggestedLength:a}=xd({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});i&&(this._isRangeSupported=!0),this._contentLength=a||this._contentLength,this._filename=Sd(r),this._isRangeSupported&&this._manager.abortRequest(e),this._headersCapability.resolve()}_onDone(e){if(e&&(this._requests.length>0?this._requests.shift().resolve({value:e.chunk,done:!1}):this._cachedChunks.push(e.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(e){this._storedError=Cd(e,this._url),this._headersCapability.reject(this._storedError);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(e){this.onProgress?.({loaded:e.loaded,total:e.lengthComputable?e.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0,this._headersCapability.reject(e);for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}},Id=class{constructor(e,t,n){this._manager=e,this._url=e.url,this._requestId=e.request({begin:t,end:n,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){let e=bd(this._manager.getRequestXhr(this._requestId)?.responseURL);e!==this._manager._responseOrigin&&(this._storedError=Error(`Expected range response-origin "${e}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(e){let t=e.chunk;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(e){this._storedError??=Cd(e,this._url);for(let e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(e){this.isStreamingSupported||this.onProgress?.({loaded:e.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){let e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};let e=Promise.withResolvers();return this._requests.push(e),e.promise}cancel(e){this._done=!0;for(let e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}},Ld=/^[a-z][a-z0-9\-+.]+:/i;function Rd(e){if(Ld.test(e))return new URL(e);let t=process.getBuiltinModule(`url`);return new URL(t.pathToFileURL(e))}var zd=class{constructor(e){this.source=e,this.url=Rd(e.url),J(this.url.protocol===`file:`,`PDFNodeStream only supports file:// URLs.`),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return J(!this._fullRequestReader,`PDFNodeStream.getFullReader can only be called once.`),this._fullRequestReader=new Bd(this),this._fullRequestReader}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;let n=new Vd(this,e,t);return this._rangeRequestReaders.push(n),n}cancelAllRequests(e){this._fullRequestReader?.cancel(e);for(let t of this._rangeRequestReaders.slice(0))t.cancel(e)}},Bd=class{constructor(e){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null;let t=e.source;this._contentLength=t.length,this._loaded=0,this._filename=null,this._disableRange=t.disableRange||!1,this._rangeChunkSize=t.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!t.disableStream,this._isRangeSupported=!t.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();let n=process.getBuiltinModule(`fs`);n.promises.lstat(this._url).then(e=>{this._contentLength=e.size,this._setReadableStream(n.createReadStream(this._url)),this._headersCapability.resolve()},e=>{e.code===`ENOENT`&&(e=new sl(`Missing PDF "${this._url}".`)),this._storedError=e,this._headersCapability.reject(e)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on(`readable`,()=>{this._readCapability.resolve()}),e.on(`end`,()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on(`error`,e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new ul(`streaming is disabled`)),this._storedError&&this._readableStream.destroy(this._storedError)}},Vd=class{constructor(e,t,n){this._url=e.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let r=e.source;this._isStreamingSupported=!r.disableStream;let i=process.getBuiltinModule(`fs`);this._setReadableStream(i.createReadStream(this._url,{start:t,end:n-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;let e=this._readableStream.read();return e===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=e.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(e).buffer,done:!1})}cancel(e){if(!this._readableStream){this._error(e);return}this._readableStream.destroy(e)}_error(e){this._storedError=e,this._readCapability.resolve()}_setReadableStream(e){this._readableStream=e,e.on(`readable`,()=>{this._readCapability.resolve()}),e.on(`end`,()=>{e.destroy(),this._done=!0,this._readCapability.resolve()}),e.on(`error`,e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}},Hd=1e5,Ud=30,Wd=.8,Gd=class e{#e=Promise.withResolvers();#t=null;#n=!1;#r=!!globalThis.FontInspector?.enabled;#i=null;#a=null;#o=0;#s=0;#c=null;#l=null;#u=0;#d=0;#f=Object.create(null);#p=[];#m=null;#h=[];#g=new WeakMap;#_=null;static#v=new Map;static#y=new Map;static#b=new WeakMap;static#x=null;static#S=new Set;constructor({textContentSource:t,container:n,viewport:r}){if(t instanceof ReadableStream)this.#m=t;else if(typeof t==`object`)this.#m=new ReadableStream({start(e){e.enqueue(t),e.close()}});else throw Error(`No "textContentSource" parameter specified.`);this.#t=this.#l=n,this.#d=r.scale*(globalThis.devicePixelRatio||1),this.#u=r.rotation,this.#a={div:null,properties:null,ctx:null};let{pageWidth:i,pageHeight:a,pageX:o,pageY:s}=r.rawDims;this.#_=[1,0,0,-1,-o,s+a],this.#s=i,this.#o=a,e.#O(),Wl(n,r),this.#e.promise.finally(()=>{e.#S.delete(this),this.#a=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){let{isWindows:e,isFirefox:t}=_l.platform;return Y(this,`fontFamilyMap`,new Map([[`sans-serif`,`${e&&t?`Calibri, `:``}sans-serif`],[`monospace`,`${e&&t?`Lucida Console, `:``}monospace`]]))}render(){let t=()=>{this.#c.read().then(({value:e,done:n})=>{if(n){this.#e.resolve();return}this.#i??=e.lang,Object.assign(this.#f,e.styles),this.#C(e.items),t()},this.#e.reject)};return this.#c=this.#m.getReader(),e.#S.add(this),t(),this.#e.promise}update({viewport:t,onBefore:n=null}){let r=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#u&&(n?.(),this.#u=i,Wl(this.#l,{rotation:i})),r!==this.#d){n?.(),this.#d=r;let t={div:null,properties:null,ctx:e.#E(this.#i)};for(let e of this.#h)t.properties=this.#g.get(e),t.div=e,this.#T(t)}}cancel(){let e=new ul(`TextLayer task cancelled.`);this.#c?.cancel(e).catch(()=>{}),this.#c=null,this.#e.reject(e)}get textDivs(){return this.#h}get textContentItemsStr(){return this.#p}#C(t){if(this.#n)return;this.#a.ctx??=e.#E(this.#i);let n=this.#h,r=this.#p;for(let e of t){if(n.length>Hd){K(`Ignoring additional textDivs for performance reasons.`),this.#n=!0;return}if(e.str===void 0){if(e.type===`beginMarkedContentProps`||e.type===`beginMarkedContent`){let t=this.#t;this.#t=document.createElement(`span`),this.#t.classList.add(`markedContent`),e.id!==null&&this.#t.setAttribute(`id`,`${e.id}`),t.append(this.#t)}else e.type===`endMarkedContent`&&(this.#t=this.#t.parentNode);continue}r.push(e.str),this.#w(e)}}#w(t){let n=document.createElement(`span`),r={angle:0,canvasWidth:0,hasText:t.str!==``,hasEOL:t.hasEOL,fontSize:0};this.#h.push(n);let i=X.transform(this.#_,t.transform),a=Math.atan2(i[1],i[0]),o=this.#f[t.fontName];o.vertical&&(a+=Math.PI/2);let s=this.#r&&o.fontSubstitution||o.fontFamily;s=e.fontFamilyMap.get(s)||s;let c=Math.hypot(i[2],i[3]),l=c*e.#k(s,this.#i),u,d;a===0?(u=i[4],d=i[5]-l):(u=i[4]+l*Math.sin(a),d=i[5]-l*Math.cos(a));let f=`calc(var(--scale-factor)*`,p=n.style;this.#t===this.#l?(p.left=`${(100*u/this.#s).toFixed(2)}%`,p.top=`${(100*d/this.#o).toFixed(2)}%`):(p.left=`${f}${u.toFixed(2)}px)`,p.top=`${f}${d.toFixed(2)}px)`),p.fontSize=`${f}${(e.#x*c).toFixed(2)}px)`,p.fontFamily=s,r.fontSize=c,n.setAttribute(`role`,`presentation`),n.textContent=t.str,n.dir=t.dir,this.#r&&(n.dataset.fontName=o.fontSubstitutionLoadedName||t.fontName),a!==0&&(r.angle=180/Math.PI*a);let m=!1;if(t.str.length>1)m=!0;else if(t.str!==` `&&t.transform[0]!==t.transform[3]){let e=Math.abs(t.transform[0]),n=Math.abs(t.transform[3]);e!==n&&Math.max(e,n)/Math.min(e,n)>1.5&&(m=!0)}if(m&&(r.canvasWidth=o.vertical?t.height:t.width),this.#g.set(n,r),this.#a.div=n,this.#a.properties=r,this.#T(this.#a),r.hasText&&this.#t.append(n),r.hasEOL){let e=document.createElement(`br`);e.setAttribute(`role`,`presentation`),this.#t.append(e)}}#T(t){let{div:n,properties:r,ctx:i}=t,{style:a}=n,o=``;if(e.#x>1&&(o=`scale(${1/e.#x})`),r.canvasWidth!==0&&r.hasText){let{fontFamily:t}=a,{canvasWidth:s,fontSize:c}=r;e.#D(i,c*this.#d,t);let{width:l}=i.measureText(n.textContent);l>0&&(o=`scaleX(${s*this.#d/l}) ${o}`)}r.angle!==0&&(o=`rotate(${r.angle}deg) ${o}`),o.length>0&&(a.transform=o)}static cleanup(){if(!(this.#S.size>0)){this.#v.clear();for(let{canvas:e}of this.#y.values())e.remove();this.#y.clear()}}static#E(e=null){let t=this.#y.get(e||=``);if(!t){let n=document.createElement(`canvas`);n.className=`hiddenCanvasElement`,n.lang=e,document.body.append(n),t=n.getContext(`2d`,{alpha:!1,willReadFrequently:!0}),this.#y.set(e,t),this.#b.set(t,{size:0,family:``})}return t}static#D(e,t,n){let r=this.#b.get(e);(t!==r.size||n!==r.family)&&(e.font=`${t}px ${n}`,r.size=t,r.family=n)}static#O(){if(this.#x!==null)return;let e=document.createElement(`div`);e.style.opacity=0,e.style.lineHeight=1,e.style.fontSize=`1px`,e.style.position=`absolute`,e.textContent=`X`,document.body.append(e),this.#x=e.getBoundingClientRect().height,e.remove()}static#k(e,t){let n=this.#v.get(e);if(n)return n;let r=this.#E(t);r.canvas.width=r.canvas.height=Ud,this.#D(r,Ud,e);let i=r.measureText(``),a=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(a){let t=a/(a+o);return this.#v.set(e,t),r.canvas.width=r.canvas.height=0,t}r.strokeStyle=`red`,r.clearRect(0,0,Ud,Ud),r.strokeText(`g`,0,0);let s=r.getImageData(0,0,Ud,Ud).data;o=0;for(let e=s.length-1-3;e>=0;e-=4)if(s[e]>0){o=Math.ceil(e/4/Ud);break}r.clearRect(0,0,Ud,Ud),r.strokeText(`A`,0,Ud),s=r.getImageData(0,0,Ud,Ud).data,a=0;for(let e=0,t=s.length;e<t;e+=4)if(s[e]>0){a=Ud-Math.floor(e/4/Ud);break}r.canvas.width=r.canvas.height=0;let c=a?a/(a+o):Wd;return this.#v.set(e,c),c}},Kd=class e{static textContent(t){let n=[],r={items:n,styles:Object.create(null)};function i(t){if(!t)return;let r=null,a=t.name;if(a===`#text`)r=t.value;else if(e.shouldBuildText(a))t?.attributes?.textContent?r=t.attributes.textContent:t.value&&(r=t.value);else return;if(r!==null&&n.push({str:r}),t.children)for(let e of t.children)i(e)}return i(t),r}static shouldBuildText(e){return e!==`textarea`&&e!==`input`&&e!==`option`&&e!==`select`}},qd=65536,Jd=100,Yd=5e3,Xd=Fc?Ou:yu,Zd=Fc?ku:xu,Qd=Fc?Du:Cu,$d=Fc?Au:Tu;function ef(e={}){typeof e==`string`||e instanceof URL?e={url:e}:(e instanceof ArrayBuffer||ArrayBuffer.isView(e))&&(e={data:e});let t=new af,{docId:n}=t,r=e.url?tf(e.url):null,i=e.data?nf(e.data):null,a=e.httpHeaders||null,o=e.withCredentials===!0,s=e.password??null,c=e.range instanceof of?e.range:null,l=Number.isInteger(e.rangeChunkSize)&&e.rangeChunkSize>0?e.rangeChunkSize:qd,u=e.worker instanceof uf?e.worker:null,d=e.verbosity,f=typeof e.docBaseUrl==`string`&&!jl(e.docBaseUrl)?e.docBaseUrl:null,p=typeof e.cMapUrl==`string`?e.cMapUrl:null,m=e.cMapPacked!==!1,h=e.CMapReaderFactory||Zd,g=typeof e.standardFontDataUrl==`string`?e.standardFontDataUrl:null,_=e.StandardFontDataFactory||$d,v=e.stopAtErrors!==!0,y=Number.isInteger(e.maxImageSize)&&e.maxImageSize>-1?e.maxImageSize:-1,b=e.isEvalSupported!==!1,x=typeof e.isOffscreenCanvasSupported==`boolean`?e.isOffscreenCanvasSupported:!Fc,S=typeof e.isImageDecoderSupported==`boolean`?e.isImageDecoderSupported:!Fc&&(_l.platform.isFirefox||!globalThis.chrome),C=Number.isInteger(e.canvasMaxAreaInBytes)?e.canvasMaxAreaInBytes:-1,w=typeof e.disableFontFace==`boolean`?e.disableFontFace:Fc,T=e.fontExtraProperties===!0,E=e.enableXfa===!0,D=e.ownerDocument||globalThis.document,O=e.disableRange===!0,k=e.disableStream===!0,A=e.disableAutoFetch===!0,j=e.pdfBug===!0,M=e.CanvasFactory||Xd,ee=e.FilterFactory||Qd,N=e.enableHWA===!0,P=c?c.length:e.length??NaN,F=typeof e.useSystemFonts==`boolean`?e.useSystemFonts:!Fc&&!w,I=typeof e.useWorkerFetch==`boolean`?e.useWorkerFetch:h===xu&&_===Tu&&p&&g&&Il(p,document.baseURI)&&Il(g,document.baseURI);Qc(d);let te={canvasFactory:new M({ownerDocument:D,enableHWA:N}),filterFactory:new ee({docId:n,ownerDocument:D}),cMapReaderFactory:I?null:new h({baseUrl:p,isCompressed:m}),standardFontDataFactory:I?null:new _({baseUrl:g})};if(!u){let e={verbosity:d,port:ud.workerPort};u=e.port?uf.fromPort(e):new uf(e),t._worker=u}let ne={docId:n,apiVersion:`4.10.38`,data:i,password:s,disableAutoFetch:A,rangeChunkSize:l,length:P,docBaseUrl:f,enableXfa:E,evaluatorOptions:{maxImageSize:y,disableFontFace:w,ignoreErrors:v,isEvalSupported:b,isOffscreenCanvasSupported:x,isImageDecoderSupported:S,canvasMaxAreaInBytes:C,fontExtraProperties:T,useSystemFonts:F,cMapUrl:I?p:null,standardFontDataUrl:I?g:null}},re={disableFontFace:w,fontExtraProperties:T,ownerDocument:D,pdfBug:j,styleElement:null,loadingParams:{disableAutoFetch:A,enableXfa:E}};return u.promise.then(function(){if(t.destroyed)throw Error(`Loading aborted`);if(u.destroyed)throw Error(`Worker was destroyed`);let e=u.messageHandler.sendWithPromise(`GetDocRequest`,ne,i?[i.buffer]:null),s;if(c)s=new hd(c,{disableRange:O,disableStream:k});else if(!i){if(!r)throw Error("getDocument - no `url` parameter provided.");let e;if(Fc){if(Il(r)){if(typeof fetch>`u`||typeof Response>`u`||!(`body`in Response.prototype))throw Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");e=Dd}else e=zd}else e=Il(r)?Dd:Pd;s=new e({url:r,length:P,httpHeaders:a,withCredentials:o,rangeChunkSize:l,disableRange:O,disableStream:k})}return e.then(e=>{if(t.destroyed)throw Error(`Loading aborted`);if(u.destroyed)throw Error(`Worker was destroyed`);let r=new _u(n,e,u.port),i=new df(r,t,s,re,te);t._transport=i,r.send(`Ready`,null)})}).catch(t._capability.reject),t}function tf(e){if(e instanceof URL)return e.href;try{return new URL(e,window.location).href}catch{if(Fc&&typeof e==`string`)return e}throw Error(`Invalid PDF url data: either string or URL-object is expected in the url property.`)}function nf(e){if(Fc&&typeof Buffer<`u`&&e instanceof Buffer)throw Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength)return e;if(typeof e==`string`)return fl(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof e==`object`&&!isNaN(e?.length))return new Uint8Array(e);throw Error(`Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.`)}function rf(e){return typeof e==`object`&&Number.isInteger(e?.num)&&e.num>=0&&Number.isInteger(e?.gen)&&e.gen>=0}var af=class e{static#e=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${e.#e++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(e){throw this._worker?.port&&delete this._worker._pendingDestroy,e}this._transport=null,this._worker?.destroy(),this._worker=null}},of=class{constructor(e,t,n=!1,r=null){this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=r,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(e){this._rangeListeners.push(e)}addProgressListener(e){this._progressListeners.push(e)}addProgressiveReadListener(e){this._progressiveReadListeners.push(e)}addProgressiveDoneListener(e){this._progressiveDoneListeners.push(e)}onDataRange(e,t){for(let n of this._rangeListeners)n(e,t)}onDataProgress(e,t){this._readyCapability.promise.then(()=>{for(let n of this._progressListeners)n(e,t)})}onDataProgressiveRead(e){this._readyCapability.promise.then(()=>{for(let t of this._progressiveReadListeners)t(e)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(let e of this._progressiveDoneListeners)e()})}transportReady(){this._readyCapability.resolve()}requestDataRange(e,t){q(`Abstract method PDFDataRangeTransport.requestDataRange`)}abort(){}},sf=class{constructor(e,t){this._pdfInfo=e,this._transport=t}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return Y(this,`isPureXfa`,!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(e){return this._transport.getPage(e)}getPageIndex(e){return this._transport.getPageIndex(e)}getDestinations(){return this._transport.getDestinations()}getDestination(e){return this._transport.getDestination(e)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getOptionalContentConfig(t)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(e=!1){return this._transport.startCleanup(e||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(e){return this._transport.cachedPageNumber(e)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}},cf=class{#e=null;#t=!1;constructor(e,t,n,r=!1){this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=r?new Fl:null,this._pdfBug=r,this.commonObjs=n.commonObjs,this.objs=new pf,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:e,rotation:t=this.rotate,offsetX:n=0,offsetY:r=0,dontFlip:i=!1}={}){return new kl({viewBox:this.view,userUnit:this.userUnit,scale:e,rotation:t,offsetX:n,offsetY:r,dontFlip:i})}getAnnotations({intent:e=`display`}={}){let{renderingIntent:t}=this._transport.getRenderingIntent(e);return this._transport.getAnnotations(this._pageIndex,t)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return Y(this,`isPureXfa`,!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:e,viewport:t,intent:n=`display`,annotationMode:r=Vc.ENABLE,transform:i=null,background:a=null,optionalContentConfigPromise:o=null,annotationCanvasMap:s=null,pageColors:c=null,printAnnotationStorage:l=null,isEditing:u=!1}){this._stats?.time(`Overall`);let d=this._transport.getRenderingIntent(n,r,l,u),{renderingIntent:f,cacheKey:p}=d;this.#t=!1,this.#r(),o||=this._transport.getOptionalContentConfig(f);let m=this._intentStates.get(p);m||(m=Object.create(null),this._intentStates.set(p,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);let h=!!(f&Bc.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(d));let g=e=>{m.renderTasks.delete(_),(this._maybeCleanupAfterRender||h)&&(this.#t=!0),this.#n(!h),e?(_.capability.reject(e),this._abortOperatorList({intentState:m,reason:e instanceof Error?e:Error(e)})):_.capability.resolve(),this._stats&&(this._stats.timeEnd(`Rendering`),this._stats.timeEnd(`Overall`),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},_=new hf({callback:g,params:{canvasContext:e,viewport:t,transform:i,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:s,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!h,pdfBug:this._pdfBug,pageColors:c});(m.renderTasks||=new Set).add(_);let v=_.task;return Promise.all([m.displayReadyCapability.promise,o]).then(([e,t])=>{if(this.destroyed){g();return}if(this._stats?.time(`Rendering`),!(t.renderingIntent&f))throw Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");_.initializeGraphics({transparency:e,optionalContentConfig:t}),_.operatorListChanged()}).catch(g),v}getOperatorList({intent:e=`display`,annotationMode:t=Vc.ENABLE,printAnnotationStorage:n=null,isEditing:r=!1}={}){function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(s))}let a=this._transport.getRenderingIntent(e,t,n,r,!0),o=this._intentStates.get(a.cacheKey);o||(o=Object.create(null),this._intentStates.set(a.cacheKey,o));let s;return o.opListReadCapability||(s=Object.create(null),s.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||=new Set).add(s),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time(`Page Request`),this._pumpOperatorList(a)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:e=!1,disableNormalization:t=!1}={}){return this._transport.messageHandler.sendWithStream(`GetTextContent`,{pageIndex:this._pageIndex,includeMarkedContent:e===!0,disableNormalization:t===!0},{highWaterMark:100,size(e){return e.items.length}})}getTextContent(e={}){if(this._transport._htmlForXfa)return this.getXfa().then(e=>Kd.textContent(e));let t=this.streamTextContent(e);return new Promise(function(e,n){function r(){i.read().then(function({value:t,done:n}){if(n){e(a);return}a.lang??=t.lang,Object.assign(a.styles,t.styles),a.items.push(...t.items),r()},n)}let i=t.getReader(),a={items:[],styles:Object.create(null),lang:null};r()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let e=[];for(let t of this._intentStates.values())if(this._abortOperatorList({intentState:t,reason:Error(`Page was destroyed.`),force:!0}),!t.opListReadCapability)for(let n of t.renderTasks)e.push(n.completed),n.cancel();return this.objs.clear(),this.#t=!1,this.#r(),Promise.all(e)}cleanup(e=!1){this.#t=!0;let t=this.#n(!1);return e&&t&&(this._stats&&=new Fl),t}#n(e=!1){if(this.#r(),!this.#t||this.destroyed)return!1;if(e)return this.#e=setTimeout(()=>{this.#e=null,this.#n(!1)},Yd),!1;for(let{renderTasks:e,operatorList:t}of this._intentStates.values())if(e.size>0||!t.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#t=!1,!0}#r(){this.#e&&=(clearTimeout(this.#e),null)}_startRenderPage(e,t){let n=this._intentStates.get(t);n&&(this._stats?.timeEnd(`Page Request`),n.displayReadyCapability?.resolve(e))}_renderPageChunk(e,t){for(let n=0,r=e.length;n<r;n++)t.operatorList.fnArray.push(e.fnArray[n]),t.operatorList.argsArray.push(e.argsArray[n]);t.operatorList.lastChunk=e.lastChunk,t.operatorList.separateAnnots=e.separateAnnots;for(let e of t.renderTasks)e.operatorListChanged();e.lastChunk&&this.#n(!0)}_pumpOperatorList({renderingIntent:e,cacheKey:t,annotationStorageSerializable:n,modifiedIds:r}){let{map:i,transfer:a}=n,o=this._transport.messageHandler.sendWithStream(`GetOperatorList`,{pageIndex:this._pageIndex,intent:e,cacheKey:t,annotationStorage:i,modifiedIds:r},a).getReader(),s=this._intentStates.get(t);s.streamReader=o;let c=()=>{o.read().then(({value:e,done:t})=>{if(t){s.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(e,s),c())},e=>{if(s.streamReader=null,!this._transport.destroyed){if(s.operatorList){s.operatorList.lastChunk=!0;for(let e of s.renderTasks)e.operatorListChanged();this.#n(!0)}if(s.displayReadyCapability)s.displayReadyCapability.reject(e);else if(s.opListReadCapability)s.opListReadCapability.reject(e);else throw e}})};c()}_abortOperatorList({intentState:e,reason:t,force:n=!1}){if(e.streamReader){if(e.streamReaderCancelTimeout&&=(clearTimeout(e.streamReaderCancelTimeout),null),!n){if(e.renderTasks.size>0)return;if(t instanceof Al){let n=Jd;t.extraDelay>0&&t.extraDelay<1e3&&(n+=t.extraDelay),e.streamReaderCancelTimeout=setTimeout(()=>{e.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:e,reason:t,force:!0})},n);return}}if(e.streamReader.cancel(new ul(t.message)).catch(()=>{}),e.streamReader=null,!this._transport.destroyed){for(let[t,n]of this._intentStates)if(n===e){this._intentStates.delete(t);break}this.cleanup()}}}get stats(){return this._stats}},lf=class{#e=new Map;#t=Promise.resolve();postMessage(e,t){let n={data:structuredClone(e,t?{transfer:t}:null)};this.#t.then(()=>{for(let[e]of this.#e)e.call(this,n)})}addEventListener(e,t,n=null){let r=null;if(n?.signal instanceof AbortSignal){let{signal:i}=n;if(i.aborted){K("LoopbackPort - cannot use an `aborted` signal.");return}let a=()=>this.removeEventListener(e,t);r=()=>i.removeEventListener(`abort`,a),i.addEventListener(`abort`,a)}this.#e.set(t,r)}removeEventListener(e,t){this.#e.get(t)?.(),this.#e.delete(t)}terminate(){for(let[,e]of this.#e)e?.();this.#e.clear()}},uf=class e{static#e=0;static#t=!1;static#n;static{Fc&&(this.#t=!0,ud.workerSrc||=`./pdf.worker.mjs`),this._isSameOrigin=(e,t)=>{let n;try{if(n=new URL(e),!n.origin||n.origin===`null`)return!1}catch{return!1}let r=new URL(t,n);return n.origin===r.origin},this._createCDNWrapper=e=>{let t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:`text/javascript`}))}}constructor({name:t=null,port:n=null,verbosity:r=$c()}={}){if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if(e.#n?.has(n))throw Error(`Cannot use more than one PDFWorker per port.`);(e.#n||=new WeakMap).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return this._readyCapability.promise}#r(){this._readyCapability.resolve(),this._messageHandler.send(`configure`,{verbosity:this.verbosity})}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(e){this._port=e,this._messageHandler=new _u(`main`,`worker`,e),this._messageHandler.on(`ready`,function(){}),this.#r()}_initialize(){if(e.#t||e.#i){this._setupFakeWorker();return}let{workerSrc:t}=e;try{e._isSameOrigin(window.location.href,t)||(t=e._createCDNWrapper(new URL(t,window.location).href));let n=new Worker(t,{type:`module`}),r=new _u(`main`,`worker`,n),i=()=>{a.abort(),r.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(Error(`Worker was destroyed`)):this._setupFakeWorker()},a=new AbortController;n.addEventListener(`error`,()=>{this._webWorker||i()},{signal:a.signal}),r.on(`test`,e=>{if(a.abort(),this.destroyed||!e){i();return}this._messageHandler=r,this._port=n,this._webWorker=n,this.#r()}),r.on(`ready`,e=>{if(a.abort(),this.destroyed){i();return}try{o()}catch{this._setupFakeWorker()}});let o=()=>{let e=new Uint8Array;r.send(`test`,e,[e.buffer])};o();return}catch{el(`The worker has been disabled.`)}this._setupFakeWorker()}_setupFakeWorker(){e.#t||=(K(`Setting up fake worker.`),!0),e._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(Error(`Worker was destroyed`));return}let n=new lf;this._port=n;let r=`fake${e.#e++}`,i=new _u(r+`_worker`,r,n);t.setup(i,n),this._messageHandler=new _u(r,r+`_worker`,n),this.#r()}).catch(e=>{this._readyCapability.reject(Error(`Setting up fake worker failed: "${e.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,e.#n?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw Error(`PDFWorker.fromPort - invalid method signature.`);let n=this.#n?.get(t.port);if(n){if(n._pendingDestroy)throw Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new e(t)}static get workerSrc(){if(ud.workerSrc)return ud.workerSrc;throw Error(`No "GlobalWorkerOptions.workerSrc" specified.`)}static get#i(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return Y(this,`_setupFakeWorkerGlobal`,(async()=>this.#i?this.#i:(await import(this.workerSrc)).WorkerMessageHandler)())}},df=class{#e=new Map;#t=new Map;#n=new Map;#r=new Map;#i=null;constructor(e,t,n,r,i){this.messageHandler=e,this.loadingTask=t,this.commonObjs=new pf,this.fontLoader=new du({ownerDocument:r.ownerDocument,styleElement:r.styleElement}),this.loadingParams=r.loadingParams,this._params=r,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.cMapReaderFactory=i.cMapReaderFactory,this.standardFontDataFactory=i.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=n,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#a(e,t=null){let n=this.#e.get(e);if(n)return n;let r=this.messageHandler.sendWithPromise(e,t);return this.#e.set(e,r),r}get annotationStorage(){return Y(this,`annotationStorage`,new lu)}getRenderingIntent(e,t=Vc.ENABLE,n=null,r=!1,i=!1){let a=Bc.DISPLAY,o=cu;switch(e){case`any`:a=Bc.ANY;break;case`display`:break;case`print`:a=Bc.PRINT;break;default:K(`getRenderingIntent - invalid intent: ${e}`)}let s=a&Bc.PRINT&&n instanceof uu?n:this.annotationStorage;switch(t){case Vc.DISABLE:a+=Bc.ANNOTATIONS_DISABLE;break;case Vc.ENABLE:break;case Vc.ENABLE_FORMS:a+=Bc.ANNOTATIONS_FORMS;break;case Vc.ENABLE_STORAGE:a+=Bc.ANNOTATIONS_STORAGE,o=s.serializable;break;default:K(`getRenderingIntent - invalid annotationMode: ${t}`)}r&&(a+=Bc.IS_EDITING),i&&(a+=Bc.OPLIST);let{ids:c,hash:l}=s.modifiedIds,u=[a,o.hash,l];return{renderingIntent:a,cacheKey:u.join(`_`),annotationStorageSerializable:o,modifiedIds:c}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#i?.reject(Error(`Worker was destroyed during onPassword callback`));let e=[];for(let t of this.#t.values())e.push(t._destroy());this.#t.clear(),this.#n.clear(),this.#r.clear(),this.hasOwnProperty(`annotationStorage`)&&this.annotationStorage.resetModified();let t=this.messageHandler.sendWithPromise(`Terminate`,null);return e.push(t),Promise.all(e).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(),Gd.cleanup(),this._networkStream?.cancelAllRequests(new ul(`Worker was terminated.`)),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:e,loadingTask:t}=this;e.on(`GetReader`,(e,t)=>{J(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=e=>{this._lastProgress={loaded:e.loaded,total:e.total}},t.onPull=()=>{this._fullReader.read().then(function({value:e,done:n}){if(n){t.close();return}J(e instanceof ArrayBuffer,`GetReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{this._fullReader.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`ReaderHeadersReady`,async e=>{await this._fullReader.headersReady;let{isStreamingSupported:n,isRangeSupported:r,contentLength:i}=this._fullReader;return(!n||!r)&&(this._lastProgress&&t.onProgress?.(this._lastProgress),this._fullReader.onProgress=e=>{t.onProgress?.({loaded:e.loaded,total:e.total})}),{isStreamingSupported:n,isRangeSupported:r,contentLength:i}}),e.on(`GetRangeReader`,(e,t)=>{J(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let n=this._networkStream.getRangeReader(e.begin,e.end);if(!n){t.close();return}t.onPull=()=>{n.read().then(function({value:e,done:n}){if(n){t.close();return}J(e instanceof ArrayBuffer,`GetRangeReader - expected an ArrayBuffer.`),t.enqueue(new Uint8Array(e),1,[e])}).catch(e=>{t.error(e)})},t.onCancel=e=>{n.cancel(e),t.ready.catch(e=>{if(!this.destroyed)throw e})}}),e.on(`GetDoc`,({pdfInfo:e})=>{this._numPages=e.numPages,this._htmlForXfa=e.htmlForXfa,delete e.htmlForXfa,t._capability.resolve(new sf(e,this))}),e.on(`DocException`,e=>{t._capability.reject(gu(e))}),e.on(`PasswordRequest`,e=>{this.#i=Promise.withResolvers();try{if(!t.onPassword)throw gu(e);t.onPassword(e=>{e instanceof Error?this.#i.reject(e):this.#i.resolve({password:e})},e.code)}catch(e){this.#i.reject(e)}return this.#i.promise}),e.on(`DataLoaded`,e=>{t.onProgress?.({loaded:e.length,total:e.length}),this.downloadInfoCapability.resolve(e)}),e.on(`StartRenderPage`,e=>{this.destroyed||this.#t.get(e.pageIndex)._startRenderPage(e.transparency,e.cacheKey)}),e.on(`commonobj`,([t,n,r])=>{if(this.destroyed||this.commonObjs.has(t))return null;switch(n){case`Font`:let{disableFontFace:i,fontExtraProperties:a,pdfBug:o}=this._params;if(`error`in r){let e=r.error;K(`Error during font loading: ${e}`),this.commonObjs.resolve(t,e);break}let s=new fu(r,{disableFontFace:i,fontExtraProperties:a,inspectFont:o&&globalThis.FontInspector?.enabled?(e,t)=>globalThis.FontInspector.fontAdded(e,t):null});this.fontLoader.bind(s).catch(()=>e.sendWithPromise(`FontFallback`,{id:t})).finally(()=>{!a&&s.data&&(s.data=null),this.commonObjs.resolve(t,s)});break;case`CopyLocalImage`:let{imageRef:c}=r;J(c,`The imageRef must be defined.`);for(let e of this.#t.values())for(let[,n]of e.objs)if(n?.ref===c)return n.dataLen?(this.commonObjs.resolve(t,structuredClone(n)),n.dataLen):null;break;case`FontPath`:case`Image`:case`Pattern`:this.commonObjs.resolve(t,r);break;default:throw Error(`Got unknown common object type ${n}`)}return null}),e.on(`obj`,([e,t,n,r])=>{if(this.destroyed)return;let i=this.#t.get(t);if(!i.objs.has(e)){if(i._intentStates.size===0){r?.bitmap?.close();return}switch(n){case`Image`:i.objs.resolve(e,r),r?.dataLen>Rc&&(i._maybeCleanupAfterRender=!0);break;case`Pattern`:i.objs.resolve(e,r);break;default:throw Error(`Got unknown object type ${n}`)}}}),e.on(`DocProgress`,e=>{this.destroyed||t.onProgress?.({loaded:e.loaded,total:e.total})}),e.on(`FetchBuiltInCMap`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.cMapReaderFactory)throw Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(e)}),e.on(`FetchStandardFontData`,async e=>{if(this.destroyed)throw Error(`Worker was destroyed.`);if(!this.standardFontDataFactory)throw Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(e)})}getData(){return this.messageHandler.sendWithPromise(`GetData`,null)}saveDocument(){this.annotationStorage.size<=0&&K("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:e,transfer:t}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise(`SaveDocument`,{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:e,filename:this._fullReader?.filename??null},t).finally(()=>{this.annotationStorage.resetModified()})}getPage(e){if(!Number.isInteger(e)||e<=0||e>this._numPages)return Promise.reject(Error(`Invalid page request.`));let t=e-1,n=this.#n.get(t);if(n)return n;let r=this.messageHandler.sendWithPromise(`GetPage`,{pageIndex:t}).then(n=>{if(this.destroyed)throw Error(`Transport destroyed`);n.refStr&&this.#r.set(n.refStr,e);let r=new cf(t,n,this,this._params.pdfBug);return this.#t.set(t,r),r});return this.#n.set(t,r),r}getPageIndex(e){return rf(e)?this.messageHandler.sendWithPromise(`GetPageIndex`,{num:e.num,gen:e.gen}):Promise.reject(Error(`Invalid pageIndex request.`))}getAnnotations(e,t){return this.messageHandler.sendWithPromise(`GetAnnotations`,{pageIndex:e,intent:t})}getFieldObjects(){return this.#a(`GetFieldObjects`)}hasJSActions(){return this.#a(`HasJSActions`)}getCalculationOrderIds(){return this.messageHandler.sendWithPromise(`GetCalculationOrderIds`,null)}getDestinations(){return this.messageHandler.sendWithPromise(`GetDestinations`,null)}getDestination(e){return typeof e==`string`?this.messageHandler.sendWithPromise(`GetDestination`,{id:e}):Promise.reject(Error(`Invalid destination request.`))}getPageLabels(){return this.messageHandler.sendWithPromise(`GetPageLabels`,null)}getPageLayout(){return this.messageHandler.sendWithPromise(`GetPageLayout`,null)}getPageMode(){return this.messageHandler.sendWithPromise(`GetPageMode`,null)}getViewerPreferences(){return this.messageHandler.sendWithPromise(`GetViewerPreferences`,null)}getOpenAction(){return this.messageHandler.sendWithPromise(`GetOpenAction`,null)}getAttachments(){return this.messageHandler.sendWithPromise(`GetAttachments`,null)}getDocJSActions(){return this.#a(`GetDocJSActions`)}getPageJSActions(e){return this.messageHandler.sendWithPromise(`GetPageJSActions`,{pageIndex:e})}getStructTree(e){return this.messageHandler.sendWithPromise(`GetStructTree`,{pageIndex:e})}getOutline(){return this.messageHandler.sendWithPromise(`GetOutline`,null)}getOptionalContentConfig(e){return this.#a(`GetOptionalContentConfig`).then(t=>new md(t,e))}getPermissions(){return this.messageHandler.sendWithPromise(`GetPermissions`,null)}getMetadata(){let e=`GetMetadata`,t=this.#e.get(e);if(t)return t;let n=this.messageHandler.sendWithPromise(e,null).then(e=>({info:e[0],metadata:e[1]?new dd(e[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#e.set(e,n),n}getMarkInfo(){return this.messageHandler.sendWithPromise(`GetMarkInfo`,null)}async startCleanup(e=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise(`Cleanup`,null);for(let e of this.#t.values())if(!e.cleanup())throw Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),this.#e.clear(),this.filterFactory.destroy(!0),Gd.cleanup()}}cachedPageNumber(e){if(!rf(e))return null;let t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`;return this.#r.get(t)??null}},ff=Symbol(`INITIAL_DATA`),pf=class{#e=Object.create(null);#t(e){return this.#e[e]||={...Promise.withResolvers(),data:ff}}get(e,t=null){if(t){let n=this.#t(e);return n.promise.then(()=>t(n.data)),null}let n=this.#e[e];if(!n||n.data===ff)throw Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){let t=this.#e[e];return!!t&&t.data!==ff}delete(e){let t=this.#e[e];return!t||t.data===ff?!1:(delete this.#e[e],!0)}resolve(e,t=null){let n=this.#t(e);n.data=t,n.resolve()}clear(){for(let e in this.#e){let{data:t}=this.#e[e];t?.bitmap?.close()}this.#e=Object.create(null)}*[Symbol.iterator](){for(let e in this.#e){let{data:t}=this.#e[e];t!==ff&&(yield[e,t])}}},mf=class{#e=null;constructor(e){this.#e=e,this.onContinue=null}get promise(){return this.#e.capability.promise}cancel(e=0){this.#e.cancel(null,e)}get separateAnnots(){let{separateAnnots:e}=this.#e.operatorList;if(!e)return!1;let{annotationCanvasMap:t}=this.#e;return e.form||e.canvas&&t?.size>0}},hf=class e{#e=null;static#t=new WeakSet;constructor({callback:e,params:t,objs:n,commonObjs:r,annotationCanvasMap:i,operatorList:a,pageIndex:o,canvasFactory:s,filterFactory:c,useRequestAnimationFrame:l=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=e,this.params=t,this.objs=n,this.commonObjs=r,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=a,this._pageIndex=o,this.canvasFactory=s,this.filterFactory=c,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=l===!0&&typeof window<`u`,this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new mf(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=t.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){if(this.cancelled)return;if(this._canvas){if(e.#t.has(this._canvas))throw Error(`Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.`);e.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:r,viewport:i,transform:a,background:o}=this.params;this.gfx=new ld(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:a,viewport:i,transparency:t,background:o}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,n=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#e&&=(window.cancelAnimationFrame(this.#e),null),e.#t.delete(this._canvas),this.callback(t||new Al(`Rendering cancelled, page ${this._pageIndex+1}`,n))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#e=window.requestAnimationFrame(()=>{this.#e=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),e.#t.delete(this._canvas),this.callback())))}},gf=`4.10.38`,_f=`f9bea397f`;function vf(e){return Math.floor(Math.max(0,Math.min(1,e))*255).toString(16).padStart(2,`0`)}function yf(e){return Math.max(0,Math.min(255,255*e))}var bf=class{static CMYK_G([e,t,n,r]){return[`G`,1-Math.min(1,.3*e+.59*n+.11*t+r)]}static G_CMYK([e]){return[`CMYK`,0,0,0,1-e]}static G_RGB([e]){return[`RGB`,e,e,e]}static G_rgb([e]){return e=yf(e),[e,e,e]}static G_HTML([e]){let t=vf(e);return`#${t}${t}${t}`}static RGB_G([e,t,n]){return[`G`,.3*e+.59*t+.11*n]}static RGB_rgb(e){return e.map(yf)}static RGB_HTML(e){return`#${e.map(vf).join(``)}`}static T_HTML(){return`#00000000`}static T_rgb(){return[null]}static CMYK_RGB([e,t,n,r]){return[`RGB`,1-Math.min(1,e+r),1-Math.min(1,n+r),1-Math.min(1,t+r)]}static CMYK_rgb([e,t,n,r]){return[yf(1-Math.min(1,e+r)),yf(1-Math.min(1,n+r)),yf(1-Math.min(1,t+r))]}static CMYK_HTML(e){let t=this.CMYK_RGB(e).slice(1);return this.RGB_HTML(t)}static RGB_CMYK([e,t,n]){let r=1-e,i=1-t,a=1-n;return[`CMYK`,r,i,a,Math.min(r,i,a)]}},xf=class{create(e,t,n=!1){if(e<=0||t<=0)throw Error(`Invalid SVG dimensions`);let r=this._createSVG(`svg:svg`);return r.setAttribute(`version`,`1.1`),n||(r.setAttribute(`width`,`${e}px`),r.setAttribute(`height`,`${t}px`)),r.setAttribute(`preserveAspectRatio`,`none`),r.setAttribute(`viewBox`,`0 0 ${e} ${t}`),r}createElement(e){if(typeof e!=`string`)throw Error(`Invalid SVG element type`);return this._createSVG(e)}_createSVG(e){q("Abstract method `_createSVG` called.")}},Sf=class extends xf{_createSVG(e){return document.createElementNS(El,e)}},Cf=class{static setupStorage(e,t,n,r,i){let a=r.getValue(t,{value:null});switch(n.name){case`textarea`:if(a.value!==null&&(e.textContent=a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})});break;case`input`:if(n.attributes.type===`radio`||n.attributes.type===`checkbox`){if(a.value===n.attributes.xfaOn?e.setAttribute(`checked`,!0):a.value===n.attributes.xfaOff&&e.removeAttribute(`checked`),i===`print`)break;e.addEventListener(`change`,e=>{r.setValue(t,{value:e.target.checked?e.target.getAttribute(`xfaOn`):e.target.getAttribute(`xfaOff`)})})}else{if(a.value!==null&&e.setAttribute(`value`,a.value),i===`print`)break;e.addEventListener(`input`,e=>{r.setValue(t,{value:e.target.value})})}break;case`select`:if(a.value!==null){e.setAttribute(`value`,a.value);for(let e of n.children)e.attributes.value===a.value?e.attributes.selected=!0:e.attributes.hasOwnProperty(`selected`)&&delete e.attributes.selected}e.addEventListener(`input`,e=>{let n=e.target.options,i=n.selectedIndex===-1?``:n[n.selectedIndex].value;r.setValue(t,{value:i})})}}static setAttributes({html:e,element:t,storage:n=null,intent:r,linkService:i}){let{attributes:a}=t,o=e instanceof HTMLAnchorElement;a.type===`radio`&&(a.name=`${a.name}-${r}`);for(let[t,n]of Object.entries(a))if(n!=null)switch(t){case`class`:n.length&&e.setAttribute(t,n.join(` `));break;case`dataId`:break;case`id`:e.setAttribute(`data-element-id`,n);break;case`style`:Object.assign(e.style,n);break;case`textContent`:e.textContent=n;break;default:(!o||t!==`href`&&t!==`newWindow`)&&e.setAttribute(t,n)}o&&i.addLinkAttributes(e,a.href,a.newWindow),n&&a.dataId&&this.setupStorage(e,a.dataId,t,n)}static render(e){let t=e.annotationStorage,n=e.linkService,r=e.xfaHtml,i=e.intent||`display`,a=document.createElement(r.name);r.attributes&&this.setAttributes({html:a,element:r,intent:i,linkService:n});let o=i!==`richText`,s=e.div;if(s.append(a),e.viewport){let t=`matrix(${e.viewport.transform.join(`,`)})`;s.style.transform=t}o&&s.setAttribute(`class`,`xfaLayer xfaFont`);let c=[];if(r.children.length===0){if(r.value){let e=document.createTextNode(r.value);a.append(e),o&&Kd.shouldBuildText(r.name)&&c.push(e)}return{textDivs:c}}let l=[[r,-1,a]];for(;l.length>0;){let[e,r,a]=l.at(-1);if(r+1===e.children.length){l.pop();continue}let s=e.children[++l.at(-1)[1]];if(s===null)continue;let{name:u}=s;if(u===`#text`){let e=document.createTextNode(s.value);c.push(e),a.append(e);continue}let d=s?.attributes?.xmlns?document.createElementNS(s.attributes.xmlns,u):document.createElement(u);if(a.append(d),s.attributes&&this.setAttributes({html:d,element:s,storage:t,intent:i,linkService:n}),s.children?.length>0)l.push([s,-1,d]);else if(s.value){let e=document.createTextNode(s.value);o&&Kd.shouldBuildText(u)&&c.push(e),d.append(e)}}for(let e of s.querySelectorAll(`.xfaNonInteractive input, .xfaNonInteractive textarea`))e.setAttribute(`readOnly`,!0);return{textDivs:c}}static update(e){let t=`matrix(${e.viewport.transform.join(`,`)})`;e.div.style.transform=t,e.div.hidden=!1}},wf=1e3,Tf=9,Ef=new WeakSet;function Df(e){return{width:e[2]-e[0],height:e[3]-e[1]}}var Of=class{static create(e){switch(e.data.annotationType){case Kc.LINK:return new Af(e);case Kc.TEXT:return new jf(e);case Kc.WIDGET:switch(e.data.fieldType){case`Tx`:return new Nf(e);case`Btn`:return e.data.radioButton?new If(e):e.data.checkBox?new Ff(e):new Lf(e);case`Ch`:return new Rf(e);case`Sig`:return new Pf(e)}return new Mf(e);case Kc.POPUP:return new zf(e);case Kc.FREETEXT:return new Vf(e);case Kc.LINE:return new Hf(e);case Kc.SQUARE:return new Uf(e);case Kc.CIRCLE:return new Wf(e);case Kc.POLYLINE:return new Gf(e);case Kc.CARET:return new qf(e);case Kc.INK:return new Jf(e);case Kc.POLYGON:return new Kf(e);case Kc.HIGHLIGHT:return new Yf(e);case Kc.UNDERLINE:return new Xf(e);case Kc.SQUIGGLY:return new Zf(e);case Kc.STRIKEOUT:return new Qf(e);case Kc.STAMP:return new $f(e);case Kc.FILEATTACHMENT:return new ep(e);default:return new kf(e)}}},kf=class e{#e=null;#t=!1;#n=null;constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:r=!1}={}){this.isRenderable=t,this.data=e.data,this.layer=e.layer,this.linkService=e.linkService,this.downloadManager=e.downloadManager,this.imageResourcesPath=e.imageResourcesPath,this.renderForms=e.renderForms,this.svgFactory=e.svgFactory,this.annotationStorage=e.annotationStorage,this.enableScripting=e.enableScripting,this.hasJSActions=e.hasJSActions,this._fieldObjects=e.fieldObjects,this.parent=e.parent,t&&(this.container=this._createContainer(n)),r&&this._createQuadrilaterals()}static _hasPopupData({titleObj:e,contentsObj:t,richText:n}){return!!(e?.str||t?.str||n?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return e._hasPopupData(this.data)}updateEdited(e){if(!this.container)return;this.#e||={rect:this.data.rect.slice(0)};let{rect:t}=e;t&&this.#r(t),this.#n?.popup.updateEdited(e)}resetEdited(){this.#e&&=(this.#r(this.#e.rect),this.#n?.popup.resetEdited(),null)}#r(e){let{container:{style:t},data:{rect:n,rotation:r},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:a,pageX:o,pageY:s}}}}=this;n?.splice(0,4,...e);let{width:c,height:l}=Df(e);t.left=`${100*(e[0]-o)/i}%`,t.top=`${100*(a-e[3]+s)/a}%`,r===0?(t.width=`${100*c/i}%`,t.height=`${100*l/a}%`):this.setRotation(r)}_createContainer(e){let{data:t,parent:{page:n,viewport:r}}=this,i=document.createElement(`section`);i.setAttribute(`data-annotation-id`,t.id),this instanceof Mf||(i.tabIndex=wf);let{style:a}=i;if(a.zIndex=this.parent.zIndex++,t.alternativeText&&(i.title=t.alternativeText),t.noRotate&&i.classList.add(`norotate`),!t.rect||this instanceof zf){let{rotation:e}=t;return!t.hasOwnCanvas&&e!==0&&this.setRotation(e,i),i}let{width:o,height:s}=Df(t.rect);if(!e&&t.borderStyle.width>0){a.borderWidth=`${t.borderStyle.width}px`;let e=t.borderStyle.horizontalCornerRadius,n=t.borderStyle.verticalCornerRadius;switch(e>0||n>0?a.borderRadius=`calc(${e}px * var(--scale-factor)) / calc(${n}px * var(--scale-factor))`:this instanceof If&&(a.borderRadius=`calc(${o}px * var(--scale-factor)) / calc(${s}px * var(--scale-factor))`),t.borderStyle.style){case qc.SOLID:a.borderStyle=`solid`;break;case qc.DASHED:a.borderStyle=`dashed`;break;case qc.BEVELED:K(`Unimplemented border style: beveled`);break;case qc.INSET:K(`Unimplemented border style: inset`);break;case qc.UNDERLINE:a.borderBottomStyle=`solid`}let r=t.borderColor||null;r?(this.#t=!0,a.borderColor=X.makeHexColor(r[0]|0,r[1]|0,r[2]|0)):a.borderWidth=0}let c=X.normalizeRect([t.rect[0],n.view[3]-t.rect[1]+n.view[1],t.rect[2],n.view[3]-t.rect[3]+n.view[1]]),{pageWidth:l,pageHeight:u,pageX:d,pageY:f}=r.rawDims;a.left=`${100*(c[0]-d)/l}%`,a.top=`${100*(c[1]-f)/u}%`;let{rotation:p}=t;return t.hasOwnCanvas||p===0?(a.width=`${100*o/l}%`,a.height=`${100*s/u}%`):this.setRotation(p,i),i}setRotation(e,t=this.container){if(!this.data.rect)return;let{pageWidth:n,pageHeight:r}=this.parent.viewport.rawDims,{width:i,height:a}=Df(this.data.rect),o,s;e%180==0?(o=100*i/n,s=100*a/r):(o=100*a/n,s=100*i/r),t.style.width=`${o}%`,t.style.height=`${s}%`,t.setAttribute(`data-main-rotation`,(360-e)%360)}get _commonActions(){let e=(e,t,n)=>{let r=n.detail[e],i=r[0],a=r.slice(1);n.target.style[t]=bf[`${i}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[t]:bf[`${i}_rgb`](a)})};return Y(this,`_commonActions`,{display:e=>{let{display:t}=e.detail,n=t%2==1;this.container.style.visibility=n?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noView:n,noPrint:t===1||t===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{let{hidden:t}=e.detail;this.container.style.visibility=t?`hidden`:`visible`,this.annotationStorage.setValue(this.data.id,{noPrint:t,noView:t})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:t=>{e(`bgColor`,`backgroundColor`,t)},fillColor:t=>{e(`fillColor`,`backgroundColor`,t)},fgColor:t=>{e(`fgColor`,`color`,t)},textColor:t=>{e(`textColor`,`color`,t)},borderColor:t=>{e(`borderColor`,`borderColor`,t)},strokeColor:t=>{e(`strokeColor`,`borderColor`,t)},rotation:e=>{let t=e.detail.rotation;this.setRotation(t),this.annotationStorage.setValue(this.data.id,{rotation:t})}})}_dispatchEventFromSandbox(e,t){let n=this._commonActions;for(let r of Object.keys(t.detail))(e[r]||n[r])?.(t)}_setDefaultPropertiesFromJS(e){if(!this.enableScripting)return;let t=this.annotationStorage.getRawValue(this.data.id);if(!t)return;let n=this._commonActions;for(let[r,i]of Object.entries(t)){let a=n[r];a&&(a({detail:{[r]:i},target:e}),delete t[r])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:e}=this.data;if(!e)return;let[t,n,r,i]=this.data.rect.map(e=>Math.fround(e));if(e.length===8){let[a,o,s,c]=e.subarray(2,6);if(r===a&&i===o&&t===s&&n===c)return}let{style:a}=this.container,o;if(this.#t){let{borderColor:e,borderWidth:t}=a;a.borderWidth=0,o=[`url('data:image/svg+xml;utf8,`,`<svg xmlns="http://www.w3.org/2000/svg"`,` preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${e}" stroke-width="${t}">`],this.container.classList.add(`hasBorder`)}let s=r-t,c=i-n,{svgFactory:l}=this,u=l.createElement(`svg`);u.classList.add(`quadrilateralsContainer`),u.setAttribute(`width`,0),u.setAttribute(`height`,0);let d=l.createElement(`defs`);u.append(d);let f=l.createElement(`clipPath`),p=`clippath_${this.data.id}`;f.setAttribute(`id`,p),f.setAttribute(`clipPathUnits`,`objectBoundingBox`),d.append(f);for(let n=2,r=e.length;n<r;n+=8){let r=e[n],a=e[n+1],u=e[n+2],d=e[n+3],p=l.createElement(`rect`),m=(u-t)/s,h=(i-a)/c,g=(r-u)/s,_=(a-d)/c;p.setAttribute(`x`,m),p.setAttribute(`y`,h),p.setAttribute(`width`,g),p.setAttribute(`height`,_),f.append(p),o?.push(`<rect vector-effect="non-scaling-stroke" x="${m}" y="${h}" width="${g}" height="${_}"/>`)}this.#t&&(o.push(`</g></svg>')`),a.backgroundImage=o.join(``)),this.container.append(u),this.container.style.clipPath=`url(#${p})`}_createPopup(){let{data:e}=this,t=this.#n=new zf({data:{color:e.color,titleObj:e.titleObj,modificationDate:e.modificationDate,contentsObj:e.contentsObj,richText:e.richText,parentRect:e.rect,borderStyle:0,id:`popup_${e.id}`,rotation:e.rotation},parent:this.parent,elements:[this]});this.parent.div.append(t.render())}render(){q("Abstract method `AnnotationElement.render` called")}_getElementsByName(e,t=null){let n=[];if(this._fieldObjects){let r=this._fieldObjects[e];if(r)for(let{page:e,id:i,exportValues:a}of r){if(e===-1||i===t)continue;let r=typeof a==`string`?a:null,o=document.querySelector(`[data-element-id="${i}"]`);if(o&&!Ef.has(o)){K(`_getElementsByName - element not allowed: ${i}`);continue}n.push({id:i,exportValue:r,domElement:o})}return n}for(let r of document.getElementsByName(e)){let{exportValue:e}=r,i=r.getAttribute(`data-element-id`);i!==t&&Ef.has(r)&&n.push({id:i,exportValue:e,domElement:r})}return n}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let e=this.getElementsToTriggerPopup();if(Array.isArray(e))for(let t of e)t.classList.add(`highlightArea`);else e.classList.add(`highlightArea`)}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:e,data:{id:t}}=this;this.container.addEventListener(`dblclick`,()=>{this.linkService.eventBus?.dispatch(`switchannotationeditormode`,{source:this,mode:e,editId:t})})}},Af=class extends kf{constructor(e,t=null){super(e,{isRenderable:!0,ignoreBorder:!!t?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=e.data.isTooltipOnly}render(){let{data:e,linkService:t}=this,n=document.createElement(`a`);n.setAttribute(`data-element-id`,e.id);let r=!1;return e.url?(t.addLinkAttributes(n,e.url,e.newWindow),r=!0):e.action?(this._bindNamedAction(n,e.action),r=!0):e.attachment?(this.#t(n,e.attachment,e.attachmentDest),r=!0):e.setOCGState?(this.#n(n,e.setOCGState),r=!0):e.dest?(this._bindLink(n,e.dest),r=!0):(e.actions&&(e.actions.Action||e.actions[`Mouse Up`]||e.actions[`Mouse Down`])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(n,e),r=!0),e.resetForm?(this._bindResetFormAction(n,e.resetForm),r=!0):this.isTooltipOnly&&!r&&(this._bindLink(n,``),r=!0)),this.container.classList.add(`linkAnnotation`),r&&this.container.append(n),this.container}#e(){this.container.setAttribute(`data-internal-link`,``)}_bindLink(e,t){e.href=this.linkService.getDestinationHash(t),e.onclick=()=>(t&&this.linkService.goToDestination(t),!1),(t||t===``)&&this.#e()}_bindNamedAction(e,t){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeNamedAction(t),!1),this.#e()}#t(e,t,n=null){e.href=this.linkService.getAnchorUrl(``),t.description&&(e.title=t.description),e.onclick=()=>(this.downloadManager?.openOrDownloadData(t.content,t.filename,n),!1),this.#e()}#n(e,t){e.href=this.linkService.getAnchorUrl(``),e.onclick=()=>(this.linkService.executeSetOCGState(t),!1),this.#e()}_bindJSAction(e,t){e.href=this.linkService.getAnchorUrl(``);let n=new Map([[`Action`,`onclick`],[`Mouse Up`,`onmouseup`],[`Mouse Down`,`onmousedown`]]);for(let r of Object.keys(t.actions)){let i=n.get(r);i&&(e[i]=()=>(this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t.id,name:r}}),!1))}e.onclick||=()=>!1,this.#e()}_bindResetFormAction(e,t){let n=e.onclick;if(n||(e.href=this.linkService.getAnchorUrl(``)),this.#e(),!this._fieldObjects){K('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),n||(e.onclick=()=>!1);return}e.onclick=()=>{n?.();let{fields:e,refs:r,include:i}=t,a=[];if(e.length!==0||r.length!==0){let t=new Set(r);for(let n of e){let e=this._fieldObjects[n]||[];for(let{id:n}of e)t.add(n)}for(let e of Object.values(this._fieldObjects))for(let n of e)t.has(n.id)===i&&a.push(n)}else for(let e of Object.values(this._fieldObjects))a.push(...e);let o=this.annotationStorage,s=[];for(let e of a){let{id:t}=e;switch(s.push(t),e.type){case`text`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}case`checkbox`:case`radiobutton`:{let n=e.defaultValue===e.exportValues;o.setValue(t,{value:n});break}case`combobox`:case`listbox`:{let n=e.defaultValue||``;o.setValue(t,{value:n});break}default:continue}let n=document.querySelector(`[data-element-id="${t}"]`);if(n){if(!Ef.has(n)){K(`_bindResetFormAction - element not allowed: ${t}`);continue}n.dispatchEvent(new Event(`resetform`))}}return this.enableScripting&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:`app`,ids:s,name:`ResetForm`}}),!1}}},jf=class extends kf{constructor(e){super(e,{isRenderable:!0})}render(){this.container.classList.add(`textAnnotation`);let e=document.createElement(`img`);return e.src=this.imageResourcesPath+`annotation-`+this.data.name.toLowerCase()+`.svg`,e.setAttribute(`data-l10n-id`,`pdfjs-text-annotation-type`),e.setAttribute(`data-l10n-args`,JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(e),this.container}},Mf=class extends kf{render(){return this.container}showElementAndHideCanvas(e){this.data.hasOwnCanvas&&(e.previousSibling?.nodeName===`CANVAS`&&(e.previousSibling.hidden=!0),e.hidden=!1)}_getKeyModifier(e){return _l.platform.isMac?e.metaKey:e.ctrlKey}_setEventListener(e,t,n,r,i){n.includes(`mouse`)?e.addEventListener(n,e=>{this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e),shift:e.shiftKey,modifier:this._getKeyModifier(e)}})}):e.addEventListener(n,e=>{if(n===`blur`){if(!t.focused||!e.relatedTarget)return;t.focused=!1}else if(n===`focus`){if(t.focused)return;t.focused=!0}i&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:this.data.id,name:r,value:i(e)}})})}_setEventListeners(e,t,n,r){for(let[i,a]of n)(a===`Action`||this.data.actions?.[a])&&((a===`Focus`||a===`Blur`)&&(t||={focused:!1}),this._setEventListener(e,t,i,a,r),a===`Focus`&&!this.data.actions?.Blur?this._setEventListener(e,t,`blur`,`Blur`,null):a===`Blur`&&!this.data.actions?.Focus&&this._setEventListener(e,t,`focus`,`Focus`,null))}_setBackgroundColor(e){let t=this.data.backgroundColor||null;e.style.backgroundColor=t===null?`transparent`:X.makeHexColor(t[0],t[1],t[2])}_setTextStyle(e){let t=[`left`,`center`,`right`],{fontColor:n}=this.data.defaultAppearanceData,r=this.data.defaultAppearanceData.fontSize||Tf,i=e.style,a,o=e=>Math.round(10*e)/10;if(this.data.multiLine){let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2),t=e/(Math.round(e/(zc*r))||1);a=Math.min(r,o(t/zc))}else{let e=Math.abs(this.data.rect[3]-this.data.rect[1]-2);a=Math.min(r,o(e/zc))}i.fontSize=`calc(${a}px * var(--scale-factor))`,i.color=X.makeHexColor(n[0],n[1],n[2]),this.data.textAlignment!==null&&(i.textAlign=t[this.data.textAlignment])}_setRequired(e,t){t?e.setAttribute(`required`,!0):e.removeAttribute(`required`),e.setAttribute(`aria-required`,t)}},Nf=class extends Mf{constructor(e){let t=e.renderForms||e.data.hasOwnCanvas||!e.data.hasAppearance&&!!e.data.fieldValue;super(e,{isRenderable:t})}setPropertyOnSiblings(e,t,n,r){let i=this.annotationStorage;for(let a of this._getElementsByName(e.name,e.id))a.domElement&&(a.domElement[t]=n),i.setValue(a.id,{[r]:n})}render(){let e=this.annotationStorage,t=this.data.id;this.container.classList.add(`textWidgetAnnotation`);let n=null;if(this.renderForms){let r=e.getValue(t,{value:this.data.fieldValue}),i=r.value||``,a=e.getValue(t,{charLimit:this.data.maxLen}).charLimit;a&&i.length>a&&(i=i.slice(0,a));let o=r.formattedValue||this.data.textContent?.join(`
|
|
440
|
+
`)||null;o&&this.data.comb&&(o=o.replaceAll(/\s+/g,``));let s={userValue:i,formattedValue:o,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(n=document.createElement(`textarea`),n.textContent=o??i,this.data.doNotScroll&&(n.style.overflowY=`hidden`)):(n=document.createElement(`input`),n.type=`text`,n.setAttribute(`value`,o??i),this.data.doNotScroll&&(n.style.overflowX=`hidden`)),this.data.hasOwnCanvas&&(n.hidden=!0),Ef.add(n),n.setAttribute(`data-element-id`,t),n.disabled=this.data.readOnly,n.name=this.data.fieldName,n.tabIndex=wf,this._setRequired(n,this.data.required),a&&(n.maxLength=a),n.addEventListener(`input`,r=>{e.setValue(t,{value:r.target.value}),this.setPropertyOnSiblings(n,`value`,r.target.value,`value`),s.formattedValue=null}),n.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue??``;n.value=s.userValue=t,s.formattedValue=null});let c=e=>{let{formattedValue:t}=s;t!=null&&(e.target.value=t),e.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener(`focus`,e=>{if(s.focused)return;let{target:t}=e;s.userValue&&(t.value=s.userValue),s.lastCommittedValue=t.value,s.commitKey=1,this.data.actions?.Focus||(s.focused=!0)}),n.addEventListener(`updatefromsandbox`,n=>{this.showElementAndHideCanvas(n.target),this._dispatchEventFromSandbox({value(n){s.userValue=n.detail.value??``,e.setValue(t,{value:s.userValue.toString()}),n.target.value=s.userValue},formattedValue(n){let{formattedValue:r}=n.detail;s.formattedValue=r,r!=null&&n.target!==document.activeElement&&(n.target.value=r),e.setValue(t,{formattedValue:r})},selRange(e){e.target.setSelectionRange(...e.detail.selRange)},charLimit:n=>{let{charLimit:r}=n.detail,{target:i}=n;if(r===0){i.removeAttribute(`maxLength`);return}i.setAttribute(`maxLength`,r);let a=s.userValue;!a||a.length<=r||(a=a.slice(0,r),i.value=s.userValue=a,e.setValue(t,{value:a}),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:a,willCommit:!0,commitKey:1,selStart:i.selectionStart,selEnd:i.selectionEnd}}))}},n)}),n.addEventListener(`keydown`,e=>{s.commitKey=1;let n=-1;if(e.key===`Escape`?n=0:e.key===`Enter`&&!this.data.multiLine?n=2:e.key===`Tab`&&(s.commitKey=3),n===-1)return;let{value:r}=e.target;s.lastCommittedValue!==r&&(s.lastCommittedValue=r,s.userValue=r,this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:r,willCommit:!0,commitKey:n,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}))});let r=c;c=null,n.addEventListener(`blur`,e=>{if(!s.focused||!e.relatedTarget)return;this.data.actions?.Blur||(s.focused=!1);let{value:n}=e.target;s.userValue=n,s.lastCommittedValue!==n&&this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:n,willCommit:!0,commitKey:s.commitKey,selStart:e.target.selectionStart,selEnd:e.target.selectionEnd}}),r(e)}),this.data.actions?.Keystroke&&n.addEventListener(`beforeinput`,e=>{s.lastCommittedValue=null;let{data:n,target:r}=e,{value:i,selectionStart:a,selectionEnd:o}=r,c=a,l=o;switch(e.inputType){case`deleteWordBackward`:{let e=i.substring(0,a).match(/\w*[^\w]*$/);e&&(c-=e[0].length);break}case`deleteWordForward`:{let e=i.substring(a).match(/^[^\w]*\w*/);e&&(l+=e[0].length);break}case`deleteContentBackward`:a===o&&--c;break;case`deleteContentForward`:a===o&&(l+=1)}e.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:i,change:n||``,willCommit:!1,selStart:c,selEnd:l}})}),this._setEventListeners(n,s,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.value)}if(c&&n.addEventListener(`blur`,c),this.data.comb){let e=(this.data.rect[2]-this.data.rect[0])/a;n.classList.add(`comb`),n.style.letterSpacing=`calc(${e}px * var(--scale-factor) - 1ch)`}}else n=document.createElement(`div`),n.textContent=this.data.fieldValue,n.style.verticalAlign=`middle`,n.style.display=`table-cell`,this.data.hasOwnCanvas&&(n.hidden=!0);return this._setTextStyle(n),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}},Pf=class extends Mf{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}},Ff=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.exportValue===t.fieldValue}).value;typeof r==`string`&&(r=r!==`Off`,e.setValue(n,{value:r})),this.container.classList.add(`buttonWidgetAnnotation`,`checkBox`);let i=document.createElement(`input`);return Ef.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`checkbox`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.setAttribute(`exportValue`,t.exportValue),i.tabIndex=wf,i.addEventListener(`change`,r=>{let{name:i,checked:a}=r.target;for(let r of this._getElementsByName(i,n)){let n=a&&r.exportValue===t.exportValue;r.domElement&&(r.domElement.checked=n),e.setValue(r.id,{value:n})}e.setValue(n,{value:a})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue||`Off`;e.target.checked=n===t.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value(t){t.target.checked=t.detail.value!==`Off`,e.setValue(n,{value:t.target.checked})}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},If=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`buttonWidgetAnnotation`,`radioButton`);let e=this.annotationStorage,t=this.data,n=t.id,r=e.getValue(n,{value:t.fieldValue===t.buttonValue}).value;if(typeof r==`string`&&(r=r!==t.buttonValue,e.setValue(n,{value:r})),r)for(let r of this._getElementsByName(t.fieldName,n))e.setValue(r.id,{value:!1});let i=document.createElement(`input`);if(Ef.add(i),i.setAttribute(`data-element-id`,n),i.disabled=t.readOnly,this._setRequired(i,this.data.required),i.type=`radio`,i.name=t.fieldName,r&&i.setAttribute(`checked`,!0),i.tabIndex=wf,i.addEventListener(`change`,t=>{let{name:r,checked:i}=t.target;for(let t of this._getElementsByName(r,n))e.setValue(t.id,{value:!1});e.setValue(n,{value:i})}),i.addEventListener(`resetform`,e=>{let n=t.defaultFieldValue;e.target.checked=n!=null&&n===t.buttonValue}),this.enableScripting&&this.hasJSActions){let r=t.buttonValue;i.addEventListener(`updatefromsandbox`,t=>{this._dispatchEventFromSandbox({value:t=>{let i=r===t.detail.value;for(let r of this._getElementsByName(t.target.name)){let t=i&&r.id===n;r.domElement&&(r.domElement.checked=t),e.setValue(r.id,{value:t})}}},t)}),this._setEventListeners(i,null,[[`change`,`Validate`],[`change`,`Action`],[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`]],e=>e.target.checked)}return this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}},Lf=class extends Af{constructor(e){super(e,{ignoreBorder:e.data.hasAppearance})}render(){let e=super.render();e.classList.add(`buttonWidgetAnnotation`,`pushButton`);let t=e.lastChild;return this.enableScripting&&this.hasJSActions&&t&&(this._setDefaultPropertiesFromJS(t),t.addEventListener(`updatefromsandbox`,e=>{this._dispatchEventFromSandbox({},e)})),e}},Rf=class extends Mf{constructor(e){super(e,{isRenderable:e.renderForms})}render(){this.container.classList.add(`choiceWidgetAnnotation`);let e=this.annotationStorage,t=this.data.id,n=e.getValue(t,{value:this.data.fieldValue}),r=document.createElement(`select`);Ef.add(r),r.setAttribute(`data-element-id`,t),r.disabled=this.data.readOnly,this._setRequired(r,this.data.required),r.name=this.data.fieldName,r.tabIndex=wf;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(r.size=this.data.options.length,this.data.multiSelect&&(r.multiple=!0)),r.addEventListener(`resetform`,e=>{let t=this.data.defaultFieldValue;for(let e of r.options)e.selected=e.value===t});for(let e of this.data.options){let t=document.createElement(`option`);t.textContent=e.displayValue,t.value=e.exportValue,n.value.includes(e.exportValue)&&(t.setAttribute(`selected`,!0),i=!1),r.append(t)}let a=null;if(i){let e=document.createElement(`option`);e.value=` `,e.setAttribute(`hidden`,!0),e.setAttribute(`selected`,!0),r.prepend(e),a=()=>{e.remove(),r.removeEventListener(`input`,a),a=null},r.addEventListener(`input`,a)}let o=e=>{let t=e?`value`:`textContent`,{options:n,multiple:i}=r;return i?Array.prototype.filter.call(n,e=>e.selected).map(e=>e[t]):n.selectedIndex===-1?null:n[n.selectedIndex][t]},s=o(!1),c=e=>{let t=e.target.options;return Array.prototype.map.call(t,e=>({displayValue:e.textContent,exportValue:e.value}))};return this.enableScripting&&this.hasJSActions?(r.addEventListener(`updatefromsandbox`,n=>{this._dispatchEventFromSandbox({value(n){a?.();let i=n.detail.value,c=new Set(Array.isArray(i)?i:[i]);for(let e of r.options)e.selected=c.has(e.value);e.setValue(t,{value:o(!0)}),s=o(!1)},multipleSelection(e){r.multiple=!0},remove(n){let i=r.options,a=n.detail.remove;i[a].selected=!1,r.remove(a),i.length>0&&Array.prototype.findIndex.call(i,e=>e.selected)===-1&&(i[0].selected=!0),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},clear(n){for(;r.length!==0;)r.remove(0);e.setValue(t,{value:null,items:[]}),s=o(!1)},insert(n){let{index:i,displayValue:a,exportValue:l}=n.detail.insert,u=r.children[i],d=document.createElement(`option`);d.textContent=a,d.value=l,u?u.before(d):r.append(d),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},items(n){let{items:i}=n.detail;for(;r.length!==0;)r.remove(0);for(let e of i){let{displayValue:t,exportValue:n}=e,i=document.createElement(`option`);i.textContent=t,i.value=n,r.append(i)}r.options.length>0&&(r.options[0].selected=!0),e.setValue(t,{value:o(!0),items:c(n)}),s=o(!1)},indices(n){let r=new Set(n.detail.indices);for(let e of n.target.options)e.selected=r.has(e.index);e.setValue(t,{value:o(!0)}),s=o(!1)},editable(e){e.target.disabled=!e.detail.editable}},n)}),r.addEventListener(`input`,n=>{let r=o(!0),i=o(!1);e.setValue(t,{value:r}),n.preventDefault(),this.linkService.eventBus?.dispatch(`dispatcheventinsandbox`,{source:this,detail:{id:t,name:`Keystroke`,value:s,change:i,changeEx:r,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(r,null,[[`focus`,`Focus`],[`blur`,`Blur`],[`mousedown`,`Mouse Down`],[`mouseenter`,`Mouse Enter`],[`mouseleave`,`Mouse Exit`],[`mouseup`,`Mouse Up`],[`input`,`Action`],[`input`,`Validate`]],e=>e.target.value)):r.addEventListener(`input`,function(n){e.setValue(t,{value:o(!0)})}),this.data.combo&&this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}},zf=class extends kf{constructor(e){let{data:t,elements:n}=e;super(e,{isRenderable:kf._hasPopupData(t)}),this.elements=n,this.popup=null}render(){this.container.classList.add(`popupAnnotation`);let e=this.popup=new Bf({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),t=[];for(let n of this.elements)n.popup=e,n.container.ariaHasPopup=`dialog`,t.push(n.data.id),n.addHighlightArea();return this.container.setAttribute(`aria-controls`,t.map(e=>`${wl}${e}`).join(`,`)),this.container}},Bf=class{#e=this.#C.bind(this);#t=this.#D.bind(this);#n=this.#E.bind(this);#r=this.#T.bind(this);#i=null;#a=null;#o=null;#s=null;#c=null;#l=null;#u=null;#d=!1;#f=null;#p=null;#m=null;#h=null;#g=null;#_=null;#v=!1;constructor({container:e,color:t,elements:n,titleObj:r,modificationDate:i,contentsObj:a,richText:o,parent:s,rect:c,parentRect:l,open:u}){this.#a=e,this.#g=r,this.#o=a,this.#h=o,this.#l=s,this.#i=t,this.#m=c,this.#u=l,this.#c=n,this.#s=zl.toDateObject(i),this.trigger=n.flatMap(e=>e.getElementsToTriggerPopup());for(let e of this.trigger)e.addEventListener(`click`,this.#r),e.addEventListener(`mouseenter`,this.#n),e.addEventListener(`mouseleave`,this.#t),e.classList.add(`popupTriggerArea`);for(let e of n)e.container?.addEventListener(`keydown`,this.#e);this.#a.hidden=!0,u&&this.#T()}render(){if(this.#f)return;let e=this.#f=document.createElement(`div`);if(e.className=`popup`,this.#i){let t=e.style.outlineColor=X.makeHexColor(...this.#i);CSS.supports(`background-color`,`color-mix(in srgb, red 30%, white)`)?e.style.backgroundColor=`color-mix(in srgb, ${t} 30%, white)`:e.style.backgroundColor=X.makeHexColor(...this.#i.map(e=>Math.floor(.7*(255-e)+e)))}let t=document.createElement(`span`);t.className=`header`;let n=document.createElement(`h1`);if(t.append(n),{dir:n.dir,str:n.textContent}=this.#g,e.append(t),this.#s){let e=document.createElement(`span`);e.classList.add(`popupDate`),e.setAttribute(`data-l10n-id`,`pdfjs-annotation-date-time-string`),e.setAttribute(`data-l10n-args`,JSON.stringify({dateObj:this.#s.valueOf()})),t.append(e)}let r=this.#y;if(r)Cf.render({xfaHtml:r,intent:`richText`,div:e}),e.lastChild.classList.add(`richText`,`popupContent`);else{let t=this._formatContents(this.#o);e.append(t)}this.#a.append(e)}get#y(){let e=this.#h,t=this.#o;return e?.str&&(!t?.str||t.str===e.str)&&this.#h.html||null}get#b(){return this.#y?.attributes?.style?.fontSize||0}get#x(){return this.#y?.attributes?.style?.color||null}#S(e){let t=[],n={str:e,html:{name:`div`,attributes:{dir:`auto`},children:[{name:`p`,children:t}]}},r={style:{color:this.#x,fontSize:this.#b?`calc(${this.#b}px * var(--scale-factor))`:``}};for(let n of e.split(`
|
|
441
|
+
`))t.push({name:`span`,value:n,attributes:r});return n}_formatContents({str:e,dir:t}){let n=document.createElement(`p`);n.classList.add(`popupContent`),n.dir=t;let r=e.split(/(?:\r\n?|\n)/);for(let e=0,t=r.length;e<t;++e){let i=r[e];n.append(document.createTextNode(i)),e<t-1&&n.append(document.createElement(`br`))}return n}#C(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key===`Enter`||e.key===`Escape`&&this.#d)&&this.#T()}updateEdited({rect:e,popupContent:t}){this.#_||={contentsObj:this.#o,richText:this.#h},e&&(this.#p=null),t&&(this.#h=this.#S(t),this.#o=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#_&&({contentsObj:this.#o,richText:this.#h}=this.#_,this.#_=null,this.#f?.remove(),this.#f=null,this.#p=null)}#w(){if(this.#p!==null)return;let{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:r,pageY:i}}}=this.#l,a=!!this.#u,o=a?this.#u:this.#m;for(let e of this.#c)if(!o||X.intersect(e.data.rect,o)!==null){o=e.data.rect,a=!0;break}let s=X.normalizeRect([o[0],e[3]-o[1]+e[1],o[2],e[3]-o[3]+e[1]]),c=a?o[2]-o[0]+5:0,l=s[0]+c,u=s[1];this.#p=[100*(l-r)/t,100*(u-i)/n];let{style:d}=this.#a;d.left=`${this.#p[0]}%`,d.top=`${this.#p[1]}%`}#T(){this.#d=!this.#d,this.#d?(this.#E(),this.#a.addEventListener(`click`,this.#r),this.#a.addEventListener(`keydown`,this.#e)):(this.#D(),this.#a.removeEventListener(`click`,this.#r),this.#a.removeEventListener(`keydown`,this.#e))}#E(){this.#f||this.render(),this.isVisible?this.#d&&this.#a.classList.add(`focused`):(this.#w(),this.#a.hidden=!1,this.#a.style.zIndex=parseInt(this.#a.style.zIndex)+1e3)}#D(){this.#a.classList.remove(`focused`),!(this.#d||!this.isVisible)&&(this.#a.hidden=!0,this.#a.style.zIndex=parseInt(this.#a.style.zIndex)-1e3)}forceHide(){this.#v=this.isVisible,this.#v&&(this.#a.hidden=!0)}maybeShow(){this.#v&&(this.#f||this.#E(),this.#v=!1,this.#a.hidden=!1)}get isVisible(){return this.#a.hidden===!1}},Vf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=W.FREETEXT}render(){if(this.container.classList.add(`freeTextAnnotation`),this.textContent){let e=document.createElement(`div`);e.classList.add(`annotationTextContent`),e.setAttribute(`role`,`comment`);for(let t of this.textContent){let n=document.createElement(`span`);n.textContent=t,e.append(n)}this.container.append(e)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},Hf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`lineAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=this.#e=this.svgFactory.createElement(`svg:line`);return i.setAttribute(`x1`,e.rect[2]-e.lineCoordinates[0]),i.setAttribute(`y1`,e.rect[3]-e.lineCoordinates[1]),i.setAttribute(`x2`,e.rect[2]-e.lineCoordinates[2]),i.setAttribute(`y2`,e.rect[3]-e.lineCoordinates[3]),i.setAttribute(`stroke-width`,e.borderStyle.width||1),i.setAttribute(`stroke`,`transparent`),i.setAttribute(`fill`,`transparent`),r.append(i),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Uf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`squareAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:rect`);return a.setAttribute(`x`,i/2),a.setAttribute(`y`,i/2),a.setAttribute(`width`,t-i),a.setAttribute(`height`,n-i),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Wf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add(`circleAnnotation`);let e=this.data,{width:t,height:n}=Df(e.rect),r=this.svgFactory.create(t,n,!0),i=e.borderStyle.width,a=this.#e=this.svgFactory.createElement(`svg:ellipse`);return a.setAttribute(`cx`,t/2),a.setAttribute(`cy`,n/2),a.setAttribute(`rx`,t/2-i/2),a.setAttribute(`ry`,n/2-i/2),a.setAttribute(`stroke-width`,i||1),a.setAttribute(`stroke`,`transparent`),a.setAttribute(`fill`,`transparent`),r.append(a),this.container.append(r),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Gf=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`polylineAnnotation`,this.svgElementName=`svg:polyline`}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,vertices:t,borderStyle:n,popupRef:r}}=this;if(!t)return this.container;let{width:i,height:a}=Df(e),o=this.svgFactory.create(i,a,!0),s=[];for(let n=0,r=t.length;n<r;n+=2){let r=t[n]-e[0],i=e[3]-t[n+1];s.push(`${r},${i}`)}s=s.join(` `);let c=this.#e=this.svgFactory.createElement(this.svgElementName);return c.setAttribute(`points`,s),c.setAttribute(`stroke-width`,n.width||1),c.setAttribute(`stroke`,`transparent`),c.setAttribute(`fill`,`transparent`),o.append(c),this.container.append(o),!r&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Kf=class extends Gf{constructor(e){super(e),this.containerClassName=`polygonAnnotation`,this.svgElementName=`svg:polygon`}},qf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add(`caretAnnotation`),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}},Jf=class extends kf{#e=null;#t=[];constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName=`inkAnnotation`,this.svgElementName=`svg:polyline`,this.annotationEditorType=this.data.it===`InkHighlight`?W.HIGHLIGHT:W.INK}#n(e,t){switch(e){case 90:return{transform:`rotate(90) translate(${-t[0]},${t[1]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};case 180:return{transform:`rotate(180) translate(${-t[2]},${t[1]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]};case 270:return{transform:`rotate(270) translate(${-t[2]},${t[3]}) scale(1,-1)`,width:t[3]-t[1],height:t[2]-t[0]};default:return{transform:`translate(${-t[0]},${t[3]}) scale(1,-1)`,width:t[2]-t[0],height:t[3]-t[1]}}}render(){this.container.classList.add(this.containerClassName);let{data:{rect:e,rotation:t,inkLists:n,borderStyle:r,popupRef:i}}=this,{transform:a,width:o,height:s}=this.#n(t,e),c=this.svgFactory.create(o,s,!0),l=this.#e=this.svgFactory.createElement(`svg:g`);c.append(l),l.setAttribute(`stroke-width`,r.width||1),l.setAttribute(`stroke-linecap`,`round`),l.setAttribute(`stroke-linejoin`,`round`),l.setAttribute(`stroke-miterlimit`,10),l.setAttribute(`stroke`,`transparent`),l.setAttribute(`fill`,`transparent`),l.setAttribute(`transform`,a);for(let e=0,t=n.length;e<t;e++){let t=this.svgFactory.createElement(this.svgElementName);this.#t.push(t),t.setAttribute(`points`,n[e].join(`,`)),l.append(t)}return!i&&this.hasPopupData&&this._createPopup(),this.container.append(c),this._editOnDoubleClick(),this.container}updateEdited(e){super.updateEdited(e);let{thickness:t,points:n,rect:r}=e,i=this.#e;if(t>=0&&i.setAttribute(`stroke-width`,t||1),n)for(let e=0,t=this.#t.length;e<t;e++)this.#t[e].setAttribute(`points`,n[e].join(`,`));if(r){let{transform:e,width:t,height:n}=this.#n(this.data.rotation,r);i.parentElement.setAttribute(`viewBox`,`0 0 ${t} ${n}`),i.setAttribute(`transform`,e)}}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add(`highlightArea`)}},Yf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=W.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`highlightAnnotation`),this._editOnDoubleClick(),this.container}},Xf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`underlineAnnotation`),this.container}},Zf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`squigglyAnnotation`),this.container}},Qf=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add(`strikeoutAnnotation`),this.container}},$f=class extends kf{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=W.STAMP}render(){return this.container.classList.add(`stampAnnotation`),this.container.setAttribute(`role`,`img`),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}},ep=class extends kf{#e=null;constructor(e){super(e,{isRenderable:!0});let{file:t}=this.data;this.filename=t.filename,this.content=t.content,this.linkService.eventBus?.dispatch(`fileattachmentannotation`,{source:this,...t})}render(){this.container.classList.add(`fileAttachmentAnnotation`);let{container:e,data:t}=this,n;t.hasAppearance||t.fillAlpha===0?n=document.createElement(`div`):(n=document.createElement(`img`),n.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(t.name)?`paperclip`:`pushpin`}.svg`,t.fillAlpha&&t.fillAlpha<1&&(n.style=`filter: opacity(${Math.round(t.fillAlpha*100)}%);`)),n.addEventListener(`dblclick`,this.#t.bind(this)),this.#e=n;let{isMac:r}=_l.platform;return e.addEventListener(`keydown`,e=>{e.key===`Enter`&&(r?e.metaKey:e.ctrlKey)&&this.#t()}),!t.popupRef&&this.hasPopupData?this._createPopup():n.classList.add(`popupTriggerArea`),e.append(n),e}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add(`highlightArea`)}#t(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}},tp=class{#e=null;#t=null;#n=new Map;#r=null;constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:r,page:i,viewport:a,structTreeLayer:o}){this.div=e,this.#e=t,this.#t=n,this.#r=o||null,this.page=i,this.viewport=a,this.zIndex=0,this._annotationEditorUIManager=r}hasEditableAnnotations(){return this.#n.size>0}async#i(e,t){let n=e.firstChild||e,r=n.id=`${wl}${t}`,i=await this.#r?.getAriaAttributes(r);if(i)for(let[e,t]of i)n.setAttribute(e,t);this.div.append(e),this.#e?.moveElementInDOM(this.div,e,n,!1)}async render(e){let{annotations:t}=e,n=this.div;Wl(n,this.viewport);let r=new Map,i={data:null,layer:n,linkService:e.linkService,downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||``,renderForms:e.renderForms!==!1,svgFactory:new Sf,annotationStorage:e.annotationStorage||new lu,enableScripting:e.enableScripting===!0,hasJSActions:e.hasJSActions,fieldObjects:e.fieldObjects,parent:this,elements:null};for(let e of t){if(e.noHTML)continue;let t=e.annotationType===Kc.POPUP;if(t){let t=r.get(e.id);if(!t)continue;i.elements=t}else{let{width:t,height:n}=Df(e.rect);if(t<=0||n<=0)continue}i.data=e;let n=Of.create(i);if(!n.isRenderable)continue;if(!t&&e.popupRef){let t=r.get(e.popupRef);t?t.push(n):r.set(e.popupRef,[n])}let a=n.render();e.hidden&&(a.style.visibility=`hidden`),await this.#i(a,e.id),n._isEditable&&(this.#n.set(n.data.id,n),this._annotationEditorUIManager?.renderAnnotationElement(n))}this.#a()}update({viewport:e}){let t=this.div;this.viewport=e,Wl(t,{rotation:e.rotation}),this.#a(),t.hidden=!1}#a(){if(!this.#t)return;let e=this.div;for(let[t,n]of this.#t){let r=e.querySelector(`[data-annotation-id="${t}"]`);if(!r)continue;n.className=`annotationContent`;let{firstChild:i}=r;i?i.nodeName===`CANVAS`?i.replaceWith(n):i.classList.contains(`annotationContent`)?i.after(n):i.before(n):r.append(n)}this.#t.clear()}getEditableAnnotations(){return Array.from(this.#n.values())}getEditableAnnotation(e){return this.#n.get(e)}},np=/\r\n?|\n/g,rp=class e extends Q{#e;#t=``;#n=`${this.id}-editor`;#r=null;#i;static _freeTextDefaultContent=``;static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let t=e.prototype,n=e=>e.isEmpty(),r=eu.TRANSLATE_SMALL,i=eu.TRANSLATE_BIG;return Y(this,`_keyboardManager`,new Ql([[[`ctrl+s`,`mac+meta+s`,`ctrl+p`,`mac+meta+p`],t.commitOrRemove,{bubbles:!0}],[[`ctrl+Enter`,`mac+meta+Enter`,`Escape`,`mac+Escape`],t.commitOrRemove],[[`ArrowLeft`,`mac+ArrowLeft`],t._translateEmpty,{args:[-r,0],checker:n}],[[`ctrl+ArrowLeft`,`mac+shift+ArrowLeft`],t._translateEmpty,{args:[-i,0],checker:n}],[[`ArrowRight`,`mac+ArrowRight`],t._translateEmpty,{args:[r,0],checker:n}],[[`ctrl+ArrowRight`,`mac+shift+ArrowRight`],t._translateEmpty,{args:[i,0],checker:n}],[[`ArrowUp`,`mac+ArrowUp`],t._translateEmpty,{args:[0,-r],checker:n}],[[`ctrl+ArrowUp`,`mac+shift+ArrowUp`],t._translateEmpty,{args:[0,-i],checker:n}],[[`ArrowDown`,`mac+ArrowDown`],t._translateEmpty,{args:[0,r],checker:n}],[[`ctrl+ArrowDown`,`mac+shift+ArrowDown`],t._translateEmpty,{args:[0,i],checker:n}]]))}static _type=`freetext`;static _editorType=W.FREETEXT;constructor(t){super({...t,name:`freeTextEditor`}),this.#e=t.color||e._defaultColor||Q._defaultLineColor,this.#i=t.fontSize||e._defaultFontSize}static initialize(e,t){Q.initialize(e,t);let n=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(n.getPropertyValue(`--freetext-padding`))}static updateDefaultParams(t,n){switch(t){case G.FREETEXT_SIZE:e._defaultFontSize=n;break;case G.FREETEXT_COLOR:e._defaultColor=n}}updateParams(e,t){switch(e){case G.FREETEXT_SIZE:this.#a(t);break;case G.FREETEXT_COLOR:this.#o(t)}}static get defaultPropertiesToUpdate(){return[[G.FREETEXT_SIZE,e._defaultFontSize],[G.FREETEXT_COLOR,e._defaultColor||Q._defaultLineColor]]}get propertiesToUpdate(){return[[G.FREETEXT_SIZE,this.#i],[G.FREETEXT_COLOR,this.#e]]}#a(e){let t=e=>{this.editorDiv.style.fontSize=`calc(${e}px * var(--scale-factor))`,this.translate(0,-(e-this.#i)*this.parentScale),this.#i=e,this.#c()},n=this.#i;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#o(e){let t=e=>{this.#e=this.editorDiv.style.color=e},n=this.#e;this.addCommands({cmd:t.bind(this,e),undo:t.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(e,t){this._uiManager.translateSelectedEditors(e,t,!0)}getInitialTranslation(){let t=this.parentScale;return[-e._internalPadding*t,-(e._internalPadding+this.#i)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(W.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove(`enabled`),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute(`aria-activedescendant`),this.#r=new AbortController;let e=this._uiManager.combinedSignal(this.#r);this.editorDiv.addEventListener(`keydown`,this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener(`focus`,this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener(`blur`,this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener(`input`,this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener(`paste`,this.editorDivPaste.bind(this),{signal:e})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add(`enabled`),this.editorDiv.contentEditable=!1,this.div.setAttribute(`aria-activedescendant`,this.#n),this._isDraggable=!0,this.#r?.abort(),this.#r=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add(`freetextEditing`))}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(e){this.width||(this.enableEditMode(),e&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===``}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add(`freetextEditing`)),super.remove()}#s(){let t=[];this.editorDiv.normalize();let n=null;for(let r of this.editorDiv.childNodes)(n?.nodeType!==Node.TEXT_NODE||r.nodeName!==`BR`)&&(t.push(e.#l(r)),n=r);return t.join(`
|
|
442
|
+
`)}#c(){let[e,t]=this.parentDimensions,n;if(this.isAttachedToDOM)n=this.div.getBoundingClientRect();else{let{currentLayer:e,div:t}=this,r=t.style.display,i=t.classList.contains(`hidden`);t.classList.remove(`hidden`),t.style.display=`hidden`,e.div.append(this.div),n=t.getBoundingClientRect(),t.remove(),t.style.display=r,t.classList.toggle(`hidden`,i)}this.rotation%180==this.parentRotation%180?(this.width=n.width/e,this.height=n.height/t):(this.width=n.height/e,this.height=n.width/t),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let e=this.#t,t=this.#t=this.#s().trimEnd();if(e===t)return;let n=e=>{if(this.#t=e,!e){this.remove();return}this.#u(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{n(t)},undo:()=>{n(e)},mustExec:!1}),this.#c()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(e){this.enterInEditMode()}keydown(e){e.target===this.div&&e.key===`Enter`&&(this.enterInEditMode(),e.preventDefault())}editorDivKeydown(t){e._keyboardManager.exec(this,t)}editorDivFocus(e){this.isEditing=!0}editorDivBlur(e){this.isEditing=!1}editorDivInput(e){this.parent.div.classList.toggle(`freetextEditing`,this.isEmpty())}disableEditing(){this.editorDiv.setAttribute(`role`,`comment`),this.editorDiv.removeAttribute(`aria-multiline`)}enableEditing(){this.editorDiv.setAttribute(`role`,`textbox`),this.editorDiv.setAttribute(`aria-multiline`,!0)}render(){if(this.div)return this.div;let e,t;this.width&&(e=this.x,t=this.y),super.render(),this.editorDiv=document.createElement(`div`),this.editorDiv.className=`internal`,this.editorDiv.setAttribute(`id`,this.#n),this.editorDiv.setAttribute(`data-l10n-id`,`pdfjs-free-text2`),this.editorDiv.setAttribute(`data-l10n-attrs`,`default-content`),this.enableEditing(),this.editorDiv.contentEditable=!0;let{style:n}=this.editorDiv;if(n.fontSize=`calc(${this.#i}px * var(--scale-factor))`,n.color=this.#e,this.div.append(this.editorDiv),this.overlayDiv=document.createElement(`div`),this.overlayDiv.classList.add(`overlay`,`enabled`),this.div.append(this.overlayDiv),Jl(this,this.div,[`dblclick`,`keydown`]),this.width){let[n,r]=this.parentDimensions;if(this.annotationElementId){let{position:i}=this._initialData,[a,o]=this.getInitialTranslation();[a,o]=this.pageTranslationToScreen(a,o);let[s,c]=this.pageDimensions,[l,u]=this.pageTranslation,d,f;switch(this.rotation){case 0:d=e+(i[0]-l)/s,f=t+this.height-(i[1]-u)/c;break;case 90:d=e+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[o,-a];break;case 180:d=e-this.width+(i[0]-l)/s,f=t-(i[1]-u)/c,[a,o]=[-a,-o];break;case 270:d=e+(i[0]-l-this.height*c)/s,f=t+(i[1]-u-this.width*s)/c,[a,o]=[-o,a]}this.setAt(d*n,f*r,a,o)}else this.setAt(e*n,t*r,this.width*n,this.height*r);this.#u(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#l(e){return(e.nodeType===Node.TEXT_NODE?e.nodeValue:e.innerText).replaceAll(np,``)}editorDivPaste(t){let n=t.clipboardData||window.clipboardData,{types:r}=n;if(r.length===1&&r[0]===`text/plain`)return;t.preventDefault();let i=e.#f(n.getData(`text`)||``).replaceAll(np,`
|
|
443
443
|
`);if(!i)return;let a=window.getSelection();if(!a.rangeCount)return;this.editorDiv.normalize(),a.deleteFromDocument();let o=a.getRangeAt(0);if(!i.includes(`
|
|
444
444
|
`)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),a.collapseToStart();return}let{startContainer:s,startOffset:c}=o,l=[],u=[];if(s.nodeType===Node.TEXT_NODE){let t=s.parentElement;if(u.push(s.nodeValue.slice(c).replaceAll(np,``)),t!==this.editorDiv){let n=l;for(let r of this.editorDiv.childNodes){if(r===t){n=u;continue}n.push(e.#l(r))}}l.push(s.nodeValue.slice(0,c).replaceAll(np,``))}else if(s===this.editorDiv){let t=l,n=0;for(let r of this.editorDiv.childNodes)n++===c&&(t=u),t.push(e.#l(r))}this.#t=`${l.join(`
|
|
445
445
|
`)}${i}${u.join(`
|
|
446
446
|
`)}`,this.#u();let d=new Range,f=l.reduce((e,t)=>e+t.length,0);for(let{firstChild:e}of this.editorDiv.childNodes)if(e.nodeType===Node.TEXT_NODE){let t=e.nodeValue.length;if(f<=t){d.setStart(e,f),d.setEnd(e,f);break}f-=t}a.removeAllRanges(),a.addRange(d)}#u(){if(this.editorDiv.replaceChildren(),this.#t)for(let e of this.#t.split(`
|
|
447
|
-
`)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),this.editorDiv.append(t)}}#d(){return this.#t.replaceAll(`\xA0`,` `)}static#f(e){return e.replaceAll(` `,`\xA0`)}get contentDiv(){return this.editorDiv}static async deserialize(t,n,r){let i=null;if(t instanceof Vf){let{data:{defaultAppearanceData:{fontSize:e,fontColor:n},rect:r,rotation:a,id:o,popupRef:s},textContent:c,textPosition:l,parent:{page:{pageNumber:u}}}=t;if(!c||c.length===0)return null;i=t={annotationType:
|
|
448
|
-
`),position:l,pageIndex:u-1,rect:r.slice(0),rotation:a,id:o,deleted:!1,popupRef:s}}let a=await super.deserialize(t,n,r);return a.#i=t.fontSize,a.#e=X.makeHexColor(...t.color),a.#t=e.#f(t.value),a.annotationElementId=t.id||null,a._initialData=i,a}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n=e._internalPadding*this.parentScale,r=this.getRect(n,n),i=Q._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#e),a={annotationType:
|
|
449
|
-
`)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),n.append(t)}let i=e._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#t}),n}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}},$=class{static PRECISION=1e-4;toSVGPath(){J("Abstract method `toSVGPath` must be implemented.")}get box(){J("Abstract getter `box` must be implemented.")}serialize(e,t){J("Abstract method `serialize` must be implemented.")}static _rescale(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o<s;o+=2)a[o]=t+e[o]*r,a[o+1]=n+e[o+1]*i;return a}static _rescaleAndSwap(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o<s;o+=2)a[o]=t+e[o+1]*r,a[o+1]=n+e[o]*i;return a}static _translate(e,t,n,r){r||=new Float32Array(e.length);for(let i=0,a=e.length;i<a;i+=2)r[i]=t+e[i],r[i+1]=n+e[i+1];return r}static svgRound(e){return Math.round(e*1e4)}static _normalizePoint(e,t,n,r,i){switch(i){case 90:return[1-t/n,e/r];case 180:return[1-e/n,1-t/r];case 270:return[t/n,1-e/r];default:return[e/n,t/r]}}static _normalizePagePoint(e,t,n){switch(n){case 90:return[1-t,e];case 180:return[1-e,1-t];case 270:return[t,1-e];default:return[e,t]}}static createBezierPoints(e,t,n,r,i,a){return[(e+5*n)/6,(t+5*r)/6,(5*n+i)/6,(5*r+a)/6,(n+i)/2,(r+a)/2]}},ip=class e{#e;#t=[];#n;#r;#i=[];#a=new Float32Array(18);#o;#s;#c;#l;#u;#d;#f=[];static#p=8;static#m=2;static#h=e.#p+e.#m;constructor({x:t,y:n},r,i,a,o,s=0){this.#e=r,this.#d=a*i,this.#r=o,this.#a.set([NaN,NaN,NaN,NaN,t,n],6),this.#n=s,this.#l=e.#p*i,this.#c=e.#h*i,this.#u=i,this.#f.push(t,n)}isEmpty(){return isNaN(this.#a[8])}#g(){let e=this.#a.subarray(4,6),t=this.#a.subarray(16,18),[n,r,i,a]=this.#e;return[(this.#o+(e[0]-t[0])/2-n)/i,(this.#s+(e[1]-t[1])/2-r)/a,(this.#o+(t[0]-e[0])/2-n)/i,(this.#s+(t[1]-e[1])/2-r)/a]}add({x:e,y:t}){this.#o=e,this.#s=t;let[n,r,i,a]=this.#e,[o,s,c,l]=this.#a.subarray(8,12),u=e-c,d=t-l,f=Math.hypot(u,d);if(f<this.#c)return!1;let p=f-this.#l,m=p/f,h=m*u,g=m*d,_=o,v=s;o=c,s=l,c+=h,l+=g,this.#f?.push(e,t);let y=-g/p,b=h/p,x=y*this.#d,S=b*this.#d;return this.#a.set(this.#a.subarray(2,8),0),this.#a.set([c+x,l+S],4),this.#a.set(this.#a.subarray(14,18),12),this.#a.set([c-x,l-S],16),isNaN(this.#a[6])?(this.#i.length===0&&(this.#a.set([o+x,s+S],2),this.#i.push(NaN,NaN,NaN,NaN,(o+x-n)/i,(s+S-r)/a),this.#a.set([o-x,s-S],14),this.#t.push(NaN,NaN,NaN,NaN,(o-x-n)/i,(s-S-r)/a)),this.#a.set([_,v,o,s,c,l],6),!this.isEmpty()):(this.#a.set([_,v,o,s,c,l],6),Math.abs(Math.atan2(v-s,_-o)-Math.atan2(g,h))<Math.PI/2?([o,s,c,l]=this.#a.subarray(2,6),this.#i.push(NaN,NaN,NaN,NaN,((o+c)/2-n)/i,((s+l)/2-r)/a),[o,s,_,v]=this.#a.subarray(14,18),this.#t.push(NaN,NaN,NaN,NaN,((_+o)/2-n)/i,((v+s)/2-r)/a),!0):([_,v,o,s,c,l]=this.#a.subarray(0,6),this.#i.push(((_+5*o)/6-n)/i,((v+5*s)/6-r)/a,((5*o+c)/6-n)/i,((5*s+l)/6-r)/a,((o+c)/2-n)/i,((s+l)/2-r)/a),[c,l,o,s,_,v]=this.#a.subarray(12,18),this.#t.push(((_+5*o)/6-n)/i,((v+5*s)/6-r)/a,((5*o+c)/6-n)/i,((5*s+l)/6-r)/a,((o+c)/2-n)/i,((s+l)/2-r)/a),!0))}toSVGPath(){if(this.isEmpty())return``;let e=this.#i,t=this.#t;if(isNaN(this.#a[6])&&!this.isEmpty())return this.#_();let n=[];n.push(`M${e[4]} ${e[5]}`);for(let t=6;t<e.length;t+=6)isNaN(e[t])?n.push(`L${e[t+4]} ${e[t+5]}`):n.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#y(n);for(let e=t.length-6;e>=6;e-=6)isNaN(t[e])?n.push(`L${t[e+4]} ${t[e+5]}`):n.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);return this.#v(n),n.join(` `)}#_(){let[e,t,n,r]=this.#e,[i,a,o,s]=this.#g();return`M${(this.#a[2]-e)/n} ${(this.#a[3]-t)/r} L${(this.#a[4]-e)/n} ${(this.#a[5]-t)/r} L${i} ${a} L${o} ${s} L${(this.#a[16]-e)/n} ${(this.#a[17]-t)/r} L${(this.#a[14]-e)/n} ${(this.#a[15]-t)/r} Z`}#v(e){let t=this.#t;e.push(`L${t[4]} ${t[5]} Z`)}#y(e){let[t,n,r,i]=this.#e,a=this.#a.subarray(4,6),o=this.#a.subarray(16,18),[s,c,l,u]=this.#g();e.push(`L${(a[0]-t)/r} ${(a[1]-n)/i} L${s} ${c} L${l} ${u} L${(o[0]-t)/r} ${(o[1]-n)/i}`)}newFreeDrawOutline(e,t,n,r,i,a){return new ap(e,t,n,r,i,a)}getOutlines(){let e=this.#i,t=this.#t,n=this.#a,[r,i,a,o]=this.#e,s=new Float32Array((this.#f?.length??0)+2);for(let e=0,t=s.length-2;e<t;e+=2)s[e]=(this.#f[e]-r)/a,s[e+1]=(this.#f[e+1]-i)/o;if(s[s.length-2]=(this.#o-r)/a,s[s.length-1]=(this.#s-i)/o,isNaN(n[6])&&!this.isEmpty())return this.#b(s);let c=new Float32Array(this.#i.length+24+this.#t.length),l=e.length;for(let t=0;t<l;t+=2){if(isNaN(e[t])){c[t]=c[t+1]=NaN;continue}c[t]=e[t],c[t+1]=e[t+1]}l=this.#S(c,l);for(let e=t.length-6;e>=6;e-=6)for(let n=0;n<6;n+=2){if(isNaN(t[e+n])){c[l]=c[l+1]=NaN,l+=2;continue}c[l]=t[e+n],c[l+1]=t[e+n+1],l+=2}return this.#x(c,l),this.newFreeDrawOutline(c,s,this.#e,this.#u,this.#n,this.#r)}#b(e){let t=this.#a,[n,r,i,a]=this.#e,[o,s,c,l]=this.#g(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(t[2]-n)/i,(t[3]-r)/a,NaN,NaN,NaN,NaN,(t[4]-n)/i,(t[5]-r)/a,NaN,NaN,NaN,NaN,o,s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,(t[16]-n)/i,(t[17]-r)/a,NaN,NaN,NaN,NaN,(t[14]-n)/i,(t[15]-r)/a],0),this.newFreeDrawOutline(u,e,this.#e,this.#u,this.#n,this.#r)}#x(e,t){let n=this.#t;return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6}#S(e,t){let n=this.#a.subarray(4,6),r=this.#a.subarray(16,18),[i,a,o,s]=this.#e,[c,l,u,d]=this.#g();return e.set([NaN,NaN,NaN,NaN,(n[0]-i)/o,(n[1]-a)/s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-a)/s],t),t+=24}},ap=class extends ${#e;#t=new Float32Array(4);#n;#r;#i;#a;#o;constructor(e,t,n,r,i,a){super(),this.#o=e,this.#i=t,this.#e=n,this.#a=r,this.#n=i,this.#r=a,this.lastPoint=[NaN,NaN],this.#s(a);let[o,s,c,l]=this.#t;for(let t=0,n=e.length;t<n;t+=2)e[t]=(e[t]-o)/c,e[t+1]=(e[t+1]-s)/l;for(let e=0,n=t.length;e<n;e+=2)t[e]=(t[e]-o)/c,t[e+1]=(t[e+1]-s)/l}toSVGPath(){let e=[`M${this.#o[4]} ${this.#o[5]}`];for(let t=6,n=this.#o.length;t<n;t+=6){if(isNaN(this.#o[t])){e.push(`L${this.#o[t+4]} ${this.#o[t+5]}`);continue}e.push(`C${this.#o[t]} ${this.#o[t+1]} ${this.#o[t+2]} ${this.#o[t+3]} ${this.#o[t+4]} ${this.#o[t+5]}`)}return e.push(`Z`),e.join(` `)}serialize([e,t,n,r],i){let a=n-e,o=r-t,s,c;switch(i){case 0:s=$._rescale(this.#o,e,r,a,-o),c=$._rescale(this.#i,e,r,a,-o);break;case 90:s=$._rescaleAndSwap(this.#o,e,t,a,o),c=$._rescaleAndSwap(this.#i,e,t,a,o);break;case 180:s=$._rescale(this.#o,n,t,-a,o),c=$._rescale(this.#i,n,t,-a,o);break;case 270:s=$._rescaleAndSwap(this.#o,n,r,-a,-o),c=$._rescaleAndSwap(this.#i,n,r,-a,-o);break}return{outline:Array.from(s),points:[Array.from(c)]}}#s(e){let t=this.#o,n=t[4],r=t[5],i=n,a=r,o=n,s=r,c=n,l=r,u=e?Math.max:Math.min;for(let e=6,d=t.length;e<d;e+=6){if(isNaN(t[e]))i=Math.min(i,t[e+4]),a=Math.min(a,t[e+5]),o=Math.max(o,t[e+4]),s=Math.max(s,t[e+5]),l<t[e+5]?(c=t[e+4],l=t[e+5]):l===t[e+5]&&(c=u(c,t[e+4]));else{let d=X.bezierBoundingBox(n,r,...t.slice(e,e+6));i=Math.min(i,d[0]),a=Math.min(a,d[1]),o=Math.max(o,d[2]),s=Math.max(s,d[3]),l<d[3]?(c=d[2],l=d[3]):l===d[3]&&(c=u(c,d[2]))}n=t[e+4],r=t[e+5]}let d=this.#t;d[0]=i-this.#n,d[1]=a-this.#n,d[2]=o-i+2*this.#n,d[3]=s-a+2*this.#n,this.lastPoint=[c,l]}get box(){return this.#t}newOutliner(e,t,n,r,i,a=0){return new ip(e,t,n,r,i,a)}getNewOutline(e,t){let[n,r,i,a]=this.#t,[o,s,c,l]=this.#e,u=i*c,d=a*l,f=n*c+o,p=r*l+s,m=this.newOutliner({x:this.#i[0]*u+f,y:this.#i[1]*d+p},this.#e,this.#a,e,this.#r,t??this.#n);for(let e=2;e<this.#i.length;e+=2)m.add({x:this.#i[e]*u+f,y:this.#i[e+1]*d+p});return m.getOutlines()}},op=class{#e;#t;#n=[];#r=[];constructor(e,t=0,n=0,r=!0){let i=1/0,a=-1/0,o=1/0,s=-1/0,c=10**-4;for(let{x:n,y:r,width:l,height:u}of e){let e=Math.floor((n-t)/c)*c,d=Math.ceil((n+l+t)/c)*c,f=Math.floor((r-t)/c)*c,p=Math.ceil((r+u+t)/c)*c,m=[e,f,p,!0],h=[d,f,p,!1];this.#n.push(m,h),i=Math.min(i,e),a=Math.max(a,d),o=Math.min(o,f),s=Math.max(s,p)}let l=a-i+2*n,u=s-o+2*n,d=i-n,f=o-n,p=this.#n.at(r?-1:-2),m=[p[0],p[2]];for(let e of this.#n){let[t,n,r]=e;e[0]=(t-d)/l,e[1]=(n-f)/u,e[2]=(r-f)/u}this.#e=new Float32Array([d,f,l,u]),this.#t=m}getOutlines(){this.#n.sort((e,t)=>e[0]-t[0]||e[1]-t[1]||e[2]-t[2]);let e=[];for(let t of this.#n)t[3]?(e.push(...this.#c(t)),this.#o(t)):(this.#s(t),e.push(...this.#c(t)));return this.#i(e)}#i(e){let t=[],n=new Set;for(let n of e){let[e,r,i]=n;t.push([e,r,n],[e,i,n])}t.sort((e,t)=>e[1]-t[1]||e[0]-t[0]);for(let e=0,r=t.length;e<r;e+=2){let r=t[e][2],i=t[e+1][2];r.push(i),i.push(r),n.add(r),n.add(i)}let r=[],i;for(;n.size>0;){let e=n.values().next().value,[t,a,o,s,c]=e;n.delete(e);let l=t,u=a;for(i=[t,o],r.push(i);;){let e;if(n.has(s))e=s;else if(n.has(c))e=c;else break;n.delete(e),[t,a,o,s,c]=e,l!==t&&(i.push(l,u,t,u===a?a:o),l=t),u=u===a?o:a}i.push(l,u)}return new sp(r,this.#e,this.#t)}#a(e){let t=this.#r,n=0,r=t.length-1;for(;n<=r;){let i=n+r>>1,a=t[i][0];if(a===e)return i;a<e?n=i+1:r=i-1}return r+1}#o([,e,t]){let n=this.#a(e);this.#r.splice(n,0,[e,t])}#s([,e,t]){let n=this.#a(e);for(let r=n;r<this.#r.length;r++){let[n,i]=this.#r[r];if(n!==e)break;if(n===e&&i===t){this.#r.splice(r,1);return}}for(let r=n-1;r>=0;r--){let[n,i]=this.#r[r];if(n!==e)break;if(n===e&&i===t){this.#r.splice(r,1);return}}}#c(e){let[t,n,r]=e,i=[[t,n,r]],a=this.#a(r);for(let e=0;e<a;e++){let[n,r]=this.#r[e];for(let e=0,a=i.length;e<a;e++){let[,o,s]=i[e];if(!(r<=o||s<=n)){if(o>=n){if(s>r)i[e][1]=r;else{if(a===1)return[];i.splice(e,1),e--,a--}continue}i[e][2]=n,s>r&&i.push([t,r,s])}}}return i}},sp=class extends ${#e;#t;constructor(e,t,n){super(),this.#t=e,this.#e=t,this.lastPoint=n}toSVGPath(){let e=[];for(let t of this.#t){let[n,r]=t;e.push(`M${n} ${r}`);for(let i=2;i<t.length;i+=2){let a=t[i],o=t[i+1];a===n?(e.push(`V${o}`),r=o):o===r&&(e.push(`H${a}`),n=a)}e.push(`Z`)}return e.join(` `)}serialize([e,t,n,r],i){let a=[],o=n-e,s=r-t;for(let t of this.#t){let n=Array(t.length);for(let i=0;i<t.length;i+=2)n[i]=e+t[i]*o,n[i+1]=r-t[i+1]*s;a.push(n)}return a}get box(){return this.#e}get classNamesForOutlining(){return[`highlightOutline`]}},cp=class extends ip{newFreeDrawOutline(e,t,n,r,i,a){return new lp(e,t,n,r,i,a)}},lp=class extends ap{newOutliner(e,t,n,r,i,a=0){return new cp(e,t,n,r,i,a)}},up=class e{#e=null;#t=null;#n;#r=null;#i=!1;#a=!1;#o=null;#s;#c=null;#l=null;#u;static#d=null;static get _keyboardManager(){return Y(this,`_keyboardManager`,new Ql([[[`Escape`,`mac+Escape`],e.prototype._hideDropdownFromKeyboard],[[` `,`mac+ `],e.prototype._colorSelectFromKeyboard],[[`ArrowDown`,`ArrowRight`,`mac+ArrowDown`,`mac+ArrowRight`],e.prototype._moveToNext],[[`ArrowUp`,`ArrowLeft`,`mac+ArrowUp`,`mac+ArrowLeft`],e.prototype._moveToPrevious],[[`Home`,`mac+Home`],e.prototype._moveToBeginning],[[`End`,`mac+End`],e.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:n=null}){t?(this.#a=!1,this.#u=K.HIGHLIGHT_COLOR,this.#o=t):(this.#a=!0,this.#u=K.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||n,this.#s=this.#l._eventBus,this.#n=t?.color||this.#l?.highlightColors.values().next().value||`#FFFF98`,e.#d||=Object.freeze({blue:`pdfjs-editor-colorpicker-blue`,green:`pdfjs-editor-colorpicker-green`,pink:`pdfjs-editor-colorpicker-pink`,red:`pdfjs-editor-colorpicker-red`,yellow:`pdfjs-editor-colorpicker-yellow`})}renderButton(){let e=this.#e=document.createElement(`button`);e.className=`colorPicker`,e.tabIndex=`0`,e.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-button`),e.setAttribute(`aria-haspopup`,!0);let t=this.#l._signal;e.addEventListener(`click`,this.#h.bind(this),{signal:t}),e.addEventListener(`keydown`,this.#m.bind(this),{signal:t});let n=this.#t=document.createElement(`span`);return n.className=`swatch`,n.setAttribute(`aria-hidden`,!0),n.style.backgroundColor=this.#n,e.append(n),e}renderMainDropdown(){let e=this.#r=this.#f();return e.setAttribute(`aria-orientation`,`horizontal`),e.setAttribute(`aria-labelledby`,`highlightColorPickerLabel`),e}#f(){let t=document.createElement(`div`),n=this.#l._signal;t.addEventListener(`contextmenu`,Ll,{signal:n}),t.className=`dropdown`,t.role=`listbox`,t.setAttribute(`aria-multiselectable`,!1),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-dropdown`);for(let[r,i]of this.#l.highlightColors){let a=document.createElement(`button`);a.tabIndex=`0`,a.role=`option`,a.setAttribute(`data-color`,i),a.title=r,a.setAttribute(`data-l10n-id`,e.#d[r]);let o=document.createElement(`span`);a.append(o),o.className=`swatch`,o.style.backgroundColor=i,a.setAttribute(`aria-selected`,i===this.#n),a.addEventListener(`click`,this.#p.bind(this,i),{signal:n}),t.append(a)}return t.addEventListener(`keydown`,this.#m.bind(this),{signal:n}),t}#p(e,t){t.stopPropagation(),this.#s.dispatch(`switchannotationeditorparams`,{source:this,type:this.#u,value:e})}_colorSelectFromKeyboard(e){if(e.target===this.#e){this.#h(e);return}let t=e.target.getAttribute(`data-color`);t&&this.#p(t,e)}_moveToNext(e){if(!this.#_){this.#h(e);return}if(e.target===this.#e){this.#r.firstChild?.focus();return}e.target.nextSibling?.focus()}_moveToPrevious(e){if(e.target===this.#r?.firstChild||e.target===this.#e){this.#_&&this._hideDropdownFromKeyboard();return}this.#_||this.#h(e),e.target.previousSibling?.focus()}_moveToBeginning(e){if(!this.#_){this.#h(e);return}this.#r.firstChild?.focus()}_moveToEnd(e){if(!this.#_){this.#h(e);return}this.#r.lastChild?.focus()}#m(t){e._keyboardManager.exec(this,t)}#h(e){if(this.#_){this.hideDropdown();return}if(this.#i=e.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener(`pointerdown`,this.#g.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#r){this.#r.classList.remove(`hidden`);return}let t=this.#r=this.#f();this.#e.append(t)}#g(e){this.#r?.contains(e.target)||this.hideDropdown()}hideDropdown(){this.#r?.classList.add(`hidden`),this.#c?.abort(),this.#c=null}get#_(){return this.#r&&!this.#r.classList.contains(`hidden`)}_hideDropdownFromKeyboard(){if(!this.#a){if(!this.#_){this.#o?.unselect();return}this.hideDropdown(),this.#e.focus({preventScroll:!0,focusVisible:this.#i})}}updateColor(e){if(this.#t&&(this.#t.style.backgroundColor=e),!this.#r)return;let t=this.#l.highlightColors.values();for(let n of this.#r.children)n.setAttribute(`aria-selected`,t.next().value===e)}destroy(){this.#e?.remove(),this.#e=null,this.#t=null,this.#r?.remove(),this.#r=null}},dp=class e extends Q{#e=null;#t=0;#n;#r=null;#i=null;#a=null;#o=null;#s=0;#c=null;#l=null;#u=null;#d=!1;#f=null;#p;#m=null;#h=``;#g;#_=``;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type=`highlight`;static _editorType=G.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId=``;static get _keyboardManager(){let t=e.prototype;return Y(this,`_keyboardManager`,new Ql([[[`ArrowLeft`,`mac+ArrowLeft`],t._moveCaret,{args:[0]}],[[`ArrowRight`,`mac+ArrowRight`],t._moveCaret,{args:[1]}],[[`ArrowUp`,`mac+ArrowUp`],t._moveCaret,{args:[2]}],[[`ArrowDown`,`mac+ArrowDown`],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:`highlightEditor`}),this.color=t.color||e._defaultColor,this.#g=t.thickness||e._defaultThickness,this.#p=t.opacity||e._defaultOpacity,this.#n=t.boxes||null,this.#_=t.methodOfCreation||``,this.#h=t.text||``,this._isDraggable=!1,t.highlightId>-1?(this.#d=!0,this.#y(t),this.#w()):this.#n&&(this.#e=t.anchorNode,this.#t=t.anchorOffset,this.#o=t.focusNode,this.#s=t.focusOffset,this.#v(),this.#w(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:`added`,type:this.#d?`free_highlight`:`highlight`,color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#g,methodOfCreation:this.#_}}get telemetryFinalData(){return{type:`highlight`,color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get(`color`).size}}#v(){let e=new op(this.#n,.001);this.#l=e.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;let t=new op(this.#n,.0025,.001,this._uiManager.direction===`ltr`);this.#a=t.getOutlines();let{lastPoint:n}=this.#a;this.#f=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#y({highlightOutlines:t,highlightId:n,clipPathId:r}){if(this.#l=t,this.#a=t.getNewOutline(this.#g/2+1.5,.0025),n>=0)this.#u=n,this.#r=r,this.parent.drawLayer.finalizeDraw(n,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#m=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},!0);else if(this.parent){let n=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#u,{bbox:e.#T(this.#l.box,(n-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#m,{bbox:e.#T(this.#a.box,n),path:{d:this.#a.toSVGPath()}})}let[i,a,o,s]=t.box;switch(this.rotation){case 0:this.x=i,this.y=a,this.width=o,this.height=s;break;case 90:{let[e,t]=this.parentDimensions;this.x=a,this.y=1-i,this.width=o*t/e,this.height=s*e/t;break}case 180:this.x=1-i,this.y=1-a,this.width=o,this.height=s;break;case 270:{let[e,t]=this.parentDimensions;this.x=1-a,this.y=i,this.width=o*t/e,this.height=s*e/t;break}}let{lastPoint:c}=this.#a;this.#f=[(c[0]-i)/o,(c[1]-a)/s]}static initialize(t,n){Q.initialize(t,n),e._defaultColor||=n.highlightColors?.values().next().value||`#fff066`}static updateDefaultParams(t,n){switch(t){case K.HIGHLIGHT_DEFAULT_COLOR:e._defaultColor=n;break;case K.HIGHLIGHT_THICKNESS:e._defaultThickness=n;break}}translateInPage(e,t){}get toolbarPosition(){return this.#f}updateParams(e,t){switch(e){case K.HIGHLIGHT_COLOR:this.#b(t);break;case K.HIGHLIGHT_THICKNESS:this.#x(t);break}}static get defaultPropertiesToUpdate(){return[[K.HIGHLIGHT_DEFAULT_COLOR,e._defaultColor],[K.HIGHLIGHT_THICKNESS,e._defaultThickness]]}get propertiesToUpdate(){return[[K.HIGHLIGHT_COLOR,this.color||e._defaultColor],[K.HIGHLIGHT_THICKNESS,this.#g||e._defaultThickness],[K.HIGHLIGHT_FREE,this.#d]]}#b(t){let n=(e,t)=>{this.color=e,this.#p=t,this.parent?.drawLayer.updateProperties(this.#u,{root:{fill:e,"fill-opacity":t}}),this.#i?.updateColor(e)},r=this.color,i=this.#p;this.addCommands({cmd:n.bind(this,t,e._defaultOpacity),undo:n.bind(this,r,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`color_changed`,color:this._uiManager.highlightColorNames.get(t)},!0)}#x(e){let t=this.#g,n=e=>{this.#g=e,this.#S(e)};this.addCommands({cmd:n.bind(this,e),undo:n.bind(this,t),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:K.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`thickness_changed`,thickness:e},!0)}async addEditToolbar(){let e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(this.#i=new up({editor:this}),e.addColorPicker(this.#i)),e):null}disableEditing(){super.disableEditing(),this.div.classList.toggle(`disabled`,!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle(`disabled`,!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(e,t){return super.getRect(e,t,this.#O())}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),e&&this.div.focus()}remove(){this.#C(),this._reportTelemetry({action:`deleted`}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#w(),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?this.#C():e&&(this.#w(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),this.show(this._isVisible),t&&this.select()}#S(e){if(!this.#d)return;this.#y({highlightOutlines:this.#l.getNewOutline(e/2)}),this.fixAndSetPosition();let[t,n]=this.parentDimensions;this.setDims(this.width*t,this.height*n)}#C(){this.#u===null||!this.parent||(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#m),this.#m=null)}#w(e=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#r}=e.drawLayer.draw({bbox:this.#l.box,root:{viewBox:`0 0 1 1`,fill:this.color,"fill-opacity":this.#p},rootClass:{highlight:!0,free:this.#d},path:{d:this.#l.toSVGPath()}},!1,!0),this.#m=e.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#d},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},this.#d),this.#c&&(this.#c.style.clipPath=this.#r))}static#T([e,t,n,r],i){switch(i){case 90:return[1-t-r,e,r,n];case 180:return[1-e-n,1-t-r,n,r];case 270:return[t,1-e-n,r,n]}return[e,t,n,r]}rotate(t){let{drawLayer:n}=this.parent,r;this.#d?(t=(t-this.rotation+360)%360,r=e.#T(this.#l.box,t)):r=e.#T([this.x,this.y,this.width,this.height],t),n.updateProperties(this.#u,{bbox:r,root:{"data-main-rotation":t}}),n.updateProperties(this.#m,{bbox:e.#T(this.#a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;let e=super.render();this.#h&&(e.setAttribute(`aria-label`,this.#h),e.setAttribute(`role`,`mark`)),this.#d?e.classList.add(`free`):this.div.addEventListener(`keydown`,this.#E.bind(this),{signal:this._uiManager._signal});let t=this.#c=document.createElement(`div`);e.append(t),t.setAttribute(`aria-hidden`,`true`),t.className=`internal`,t.style.clipPath=this.#r;let[n,r]=this.parentDimensions;return this.setDims(this.width*n,this.height*r),Jl(this,this.#c,[`pointerover`,`pointerleave`]),this.enableEditing(),e}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1}})}#E(t){e._keyboardManager.exec(this,t)}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:this.#D(!0);break;case 1:case 3:this.#D(!1);break}}#D(e){if(!this.#e)return;let t=window.getSelection();e?t.setPosition(this.#e,this.#t):t.setPosition(this.#o,this.#s)}select(){super.select(),this.#m&&this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#m&&(this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{selected:!1}}),this.#d||this.#D(!1))}get _mustFixPosition(){return!this.#d}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.updateProperties(this.#u,{rootClass:{hidden:!e}}),this.parent.drawLayer.updateProperties(this.#m,{rootClass:{hidden:!e}}))}#O(){return this.#d?this.rotation:0}#k(){if(this.#d)return null;let[e,t]=this.pageDimensions,[n,r]=this.pageTranslation,i=this.#n,a=new Float32Array(i.length*8),o=0;for(let{x:s,y:c,width:l,height:u}of i){let i=s*e+n,d=(1-c)*t+r;a[o]=a[o+4]=i,a[o+1]=a[o+3]=d,a[o+2]=a[o+6]=i+l*e,a[o+5]=a[o+7]=d-u*t,o+=8}return a}#A(e){return this.#l.serialize(e,this.#O())}static startHighlighting(e,t,{target:n,x:r,y:i}){let{x:a,y:o,width:s,height:c}=n.getBoundingClientRect(),l=new AbortController,u=e.combinedSignal(l),d=t=>{l.abort(),this.#M(e,t)};window.addEventListener(`blur`,d,{signal:u}),window.addEventListener(`pointerup`,d,{signal:u}),window.addEventListener(`pointerdown`,Rl,{capture:!0,passive:!1,signal:u}),window.addEventListener(`contextmenu`,Ll,{signal:u}),n.addEventListener(`pointermove`,this.#j.bind(this,e),{signal:u}),this._freeHighlight=new cp({x:r,y:i},[a,o,s,c],e.scale,this._defaultThickness/2,t,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:`0 0 1 1`,fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#j(e,t){this._freeHighlight.add(t)&&e.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#M(e,t){this._freeHighlight.isEmpty()?e.drawLayer.remove(this._freeHighlightId):e.createAndAddNewEditor(t,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:`main_toolbar`}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=``}static async deserialize(e,t,n){let r=null;if(e instanceof Yf){let{data:{quadPoints:t,rect:n,rotation:i,id:a,color:o,opacity:s,popupRef:c},parent:{page:{pageNumber:l}}}=e;r=e={annotationType:G.HIGHLIGHT,color:Array.from(o),opacity:s,quadPoints:t,boxes:null,pageIndex:l-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:c}}else if(e instanceof Jf){let{data:{inkLists:t,rect:n,rotation:i,id:a,color:o,borderStyle:{rawWidth:s},popupRef:c},parent:{page:{pageNumber:l}}}=e;r=e={annotationType:G.HIGHLIGHT,color:Array.from(o),thickness:s,inkLists:t,boxes:null,pageIndex:l-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:c}}let{color:i,quadPoints:a,inkLists:o,opacity:s}=e,c=await super.deserialize(e,t,n);c.color=X.makeHexColor(...i),c.#p=s||1,o&&(c.#g=e.thickness),c.annotationElementId=e.id||null,c._initialData=r;let[l,u]=c.pageDimensions,[d,f]=c.pageTranslation;if(a){let e=c.#n=[];for(let t=0;t<a.length;t+=8)e.push({x:(a[t]-d)/l,y:1-(a[t+1]-f)/u,width:(a[t+2]-a[t])/l,height:(a[t+1]-a[t+5])/u});c.#v(),c.#w(),c.rotate(c.rotation)}else if(o){c.#d=!0;let e=o[0],n={x:e[0]-d,y:u-(e[1]-f)},r=new cp(n,[0,0,l,u],1,c.#g/2,!0,.001);for(let t=0,i=e.length;t<i;t+=2)n.x=e[t]-d,n.y=u-(e[t+1]-f),r.add(n);let{id:i,clipPathId:a}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:`0 0 1 1`,fill:c.color,"fill-opacity":c._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:r.toSVGPath()}},!0,!0);c.#y({highlightOutlines:r.getOutlines(),highlightId:i,clipPathId:a}),c.#w()}return c}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();let t=this.getRect(0,0),n=Q._colorManager.convert(this.color),r={annotationType:G.HIGHLIGHT,color:n,opacity:this.#p,thickness:this.#g,quadPoints:this.#k(),outlines:this.#A(t),pageIndex:this.pageIndex,rect:t,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#N(r)?null:(r.id=this.annotationElementId,r)}#N(e){let{color:t}=this._initialData;return e.color.some((e,n)=>e!==t[n])}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}},fp=class{#e=Object.create(null);updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(let[t,n]of Object.entries(e))this.updateProperty(t,n)}updateSVGProperty(e,t){this.#e[e]=t}toSVGProperties(){let e=this.#e;return this.#e=Object.create(null),{root:e}}reset(){this.#e=Object.create(null)}updateAll(e=this){this.updateProperties(e)}clone(){J(`Not implemented`)}},pp=class e extends Q{#e=null;#t;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#n=null;static#r=null;static#i=null;static#a=NaN;static#o=null;static#s=null;static#c=NaN;static _INNER_MARGIN=3;constructor(e){super(e),this.#t=e.mustBeCommitted||!1,e.drawOutlines&&(this.#l(e),this.#f())}#l({drawOutlines:e,drawId:t,drawingOptions:n}){this.#e=e,this._drawingOptions||=n,t>=0?(this._drawId=t,this.parent.drawLayer.finalizeDraw(t,e.defaultProperties)):this._drawId=this.#u(e,this.parent),this.#h(e.box)}#u(t,n){let{id:r}=n.drawLayer.draw(e._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return r}static _mergeSVGProperties(e,t){let n=new Set(Object.keys(e));for(let[r,i]of Object.entries(t))n.has(r)?Object.assign(e[r],i):e[r]=i;return e}static getDefaultDrawingOptions(e){J(`Not implemented`)}static get typesMap(){J(`Not implemented`)}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,n){let r=this.typesMap.get(t);r&&this._defaultDrawingOptions.updateProperty(r,n),this._currentParent&&(e.#n.updateProperty(r,n),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(e,t){let n=this.constructor.typesMap.get(e);n&&this._updateProperty(e,n,t)}static get defaultPropertiesToUpdate(){let e=[],t=this._defaultDrawingOptions;for(let[n,r]of this.typesMap)e.push([n,t[r]]);return e}get propertiesToUpdate(){let e=[],{_drawingOptions:t}=this;for(let[n,r]of this.constructor.typesMap)e.push([n,t[r]]);return e}_updateProperty(e,t,n){let r=this._drawingOptions,i=r[t],a=e=>{r.updateProperty(t,e);let n=this.#e.updateProperty(t,e);n&&this.#h(n),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties())};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizingSVGProperties(this.#m()),{bbox:this.#g()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizedSVGProperties(this.#m()),{bbox:this.#g()}))}_onTranslating(e,t){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#g(e,t)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathTranslatedSVGProperties(this.#m(),this.parentDimensions),{bbox:this.#g()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle(`disabled`,!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle(`disabled`,!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#t&&(this.#t=!1,this.commit(),this.parent.setSelected(this),e&&this.isOnScreen&&this.div.focus())}remove(){this.#d(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#h(this.#e.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?(this._uiManager.removeShouldRescale(this),this.#d()):e&&(this._uiManager.addShouldRescale(this),this.#f(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),t&&this.select()}#d(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(e=this.parent){if(!(this._drawId!==null&&this.parent===e)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,e.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#u(this.#e,e)}}#p([e,t,n,r]){let{parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[t,1-e,a/i*n,i/a*r];case 180:return[1-e,1-t,n,r];case 270:return[1-t,e,a/i*n,i/a*r];default:return[e,t,n,r]}}#m(){let{x:e,y:t,width:n,height:r,parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[1-t,e,i/a*n,a/i*r];case 180:return[1-e,1-t,n,r];case 270:return[t,1-e,i/a*n,a/i*r];default:return[e,t,n,r]}}#h(e){if([this.x,this.y,this.width,this.height]=this.#p(e),this.div){this.fixAndSetPosition();let[e,t]=this.parentDimensions;this.setDims(this.width*e,this.height*t)}this._onResized()}#g(){let{x:e,y:t,width:n,height:r,rotation:i,parentRotation:a,parentDimensions:[o,s]}=this;switch((i*4+a)/90){case 1:return[1-t-r,e,r,n];case 2:return[1-e-n,1-t-r,n,r];case 3:return[t,1-e-n,r,n];case 4:return[e,t-o/s*n,s/o*r,o/s*n];case 5:return[1-t,e,o/s*n,s/o*r];case 6:return[1-e-s/o*r,1-t,s/o*r,o/s*n];case 7:return[t-o/s*n,1-e-s/o*r,o/s*n,s/o*r];case 8:return[e-n,t-r,n,r];case 9:return[1-t,e-n,r,n];case 10:return[1-e,1-t,n,r];case 11:return[t-r,1-e,r,n];case 12:return[e-s/o*r,t,s/o*r,o/s*n];case 13:return[1-t-o/s*n,e-s/o*r,o/s*n,s/o*r];case 14:return[1-e,1-t-o/s*n,s/o*r,o/s*n];case 15:return[t,1-e,o/s*n,s/o*r];default:return[e,t,n,r]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties({bbox:this.#g()},this.#e.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#h(this.#e.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let e=super.render();e.classList.add(`draw`);let t=document.createElement(`div`);e.append(t),t.setAttribute(`aria-hidden`,`true`),t.className=`internal`;let[n,r]=this.parentDimensions;return this.setDims(this.width*n,this.height*r),this._uiManager.addShouldRescale(this),this.disableEditing(),e}static createDrawerInstance(e,t,n,r,i){J(`Not implemented`)}static startDrawing(t,n,r,i){let{target:a,offsetX:o,offsetY:s,pointerId:c,pointerType:l}=i;if(e.#o&&e.#o!==l)return;let{viewport:{rotation:u}}=t,{width:d,height:f}=a.getBoundingClientRect(),p=e.#r=new AbortController,m=t.combinedSignal(p);if(e.#a||=c,e.#o??=l,window.addEventListener(`pointerup`,t=>{e.#a===t.pointerId?this._endDraw(t):e.#s?.delete(t.pointerId)},{signal:m}),window.addEventListener(`pointercancel`,t=>{e.#a===t.pointerId?this._currentParent.endDrawingSession():e.#s?.delete(t.pointerId)},{signal:m}),window.addEventListener(`pointerdown`,t=>{e.#o===t.pointerType&&((e.#s||=new Set).add(t.pointerId),e.#n.isCancellable()&&(e.#n.removeLastElement(),e.#n.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:m}),window.addEventListener(`contextmenu`,Ll,{signal:m}),a.addEventListener(`pointermove`,this._drawMove.bind(this),{signal:m}),a.addEventListener(`touchmove`,t=>{t.timeStamp===e.#c&&Rl(t)},{signal:m}),t.toggleDrawing(),n._editorUndoBar?.hide(),e.#n){t.drawLayer.updateProperties(this._currentDrawId,e.#n.startNew(o,s,d,f,u));return}n.updateUIForDefaultProperties(this),e.#n=this.createDrawerInstance(o,s,d,f,u),e.#i=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(e.#i.toSVGProperties(),e.#n.defaultSVGProperties),!0,!1)}static _drawMove(t){if(e.#c=-1,!e.#n)return;let{offsetX:n,offsetY:r,pointerId:i}=t;if(e.#a===i){if(e.#s?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,e.#n.add(n,r)),e.#c=t.timeStamp,Rl(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,e.#n=null,e.#i=null,e.#o=null,e.#c=NaN),e.#r&&(e.#r.abort(),e.#r=null,e.#a=NaN,e.#s=null)}static _endDraw(t){let n=this._currentParent;if(n){if(n.toggleDrawing(!0),this._cleanup(!1),t&&n.drawLayer.updateProperties(this._currentDrawId,e.#n.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){let t=e.#n,r=this._currentDrawId,i=t.getLastElement();n.addCommands({cmd:()=>{n.drawLayer.updateProperties(r,t.setLastElement(i))},undo:()=>{n.drawLayer.updateProperties(r,t.removeLastElement())},mustExec:!1,type:K.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){let n=this._currentParent;if(!n)return null;if(n.toggleDrawing(!0),n.cleanUndoStack(K.DRAW_STEP),!e.#n.isEmpty()){let{pageDimensions:[r,i],scale:a}=n,o=n.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:e.#n.getOutlines(r*a,i*a,a,this._INNER_MARGIN),drawingOptions:e.#i,mustBeCommitted:!t});return this._cleanup(!0),o}return n.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,t,n,r,i,a){J(`Not implemented`)}static async deserialize(e,t,n){let{rawDims:{pageWidth:r,pageHeight:i,pageX:a,pageY:o}}=t.viewport,s=this.deserializeDraw(a,o,r,i,this._INNER_MARGIN,e),c=await super.deserialize(e,t,n);return c.createDrawingOptions(e),c.#l({drawOutlines:s}),c.#f(),c.onScaleChanging(),c.rotate(),c}serializeDraw(e){let[t,n]=this.pageTranslation,[r,i]=this.pageDimensions;return this.#e.serialize([t,n,r,i],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}},mp=class{#e=new Float64Array(6);#t;#n;#r;#i;#a;#o=``;#s=0;#c=new hp;#l;#u;constructor(e,t,n,r,i,a){this.#l=n,this.#u=r,this.#r=i,this.#i=a,[e,t]=this.#d(e,t);let o=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t],this.#n=[{line:o,points:this.#a}],this.#e.set(o,0)}updateProperty(e,t){e===`stroke-width`&&(this.#i=t)}#d(e,t){return $._normalizePoint(e,t,this.#l,this.#u,this.#r)}isEmpty(){return!this.#n||this.#n.length===0}isCancellable(){return this.#a.length<=10}add(e,t){[e,t]=this.#d(e,t);let[n,r,i,a]=this.#e.subarray(2,6),o=e-i,s=t-a;return Math.hypot(this.#l*o,this.#u*s)<=2?null:(this.#a.push(e,t),isNaN(n)?(this.#e.set([i,a,e,t],2),this.#t.push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(this.#e[0])&&this.#t.splice(6,6),this.#e.set([n,r,i,a,e,t],0),this.#t.push(...$.createBezierPoints(n,r,i,a,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){return this.add(e,t)||(this.#a.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,n,r,i){this.#l=n,this.#u=r,this.#r=i,[e,t]=this.#d(e,t);let a=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t];let o=this.#n.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#n.push({line:a,points:this.#a}),this.#e.set(a,0),this.#s=0,this.toSVGPath(),null}getLastElement(){return this.#n.at(-1)}setLastElement(e){return this.#n?(this.#n.push(e),this.#t=e.line,this.#a=e.points,this.#s=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(e)}removeLastElement(){if(!this.#n)return this.#c.removeLastElement();this.#n.pop(),this.#o=``;for(let e=0,t=this.#n.length;e<t;e++){let{line:t,points:n}=this.#n[e];this.#t=t,this.#a=n,this.#s=0,this.toSVGPath()}return{path:{d:this.#o}}}toSVGPath(){let e=$.svgRound(this.#t[4]),t=$.svgRound(this.#t[5]);if(this.#a.length===2)return this.#o=`${this.#o} M ${e} ${t} Z`,this.#o;if(this.#a.length<=6){let n=this.#o.lastIndexOf(`M`);this.#o=`${this.#o.slice(0,n)} M ${e} ${t}`,this.#s=6}if(this.#a.length===4){let e=$.svgRound(this.#t[10]),t=$.svgRound(this.#t[11]);return this.#o=`${this.#o} L ${e} ${t}`,this.#s=12,this.#o}let n=[];this.#s===0&&(n.push(`M ${e} ${t}`),this.#s=6);for(let e=this.#s,t=this.#t.length;e<t;e+=6){let[t,r,i,a,o,s]=this.#t.slice(e,e+6).map($.svgRound);n.push(`C${t} ${r} ${i} ${a} ${o} ${s}`)}return this.#o+=n.join(` `),this.#s=this.#t.length,this.#o}getOutlines(e,t,n,r){let i=this.#n.at(-1);return i.line=new Float32Array(i.line),i.points=new Float32Array(i.points),this.#c.build(this.#n,e,t,n,this.#r,this.#i,r),this.#e=null,this.#t=null,this.#n=null,this.#o=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:`0 0 10000 10000`},rootClass:{draw:!0},bbox:[0,0,1,1]}}},hp=class e extends ${#e;#t=0;#n;#r;#i;#a;#o;#s;#c;build(e,t,n,r,i,a,o){this.#i=t,this.#a=n,this.#o=r,this.#s=i,this.#c=a,this.#n=o??0,this.#r=e,this.#d()}setLastElement(e){return this.#r.push(e),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#r.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){let e=[];for(let{line:t}of this.#r){if(e.push(`M${$.svgRound(t[4])} ${$.svgRound(t[5])}`),t.length===6){e.push(`Z`);continue}if(t.length===12){e.push(`L${$.svgRound(t[10])} ${$.svgRound(t[11])}`);continue}for(let n=6,r=t.length;n<r;n+=6){let[r,i,a,o,s,c]=t.subarray(n,n+6).map($.svgRound);e.push(`C${r} ${i} ${a} ${o} ${s} ${c}`)}}return e.join(``)}serialize([e,t,n,r],i){let a=[],o=[],[s,c,l,u]=this.#u(),d,f,p,m,h,g,_,v,y;switch(this.#s){case 0:y=$._rescale,d=e,f=t+r,p=n,m=-r,h=e+s*n,g=t+(1-c-u)*r,_=e+(s+l)*n,v=t+(1-c)*r;break;case 90:y=$._rescaleAndSwap,d=e,f=t,p=n,m=r,h=e+c*n,g=t+s*r,_=e+(c+u)*n,v=t+(s+l)*r;break;case 180:y=$._rescale,d=e+n,f=t,p=-n,m=r,h=e+(1-s-l)*n,g=t+c*r,_=e+(1-s)*n,v=t+(c+u)*r;break;case 270:y=$._rescaleAndSwap,d=e+n,f=t+r,p=-n,m=-r,h=e+(1-c-u)*n,g=t+(1-s-l)*r,_=e+(1-c)*n,v=t+(1-s)*r;break}for(let{line:e,points:t}of this.#r)a.push(y(e,d,f,p,m,i?Array(e.length):null)),o.push(y(t,d,f,p,m,i?Array(t.length):null));return{lines:a,points:o,rect:[h,g,_,v]}}static deserialize(t,n,r,i,a,{paths:{lines:o,points:s},rotation:c,thickness:l}){let u=[],d,f,p,m,h;switch(c){case 0:h=$._rescale,d=-t/r,f=n/i+1,p=1/r,m=-1/i;break;case 90:h=$._rescaleAndSwap,d=-n/i,f=-t/r,p=1/i,m=1/r;break;case 180:h=$._rescale,d=t/r+1,f=-n/i,p=-1/r,m=1/i;break;case 270:h=$._rescaleAndSwap,d=n/i+1,f=t/r+1,p=-1/i,m=-1/r;break}if(!o){o=[];for(let e of s){let t=e.length;if(t===2){o.push(new Float32Array([NaN,NaN,NaN,NaN,e[0],e[1]]));continue}if(t===4){o.push(new Float32Array([NaN,NaN,NaN,NaN,e[0],e[1],NaN,NaN,NaN,NaN,e[2],e[3]]));continue}let n=new Float32Array(3*(t-2));o.push(n);let[r,i,a,s]=e.subarray(0,4);n.set([NaN,NaN,NaN,NaN,r,i],0);for(let o=4;o<t;o+=2){let t=e[o],c=e[o+1];n.set($.createBezierPoints(r,i,a,s,t,c),(o-2)*3),[r,i,a,s]=[a,s,t,c]}}}for(let e=0,t=o.length;e<t;e++)u.push({line:h(o[e].map(e=>e??NaN),d,f,p,m),points:h(s[e].map(e=>e??NaN),d,f,p,m)});let g=new e;return g.build(u,r,i,1,c,l,a),g}#l(e=this.#c){let t=this.#n+e/2*this.#o;return this.#s%180==0?[t/this.#i,t/this.#a]:[t/this.#a,t/this.#i]}#u(){let[e,t,n,r]=this.#e,[i,a]=this.#l(0);return[e+i,t+a,n-2*i,r-2*a]}#d(){let e=this.#e=new Float32Array([1/0,1/0,-1/0,-1/0]);for(let{line:t}of this.#r){if(t.length<=12){for(let n=4,r=t.length;n<r;n+=6){let[r,i]=t.subarray(n,n+2);e[0]=Math.min(e[0],r),e[1]=Math.min(e[1],i),e[2]=Math.max(e[2],r),e[3]=Math.max(e[3],i)}continue}let n=t[4],r=t[5];for(let i=6,a=t.length;i<a;i+=6){let[a,o,s,c,l,u]=t.subarray(i,i+6);X.bezierBoundingBox(n,r,a,o,s,c,l,u,e),n=l,r=u}}let[t,n]=this.#l();e[0]=Math.min(1,Math.max(0,e[0]-t)),e[1]=Math.min(1,Math.max(0,e[1]-n)),e[2]=Math.min(1,Math.max(0,e[2]+t)),e[3]=Math.min(1,Math.max(0,e[3]+n)),e[2]-=e[0],e[3]-=e[1]}get box(){return this.#e}updateProperty(e,t){return e===`stroke-width`?this.#f(t):null}#f(e){let[t,n]=this.#l();this.#c=e;let[r,i]=this.#l(),[a,o]=[r-t,i-n],s=this.#e;return s[0]-=a,s[1]-=o,s[2]+=2*a,s[3]+=2*o,s}updateParentDimensions([e,t],n){let[r,i]=this.#l();this.#i=e,this.#a=t,this.#o=n;let[a,o]=this.#l(),s=a-r,c=o-i,l=this.#e;return l[0]-=s,l[1]-=c,l[2]+=2*s,l[3]+=2*c,l}updateRotation(e){return this.#t=e,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#e.map($.svgRound).join(` `)}get defaultProperties(){let[e,t]=this.#e;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`}}}get rotationTransform(){let[,,e,t]=this.#e,n=0,r=0,i=0,a=0,o=0,s=0;switch(this.#t){case 90:r=t/e,i=-e/t,o=e;break;case 180:n=-1,a=-1,o=e,s=t;break;case 270:r=-t/e,i=e/t,s=t;break;default:return``}return`matrix(${n} ${r} ${i} ${a} ${$.svgRound(o)} ${$.svgRound(s)})`}getPathResizingSVGProperties([e,t,n,r]){let[i,a]=this.#l(),[o,s,c,l]=this.#e;if(Math.abs(c-i)<=$.PRECISION||Math.abs(l-a)<=$.PRECISION){let i=e+n/2-(o+c/2),a=t+r/2-(s+l/2);return{path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:`${this.rotationTransform} translate(${i} ${a})`}}}let u=(n-2*i)/(c-2*i),d=(r-2*a)/(l-2*a),f=c/n,p=l/r;return{path:{"transform-origin":`${$.svgRound(o)} ${$.svgRound(s)}`,transform:`${this.rotationTransform} scale(${f} ${p}) translate(${$.svgRound(i)} ${$.svgRound(a)}) scale(${u} ${d}) translate(${$.svgRound(-i)} ${$.svgRound(-a)})`}}}getPathResizedSVGProperties([e,t,n,r]){let[i,a]=this.#l(),o=this.#e,[s,c,l,u]=o;if(o[0]=e,o[1]=t,o[2]=n,o[3]=r,Math.abs(l-i)<=$.PRECISION||Math.abs(u-a)<=$.PRECISION){let i=e+n/2-(s+l/2),a=t+r/2-(c+u/2);for(let{line:e,points:t}of this.#r)$._translate(e,i,a,e),$._translate(t,i,a,t);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}let d=(n-2*i)/(l-2*i),f=(r-2*a)/(u-2*a),p=-d*(s+i)+e+i,m=-f*(c+a)+t+a;if(d!==1||f!==1||p!==0||m!==0)for(let{line:e,points:t}of this.#r)$._rescale(e,p,m,d,f,e),$._rescale(t,p,m,d,f,t);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([e,t],n){let[r,i]=n,a=this.#e,o=e-a[0],s=t-a[1];if(this.#i===r&&this.#a===i)for(let{line:e,points:t}of this.#r)$._translate(e,o,s,e),$._translate(t,o,s,t);else{let e=this.#i/r,t=this.#a/i;this.#i=r,this.#a=i;for(let{line:n,points:r}of this.#r)$._rescale(n,o,s,e,t,n),$._rescale(r,o,s,e,t,r);a[2]*=e,a[3]*=t}return a[0]=e,a[1]=t,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`}}}get defaultSVGProperties(){let e=this.#e;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${$.svgRound(e[0])} ${$.svgRound(e[1])}`,transform:this.rotationTransform||null},bbox:e}}},gp=class e extends fp{#e;constructor(e){super(),this.#e=e,super.updateProperties({fill:`none`,stroke:Q._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-miterlimit":10})}updateSVGProperty(e,t){e===`stroke-width`&&(t??=this[`stroke-width`],t*=this.#e.realScale),super.updateSVGProperty(e,t)}clone(){let t=new e(this.#e);return t.updateAll(this),t}},_p=class e extends pp{static _type=`ink`;static _editorType=G.INK;static _defaultDrawingOptions=null;constructor(e){super({...e,name:`inkEditor`}),this._willKeepAspectRatio=!0}static initialize(e,t){Q.initialize(e,t),this._defaultDrawingOptions=new gp(t.viewParameters)}static getDefaultDrawingOptions(e){let t=this._defaultDrawingOptions.clone();return t.updateProperties(e),t}static get supportMultipleDrawings(){return!0}static get typesMap(){return Y(this,`typesMap`,new Map([[K.INK_THICKNESS,`stroke-width`],[K.INK_COLOR,`stroke`],[K.INK_OPACITY,`stroke-opacity`]]))}static createDrawerInstance(e,t,n,r,i){return new mp(e,t,n,r,i,this._defaultDrawingOptions[`stroke-width`])}static deserializeDraw(e,t,n,r,i,a){return hp.deserialize(e,t,n,r,i,a)}static async deserialize(e,t,n){let r=null;if(e instanceof Jf){let{data:{inkLists:t,rect:n,rotation:i,id:a,color:o,opacity:s,borderStyle:{rawWidth:c},popupRef:l},parent:{page:{pageNumber:u}}}=e;r=e={annotationType:G.INK,color:Array.from(o),thickness:c,opacity:s,paths:{points:t},boxes:null,pageIndex:u-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:l}}let i=await super.deserialize(e,t,n);return i.annotationElementId=e.id||null,i._initialData=r,i}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();let{_drawId:e,_drawingOptions:t,parent:n}=this;t.updateSVGProperty(`stroke-width`),n.drawLayer.updateProperties(e,t.toSVGProperties())}static onScaleChangingWhenDrawing(){let e=this._currentParent;e&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty(`stroke-width`),e.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:n,opacity:r}){this._drawingOptions=e.getDefaultDrawingOptions({stroke:X.makeHexColor(...t),"stroke-width":n,"stroke-opacity":r})}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let{lines:t,points:n,rect:r}=this.serializeDraw(e),{_drawingOptions:{stroke:i,"stroke-opacity":a,"stroke-width":o}}=this,s={annotationType:G.INK,color:Q._colorManager.convert(i),opacity:a,thickness:o,paths:{lines:t,points:n},pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?s:this.annotationElementId&&!this.#e(s)?null:(s.id=this.annotationElementId,s)}#e(e){let{color:t,thickness:n,opacity:r,pageIndex:i}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||e.color.some((e,n)=>e!==t[n])||e.thickness!==n||e.opacity!==r||e.pageIndex!==i}renderAnnotationElement(e){let{points:t,rect:n}=this.serializeDraw(!1);return e.updateEdited({rect:n,thickness:this._drawingOptions[`stroke-width`],points:t}),null}},vp=class e extends Q{#e=null;#t=null;#n=null;#r=null;#i=null;#a=``;#o=null;#s=null;#c=!1;#l=!1;static _type=`stamp`;static _editorType=G.STAMP;constructor(e){super({...e,name:`stampEditor`}),this.#r=e.bitmapUrl,this.#i=e.bitmapFile}static initialize(e,t){Q.initialize(e,t)}static get supportedTypes(){return Y(this,`supportedTypes`,[`apng`,`avif`,`bmp`,`gif`,`jpeg`,`png`,`svg+xml`,`webp`,`x-icon`].map(e=>`image/${e}`))}static get supportedTypesStr(){return Y(this,`supportedTypesStr`,this.supportedTypes.join(`,`))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,t){t.pasteEditor(G.STAMP,{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:`stamp`,hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(e){let t=e.get(`hasAltText`);return{hasAltText:t.get(!0)??0,hasNoAltText:t.get(!1)??0}}#u(e,t=!1){if(!e){this.remove();return}this.#e=e.bitmap,t||(this.#t=e.id,this.#c=e.isSvg),e.file&&(this.#a=e.file.name),this.#p()}#d(){if(this.#n=null,this._uiManager.enableWaiting(!1),this.#o){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._reportTelemetry({action:`pdfjs.image.image_added`,data:{alt_text_modal:!1,alt_text_type:`empty`}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(e=null,t=!0){if(this.hasAltTextData())return null;let{mlManager:n}=this._uiManager;if(!n)throw Error(`No ML.`);if(!await n.isEnabledFor(`altText`))throw Error(`ML isn't enabled for alt text.`);let{data:r,width:i,height:a}=e||this.copyCanvas(null,null,!0).imageData,o=await n.guess({name:`altText`,request:{data:r,width:i,height:a,channels:r.length/(i*a)}});if(!o)throw Error(`No response from the AI service.`);if(o.error)throw Error(`Error from the AI service.`);if(o.cancel)return null;if(!o.output)throw Error(`No valid response from the AI service.`);let s=o.output;return await this.setGuessedAltText(s),t&&!this.hasAltTextData()&&(this.altTextData={alt:s,decorative:!1}),s}#f(){if(this.#t){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#t).then(e=>this.#u(e,!0)).finally(()=>this.#d());return}if(this.#r){let e=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromUrl(e).then(e=>this.#u(e)).finally(()=>this.#d());return}if(this.#i){let e=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromFile(e).then(e=>this.#u(e)).finally(()=>this.#d());return}let t=document.createElement(`input`);t.type=`file`,t.accept=e.supportedTypesStr;let n=this._uiManager._signal;this.#n=new Promise(e=>{t.addEventListener(`change`,async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);let e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:`pdfjs.image.image_selected`,data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#u(e)}e()},{signal:n}),t.addEventListener(`cancel`,()=>{this.remove(),e()},{signal:n})}).finally(()=>this.#d()),t.click()}remove(){this.#t&&(this.#e=null,this._uiManager.imageManager.deleteId(this.#t),this.#o?.remove(),this.#o=null,this.#s&&=(clearTimeout(this.#s),null)),super.remove()}rebuild(){if(!this.parent){this.#t&&this.#f();return}super.rebuild(),this.div!==null&&(this.#t&&this.#o===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(e){this._isDraggable=!0,e&&this.div.focus()}isEmpty(){return!(this.#n||this.#e||this.#r||this.#i||this.#t)}get isResizable(){return!0}render(){if(this.div)return this.div;let e,t;if(this.width&&(e=this.x,t=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute(`role`,`figure`),this.addAltTextButton(),this.#e?this.#p():this.#f(),this.width&&!this.annotationElementId){let[n,r]=this.parentDimensions;this.setAt(e*n,t*r,this.width*n,this.height*r)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(this.#s!==null&&clearTimeout(this.#s),this.#s=setTimeout(()=>{this.#s=null,this.#h()},200))}#p(){let{div:e}=this,{width:t,height:n}=this.#e,[r,i]=this.pageDimensions,a=.75;if(this.width)t=this.width*r,n=this.height*i;else if(t>a*r||n>a*i){let e=Math.min(a*r/t,a*i/n);t*=e,n*=e}let[o,s]=this.parentDimensions;this.setDims(t*o/r,n*s/i),this._uiManager.enableWaiting(!1);let c=this.#o=document.createElement(`canvas`);c.setAttribute(`role`,`img`),this.addContainer(c),this.width=t/r,this.height=n/i,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),this.#h(),this.#l||=(this.parent.addUndoableEditor(this),!0),this._reportTelemetry({action:`inserted_image`}),this.#a&&c.setAttribute(`aria-label`,this.#a)}copyCanvas(e,t,n=!1){e||=224;let{width:r,height:i}=this.#e,a=new Gl,o=this.#e,s=r,c=i,l=null;if(t){if(r>t||i>t){let e=Math.min(t/r,t/i);s=Math.floor(r*e),c=Math.floor(i*e)}l=document.createElement(`canvas`);let e=l.width=Math.ceil(s*a.sx),n=l.height=Math.ceil(c*a.sy);this.#c||(o=this.#m(e,n));let u=l.getContext(`2d`);u.filter=this._uiManager.hcmFilter;let d=`white`,f=`#cfcfd8`;this._uiManager.hcmFilter===`none`?window.matchMedia?.(`(prefers-color-scheme: dark)`).matches&&(d=`#8f8f9d`,f=`#42414d`):f=`black`;let p=15*a.sx,m=15*a.sy,h=new OffscreenCanvas(p*2,m*2),g=h.getContext(`2d`);g.fillStyle=d,g.fillRect(0,0,p*2,m*2),g.fillStyle=f,g.fillRect(0,0,p,m),g.fillRect(p,m,p,m),u.fillStyle=u.createPattern(h,`repeat`),u.fillRect(0,0,e,n),u.drawImage(o,0,0,o.width,o.height,0,0,e,n)}let u=null;if(n){let t,n;if(a.symmetric&&o.width<e&&o.height<e)t=o.width,n=o.height;else if(o=this.#e,r>e||i>e){let a=Math.min(e/r,e/i);t=Math.floor(r*a),n=Math.floor(i*a),this.#c||(o=this.#m(t,n))}let s=new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0});s.drawImage(o,0,0,o.width,o.height,0,0,t,n),u={width:t,height:n,data:s.getImageData(0,0,t,n).data}}return{canvas:l,width:s,height:c,imageData:u}}#m(e,t){let{width:n,height:r}=this.#e,i=n,a=r,o=this.#e;for(;i>2*e||a>2*t;){let n=i,r=a;i>2*e&&(i=i>=16384?Math.floor(i/2)-1:Math.ceil(i/2)),a>2*t&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));let s=new OffscreenCanvas(i,a);s.getContext(`2d`).drawImage(o,0,0,n,r,0,0,i,a),o=s.transferToImageBitmap()}return o}#h(){let[e,t]=this.parentDimensions,{width:n,height:r}=this,i=new Gl,a=Math.ceil(n*e*i.sx),o=Math.ceil(r*t*i.sy),s=this.#o;if(!s||s.width===a&&s.height===o)return;s.width=a,s.height=o;let c=this.#c?this.#e:this.#m(a,o),l=s.getContext(`2d`);l.filter=this._uiManager.hcmFilter,l.drawImage(c,0,0,c.width,c.height,0,0,a,o)}getImageForAltText(){return this.#o}#g(e){if(e){if(this.#c){let e=this._uiManager.imageManager.getSvgUrl(this.#t);if(e)return e}let e=document.createElement(`canvas`);return{width:e.width,height:e.height}=this.#e,e.getContext(`2d`).drawImage(this.#e,0,0),e.toDataURL()}if(this.#c){let[e,t]=this.pageDimensions,n=Math.round(this.width*e*Dl.PDF_TO_CSS_UNITS),r=Math.round(this.height*t*Dl.PDF_TO_CSS_UNITS),i=new OffscreenCanvas(n,r);return i.getContext(`2d`).drawImage(this.#e,0,0,this.#e.width,this.#e.height,0,0,n,r),i.transferToImageBitmap()}return structuredClone(this.#e)}static async deserialize(e,t,n){let r=null;if(e instanceof $f){let{data:{rect:i,rotation:a,id:o,structParent:s,popupRef:c},container:l,parent:{page:{pageNumber:u}}}=e,d=l.querySelector(`canvas`),f=n.imageManager.getFromCanvas(l.id,d);d.remove();let p=(await t._structTree.getAriaAttributes(`${wl}${o}`))?.get(`aria-label`)||``;r=e={annotationType:G.STAMP,bitmapId:f.id,bitmap:f.bitmap,pageIndex:u-1,rect:i.slice(0),rotation:a,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:s,popupRef:c}}let i=await super.deserialize(e,t,n),{rect:a,bitmap:o,bitmapUrl:s,bitmapId:c,isSvg:l,accessibilityData:u}=e;c&&n.imageManager.isValidId(c)?(i.#t=c,o&&(i.#e=o)):i.#r=s,i.#c=l;let[d,f]=i.pageDimensions;return i.width=(a[2]-a[0])/d,i.height=(a[3]-a[1])/f,i.annotationElementId=e.id||null,u&&(i.altTextData=u),i._initialData=r,i.#l=!!r,i}serialize(e=!1,t=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n={annotationType:G.STAMP,bitmapId:this.#t,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(e)return n.bitmapUrl=this.#g(!0),n.accessibilityData=this.serializeAltText(!0),n;let{decorative:r,altText:i}=this.serializeAltText(!1);if(!r&&i&&(n.accessibilityData={type:`Figure`,alt:i}),this.annotationElementId){let e=this.#_(n);if(e.isSame)return null;e.isSameAltText?delete n.accessibilityData:n.accessibilityData.structParent=this._initialData.structParent??-1}if(n.id=this.annotationElementId,t===null)return n;t.stamps||=new Map;let a=this.#c?(n.rect[2]-n.rect[0])*(n.rect[3]-n.rect[1]):null;if(!t.stamps.has(this.#t))t.stamps.set(this.#t,{area:a,serialized:n}),n.bitmap=this.#g(!1);else if(this.#c){let e=t.stamps.get(this.#t);a>e.area&&(e.area=a,e.serialized.bitmap.close(),e.serialized.bitmap=this.#g(!1))}return n}#_(e){let{pageIndex:t,accessibilityData:{altText:n}}=this._initialData,r=e.pageIndex===t,i=(e.accessibilityData?.alt||``)===n;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&r&&i,isSameAltText:i}}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}},yp=class e{#e;#t=!1;#n=null;#r=null;#i=null;#a=new Map;#o=!1;#s=!1;#c=!1;#l=null;#u=null;#d=null;#f=null;#p;static _initialized=!1;static#m=new Map([rp,_p,vp,dp].map(e=>[e._editorType,e]));constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:i,accessibilityManager:a,annotationLayer:o,drawLayer:s,textLayer:c,viewport:l,l10n:u}){let d=[...e.#m.values()];if(!e._initialized){e._initialized=!0;for(let e of d)e.initialize(u,t)}t.registerEditorTypes(d),this.#p=t,this.pageIndex=n,this.div=r,this.#e=a,this.#n=o,this.viewport=l,this.#d=c,this.drawLayer=s,this._structTree=i,this.#p.addLayer(this)}get isEmpty(){return this.#a.size===0}get isInvisible(){return this.isEmpty&&this.#p.getMode()===G.NONE}updateToolbar(e){this.#p.updateToolbar(e)}updateMode(t=this.#p.getMode()){switch(this.#y(),t){case G.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case G.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case G.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:n}=this.div;for(let r of e.#m.values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(e){return e===this.#d?.div}setEditingState(e){this.#p.setEditingState(e)}addCommands(e){this.#p.addCommands(e)}cleanUndoStack(e){this.#p.cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle(`drawing`,!e)}togglePointerEvents(e=!1){this.div.classList.toggle(`disabled`,!e)}toggleAnnotationLayerPointerEvents(e=!1){this.#n?.div.classList.toggle(`disabled`,!e)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);let e=new Set;for(let t of this.#a.values())t.enableEditing(),t.show(!0),t.annotationElementId&&(this.#p.removeChangedExistingAnnotation(t),e.add(t.annotationElementId));if(!this.#n){this.#c=!1;return}let t=this.#n.getEditableAnnotations();for(let n of t){if(n.hide(),this.#p.isDeletedAnnotationElement(n.data.id)||e.has(n.data.id))continue;let t=await this.deserialize(n);t&&(this.addOrRebuild(t),t.enableEditing())}this.#c=!1}disable(){this.#s=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let t=new Map,n=new Map;for(let e of this.#a.values())if(e.disableEditing(),e.annotationElementId){if(e.serialize()!==null){t.set(e.annotationElementId,e);continue}else n.set(e.annotationElementId,e);this.getEditableAnnotation(e.annotationElementId)?.show(),e.remove()}if(this.#n){let e=this.#n.getEditableAnnotations();for(let r of e){let{id:e}=r.data;if(this.#p.isDeletedAnnotationElement(e))continue;let i=n.get(e);if(i){i.resetAnnotationElement(r),i.show(!1),r.show();continue}i=t.get(e),i&&(this.#p.addChangedExistingAnnotation(i),i.renderAnnotationElement(r)&&i.show(!1)),r.show()}}this.#y(),this.isEmpty&&(this.div.hidden=!0);let{classList:r}=this.div;for(let t of e.#m.values())r.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#s=!1}getEditableAnnotation(e){return this.#n?.getEditableAnnotation(e)||null}setActiveEditor(e){this.#p.getActive()!==e&&this.#p.setActiveEditor(e)}enableTextSelection(){if(this.div.tabIndex=-1,this.#d?.div&&!this.#f){this.#f=new AbortController;let e=this.#p.combinedSignal(this.#f);this.#d.div.addEventListener(`pointerdown`,this.#h.bind(this),{signal:e}),this.#d.div.classList.add(`highlighting`)}}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#d.div.classList.remove(`highlighting`))}#h(e){this.#p.unselectAll();let{target:t}=e;if(t===this.#d.div||(t.getAttribute(`role`)===`img`||t.classList.contains(`endOfContent`))&&this.#d.div.contains(t)){let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t)return;this.#p.showAllEditors(`highlight`,!0,!0),this.#d.div.classList.add(`free`),this.toggleDrawing(),dp.startHighlighting(this,this.#p.direction===`ltr`,{target:this.#d.div,x:e.x,y:e.y}),this.#d.div.addEventListener(`pointerup`,()=>{this.#d.div.classList.remove(`free`),this.toggleDrawing(!0)},{once:!0,signal:this.#p._signal}),e.preventDefault()}}enableClick(){if(this.#r)return;this.#r=new AbortController;let e=this.#p.combinedSignal(this.#r);this.div.addEventListener(`pointerdown`,this.pointerdown.bind(this),{signal:e});let t=this.pointerup.bind(this);this.div.addEventListener(`pointerup`,t,{signal:e}),this.div.addEventListener(`pointercancel`,t,{signal:e})}disableClick(){this.#r?.abort(),this.#r=null}attach(e){this.#a.set(e.id,e);let{annotationElementId:t}=e;t&&this.#p.isDeletedAnnotationElement(t)&&this.#p.removeDeletedAnnotationElement(e)}detach(e){this.#a.delete(e.id),this.#e?.removePointerInTextLayer(e.contentDiv),!this.#s&&e.annotationElementId&&this.#p.addDeletedAnnotationElement(e)}remove(e){this.detach(e),this.#p.removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){e.parent!==this&&(e.parent&&e.annotationElementId&&(this.#p.addDeletedAnnotationElement(e.annotationElementId),Q.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),e.parent?.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),this.#p.addEditor(e),this.attach(e),!e.isAttachedToDOM){let t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!this.#c),this.#p.addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){if(!e.isAttachedToDOM)return;let{activeElement:t}=document;e.div.contains(t)&&!this.#i&&(e._focusEventsAllowed=!1,this.#i=setTimeout(()=>{this.#i=null,e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this.#p._signal}),t.focus())},0)),e._structTreeParentId=this.#e?.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||=this,e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){this.addCommands({cmd:()=>e._uiManager.rebuild(e),undo:()=>{e.remove()},mustExec:!1})}getNextId(){return this.#p.getId()}get#g(){return e.#m.get(this.#p.getMode())}combinedSignal(e){return this.#p.combinedSignal(e)}#_(e){let t=this.#g;return t?new t.prototype.constructor(e):null}canCreateNewEmptyEditor(){return this.#g?.canCreateNewEmptyEditor()}pasteEditor(e,t){this.#p.updateToolbar(e),this.#p.updateMode(e);let{offsetX:n,offsetY:r}=this.#v(),i=this.getNextId(),a=this.#_({parent:this,id:i,x:n,y:r,uiManager:this.#p,isCentered:!0,...t});a&&this.add(a)}async deserialize(t){return await e.#m.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#p)||null}createAndAddNewEditor(e,t,n={}){let r=this.getNextId(),i=this.#_({parent:this,id:r,x:e.offsetX,y:e.offsetY,uiManager:this.#p,isCentered:t,...n});return i&&this.add(i),i}#v(){let{x:e,y:t,width:n,height:r}=this.div.getBoundingClientRect(),i=Math.max(0,e),a=Math.max(0,t),o=Math.min(window.innerWidth,e+n),s=Math.min(window.innerHeight,t+r),c=(i+o)/2-e,l=(a+s)/2-t,[u,d]=this.viewport.rotation%180==0?[c,l]:[l,c];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#v(),!0)}setSelected(e){this.#p.setSelected(e)}toggleSelected(e){this.#p.toggleSelected(e)}unselect(e){this.#p.unselect(e)}pointerup(e){let{isMac:t}=_l.platform;if(!(e.button!==0||e.ctrlKey&&t)&&e.target===this.div&&this.#o&&(this.#o=!1,!(this.#g?.isDrawer&&this.#g.supportMultipleDrawings))){if(!this.#t){this.#t=!0;return}if(this.#p.getMode()===G.STAMP){this.#p.unselectAll();return}this.createAndAddNewEditor(e,!1)}}pointerdown(e){if(this.#p.getMode()===G.HIGHLIGHT&&this.enableTextSelection(),this.#o){this.#o=!1;return}let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(this.#o=!0,this.#g?.isDrawer){this.startDrawingSession(e);return}let n=this.#p.getActive();this.#t=!n||n.isEmpty()}startDrawingSession(e){if(this.div.focus(),this.#l){this.#g.startDrawing(this,this.#p,!1,e);return}this.#p.setCurrentDrawingSession(this),this.#l=new AbortController;let t=this.#p.combinedSignal(this.#l);this.div.addEventListener(`blur`,({relatedTarget:e})=>{e&&!this.div.contains(e)&&(this.#u=null,this.commitOrRemove())},{signal:t}),this.#g.startDrawing(this,this.#p,!1,e)}pause(e){if(e){let{activeElement:e}=document;this.div.contains(e)&&(this.#u=e);return}this.#u&&setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(e=!1){return this.#l?(this.#p.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#u=null,this.#g.endDrawing(e)):null}findNewParent(e,t,n){let r=this.#p.findParent(t,n);return r===null||r===this?!1:(r.changeParent(e),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#g.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#p.getActive()?.parent===this&&(this.#p.commitOrRemove(),this.#p.setActiveEditor(null)),this.#i&&=(clearTimeout(this.#i),null);for(let e of this.#a.values())this.#e?.removePointerInTextLayer(e.contentDiv),e.setParent(null),e.isAttachedToDOM=!1,e.div.remove();this.div=null,this.#a.clear(),this.#p.removeLayer(this)}#y(){for(let e of this.#a.values())e.isEmpty()&&e.remove()}render({viewport:e}){this.viewport=e,Wl(this.div,e);for(let e of this.#p.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:e}){this.#p.commitOrRemove(),this.#y();let t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,Wl(this.div,{rotation:n}),t!==n)for(let e of this.#a.values())e.rotate(n)}get pageDimensions(){let{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return this.#p.viewParameters.realScale}},bp=class e{#e=null;#t=0;#n=new Map;#r=new Map;constructor({pageIndex:e}){this.pageIndex=e}setParent(e){if(!this.#e){this.#e=e;return}if(this.#e!==e){if(this.#n.size>0)for(let t of this.#n.values())t.remove(),e.append(t);this.#e=e}}static get _svgFactory(){return Y(this,`_svgFactory`,new Sf)}static#i(e,[t,n,r,i]){let{style:a}=e;a.top=`${100*n}%`,a.left=`${100*t}%`,a.width=`${100*r}%`,a.height=`${100*i}%`}#a(){let t=e._svgFactory.create(1,1,!0);return this.#e.append(t),t.setAttribute(`aria-hidden`,!0),t}#o(t,n){let r=e._svgFactory.createElement(`clipPath`);t.append(r);let i=`clip_${n}`;r.setAttribute(`id`,i),r.setAttribute(`clipPathUnits`,`objectBoundingBox`);let a=e._svgFactory.createElement(`use`);return r.append(a),a.setAttribute(`href`,`#${n}`),a.classList.add(`clip`),i}#s(e,t){for(let[n,r]of Object.entries(t))r===null?e.removeAttribute(n):e.setAttribute(n,r)}draw(t,n=!1,r=!1){let i=this.#t++,a=this.#a(),o=e._svgFactory.createElement(`defs`);a.append(o);let s=e._svgFactory.createElement(`path`);o.append(s);let c=`path_p${this.pageIndex}_${i}`;s.setAttribute(`id`,c),s.setAttribute(`vector-effect`,`non-scaling-stroke`),n&&this.#r.set(i,s);let l=r?this.#o(o,c):null,u=e._svgFactory.createElement(`use`);return a.append(u),u.setAttribute(`href`,`#${c}`),this.updateProperties(a,t),this.#n.set(i,a),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,n){let r=this.#t++,i=this.#a(),a=e._svgFactory.createElement(`defs`);i.append(a);let o=e._svgFactory.createElement(`path`);a.append(o);let s=`path_p${this.pageIndex}_${r}`;o.setAttribute(`id`,s),o.setAttribute(`vector-effect`,`non-scaling-stroke`);let c;if(n){let t=e._svgFactory.createElement(`mask`);a.append(t),c=`mask_p${this.pageIndex}_${r}`,t.setAttribute(`id`,c),t.setAttribute(`maskUnits`,`objectBoundingBox`);let n=e._svgFactory.createElement(`rect`);t.append(n),n.setAttribute(`width`,`1`),n.setAttribute(`height`,`1`),n.setAttribute(`fill`,`white`);let i=e._svgFactory.createElement(`use`);t.append(i),i.setAttribute(`href`,`#${s}`),i.setAttribute(`stroke`,`none`),i.setAttribute(`fill`,`black`),i.setAttribute(`fill-rule`,`nonzero`),i.classList.add(`mask`)}let l=e._svgFactory.createElement(`use`);i.append(l),l.setAttribute(`href`,`#${s}`),c&&l.setAttribute(`mask`,`url(#${c})`);let u=l.cloneNode();return i.append(u),l.classList.add(`mainOutline`),u.classList.add(`secondaryOutline`),this.updateProperties(i,t),this.#n.set(r,i),r}finalizeDraw(e,t){this.#r.delete(e),this.updateProperties(e,t)}updateProperties(t,n){if(!n)return;let{root:r,bbox:i,rootClass:a,path:o}=n,s=typeof t==`number`?this.#n.get(t):t;if(s){if(r&&this.#s(s,r),i&&e.#i(s,i),a){let{classList:e}=s;for(let[t,n]of Object.entries(a))e.toggle(t,n)}if(o){let e=s.firstChild.firstChild;this.#s(e,o)}}}updateParent(e,t){if(t===this)return;let n=this.#n.get(e);n&&(t.#e.append(n),this.#n.delete(e),t.#n.set(e,n))}remove(e){this.#r.delete(e),this.#e!==null&&(this.#n.get(e).remove(),this.#n.delete(e))}destroy(){this.#e=null;for(let e of this.#n.values())e.remove();this.#n.clear(),this.#r.clear()}};globalThis.pdfjsTestingUtils={HighlightOutliner:op},W.AbortException,W.AnnotationEditorLayer,W.AnnotationEditorParamsType,W.AnnotationEditorType,W.AnnotationEditorUIManager,W.AnnotationLayer,W.AnnotationMode,W.ColorPicker,W.DOMSVGFactory,W.DrawLayer,W.FeatureTest;var xp=W.GlobalWorkerOptions;W.ImageKind,W.InvalidPDFException,W.MissingPDFException,W.OPS,W.OutputScale,W.PDFDataRangeTransport,W.PDFDateString,W.PDFWorker,W.PasswordResponses,W.PermissionFlag,W.PixelsPerInch,W.RenderingCancelledException,W.TextLayer,W.TouchManager,W.UnexpectedResponseException,W.Util,W.VerbosityLevel,W.XfaLayer,W.build,W.createValidAbsoluteUrl,W.fetchData;var Sp=W.getDocument;W.getFilenameFromUrl,W.getPdfFilenameFromUrl,W.getXfaPageViewport,W.isDataScheme,W.isPdfFile,W.noContextMenu,W.normalizeUnicode,W.setLayerDimensions,W.shadow,W.stopEvent;var Cp=W.version,wp=null;function Tp(){let e=document.createElement(`div`);e.style.width=`1in`,document.body.append(e);let t=e.offsetWidth;return e.remove(),t}function Ep(){let e=wp??Tp();return wp=e,e/72}function Dp(e,t=500){if(typeof e!=`function`)throw TypeError(`The first argument is not a function.`);let n=null;return function(...r){n&&clearTimeout(n),n=setTimeout(()=>{n=null,e.apply(this,r)},t)}}function Op(e){return e.arrayBuffer?e.arrayBuffer():new Promise((t,n)=>{let r=new FileReader;r.addEventListener(`load`,()=>{let e=r.result;if(!(e instanceof ArrayBuffer)){n(Error(`Failed to read file as ArrayBuffer.`));return}t(e)}),r.addEventListener(`error`,n),r.readAsArrayBuffer(e)})}Ap()||(xp.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Cp}/pdf.worker.min.mjs`);function kp(){if(typeof window>`u`)return!0;try{return window.self===window.top}catch{return!1}}function Ap(){try{return typeof OffscreenCanvas<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen==`function`&&kp()}catch{return!1}}function jp(e,t){let n=Ep()/window.devicePixelRatio,r={...e,id:t,units:n};return Ap()?Mp(r):Np(r)}async function Mp({data:e,password:t,id:n,page:r,units:i,scale:a}){let o=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require("url").pathToFileURL(__dirname+`/assets/pdfjs.worker-635tbwI0.js`).href:new URL(`assets/pdfjs.worker-635tbwI0.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});try{return o.postMessage({data:e,password:t,id:n,page:r,units:i,scale:a}),await new Promise((e,t)=>{let r=i=>{if(i.data.status){if(i.data.status===`success`){let{bitmap:t,width:r,height:a,pages:o}=i.data;if(t&&n){let n=document.createElement(`canvas`),i=n.getContext(`2d`);n.width=r,n.height=a,i?.drawImage(t,0,0),t.close(),e({pages:o,canvas:n})}else e({pages:o,canvas:null})}i.data.status===`error`&&t(i.data.error),o.removeEventListener(`message`,r)}};o.addEventListener(`message`,r),o.addEventListener(`error`,e=>{t(Error(`Worker error: ${e.message}`))},{once:!0})})}finally{o.terminate()}}async function Np({data:e,password:t,id:n,page:r,scale:i,units:a}){let o=await Sp({data:await Op(e),password:t}).promise;try{let e=o.numPages;if(!n)return{canvas:null,pages:e};let t=await o.getPage(r),s=t.getViewport({scale:i}),c=document.createElement(`canvas`),l=c.getContext(`2d`);if(!l)throw Error(`Failed to get 2d context`);let u={canvasContext:l,viewport:s,transform:[a,0,0,a,0,0]};return c.width=Math.floor(s.width*a),c.height=Math.floor(s.height*a),await t.render(u).promise,{canvas:c,pages:e}}finally{o.destroy()}}var Pp=new Map;function Fp(e){let t=new jo(e);return Pp.set(e,t),t}function Ip(e){let t=Date.now();return{PDFId:`${e.name}-${t}`,name:e.name.replace(/.pdf/,``),updateDate:t,data:e}}async function Lp({src:e},t,n){if(!e||!n)return null;let{objects:r,options:i}=await Ys(e),a=r.filter(e=>e!==null),o=oo.groupSVGElements(a,i);for(let e of a)e.stroke=n;return o.hoverCursor=`pointer`,o.stroke=`${n}-${t}`,o}function Rp(e,t){Pp.get(e)&&Vp(e,qp(t,1/3))}async function zp(e,t){let n=Date.now(),r={PDFId:`${e.name}-${n}`,name:e.name.replace(/.png|.jpg|.jpeg/,``),updateDate:n,data:e};return t&&Bp(t,{data:e}),{...r,pages:1}}async function Bp(e,{data:t,scale:n=.5}){if(!Pp.get(e))return;let r=URL.createObjectURL(t),i=await Fs.fromURL(r);i.scale(n),Vp(e,i),URL.revokeObjectURL(r)}function Vp(e,t){let n=Pp.get(e);n&&(n.setDimensions({width:t.getScaledWidth(),height:t.getScaledHeight()}),t.set({originX:`left`,originY:`top`,left:0,top:0}),n.backgroundImage=t,n.renderAll())}function Hp(e,t){if(!t)return;let{oCoords:n}=e;if(!n)return;let{x:r,y:i}=n.tl.touchCorner.tl,{height:a,width:o,scaleY:s,scaleX:c}=t;t.top=i-a*s/2,t.left=r-o*c/2,t.setCoords()}function Up(e,t,n){!n||!e||(n.scale(1/t),Hp(e,n))}function Wp(e,t){if(!e)return;let n=e._cornerSize||6;e.borderScaleFactor=1/t,e.cornerSize=1/t*n,e.touchCornerSize=n*4*(1/t),e.setCoords()}function Gp(e){let t=Pp.get(e);t&&(t.discardActiveObject(),t.renderAll())}function Kp(e){let t=Pp.get(e);t&&(t.clear(),Pp.delete(e))}function qp(e,t){return new Fs(e,{scaleX:t,scaleY:t})}function Jp(e,t){if(!t)return;let{left:n,top:r}=e,i=t.x*e.getScaledWidth(),a=t.y*e.getScaledHeight();e.set({left:n-i,top:r-a,originX:`left`,originY:`top`})}function Yp(e,t,n){let r=e.type;return{"application/pdf":Xp,"image/png":Qp,"image/jpeg":Qp}[r]?.(e,t,n)??Promise.reject(Error(`Unsupported ${r} file type.`))}async function Xp(e,t,n){let r=Ip(e),i=await Zp({page:1,data:e,scale:.8,password:t},n);return{...r,pages:i}}async function Zp(e,t){let{canvas:n,pages:r}=await jp(e,t);return n&&t&&Rp(t,n),r}async function Qp(e,t,n){return await zp(e,n)}function $p(e,t){let n=Pp.get(e);if(!n)return;let r=n.getActiveObject();r&&(r instanceof Ca?r.forEachObject(e=>{e.set(t)}):r.set(t),n.renderAll())}async function em(e,t){let n=Pp.get(e);if(!n)return;let r=n?.getActiveObject();if(!r)return;let i=await r.clone(c);i instanceof Ca?i.forEachObject(e=>{n.add(e),t(n,e)}):(n.add(i),t(n,i)),Jp(i,{x:-.1,y:-.1}),n.setActiveObject(i)}function tm(e){let t=Pp.get(e);if(!t)return;let n=t.getActiveObject();n&&(n instanceof Ca?(n.forEachObject(e=>{t.remove(e)}),t.discardActiveObject()):t.remove(n))}function nm(e){let{id:n=``,selectionOptions:r,pointerDown:o,pointerMove:c,pointerUp:l,selectionCreated:u,selectionCleared:d}=e||{},f=(0,t.useRef)(null),p=(0,t.useRef)(null),m=(0,t.useRef)(1),h=(0,t.useRef)({...s});function g(){if(!n||Pp.has(n))return;let e=Fp(n);return e.on(`selection:created`,t=>{if(u?.(t),t.selected.length<=1)return;let n=e.getActiveObject();n&&(p.current=n,r?.value&&p.current.set(r.value),p.current._cornerSize=p.current.cornerSize,T(m.current))}),e.on(`selection:cleared`,t=>{d?.(t),D(e)}),o&&e.on(`mouse:down`,o),c&&e.on(`mouse:move`,c),l&&e.on(`mouse:up`,l),e}function _(e,t){return Yp(e,t,n)}function v(e){return Zp(e,n)}function y({data:e,scale:t=.5}){return Bp(n,{data:e,scale:t})}async function b(e,t,r){let a=Pp.get(n);if(!a)return;let o=await Fs.fromURL(e,{},{...i,...t});Jp(o,r),a.add(o),S(a,o),a.setActiveObject(o)}function x(e,t,r){let i=Pp.get(n);if(!i)return;let o=new ls(e,{...a,...t});Jp(o,r),i.add(o),S(i,o),i.setActiveObject(o)}function S(e,t){t.on(`selected`,t=>C({canvas:e,target:t.target})),t.on(`modified`,t=>C({canvas:e,target:t.target})),t.on(`scaling`,()=>D(e)),t.on(`moving`,()=>D(e)),t.on(`rotating`,()=>D(e)),t._cornerSize=t._cornerSize??t.cornerSize}async function C({canvas:e,target:t,stroke:n=h.current.stroke,uuid:r=Date.now()}){if(e.getActiveObjects().length>1||f.current?.stroke===`${n}-${r}`)return;let i=await Lp(h.current,r,n);D(e),f.current=i,p.current=t,w(e,t,r),T(m.current,!0),i&&e.add(i)}function w(e,t,n){f.current&&(f.current.on(`selected`,()=>{e.remove(t),D(e)}),f.current.on(`mouseover`,()=>{C({canvas:e,target:t,stroke:h.current.hoverStroke,uuid:n})}),f.current.on(`mouseout`,()=>{C({canvas:e,target:t,stroke:h.current.stroke,uuid:n})}))}function T(e,t=!1){let r=Pp.get(n);m.current=e,r&&(Wp(p.current,e),Up(p.current,e,f.current),!t&&r.renderAll())}function E(e){if(!e)return;h.current={...h.current,...e};let t=Pp.get(n);!f||!p.current||!t||C({target:p.current,canvas:t})}function D(e){p.current=null,f.current&&=(e.remove(f.current),null)}function O(){Gp(n)}function k(){Kp(n)}function A(e){$p(n,e)}function j(){return em(n,S)}function M(){tm(n)}return{createCanvas:g,loadFile:_,specifyPage:v,renderImage:y,addFabric:b,addTextFabric:x,clearActive:O,deleteCanvas:k,scaleFabric:T,setCloseSvgOptions:E,setActiveFabric:A,copyActiveFabric:j,deleteActiveFabric:M}}function rm(e){let n=(0,t.useRef)(0);return(0,t.useEffect)(()=>{let t=Dp(()=>{let{innerWidth:t}=globalThis;t!==n.current&&(n.current=t,e())});return n.current=window.innerWidth,window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[]),null}var im=n((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),am=n((e=>{process.env.NODE_ENV!==`production`&&(function(){function t(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===O?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case _:return`Fragment`;case y:return`Profiler`;case v:return`StrictMode`;case C:return`Suspense`;case w:return`SuspenseList`;case D:return`Activity`}if(typeof e==`object`)switch(typeof e.tag==`number`&&console.error(`Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.`),e.$$typeof){case g:return`Portal`;case x:return e.displayName||`Context`;case b:return(e._context.displayName||`Context`)+`.Consumer`;case S:var n=e.render;return e=e.displayName,e||=(e=n.displayName||n.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case T:return n=e.displayName||null,n===null?t(e.type)||`Memo`:n;case E:n=e._payload,e=e._init;try{return t(e(n))}catch{}}return null}function n(e){return``+e}function r(e){try{n(e);var t=!1}catch{t=!0}if(t){t=console;var r=t.error,i=typeof Symbol==`function`&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||`Object`;return r.call(t,`The provided key is an unsupported type %s. This value must be coerced to a string before using it here.`,i),n(e)}}function i(e){if(e===_)return`<>`;if(typeof e==`object`&&e&&e.$$typeof===E)return`<...>`;try{var n=t(e);return n?`<`+n+`>`:`<...>`}catch{return`<...>`}}function a(){var e=k.A;return e===null?null:e.getOwner()}function o(){return Error(`react-stack-top-frame`)}function s(e){if(A.call(e,`key`)){var t=Object.getOwnPropertyDescriptor(e,`key`).get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function c(e,t){function n(){ee||(ee=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}n.isReactWarning=!0,Object.defineProperty(e,"key",{get:n,configurable:!0})}function l(){var e=t(this.type);return N[e]||(N[e]=!0,console.error(`Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.`)),e=this.props.ref,e===void 0?null:e}function u(e,t,n,r,i,a){var o=n.ref;return e={$$typeof:h,type:e,key:t,props:n,_owner:r},(o===void 0?null:o)===null?Object.defineProperty(e,"ref",{enumerable:!1,value:null}):Object.defineProperty(e,"ref",{enumerable:!1,get:l}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:i}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:a}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function d(e,n,i,o,l,d){var p=n.children;if(p!==void 0)if(o)if(j(p)){for(o=0;o<p.length;o++)f(p[o]);Object.freeze&&Object.freeze(p)}else console.error(`React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.`);else f(p);if(A.call(n,`key`)){p=t(e);var m=Object.keys(n).filter(function(e){return e!==`key`});o=0<m.length?`{key: someKey, `+m.join(`: ..., `)+`: ...}`:`{key: someKey}`,I[p+o]||(m=0<m.length?`{`+m.join(`: ..., `)+`: ...}`:`{}`,console.error(`A props object containing a "key" prop is being spread into JSX:
|
|
450
|
-
let props = %s;
|
|
451
|
-
<%s {...props} />
|
|
452
|
-
React keys must be passed directly to JSX without using spread:
|
|
453
|
-
let props = %s;
|
|
454
|
-
<%s key={someKey} {...props} />`,o,p,m,p),I[p+o]=!0)}if(p=null,i!==void 0&&(r(i),p=``+i),s(n)&&(r(n.key),p=``+n.key),`key`in n)for(var h in i={},n)h!==`key`&&(i[h]=n[h]);else i=n;return p&&c(i,typeof e==`function`?e.displayName||e.name||`Unknown`:e),u(e,p,i,a(),l,d)}function f(e){p(e)?e._store&&(e._store.validated=1):typeof e==`object`&&e&&e.$$typeof===E&&(e._payload.status===`fulfilled`?p(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function p(e){return typeof e==`object`&&!!e&&e.$$typeof===h}var m=require("react"),h=Symbol.for(`react.transitional.element`),g=Symbol.for(`react.portal`),_=Symbol.for(`react.fragment`),v=Symbol.for(`react.strict_mode`),y=Symbol.for(`react.profiler`),b=Symbol.for(`react.consumer`),x=Symbol.for(`react.context`),S=Symbol.for(`react.forward_ref`),C=Symbol.for(`react.suspense`),w=Symbol.for(`react.suspense_list`),T=Symbol.for(`react.memo`),E=Symbol.for(`react.lazy`),D=Symbol.for(`react.activity`),O=Symbol.for(`react.client.reference`),k=m.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,A=Object.prototype.hasOwnProperty,j=Array.isArray,M=console.createTask?console.createTask:function(){return null};m={react_stack_bottom_frame:function(e){return e()}};var ee,N={},P=m.react_stack_bottom_frame.bind(m,o)(),F=M(i(o)),I={};e.Fragment=_,e.jsx=function(e,t,n){var r=1e4>k.recentlyCreatedOwnerStacks++;return d(e,t,n,!1,r?Error(`react-stack-top-frame`):P,r?M(i(e)):F)},e.jsxs=function(e,t,n){var r=1e4>k.recentlyCreatedOwnerStacks++;return d(e,t,n,!0,r?Error(`react-stack-top-frame`):P,r?M(i(e)):F)}})()})),om=n(((e,t)=>{process.env.NODE_ENV===`production`?t.exports=im():t.exports=am()}))(),sm=(0,t.forwardRef)(cm);function cm({file:e,page:n=1,canvasId:r=`PDF-canvas`,fileZoom:i=1,fileScale:a=1,canvasScale:s=1,canvasClass:c=``,isDrop:l=!1,password:u,dropTextOptions:d,dropImageOptions:f,closeSvgOptions:p,selectionOptions:m,manualReload:h,onLoaded:g,onReload:_,onPointerDown:v,onPointerMove:y,onPointerUp:b,onSelectionCreated:x,onSelectionCleared:S},C){let w=(0,t.useRef)(null),T=`${r}-${n-1}`,E=(0,t.useMemo)(()=>i*s,[i,s]),{createCanvas:D,specifyPage:O,addFabric:k,addTextFabric:A,renderImage:j,clearActive:M,deleteCanvas:ee,scaleFabric:N,setActiveFabric:P,setCloseSvgOptions:F,copyActiveFabric:I,deleteActiveFabric:te}=nm({id:T,selectionOptions:(0,t.useMemo)(()=>({...o,...m}),[m]),pointerDown:v,pointerMove:y,pointerUp:b,selectionCreated:x,selectionCleared:S});rm(oe);async function ne(){requestAnimationFrame(async()=>{if(D(),e.data?.type.startsWith(`image/`)){let t=e.data;t&&j({data:t,scale:a/3}),g?.();return}let t=e.data;t&&await O({page:n,data:t,scale:a,password:u}),g?.()})}function re(e){if(e.preventDefault(),e.stopPropagation(),!l||!e.dataTransfer)return;let{dataTransfer:t,nativeEvent:n}=e,{offsetX:r,offsetY:i}=n,a=t.getData(`text/plain`),o=t.getData(`text/uri-list`),s=t.getData(`custom/offset`),c=s?JSON.parse(s):null,u={top:i,left:r},d={x:c?.offsetX??0,y:c?.offsetY??0};o?ie(o,u,d):a&&ae(a,u,d)}function ie(e,t,n){k(e,{...f,...t},n)}function ae(e,t,n){A(e,{...d,...t},n)}function oe(){h||ne(),_?.()}return(0,t.useImperativeHandle)(C,()=>({reload:ne,addImage:ie,addText:ae,clearActive:M,deleteCanvas:ee,setActiveFabric:P,copyActiveFabric:I,deleteActiveFabric:te,canvasRef:w})),(0,t.useEffect)(()=>{oe()},[a,n,e,u]),(0,t.useEffect)(()=>{N(E)},[E]),(0,t.useEffect)(()=>{F(p)},[p]),(0,t.useEffect)(()=>()=>ee(),[]),(0,om.jsx)(`div`,{style:{transform:`scale(${E})`},onDragOver:e=>e.preventDefault(),onDragEnter:e=>e.preventDefault(),onDrop:re,children:(0,om.jsx)(`canvas`,{id:T,ref:w,className:c})})}e.default=sm,e.loadFile=Yp,e.useFabric=nm});
|
|
447
|
+
`)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),this.editorDiv.append(t)}}#d(){return this.#t.replaceAll(`\xA0`,` `)}static#f(e){return e.replaceAll(` `,`\xA0`)}get contentDiv(){return this.editorDiv}static async deserialize(t,n,r){let i=null;if(t instanceof Vf){let{data:{defaultAppearanceData:{fontSize:e,fontColor:n},rect:r,rotation:a,id:o,popupRef:s},textContent:c,textPosition:l,parent:{page:{pageNumber:u}}}=t;if(!c||c.length===0)return null;i=t={annotationType:W.FREETEXT,color:Array.from(n),fontSize:e,value:c.join(`
|
|
448
|
+
`),position:l,pageIndex:u-1,rect:r.slice(0),rotation:a,id:o,deleted:!1,popupRef:s}}let a=await super.deserialize(t,n,r);return a.#i=t.fontSize,a.#e=X.makeHexColor(...t.color),a.#t=e.#f(t.value),a.annotationElementId=t.id||null,a._initialData=i,a}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n=e._internalPadding*this.parentScale,r=this.getRect(n,n),i=Q._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#e),a={annotationType:W.FREETEXT,color:i,fontSize:this.#i,value:this.#d(),pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?a:this.annotationElementId&&!this.#p(a)?null:(a.id=this.annotationElementId,a)}#p(e){let{value:t,fontSize:n,color:r,pageIndex:i}=this._initialData;return this._hasBeenMoved||e.value!==t||e.fontSize!==n||e.color.some((e,t)=>e!==r[t])||e.pageIndex!==i}renderAnnotationElement(t){let n=super.renderAnnotationElement(t);if(this.deleted)return n;let{style:r}=n;r.fontSize=`calc(${this.#i}px * var(--scale-factor))`,r.color=this.#e,n.replaceChildren();for(let e of this.#t.split(`
|
|
449
|
+
`)){let t=document.createElement(`div`);t.append(e?document.createTextNode(e):document.createElement(`br`)),n.append(t)}let i=e._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#t}),n}resetAnnotationElement(e){super.resetAnnotationElement(e),e.resetEdited()}},$=class{static PRECISION=1e-4;toSVGPath(){q("Abstract method `toSVGPath` must be implemented.")}get box(){q("Abstract getter `box` must be implemented.")}serialize(e,t){q("Abstract method `serialize` must be implemented.")}static _rescale(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o<s;o+=2)a[o]=t+e[o]*r,a[o+1]=n+e[o+1]*i;return a}static _rescaleAndSwap(e,t,n,r,i,a){a||=new Float32Array(e.length);for(let o=0,s=e.length;o<s;o+=2)a[o]=t+e[o+1]*r,a[o+1]=n+e[o]*i;return a}static _translate(e,t,n,r){r||=new Float32Array(e.length);for(let i=0,a=e.length;i<a;i+=2)r[i]=t+e[i],r[i+1]=n+e[i+1];return r}static svgRound(e){return Math.round(e*1e4)}static _normalizePoint(e,t,n,r,i){switch(i){case 90:return[1-t/n,e/r];case 180:return[1-e/n,1-t/r];case 270:return[t/n,1-e/r];default:return[e/n,t/r]}}static _normalizePagePoint(e,t,n){switch(n){case 90:return[1-t,e];case 180:return[1-e,1-t];case 270:return[t,1-e];default:return[e,t]}}static createBezierPoints(e,t,n,r,i,a){return[(e+5*n)/6,(t+5*r)/6,(5*n+i)/6,(5*r+a)/6,(n+i)/2,(r+a)/2]}},ip=class e{#e;#t=[];#n;#r;#i=[];#a=new Float32Array(18);#o;#s;#c;#l;#u;#d;#f=[];static#p=8;static#m=2;static#h=e.#p+e.#m;constructor({x:t,y:n},r,i,a,o,s=0){this.#e=r,this.#d=a*i,this.#r=o,this.#a.set([NaN,NaN,NaN,NaN,t,n],6),this.#n=s,this.#l=e.#p*i,this.#c=e.#h*i,this.#u=i,this.#f.push(t,n)}isEmpty(){return isNaN(this.#a[8])}#g(){let e=this.#a.subarray(4,6),t=this.#a.subarray(16,18),[n,r,i,a]=this.#e;return[(this.#o+(e[0]-t[0])/2-n)/i,(this.#s+(e[1]-t[1])/2-r)/a,(this.#o+(t[0]-e[0])/2-n)/i,(this.#s+(t[1]-e[1])/2-r)/a]}add({x:e,y:t}){this.#o=e,this.#s=t;let[n,r,i,a]=this.#e,[o,s,c,l]=this.#a.subarray(8,12),u=e-c,d=t-l,f=Math.hypot(u,d);if(f<this.#c)return!1;let p=f-this.#l,m=p/f,h=m*u,g=m*d,_=o,v=s;o=c,s=l,c+=h,l+=g,this.#f?.push(e,t);let y=-g/p,b=h/p,x=y*this.#d,S=b*this.#d;return this.#a.set(this.#a.subarray(2,8),0),this.#a.set([c+x,l+S],4),this.#a.set(this.#a.subarray(14,18),12),this.#a.set([c-x,l-S],16),isNaN(this.#a[6])?(this.#i.length===0&&(this.#a.set([o+x,s+S],2),this.#i.push(NaN,NaN,NaN,NaN,(o+x-n)/i,(s+S-r)/a),this.#a.set([o-x,s-S],14),this.#t.push(NaN,NaN,NaN,NaN,(o-x-n)/i,(s-S-r)/a)),this.#a.set([_,v,o,s,c,l],6),!this.isEmpty()):(this.#a.set([_,v,o,s,c,l],6),Math.abs(Math.atan2(v-s,_-o)-Math.atan2(g,h))<Math.PI/2?([o,s,c,l]=this.#a.subarray(2,6),this.#i.push(NaN,NaN,NaN,NaN,((o+c)/2-n)/i,((s+l)/2-r)/a),[o,s,_,v]=this.#a.subarray(14,18),this.#t.push(NaN,NaN,NaN,NaN,((_+o)/2-n)/i,((v+s)/2-r)/a),!0):([_,v,o,s,c,l]=this.#a.subarray(0,6),this.#i.push(((_+5*o)/6-n)/i,((v+5*s)/6-r)/a,((5*o+c)/6-n)/i,((5*s+l)/6-r)/a,((o+c)/2-n)/i,((s+l)/2-r)/a),[c,l,o,s,_,v]=this.#a.subarray(12,18),this.#t.push(((_+5*o)/6-n)/i,((v+5*s)/6-r)/a,((5*o+c)/6-n)/i,((5*s+l)/6-r)/a,((o+c)/2-n)/i,((s+l)/2-r)/a),!0))}toSVGPath(){if(this.isEmpty())return``;let e=this.#i,t=this.#t;if(isNaN(this.#a[6])&&!this.isEmpty())return this.#_();let n=[];n.push(`M${e[4]} ${e[5]}`);for(let t=6;t<e.length;t+=6)isNaN(e[t])?n.push(`L${e[t+4]} ${e[t+5]}`):n.push(`C${e[t]} ${e[t+1]} ${e[t+2]} ${e[t+3]} ${e[t+4]} ${e[t+5]}`);this.#y(n);for(let e=t.length-6;e>=6;e-=6)isNaN(t[e])?n.push(`L${t[e+4]} ${t[e+5]}`):n.push(`C${t[e]} ${t[e+1]} ${t[e+2]} ${t[e+3]} ${t[e+4]} ${t[e+5]}`);return this.#v(n),n.join(` `)}#_(){let[e,t,n,r]=this.#e,[i,a,o,s]=this.#g();return`M${(this.#a[2]-e)/n} ${(this.#a[3]-t)/r} L${(this.#a[4]-e)/n} ${(this.#a[5]-t)/r} L${i} ${a} L${o} ${s} L${(this.#a[16]-e)/n} ${(this.#a[17]-t)/r} L${(this.#a[14]-e)/n} ${(this.#a[15]-t)/r} Z`}#v(e){let t=this.#t;e.push(`L${t[4]} ${t[5]} Z`)}#y(e){let[t,n,r,i]=this.#e,a=this.#a.subarray(4,6),o=this.#a.subarray(16,18),[s,c,l,u]=this.#g();e.push(`L${(a[0]-t)/r} ${(a[1]-n)/i} L${s} ${c} L${l} ${u} L${(o[0]-t)/r} ${(o[1]-n)/i}`)}newFreeDrawOutline(e,t,n,r,i,a){return new ap(e,t,n,r,i,a)}getOutlines(){let e=this.#i,t=this.#t,n=this.#a,[r,i,a,o]=this.#e,s=new Float32Array((this.#f?.length??0)+2);for(let e=0,t=s.length-2;e<t;e+=2)s[e]=(this.#f[e]-r)/a,s[e+1]=(this.#f[e+1]-i)/o;if(s[s.length-2]=(this.#o-r)/a,s[s.length-1]=(this.#s-i)/o,isNaN(n[6])&&!this.isEmpty())return this.#b(s);let c=new Float32Array(this.#i.length+24+this.#t.length),l=e.length;for(let t=0;t<l;t+=2){if(isNaN(e[t])){c[t]=c[t+1]=NaN;continue}c[t]=e[t],c[t+1]=e[t+1]}l=this.#S(c,l);for(let e=t.length-6;e>=6;e-=6)for(let n=0;n<6;n+=2){if(isNaN(t[e+n])){c[l]=c[l+1]=NaN,l+=2;continue}c[l]=t[e+n],c[l+1]=t[e+n+1],l+=2}return this.#x(c,l),this.newFreeDrawOutline(c,s,this.#e,this.#u,this.#n,this.#r)}#b(e){let t=this.#a,[n,r,i,a]=this.#e,[o,s,c,l]=this.#g(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(t[2]-n)/i,(t[3]-r)/a,NaN,NaN,NaN,NaN,(t[4]-n)/i,(t[5]-r)/a,NaN,NaN,NaN,NaN,o,s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,(t[16]-n)/i,(t[17]-r)/a,NaN,NaN,NaN,NaN,(t[14]-n)/i,(t[15]-r)/a],0),this.newFreeDrawOutline(u,e,this.#e,this.#u,this.#n,this.#r)}#x(e,t){let n=this.#t;return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6}#S(e,t){let n=this.#a.subarray(4,6),r=this.#a.subarray(16,18),[i,a,o,s]=this.#e,[c,l,u,d]=this.#g();return e.set([NaN,NaN,NaN,NaN,(n[0]-i)/o,(n[1]-a)/s,NaN,NaN,NaN,NaN,c,l,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-a)/s],t),t+=24}},ap=class extends ${#e;#t=new Float32Array(4);#n;#r;#i;#a;#o;constructor(e,t,n,r,i,a){super(),this.#o=e,this.#i=t,this.#e=n,this.#a=r,this.#n=i,this.#r=a,this.lastPoint=[NaN,NaN],this.#s(a);let[o,s,c,l]=this.#t;for(let t=0,n=e.length;t<n;t+=2)e[t]=(e[t]-o)/c,e[t+1]=(e[t+1]-s)/l;for(let e=0,n=t.length;e<n;e+=2)t[e]=(t[e]-o)/c,t[e+1]=(t[e+1]-s)/l}toSVGPath(){let e=[`M${this.#o[4]} ${this.#o[5]}`];for(let t=6,n=this.#o.length;t<n;t+=6){if(isNaN(this.#o[t])){e.push(`L${this.#o[t+4]} ${this.#o[t+5]}`);continue}e.push(`C${this.#o[t]} ${this.#o[t+1]} ${this.#o[t+2]} ${this.#o[t+3]} ${this.#o[t+4]} ${this.#o[t+5]}`)}return e.push(`Z`),e.join(` `)}serialize([e,t,n,r],i){let a=n-e,o=r-t,s,c;switch(i){case 0:s=$._rescale(this.#o,e,r,a,-o),c=$._rescale(this.#i,e,r,a,-o);break;case 90:s=$._rescaleAndSwap(this.#o,e,t,a,o),c=$._rescaleAndSwap(this.#i,e,t,a,o);break;case 180:s=$._rescale(this.#o,n,t,-a,o),c=$._rescale(this.#i,n,t,-a,o);break;case 270:s=$._rescaleAndSwap(this.#o,n,r,-a,-o),c=$._rescaleAndSwap(this.#i,n,r,-a,-o)}return{outline:Array.from(s),points:[Array.from(c)]}}#s(e){let t=this.#o,n=t[4],r=t[5],i=n,a=r,o=n,s=r,c=n,l=r,u=e?Math.max:Math.min;for(let e=6,d=t.length;e<d;e+=6){if(isNaN(t[e]))i=Math.min(i,t[e+4]),a=Math.min(a,t[e+5]),o=Math.max(o,t[e+4]),s=Math.max(s,t[e+5]),l<t[e+5]?(c=t[e+4],l=t[e+5]):l===t[e+5]&&(c=u(c,t[e+4]));else{let d=X.bezierBoundingBox(n,r,...t.slice(e,e+6));i=Math.min(i,d[0]),a=Math.min(a,d[1]),o=Math.max(o,d[2]),s=Math.max(s,d[3]),l<d[3]?(c=d[2],l=d[3]):l===d[3]&&(c=u(c,d[2]))}n=t[e+4],r=t[e+5]}let d=this.#t;d[0]=i-this.#n,d[1]=a-this.#n,d[2]=o-i+2*this.#n,d[3]=s-a+2*this.#n,this.lastPoint=[c,l]}get box(){return this.#t}newOutliner(e,t,n,r,i,a=0){return new ip(e,t,n,r,i,a)}getNewOutline(e,t){let[n,r,i,a]=this.#t,[o,s,c,l]=this.#e,u=i*c,d=a*l,f=n*c+o,p=r*l+s,m=this.newOutliner({x:this.#i[0]*u+f,y:this.#i[1]*d+p},this.#e,this.#a,e,this.#r,t??this.#n);for(let e=2;e<this.#i.length;e+=2)m.add({x:this.#i[e]*u+f,y:this.#i[e+1]*d+p});return m.getOutlines()}},op=class{#e;#t;#n=[];#r=[];constructor(e,t=0,n=0,r=!0){let i=1/0,a=-1/0,o=1/0,s=-1/0,c=10**-4;for(let{x:n,y:r,width:l,height:u}of e){let e=Math.floor((n-t)/c)*c,d=Math.ceil((n+l+t)/c)*c,f=Math.floor((r-t)/c)*c,p=Math.ceil((r+u+t)/c)*c,m=[e,f,p,!0],h=[d,f,p,!1];this.#n.push(m,h),i=Math.min(i,e),a=Math.max(a,d),o=Math.min(o,f),s=Math.max(s,p)}let l=a-i+2*n,u=s-o+2*n,d=i-n,f=o-n,p=this.#n.at(r?-1:-2),m=[p[0],p[2]];for(let e of this.#n){let[t,n,r]=e;e[0]=(t-d)/l,e[1]=(n-f)/u,e[2]=(r-f)/u}this.#e=new Float32Array([d,f,l,u]),this.#t=m}getOutlines(){this.#n.sort((e,t)=>e[0]-t[0]||e[1]-t[1]||e[2]-t[2]);let e=[];for(let t of this.#n)t[3]?(e.push(...this.#c(t)),this.#o(t)):(this.#s(t),e.push(...this.#c(t)));return this.#i(e)}#i(e){let t=[],n=new Set;for(let n of e){let[e,r,i]=n;t.push([e,r,n],[e,i,n])}t.sort((e,t)=>e[1]-t[1]||e[0]-t[0]);for(let e=0,r=t.length;e<r;e+=2){let r=t[e][2],i=t[e+1][2];r.push(i),i.push(r),n.add(r),n.add(i)}let r=[],i;for(;n.size>0;){let e=n.values().next().value,[t,a,o,s,c]=e;n.delete(e);let l=t,u=a;for(i=[t,o],r.push(i);;){let e;if(n.has(s))e=s;else if(n.has(c))e=c;else break;n.delete(e),[t,a,o,s,c]=e,l!==t&&(i.push(l,u,t,u===a?a:o),l=t),u=u===a?o:a}i.push(l,u)}return new sp(r,this.#e,this.#t)}#a(e){let t=this.#r,n=0,r=t.length-1;for(;n<=r;){let i=n+r>>1,a=t[i][0];if(a===e)return i;a<e?n=i+1:r=i-1}return r+1}#o([,e,t]){let n=this.#a(e);this.#r.splice(n,0,[e,t])}#s([,e,t]){let n=this.#a(e);for(let r=n;r<this.#r.length;r++){let[n,i]=this.#r[r];if(n!==e)break;if(n===e&&i===t){this.#r.splice(r,1);return}}for(let r=n-1;r>=0;r--){let[n,i]=this.#r[r];if(n!==e)break;if(n===e&&i===t){this.#r.splice(r,1);return}}}#c(e){let[t,n,r]=e,i=[[t,n,r]],a=this.#a(r);for(let e=0;e<a;e++){let[n,r]=this.#r[e];for(let e=0,a=i.length;e<a;e++){let[,o,s]=i[e];if(!(r<=o||s<=n)){if(o>=n){if(s>r)i[e][1]=r;else{if(a===1)return[];i.splice(e,1),e--,a--}continue}i[e][2]=n,s>r&&i.push([t,r,s])}}}return i}},sp=class extends ${#e;#t;constructor(e,t,n){super(),this.#t=e,this.#e=t,this.lastPoint=n}toSVGPath(){let e=[];for(let t of this.#t){let[n,r]=t;e.push(`M${n} ${r}`);for(let i=2;i<t.length;i+=2){let a=t[i],o=t[i+1];a===n?(e.push(`V${o}`),r=o):o===r&&(e.push(`H${a}`),n=a)}e.push(`Z`)}return e.join(` `)}serialize([e,t,n,r],i){let a=[],o=n-e,s=r-t;for(let t of this.#t){let n=Array(t.length);for(let i=0;i<t.length;i+=2)n[i]=e+t[i]*o,n[i+1]=r-t[i+1]*s;a.push(n)}return a}get box(){return this.#e}get classNamesForOutlining(){return[`highlightOutline`]}},cp=class extends ip{newFreeDrawOutline(e,t,n,r,i,a){return new lp(e,t,n,r,i,a)}},lp=class extends ap{newOutliner(e,t,n,r,i,a=0){return new cp(e,t,n,r,i,a)}},up=class e{#e=null;#t=null;#n;#r=null;#i=!1;#a=!1;#o=null;#s;#c=null;#l=null;#u;static#d=null;static get _keyboardManager(){return Y(this,`_keyboardManager`,new Ql([[[`Escape`,`mac+Escape`],e.prototype._hideDropdownFromKeyboard],[[` `,`mac+ `],e.prototype._colorSelectFromKeyboard],[[`ArrowDown`,`ArrowRight`,`mac+ArrowDown`,`mac+ArrowRight`],e.prototype._moveToNext],[[`ArrowUp`,`ArrowLeft`,`mac+ArrowUp`,`mac+ArrowLeft`],e.prototype._moveToPrevious],[[`Home`,`mac+Home`],e.prototype._moveToBeginning],[[`End`,`mac+End`],e.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:n=null}){t?(this.#a=!1,this.#u=G.HIGHLIGHT_COLOR,this.#o=t):(this.#a=!0,this.#u=G.HIGHLIGHT_DEFAULT_COLOR),this.#l=t?._uiManager||n,this.#s=this.#l._eventBus,this.#n=t?.color||this.#l?.highlightColors.values().next().value||`#FFFF98`,e.#d||=Object.freeze({blue:`pdfjs-editor-colorpicker-blue`,green:`pdfjs-editor-colorpicker-green`,pink:`pdfjs-editor-colorpicker-pink`,red:`pdfjs-editor-colorpicker-red`,yellow:`pdfjs-editor-colorpicker-yellow`})}renderButton(){let e=this.#e=document.createElement(`button`);e.className=`colorPicker`,e.tabIndex=`0`,e.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-button`),e.setAttribute(`aria-haspopup`,!0);let t=this.#l._signal;e.addEventListener(`click`,this.#h.bind(this),{signal:t}),e.addEventListener(`keydown`,this.#m.bind(this),{signal:t});let n=this.#t=document.createElement(`span`);return n.className=`swatch`,n.setAttribute(`aria-hidden`,!0),n.style.backgroundColor=this.#n,e.append(n),e}renderMainDropdown(){let e=this.#r=this.#f();return e.setAttribute(`aria-orientation`,`horizontal`),e.setAttribute(`aria-labelledby`,`highlightColorPickerLabel`),e}#f(){let t=document.createElement(`div`),n=this.#l._signal;t.addEventListener(`contextmenu`,Ll,{signal:n}),t.className=`dropdown`,t.role=`listbox`,t.setAttribute(`aria-multiselectable`,!1),t.setAttribute(`aria-orientation`,`vertical`),t.setAttribute(`data-l10n-id`,`pdfjs-editor-colorpicker-dropdown`);for(let[r,i]of this.#l.highlightColors){let a=document.createElement(`button`);a.tabIndex=`0`,a.role=`option`,a.setAttribute(`data-color`,i),a.title=r,a.setAttribute(`data-l10n-id`,e.#d[r]);let o=document.createElement(`span`);a.append(o),o.className=`swatch`,o.style.backgroundColor=i,a.setAttribute(`aria-selected`,i===this.#n),a.addEventListener(`click`,this.#p.bind(this,i),{signal:n}),t.append(a)}return t.addEventListener(`keydown`,this.#m.bind(this),{signal:n}),t}#p(e,t){t.stopPropagation(),this.#s.dispatch(`switchannotationeditorparams`,{source:this,type:this.#u,value:e})}_colorSelectFromKeyboard(e){if(e.target===this.#e){this.#h(e);return}let t=e.target.getAttribute(`data-color`);t&&this.#p(t,e)}_moveToNext(e){if(!this.#_){this.#h(e);return}if(e.target===this.#e){this.#r.firstChild?.focus();return}e.target.nextSibling?.focus()}_moveToPrevious(e){if(e.target===this.#r?.firstChild||e.target===this.#e){this.#_&&this._hideDropdownFromKeyboard();return}this.#_||this.#h(e),e.target.previousSibling?.focus()}_moveToBeginning(e){if(!this.#_){this.#h(e);return}this.#r.firstChild?.focus()}_moveToEnd(e){if(!this.#_){this.#h(e);return}this.#r.lastChild?.focus()}#m(t){e._keyboardManager.exec(this,t)}#h(e){if(this.#_){this.hideDropdown();return}if(this.#i=e.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener(`pointerdown`,this.#g.bind(this),{signal:this.#l.combinedSignal(this.#c)})),this.#r){this.#r.classList.remove(`hidden`);return}let t=this.#r=this.#f();this.#e.append(t)}#g(e){this.#r?.contains(e.target)||this.hideDropdown()}hideDropdown(){this.#r?.classList.add(`hidden`),this.#c?.abort(),this.#c=null}get#_(){return this.#r&&!this.#r.classList.contains(`hidden`)}_hideDropdownFromKeyboard(){if(!this.#a){if(!this.#_){this.#o?.unselect();return}this.hideDropdown(),this.#e.focus({preventScroll:!0,focusVisible:this.#i})}}updateColor(e){if(this.#t&&(this.#t.style.backgroundColor=e),!this.#r)return;let t=this.#l.highlightColors.values();for(let n of this.#r.children)n.setAttribute(`aria-selected`,t.next().value===e)}destroy(){this.#e?.remove(),this.#e=null,this.#t=null,this.#r?.remove(),this.#r=null}},dp=class e extends Q{#e=null;#t=0;#n;#r=null;#i=null;#a=null;#o=null;#s=0;#c=null;#l=null;#u=null;#d=!1;#f=null;#p;#m=null;#h=``;#g;#_=``;static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type=`highlight`;static _editorType=W.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId=``;static get _keyboardManager(){let t=e.prototype;return Y(this,`_keyboardManager`,new Ql([[[`ArrowLeft`,`mac+ArrowLeft`],t._moveCaret,{args:[0]}],[[`ArrowRight`,`mac+ArrowRight`],t._moveCaret,{args:[1]}],[[`ArrowUp`,`mac+ArrowUp`],t._moveCaret,{args:[2]}],[[`ArrowDown`,`mac+ArrowDown`],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:`highlightEditor`}),this.color=t.color||e._defaultColor,this.#g=t.thickness||e._defaultThickness,this.#p=t.opacity||e._defaultOpacity,this.#n=t.boxes||null,this.#_=t.methodOfCreation||``,this.#h=t.text||``,this._isDraggable=!1,t.highlightId>-1?(this.#d=!0,this.#y(t),this.#w()):this.#n&&(this.#e=t.anchorNode,this.#t=t.anchorOffset,this.#o=t.focusNode,this.#s=t.focusOffset,this.#v(),this.#w(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:`added`,type:this.#d?`free_highlight`:`highlight`,color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#g,methodOfCreation:this.#_}}get telemetryFinalData(){return{type:`highlight`,color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get(`color`).size}}#v(){let e=new op(this.#n,.001);this.#l=e.getOutlines(),[this.x,this.y,this.width,this.height]=this.#l.box;let t=new op(this.#n,.0025,.001,this._uiManager.direction===`ltr`);this.#a=t.getOutlines();let{lastPoint:n}=this.#a;this.#f=[(n[0]-this.x)/this.width,(n[1]-this.y)/this.height]}#y({highlightOutlines:t,highlightId:n,clipPathId:r}){if(this.#l=t,this.#a=t.getNewOutline(this.#g/2+1.5,.0025),n>=0)this.#u=n,this.#r=r,this.parent.drawLayer.finalizeDraw(n,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#m=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},!0);else if(this.parent){let n=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#u,{bbox:e.#T(this.#l.box,(n-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#m,{bbox:e.#T(this.#a.box,n),path:{d:this.#a.toSVGPath()}})}let[i,a,o,s]=t.box;switch(this.rotation){case 0:this.x=i,this.y=a,this.width=o,this.height=s;break;case 90:{let[e,t]=this.parentDimensions;this.x=a,this.y=1-i,this.width=o*t/e,this.height=s*e/t;break}case 180:this.x=1-i,this.y=1-a,this.width=o,this.height=s;break;case 270:{let[e,t]=this.parentDimensions;this.x=1-a,this.y=i,this.width=o*t/e,this.height=s*e/t;break}}let{lastPoint:c}=this.#a;this.#f=[(c[0]-i)/o,(c[1]-a)/s]}static initialize(t,n){Q.initialize(t,n),e._defaultColor||=n.highlightColors?.values().next().value||`#fff066`}static updateDefaultParams(t,n){switch(t){case G.HIGHLIGHT_DEFAULT_COLOR:e._defaultColor=n;break;case G.HIGHLIGHT_THICKNESS:e._defaultThickness=n}}translateInPage(e,t){}get toolbarPosition(){return this.#f}updateParams(e,t){switch(e){case G.HIGHLIGHT_COLOR:this.#b(t);break;case G.HIGHLIGHT_THICKNESS:this.#x(t)}}static get defaultPropertiesToUpdate(){return[[G.HIGHLIGHT_DEFAULT_COLOR,e._defaultColor],[G.HIGHLIGHT_THICKNESS,e._defaultThickness]]}get propertiesToUpdate(){return[[G.HIGHLIGHT_COLOR,this.color||e._defaultColor],[G.HIGHLIGHT_THICKNESS,this.#g||e._defaultThickness],[G.HIGHLIGHT_FREE,this.#d]]}#b(t){let n=(e,t)=>{this.color=e,this.#p=t,this.parent?.drawLayer.updateProperties(this.#u,{root:{fill:e,"fill-opacity":t}}),this.#i?.updateColor(e)},r=this.color,i=this.#p;this.addCommands({cmd:n.bind(this,t,e._defaultOpacity),undo:n.bind(this,r,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`color_changed`,color:this._uiManager.highlightColorNames.get(t)},!0)}#x(e){let t=this.#g,n=e=>{this.#g=e,this.#S(e)};this.addCommands({cmd:n.bind(this,e),undo:n.bind(this,t),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:G.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:`thickness_changed`,thickness:e},!0)}async addEditToolbar(){let e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(this.#i=new up({editor:this}),e.addColorPicker(this.#i)),e):null}disableEditing(){super.disableEditing(),this.div.classList.toggle(`disabled`,!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle(`disabled`,!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(e,t){return super.getRect(e,t,this.#O())}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),e&&this.div.focus()}remove(){this.#C(),this._reportTelemetry({action:`deleted`}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#w(),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?this.#C():e&&(this.#w(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),this.show(this._isVisible),t&&this.select()}#S(e){if(!this.#d)return;this.#y({highlightOutlines:this.#l.getNewOutline(e/2)}),this.fixAndSetPosition();let[t,n]=this.parentDimensions;this.setDims(this.width*t,this.height*n)}#C(){this.#u===null||!this.parent||(this.parent.drawLayer.remove(this.#u),this.#u=null,this.parent.drawLayer.remove(this.#m),this.#m=null)}#w(e=this.parent){this.#u===null&&({id:this.#u,clipPathId:this.#r}=e.drawLayer.draw({bbox:this.#l.box,root:{viewBox:`0 0 1 1`,fill:this.color,"fill-opacity":this.#p},rootClass:{highlight:!0,free:this.#d},path:{d:this.#l.toSVGPath()}},!1,!0),this.#m=e.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#d},bbox:this.#a.box,path:{d:this.#a.toSVGPath()}},this.#d),this.#c&&(this.#c.style.clipPath=this.#r))}static#T([e,t,n,r],i){switch(i){case 90:return[1-t-r,e,r,n];case 180:return[1-e-n,1-t-r,n,r];case 270:return[t,1-e-n,r,n]}return[e,t,n,r]}rotate(t){let{drawLayer:n}=this.parent,r;this.#d?(t=(t-this.rotation+360)%360,r=e.#T(this.#l.box,t)):r=e.#T([this.x,this.y,this.width,this.height],t),n.updateProperties(this.#u,{bbox:r,root:{"data-main-rotation":t}}),n.updateProperties(this.#m,{bbox:e.#T(this.#a.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;let e=super.render();this.#h&&(e.setAttribute(`aria-label`,this.#h),e.setAttribute(`role`,`mark`)),this.#d?e.classList.add(`free`):this.div.addEventListener(`keydown`,this.#E.bind(this),{signal:this._uiManager._signal});let t=this.#c=document.createElement(`div`);e.append(t),t.setAttribute(`aria-hidden`,`true`),t.className=`internal`,t.style.clipPath=this.#r;let[n,r]=this.parentDimensions;return this.setDims(this.width*n,this.height*r),Jl(this,this.#c,[`pointerover`,`pointerleave`]),this.enableEditing(),e}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1}})}#E(t){e._keyboardManager.exec(this,t)}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:this.#D(!0);break;case 1:case 3:this.#D(!1)}}#D(e){if(!this.#e)return;let t=window.getSelection();e?t.setPosition(this.#e,this.#t):t.setPosition(this.#o,this.#s)}select(){super.select(),this.#m&&this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#m&&(this.parent?.drawLayer.updateProperties(this.#m,{rootClass:{selected:!1}}),this.#d||this.#D(!1))}get _mustFixPosition(){return!this.#d}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.updateProperties(this.#u,{rootClass:{hidden:!e}}),this.parent.drawLayer.updateProperties(this.#m,{rootClass:{hidden:!e}}))}#O(){return this.#d?this.rotation:0}#k(){if(this.#d)return null;let[e,t]=this.pageDimensions,[n,r]=this.pageTranslation,i=this.#n,a=new Float32Array(i.length*8),o=0;for(let{x:s,y:c,width:l,height:u}of i){let i=s*e+n,d=(1-c)*t+r;a[o]=a[o+4]=i,a[o+1]=a[o+3]=d,a[o+2]=a[o+6]=i+l*e,a[o+5]=a[o+7]=d-u*t,o+=8}return a}#A(e){return this.#l.serialize(e,this.#O())}static startHighlighting(e,t,{target:n,x:r,y:i}){let{x:a,y:o,width:s,height:c}=n.getBoundingClientRect(),l=new AbortController,u=e.combinedSignal(l),d=t=>{l.abort(),this.#M(e,t)};window.addEventListener(`blur`,d,{signal:u}),window.addEventListener(`pointerup`,d,{signal:u}),window.addEventListener(`pointerdown`,Rl,{capture:!0,passive:!1,signal:u}),window.addEventListener(`contextmenu`,Ll,{signal:u}),n.addEventListener(`pointermove`,this.#j.bind(this,e),{signal:u}),this._freeHighlight=new cp({x:r,y:i},[a,o,s,c],e.scale,this._defaultThickness/2,t,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:`0 0 1 1`,fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#j(e,t){this._freeHighlight.add(t)&&e.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#M(e,t){this._freeHighlight.isEmpty()?e.drawLayer.remove(this._freeHighlightId):e.createAndAddNewEditor(t,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:`main_toolbar`}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=``}static async deserialize(e,t,n){let r=null;if(e instanceof Yf){let{data:{quadPoints:t,rect:n,rotation:i,id:a,color:o,opacity:s,popupRef:c},parent:{page:{pageNumber:l}}}=e;r=e={annotationType:W.HIGHLIGHT,color:Array.from(o),opacity:s,quadPoints:t,boxes:null,pageIndex:l-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:c}}else if(e instanceof Jf){let{data:{inkLists:t,rect:n,rotation:i,id:a,color:o,borderStyle:{rawWidth:s},popupRef:c},parent:{page:{pageNumber:l}}}=e;r=e={annotationType:W.HIGHLIGHT,color:Array.from(o),thickness:s,inkLists:t,boxes:null,pageIndex:l-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:c}}let{color:i,quadPoints:a,inkLists:o,opacity:s}=e,c=await super.deserialize(e,t,n);c.color=X.makeHexColor(...i),c.#p=s||1,o&&(c.#g=e.thickness),c.annotationElementId=e.id||null,c._initialData=r;let[l,u]=c.pageDimensions,[d,f]=c.pageTranslation;if(a){let e=c.#n=[];for(let t=0;t<a.length;t+=8)e.push({x:(a[t]-d)/l,y:1-(a[t+1]-f)/u,width:(a[t+2]-a[t])/l,height:(a[t+1]-a[t+5])/u});c.#v(),c.#w(),c.rotate(c.rotation)}else if(o){c.#d=!0;let e=o[0],n={x:e[0]-d,y:u-(e[1]-f)},r=new cp(n,[0,0,l,u],1,c.#g/2,!0,.001);for(let t=0,i=e.length;t<i;t+=2)n.x=e[t]-d,n.y=u-(e[t+1]-f),r.add(n);let{id:i,clipPathId:a}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:`0 0 1 1`,fill:c.color,"fill-opacity":c._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:r.toSVGPath()}},!0,!0);c.#y({highlightOutlines:r.getOutlines(),highlightId:i,clipPathId:a}),c.#w()}return c}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();let t=this.getRect(0,0),n=Q._colorManager.convert(this.color),r={annotationType:W.HIGHLIGHT,color:n,opacity:this.#p,thickness:this.#g,quadPoints:this.#k(),outlines:this.#A(t),pageIndex:this.pageIndex,rect:t,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#N(r)?null:(r.id=this.annotationElementId,r)}#N(e){let{color:t}=this._initialData;return e.color.some((e,n)=>e!==t[n])}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}},fp=class{#e=Object.create(null);updateProperty(e,t){this[e]=t,this.updateSVGProperty(e,t)}updateProperties(e){if(e)for(let[t,n]of Object.entries(e))this.updateProperty(t,n)}updateSVGProperty(e,t){this.#e[e]=t}toSVGProperties(){let e=this.#e;return this.#e=Object.create(null),{root:e}}reset(){this.#e=Object.create(null)}updateAll(e=this){this.updateProperties(e)}clone(){q(`Not implemented`)}},pp=class e extends Q{#e=null;#t;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#n=null;static#r=null;static#i=null;static#a=NaN;static#o=null;static#s=null;static#c=NaN;static _INNER_MARGIN=3;constructor(e){super(e),this.#t=e.mustBeCommitted||!1,e.drawOutlines&&(this.#l(e),this.#f())}#l({drawOutlines:e,drawId:t,drawingOptions:n}){this.#e=e,this._drawingOptions||=n,t>=0?(this._drawId=t,this.parent.drawLayer.finalizeDraw(t,e.defaultProperties)):this._drawId=this.#u(e,this.parent),this.#h(e.box)}#u(t,n){let{id:r}=n.drawLayer.draw(e._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return r}static _mergeSVGProperties(e,t){let n=new Set(Object.keys(e));for(let[r,i]of Object.entries(t))n.has(r)?Object.assign(e[r],i):e[r]=i;return e}static getDefaultDrawingOptions(e){q(`Not implemented`)}static get typesMap(){q(`Not implemented`)}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,n){let r=this.typesMap.get(t);r&&this._defaultDrawingOptions.updateProperty(r,n),this._currentParent&&(e.#n.updateProperty(r,n),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(e,t){let n=this.constructor.typesMap.get(e);n&&this._updateProperty(e,n,t)}static get defaultPropertiesToUpdate(){let e=[],t=this._defaultDrawingOptions;for(let[n,r]of this.typesMap)e.push([n,t[r]]);return e}get propertiesToUpdate(){let e=[],{_drawingOptions:t}=this;for(let[n,r]of this.constructor.typesMap)e.push([n,t[r]]);return e}_updateProperty(e,t,n){let r=this._drawingOptions,i=r[t],a=e=>{r.updateProperty(t,e);let n=this.#e.updateProperty(t,e);n&&this.#h(n),this.parent?.drawLayer.updateProperties(this._drawId,r.toSVGProperties())};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizingSVGProperties(this.#m()),{bbox:this.#g()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathResizedSVGProperties(this.#m()),{bbox:this.#g()}))}_onTranslating(e,t){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#g(e,t)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties(this.#e.getPathTranslatedSVGProperties(this.#m(),this.parentDimensions),{bbox:this.#g()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle(`disabled`,!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle(`disabled`,!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#t&&(this.#t=!1,this.commit(),this.parent.setSelected(this),e&&this.isOnScreen&&this.div.focus())}remove(){this.#d(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#h(this.#e.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){let t=!1;this.parent&&!e?(this._uiManager.removeShouldRescale(this),this.#d()):e&&(this._uiManager.addShouldRescale(this),this.#f(e),t=!this.parent&&this.div?.classList.contains(`selectedEditor`)),super.setParent(e),t&&this.select()}#d(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(e=this.parent){if(this._drawId===null||this.parent!==e){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,e.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#u(this.#e,e)}}#p([e,t,n,r]){let{parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[t,1-e,a/i*n,i/a*r];case 180:return[1-e,1-t,n,r];case 270:return[1-t,e,a/i*n,i/a*r];default:return[e,t,n,r]}}#m(){let{x:e,y:t,width:n,height:r,parentDimensions:[i,a],rotation:o}=this;switch(o){case 90:return[1-t,e,i/a*n,a/i*r];case 180:return[1-e,1-t,n,r];case 270:return[t,1-e,i/a*n,a/i*r];default:return[e,t,n,r]}}#h(e){if([this.x,this.y,this.width,this.height]=this.#p(e),this.div){this.fixAndSetPosition();let[e,t]=this.parentDimensions;this.setDims(this.width*e,this.height*t)}this._onResized()}#g(){let{x:e,y:t,width:n,height:r,rotation:i,parentRotation:a,parentDimensions:[o,s]}=this;switch((i*4+a)/90){case 1:return[1-t-r,e,r,n];case 2:return[1-e-n,1-t-r,n,r];case 3:return[t,1-e-n,r,n];case 4:return[e,t-o/s*n,s/o*r,o/s*n];case 5:return[1-t,e,o/s*n,s/o*r];case 6:return[1-e-s/o*r,1-t,s/o*r,o/s*n];case 7:return[t-o/s*n,1-e-s/o*r,o/s*n,s/o*r];case 8:return[e-n,t-r,n,r];case 9:return[1-t,e-n,r,n];case 10:return[1-e,1-t,n,r];case 11:return[t-r,1-e,r,n];case 12:return[e-s/o*r,t,s/o*r,o/s*n];case 13:return[1-t-o/s*n,e-s/o*r,o/s*n,s/o*r];case 14:return[1-e,1-t-o/s*n,s/o*r,o/s*n];case 15:return[t,1-e,o/s*n,s/o*r];default:return[e,t,n,r]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,e._mergeSVGProperties({bbox:this.#g()},this.#e.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#h(this.#e.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;let e=super.render();e.classList.add(`draw`);let t=document.createElement(`div`);e.append(t),t.setAttribute(`aria-hidden`,`true`),t.className=`internal`;let[n,r]=this.parentDimensions;return this.setDims(this.width*n,this.height*r),this._uiManager.addShouldRescale(this),this.disableEditing(),e}static createDrawerInstance(e,t,n,r,i){q(`Not implemented`)}static startDrawing(t,n,r,i){let{target:a,offsetX:o,offsetY:s,pointerId:c,pointerType:l}=i;if(e.#o&&e.#o!==l)return;let{viewport:{rotation:u}}=t,{width:d,height:f}=a.getBoundingClientRect(),p=e.#r=new AbortController,m=t.combinedSignal(p);if(e.#a||=c,e.#o??=l,window.addEventListener(`pointerup`,t=>{e.#a===t.pointerId?this._endDraw(t):e.#s?.delete(t.pointerId)},{signal:m}),window.addEventListener(`pointercancel`,t=>{e.#a===t.pointerId?this._currentParent.endDrawingSession():e.#s?.delete(t.pointerId)},{signal:m}),window.addEventListener(`pointerdown`,t=>{e.#o===t.pointerType&&((e.#s||=new Set).add(t.pointerId),e.#n.isCancellable()&&(e.#n.removeLastElement(),e.#n.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:m}),window.addEventListener(`contextmenu`,Ll,{signal:m}),a.addEventListener(`pointermove`,this._drawMove.bind(this),{signal:m}),a.addEventListener(`touchmove`,t=>{t.timeStamp===e.#c&&Rl(t)},{signal:m}),t.toggleDrawing(),n._editorUndoBar?.hide(),e.#n){t.drawLayer.updateProperties(this._currentDrawId,e.#n.startNew(o,s,d,f,u));return}n.updateUIForDefaultProperties(this),e.#n=this.createDrawerInstance(o,s,d,f,u),e.#i=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(e.#i.toSVGProperties(),e.#n.defaultSVGProperties),!0,!1)}static _drawMove(t){if(e.#c=-1,!e.#n)return;let{offsetX:n,offsetY:r,pointerId:i}=t;if(e.#a===i){if(e.#s?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,e.#n.add(n,r)),e.#c=t.timeStamp,Rl(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,e.#n=null,e.#i=null,e.#o=null,e.#c=NaN),e.#r&&(e.#r.abort(),e.#r=null,e.#a=NaN,e.#s=null)}static _endDraw(t){let n=this._currentParent;if(n){if(n.toggleDrawing(!0),this._cleanup(!1),t&&n.drawLayer.updateProperties(this._currentDrawId,e.#n.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){let t=e.#n,r=this._currentDrawId,i=t.getLastElement();n.addCommands({cmd:()=>{n.drawLayer.updateProperties(r,t.setLastElement(i))},undo:()=>{n.drawLayer.updateProperties(r,t.removeLastElement())},mustExec:!1,type:G.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){let n=this._currentParent;if(!n)return null;if(n.toggleDrawing(!0),n.cleanUndoStack(G.DRAW_STEP),!e.#n.isEmpty()){let{pageDimensions:[r,i],scale:a}=n,o=n.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:e.#n.getOutlines(r*a,i*a,a,this._INNER_MARGIN),drawingOptions:e.#i,mustBeCommitted:!t});return this._cleanup(!0),o}return n.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,t,n,r,i,a){q(`Not implemented`)}static async deserialize(e,t,n){let{rawDims:{pageWidth:r,pageHeight:i,pageX:a,pageY:o}}=t.viewport,s=this.deserializeDraw(a,o,r,i,this._INNER_MARGIN,e),c=await super.deserialize(e,t,n);return c.createDrawingOptions(e),c.#l({drawOutlines:s}),c.#f(),c.onScaleChanging(),c.rotate(),c}serializeDraw(e){let[t,n]=this.pageTranslation,[r,i]=this.pageDimensions;return this.#e.serialize([t,n,r,i],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}},mp=class{#e=new Float64Array(6);#t;#n;#r;#i;#a;#o=``;#s=0;#c=new hp;#l;#u;constructor(e,t,n,r,i,a){this.#l=n,this.#u=r,this.#r=i,this.#i=a,[e,t]=this.#d(e,t);let o=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t],this.#n=[{line:o,points:this.#a}],this.#e.set(o,0)}updateProperty(e,t){e===`stroke-width`&&(this.#i=t)}#d(e,t){return $._normalizePoint(e,t,this.#l,this.#u,this.#r)}isEmpty(){return!this.#n||this.#n.length===0}isCancellable(){return this.#a.length<=10}add(e,t){[e,t]=this.#d(e,t);let[n,r,i,a]=this.#e.subarray(2,6),o=e-i,s=t-a;return Math.hypot(this.#l*o,this.#u*s)<=2?null:(this.#a.push(e,t),isNaN(n)?(this.#e.set([i,a,e,t],2),this.#t.push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(this.#e[0])&&this.#t.splice(6,6),this.#e.set([n,r,i,a,e,t],0),this.#t.push(...$.createBezierPoints(n,r,i,a,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){return this.add(e,t)||(this.#a.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,n,r,i){this.#l=n,this.#u=r,this.#r=i,[e,t]=this.#d(e,t);let a=this.#t=[NaN,NaN,NaN,NaN,e,t];this.#a=[e,t];let o=this.#n.at(-1);return o&&(o.line=new Float32Array(o.line),o.points=new Float32Array(o.points)),this.#n.push({line:a,points:this.#a}),this.#e.set(a,0),this.#s=0,this.toSVGPath(),null}getLastElement(){return this.#n.at(-1)}setLastElement(e){return this.#n?(this.#n.push(e),this.#t=e.line,this.#a=e.points,this.#s=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(e)}removeLastElement(){if(!this.#n)return this.#c.removeLastElement();this.#n.pop(),this.#o=``;for(let e=0,t=this.#n.length;e<t;e++){let{line:t,points:n}=this.#n[e];this.#t=t,this.#a=n,this.#s=0,this.toSVGPath()}return{path:{d:this.#o}}}toSVGPath(){let e=$.svgRound(this.#t[4]),t=$.svgRound(this.#t[5]);if(this.#a.length===2)return this.#o=`${this.#o} M ${e} ${t} Z`,this.#o;if(this.#a.length<=6){let n=this.#o.lastIndexOf(`M`);this.#o=`${this.#o.slice(0,n)} M ${e} ${t}`,this.#s=6}if(this.#a.length===4){let e=$.svgRound(this.#t[10]),t=$.svgRound(this.#t[11]);return this.#o=`${this.#o} L ${e} ${t}`,this.#s=12,this.#o}let n=[];this.#s===0&&(n.push(`M ${e} ${t}`),this.#s=6);for(let e=this.#s,t=this.#t.length;e<t;e+=6){let[t,r,i,a,o,s]=this.#t.slice(e,e+6).map($.svgRound);n.push(`C${t} ${r} ${i} ${a} ${o} ${s}`)}return this.#o+=n.join(` `),this.#s=this.#t.length,this.#o}getOutlines(e,t,n,r){let i=this.#n.at(-1);return i.line=new Float32Array(i.line),i.points=new Float32Array(i.points),this.#c.build(this.#n,e,t,n,this.#r,this.#i,r),this.#e=null,this.#t=null,this.#n=null,this.#o=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:`0 0 10000 10000`},rootClass:{draw:!0},bbox:[0,0,1,1]}}},hp=class e extends ${#e;#t=0;#n;#r;#i;#a;#o;#s;#c;build(e,t,n,r,i,a,o){this.#i=t,this.#a=n,this.#o=r,this.#s=i,this.#c=a,this.#n=o??0,this.#r=e,this.#d()}setLastElement(e){return this.#r.push(e),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#r.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){let e=[];for(let{line:t}of this.#r){if(e.push(`M${$.svgRound(t[4])} ${$.svgRound(t[5])}`),t.length===6){e.push(`Z`);continue}if(t.length===12){e.push(`L${$.svgRound(t[10])} ${$.svgRound(t[11])}`);continue}for(let n=6,r=t.length;n<r;n+=6){let[r,i,a,o,s,c]=t.subarray(n,n+6).map($.svgRound);e.push(`C${r} ${i} ${a} ${o} ${s} ${c}`)}}return e.join(``)}serialize([e,t,n,r],i){let a=[],o=[],[s,c,l,u]=this.#u(),d,f,p,m,h,g,_,v,y;switch(this.#s){case 0:y=$._rescale,d=e,f=t+r,p=n,m=-r,h=e+s*n,g=t+(1-c-u)*r,_=e+(s+l)*n,v=t+(1-c)*r;break;case 90:y=$._rescaleAndSwap,d=e,f=t,p=n,m=r,h=e+c*n,g=t+s*r,_=e+(c+u)*n,v=t+(s+l)*r;break;case 180:y=$._rescale,d=e+n,f=t,p=-n,m=r,h=e+(1-s-l)*n,g=t+c*r,_=e+(1-s)*n,v=t+(c+u)*r;break;case 270:y=$._rescaleAndSwap,d=e+n,f=t+r,p=-n,m=-r,h=e+(1-c-u)*n,g=t+(1-s-l)*r,_=e+(1-c)*n,v=t+(1-s)*r}for(let{line:e,points:t}of this.#r)a.push(y(e,d,f,p,m,i?Array(e.length):null)),o.push(y(t,d,f,p,m,i?Array(t.length):null));return{lines:a,points:o,rect:[h,g,_,v]}}static deserialize(t,n,r,i,a,{paths:{lines:o,points:s},rotation:c,thickness:l}){let u=[],d,f,p,m,h;switch(c){case 0:h=$._rescale,d=-t/r,f=n/i+1,p=1/r,m=-1/i;break;case 90:h=$._rescaleAndSwap,d=-n/i,f=-t/r,p=1/i,m=1/r;break;case 180:h=$._rescale,d=t/r+1,f=-n/i,p=-1/r,m=1/i;break;case 270:h=$._rescaleAndSwap,d=n/i+1,f=t/r+1,p=-1/i,m=-1/r}if(!o){o=[];for(let e of s){let t=e.length;if(t===2){o.push(new Float32Array([NaN,NaN,NaN,NaN,e[0],e[1]]));continue}if(t===4){o.push(new Float32Array([NaN,NaN,NaN,NaN,e[0],e[1],NaN,NaN,NaN,NaN,e[2],e[3]]));continue}let n=new Float32Array(3*(t-2));o.push(n);let[r,i,a,s]=e.subarray(0,4);n.set([NaN,NaN,NaN,NaN,r,i],0);for(let o=4;o<t;o+=2){let t=e[o],c=e[o+1];n.set($.createBezierPoints(r,i,a,s,t,c),(o-2)*3),[r,i,a,s]=[a,s,t,c]}}}for(let e=0,t=o.length;e<t;e++)u.push({line:h(o[e].map(e=>e??NaN),d,f,p,m),points:h(s[e].map(e=>e??NaN),d,f,p,m)});let g=new e;return g.build(u,r,i,1,c,l,a),g}#l(e=this.#c){let t=this.#n+e/2*this.#o;return this.#s%180==0?[t/this.#i,t/this.#a]:[t/this.#a,t/this.#i]}#u(){let[e,t,n,r]=this.#e,[i,a]=this.#l(0);return[e+i,t+a,n-2*i,r-2*a]}#d(){let e=this.#e=new Float32Array([1/0,1/0,-1/0,-1/0]);for(let{line:t}of this.#r){if(t.length<=12){for(let n=4,r=t.length;n<r;n+=6){let[r,i]=t.subarray(n,n+2);e[0]=Math.min(e[0],r),e[1]=Math.min(e[1],i),e[2]=Math.max(e[2],r),e[3]=Math.max(e[3],i)}continue}let n=t[4],r=t[5];for(let i=6,a=t.length;i<a;i+=6){let[a,o,s,c,l,u]=t.subarray(i,i+6);X.bezierBoundingBox(n,r,a,o,s,c,l,u,e),n=l,r=u}}let[t,n]=this.#l();e[0]=Math.min(1,Math.max(0,e[0]-t)),e[1]=Math.min(1,Math.max(0,e[1]-n)),e[2]=Math.min(1,Math.max(0,e[2]+t)),e[3]=Math.min(1,Math.max(0,e[3]+n)),e[2]-=e[0],e[3]-=e[1]}get box(){return this.#e}updateProperty(e,t){return e===`stroke-width`?this.#f(t):null}#f(e){let[t,n]=this.#l();this.#c=e;let[r,i]=this.#l(),[a,o]=[r-t,i-n],s=this.#e;return s[0]-=a,s[1]-=o,s[2]+=2*a,s[3]+=2*o,s}updateParentDimensions([e,t],n){let[r,i]=this.#l();this.#i=e,this.#a=t,this.#o=n;let[a,o]=this.#l(),s=a-r,c=o-i,l=this.#e;return l[0]-=s,l[1]-=c,l[2]+=2*s,l[3]+=2*c,l}updateRotation(e){return this.#t=e,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#e.map($.svgRound).join(` `)}get defaultProperties(){let[e,t]=this.#e;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`}}}get rotationTransform(){let[,,e,t]=this.#e,n=0,r=0,i=0,a=0,o=0,s=0;switch(this.#t){case 90:r=t/e,i=-e/t,o=e;break;case 180:n=-1,a=-1,o=e,s=t;break;case 270:r=-t/e,i=e/t,s=t;break;default:return``}return`matrix(${n} ${r} ${i} ${a} ${$.svgRound(o)} ${$.svgRound(s)})`}getPathResizingSVGProperties([e,t,n,r]){let[i,a]=this.#l(),[o,s,c,l]=this.#e;if(Math.abs(c-i)<=$.PRECISION||Math.abs(l-a)<=$.PRECISION){let i=e+n/2-(o+c/2),a=t+r/2-(s+l/2);return{path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:`${this.rotationTransform} translate(${i} ${a})`}}}let u=(n-2*i)/(c-2*i),d=(r-2*a)/(l-2*a),f=c/n,p=l/r;return{path:{"transform-origin":`${$.svgRound(o)} ${$.svgRound(s)}`,transform:`${this.rotationTransform} scale(${f} ${p}) translate(${$.svgRound(i)} ${$.svgRound(a)}) scale(${u} ${d}) translate(${$.svgRound(-i)} ${$.svgRound(-a)})`}}}getPathResizedSVGProperties([e,t,n,r]){let[i,a]=this.#l(),o=this.#e,[s,c,l,u]=o;if(o[0]=e,o[1]=t,o[2]=n,o[3]=r,Math.abs(l-i)<=$.PRECISION||Math.abs(u-a)<=$.PRECISION){let i=e+n/2-(s+l/2),a=t+r/2-(c+u/2);for(let{line:e,points:t}of this.#r)$._translate(e,i,a,e),$._translate(t,i,a,t);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}let d=(n-2*i)/(l-2*i),f=(r-2*a)/(u-2*a),p=-d*(s+i)+e+i,m=-f*(c+a)+t+a;if(d!==1||f!==1||p!==0||m!==0)for(let{line:e,points:t}of this.#r)$._rescale(e,p,m,d,f,e),$._rescale(t,p,m,d,f,t);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([e,t],n){let[r,i]=n,a=this.#e,o=e-a[0],s=t-a[1];if(this.#i===r&&this.#a===i)for(let{line:e,points:t}of this.#r)$._translate(e,o,s,e),$._translate(t,o,s,t);else{let e=this.#i/r,t=this.#a/i;this.#i=r,this.#a=i;for(let{line:n,points:r}of this.#r)$._rescale(n,o,s,e,t,n),$._rescale(r,o,s,e,t,r);a[2]*=e,a[3]*=t}return a[0]=e,a[1]=t,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${$.svgRound(e)} ${$.svgRound(t)}`}}}get defaultSVGProperties(){let e=this.#e;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${$.svgRound(e[0])} ${$.svgRound(e[1])}`,transform:this.rotationTransform||null},bbox:e}}},gp=class e extends fp{#e;constructor(e){super(),this.#e=e,super.updateProperties({fill:`none`,stroke:Q._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":`round`,"stroke-linejoin":`round`,"stroke-miterlimit":10})}updateSVGProperty(e,t){e===`stroke-width`&&(t??=this[`stroke-width`],t*=this.#e.realScale),super.updateSVGProperty(e,t)}clone(){let t=new e(this.#e);return t.updateAll(this),t}},_p=class e extends pp{static _type=`ink`;static _editorType=W.INK;static _defaultDrawingOptions=null;constructor(e){super({...e,name:`inkEditor`}),this._willKeepAspectRatio=!0}static initialize(e,t){Q.initialize(e,t),this._defaultDrawingOptions=new gp(t.viewParameters)}static getDefaultDrawingOptions(e){let t=this._defaultDrawingOptions.clone();return t.updateProperties(e),t}static get supportMultipleDrawings(){return!0}static get typesMap(){return Y(this,`typesMap`,new Map([[G.INK_THICKNESS,`stroke-width`],[G.INK_COLOR,`stroke`],[G.INK_OPACITY,`stroke-opacity`]]))}static createDrawerInstance(e,t,n,r,i){return new mp(e,t,n,r,i,this._defaultDrawingOptions[`stroke-width`])}static deserializeDraw(e,t,n,r,i,a){return hp.deserialize(e,t,n,r,i,a)}static async deserialize(e,t,n){let r=null;if(e instanceof Jf){let{data:{inkLists:t,rect:n,rotation:i,id:a,color:o,opacity:s,borderStyle:{rawWidth:c},popupRef:l},parent:{page:{pageNumber:u}}}=e;r=e={annotationType:W.INK,color:Array.from(o),thickness:c,opacity:s,paths:{points:t},boxes:null,pageIndex:u-1,rect:n.slice(0),rotation:i,id:a,deleted:!1,popupRef:l}}let i=await super.deserialize(e,t,n);return i.annotationElementId=e.id||null,i._initialData=r,i}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();let{_drawId:e,_drawingOptions:t,parent:n}=this;t.updateSVGProperty(`stroke-width`),n.drawLayer.updateProperties(e,t.toSVGProperties())}static onScaleChangingWhenDrawing(){let e=this._currentParent;e&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty(`stroke-width`),e.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:n,opacity:r}){this._drawingOptions=e.getDefaultDrawingOptions({stroke:X.makeHexColor(...t),"stroke-width":n,"stroke-opacity":r})}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let{lines:t,points:n,rect:r}=this.serializeDraw(e),{_drawingOptions:{stroke:i,"stroke-opacity":a,"stroke-width":o}}=this,s={annotationType:W.INK,color:Q._colorManager.convert(i),opacity:a,thickness:o,paths:{lines:t,points:n},pageIndex:this.pageIndex,rect:r,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?s:this.annotationElementId&&!this.#e(s)?null:(s.id=this.annotationElementId,s)}#e(e){let{color:t,thickness:n,opacity:r,pageIndex:i}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||e.color.some((e,n)=>e!==t[n])||e.thickness!==n||e.opacity!==r||e.pageIndex!==i}renderAnnotationElement(e){let{points:t,rect:n}=this.serializeDraw(!1);return e.updateEdited({rect:n,thickness:this._drawingOptions[`stroke-width`],points:t}),null}},vp=class e extends Q{#e=null;#t=null;#n=null;#r=null;#i=null;#a=``;#o=null;#s=null;#c=!1;#l=!1;static _type=`stamp`;static _editorType=W.STAMP;constructor(e){super({...e,name:`stampEditor`}),this.#r=e.bitmapUrl,this.#i=e.bitmapFile}static initialize(e,t){Q.initialize(e,t)}static get supportedTypes(){return Y(this,`supportedTypes`,[`apng`,`avif`,`bmp`,`gif`,`jpeg`,`png`,`svg+xml`,`webp`,`x-icon`].map(e=>`image/${e}`))}static get supportedTypesStr(){return Y(this,`supportedTypesStr`,this.supportedTypes.join(`,`))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,t){t.pasteEditor(W.STAMP,{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:`stamp`,hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(e){let t=e.get(`hasAltText`);return{hasAltText:t.get(!0)??0,hasNoAltText:t.get(!1)??0}}#u(e,t=!1){if(!e){this.remove();return}this.#e=e.bitmap,t||(this.#t=e.id,this.#c=e.isSvg),e.file&&(this.#a=e.file.name),this.#p()}#d(){if(this.#n=null,this._uiManager.enableWaiting(!1),this.#o){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#e){this._reportTelemetry({action:`pdfjs.image.image_added`,data:{alt_text_modal:!1,alt_text_type:`empty`}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(e=null,t=!0){if(this.hasAltTextData())return null;let{mlManager:n}=this._uiManager;if(!n)throw Error(`No ML.`);if(!await n.isEnabledFor(`altText`))throw Error(`ML isn't enabled for alt text.`);let{data:r,width:i,height:a}=e||this.copyCanvas(null,null,!0).imageData,o=await n.guess({name:`altText`,request:{data:r,width:i,height:a,channels:r.length/(i*a)}});if(!o)throw Error(`No response from the AI service.`);if(o.error)throw Error(`Error from the AI service.`);if(o.cancel)return null;if(!o.output)throw Error(`No valid response from the AI service.`);let s=o.output;return await this.setGuessedAltText(s),t&&!this.hasAltTextData()&&(this.altTextData={alt:s,decorative:!1}),s}#f(){if(this.#t){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#t).then(e=>this.#u(e,!0)).finally(()=>this.#d());return}if(this.#r){let e=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromUrl(e).then(e=>this.#u(e)).finally(()=>this.#d());return}if(this.#i){let e=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#n=this._uiManager.imageManager.getFromFile(e).then(e=>this.#u(e)).finally(()=>this.#d());return}let t=document.createElement(`input`);t.type=`file`,t.accept=e.supportedTypesStr;let n=this._uiManager._signal;this.#n=new Promise(e=>{t.addEventListener(`change`,async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);let e=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:`pdfjs.image.image_selected`,data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#u(e)}e()},{signal:n}),t.addEventListener(`cancel`,()=>{this.remove(),e()},{signal:n})}).finally(()=>this.#d()),t.click()}remove(){this.#t&&(this.#e=null,this._uiManager.imageManager.deleteId(this.#t),this.#o?.remove(),this.#o=null,this.#s&&=(clearTimeout(this.#s),null)),super.remove()}rebuild(){if(!this.parent){this.#t&&this.#f();return}super.rebuild(),this.div!==null&&(this.#t&&this.#o===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(e){this._isDraggable=!0,e&&this.div.focus()}isEmpty(){return!(this.#n||this.#e||this.#r||this.#i||this.#t)}get isResizable(){return!0}render(){if(this.div)return this.div;let e,t;if(this.width&&(e=this.x,t=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute(`role`,`figure`),this.addAltTextButton(),this.#e?this.#p():this.#f(),this.width&&!this.annotationElementId){let[n,r]=this.parentDimensions;this.setAt(e*n,t*r,this.width*n,this.height*r)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){this.parent&&(this.#s!==null&&clearTimeout(this.#s),this.#s=setTimeout(()=>{this.#s=null,this.#h()},200))}#p(){let{div:e}=this,{width:t,height:n}=this.#e,[r,i]=this.pageDimensions,a=.75;if(this.width)t=this.width*r,n=this.height*i;else if(t>a*r||n>a*i){let e=Math.min(a*r/t,a*i/n);t*=e,n*=e}let[o,s]=this.parentDimensions;this.setDims(t*o/r,n*s/i),this._uiManager.enableWaiting(!1);let c=this.#o=document.createElement(`canvas`);c.setAttribute(`role`,`img`),this.addContainer(c),this.width=t/r,this.height=n/i,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),this.#h(),this.#l||=(this.parent.addUndoableEditor(this),!0),this._reportTelemetry({action:`inserted_image`}),this.#a&&c.setAttribute(`aria-label`,this.#a)}copyCanvas(e,t,n=!1){e||=224;let{width:r,height:i}=this.#e,a=new Gl,o=this.#e,s=r,c=i,l=null;if(t){if(r>t||i>t){let e=Math.min(t/r,t/i);s=Math.floor(r*e),c=Math.floor(i*e)}l=document.createElement(`canvas`);let e=l.width=Math.ceil(s*a.sx),n=l.height=Math.ceil(c*a.sy);this.#c||(o=this.#m(e,n));let u=l.getContext(`2d`);u.filter=this._uiManager.hcmFilter;let d=`white`,f=`#cfcfd8`;this._uiManager.hcmFilter===`none`?window.matchMedia?.(`(prefers-color-scheme: dark)`).matches&&(d=`#8f8f9d`,f=`#42414d`):f=`black`;let p=15*a.sx,m=15*a.sy,h=new OffscreenCanvas(p*2,m*2),g=h.getContext(`2d`);g.fillStyle=d,g.fillRect(0,0,p*2,m*2),g.fillStyle=f,g.fillRect(0,0,p,m),g.fillRect(p,m,p,m),u.fillStyle=u.createPattern(h,`repeat`),u.fillRect(0,0,e,n),u.drawImage(o,0,0,o.width,o.height,0,0,e,n)}let u=null;if(n){let t,n;if(a.symmetric&&o.width<e&&o.height<e)t=o.width,n=o.height;else if(o=this.#e,r>e||i>e){let a=Math.min(e/r,e/i);t=Math.floor(r*a),n=Math.floor(i*a),this.#c||(o=this.#m(t,n))}let s=new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0});s.drawImage(o,0,0,o.width,o.height,0,0,t,n),u={width:t,height:n,data:s.getImageData(0,0,t,n).data}}return{canvas:l,width:s,height:c,imageData:u}}#m(e,t){let{width:n,height:r}=this.#e,i=n,a=r,o=this.#e;for(;i>2*e||a>2*t;){let n=i,r=a;i>2*e&&(i=i>=16384?Math.floor(i/2)-1:Math.ceil(i/2)),a>2*t&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));let s=new OffscreenCanvas(i,a);s.getContext(`2d`).drawImage(o,0,0,n,r,0,0,i,a),o=s.transferToImageBitmap()}return o}#h(){let[e,t]=this.parentDimensions,{width:n,height:r}=this,i=new Gl,a=Math.ceil(n*e*i.sx),o=Math.ceil(r*t*i.sy),s=this.#o;if(!s||s.width===a&&s.height===o)return;s.width=a,s.height=o;let c=this.#c?this.#e:this.#m(a,o),l=s.getContext(`2d`);l.filter=this._uiManager.hcmFilter,l.drawImage(c,0,0,c.width,c.height,0,0,a,o)}getImageForAltText(){return this.#o}#g(e){if(e){if(this.#c){let e=this._uiManager.imageManager.getSvgUrl(this.#t);if(e)return e}let e=document.createElement(`canvas`);return{width:e.width,height:e.height}=this.#e,e.getContext(`2d`).drawImage(this.#e,0,0),e.toDataURL()}if(this.#c){let[e,t]=this.pageDimensions,n=Math.round(this.width*e*Dl.PDF_TO_CSS_UNITS),r=Math.round(this.height*t*Dl.PDF_TO_CSS_UNITS),i=new OffscreenCanvas(n,r);return i.getContext(`2d`).drawImage(this.#e,0,0,this.#e.width,this.#e.height,0,0,n,r),i.transferToImageBitmap()}return structuredClone(this.#e)}static async deserialize(e,t,n){let r=null;if(e instanceof $f){let{data:{rect:i,rotation:a,id:o,structParent:s,popupRef:c},container:l,parent:{page:{pageNumber:u}}}=e,d=l.querySelector(`canvas`),f=n.imageManager.getFromCanvas(l.id,d);d.remove();let p=(await t._structTree.getAriaAttributes(`${wl}${o}`))?.get(`aria-label`)||``;r=e={annotationType:W.STAMP,bitmapId:f.id,bitmap:f.bitmap,pageIndex:u-1,rect:i.slice(0),rotation:a,id:o,deleted:!1,accessibilityData:{decorative:!1,altText:p},isSvg:!1,structParent:s,popupRef:c}}let i=await super.deserialize(e,t,n),{rect:a,bitmap:o,bitmapUrl:s,bitmapId:c,isSvg:l,accessibilityData:u}=e;c&&n.imageManager.isValidId(c)?(i.#t=c,o&&(i.#e=o)):i.#r=s,i.#c=l;let[d,f]=i.pageDimensions;return i.width=(a[2]-a[0])/d,i.height=(a[3]-a[1])/f,i.annotationElementId=e.id||null,u&&(i.altTextData=u),i._initialData=r,i.#l=!!r,i}serialize(e=!1,t=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();let n={annotationType:W.STAMP,bitmapId:this.#t,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(e)return n.bitmapUrl=this.#g(!0),n.accessibilityData=this.serializeAltText(!0),n;let{decorative:r,altText:i}=this.serializeAltText(!1);if(!r&&i&&(n.accessibilityData={type:`Figure`,alt:i}),this.annotationElementId){let e=this.#_(n);if(e.isSame)return null;e.isSameAltText?delete n.accessibilityData:n.accessibilityData.structParent=this._initialData.structParent??-1}if(n.id=this.annotationElementId,t===null)return n;t.stamps||=new Map;let a=this.#c?(n.rect[2]-n.rect[0])*(n.rect[3]-n.rect[1]):null;if(!t.stamps.has(this.#t))t.stamps.set(this.#t,{area:a,serialized:n}),n.bitmap=this.#g(!1);else if(this.#c){let e=t.stamps.get(this.#t);a>e.area&&(e.area=a,e.serialized.bitmap.close(),e.serialized.bitmap=this.#g(!1))}return n}#_(e){let{pageIndex:t,accessibilityData:{altText:n}}=this._initialData,r=e.pageIndex===t,i=(e.accessibilityData?.alt||``)===n;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&r&&i,isSameAltText:i}}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}},yp=class e{#e;#t=!1;#n=null;#r=null;#i=null;#a=new Map;#o=!1;#s=!1;#c=!1;#l=null;#u=null;#d=null;#f=null;#p;static _initialized=!1;static#m=new Map([rp,_p,vp,dp].map(e=>[e._editorType,e]));constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:i,accessibilityManager:a,annotationLayer:o,drawLayer:s,textLayer:c,viewport:l,l10n:u}){let d=[...e.#m.values()];if(!e._initialized){e._initialized=!0;for(let e of d)e.initialize(u,t)}t.registerEditorTypes(d),this.#p=t,this.pageIndex=n,this.div=r,this.#e=a,this.#n=o,this.viewport=l,this.#d=c,this.drawLayer=s,this._structTree=i,this.#p.addLayer(this)}get isEmpty(){return this.#a.size===0}get isInvisible(){return this.isEmpty&&this.#p.getMode()===W.NONE}updateToolbar(e){this.#p.updateToolbar(e)}updateMode(t=this.#p.getMode()){switch(this.#y(),t){case W.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case W.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case W.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);let{classList:n}=this.div;for(let r of e.#m.values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(e){return e===this.#d?.div}setEditingState(e){this.#p.setEditingState(e)}addCommands(e){this.#p.addCommands(e)}cleanUndoStack(e){this.#p.cleanUndoStack(e)}toggleDrawing(e=!1){this.div.classList.toggle(`drawing`,!e)}togglePointerEvents(e=!1){this.div.classList.toggle(`disabled`,!e)}toggleAnnotationLayerPointerEvents(e=!1){this.#n?.div.classList.toggle(`disabled`,!e)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);let e=new Set;for(let t of this.#a.values())t.enableEditing(),t.show(!0),t.annotationElementId&&(this.#p.removeChangedExistingAnnotation(t),e.add(t.annotationElementId));if(!this.#n){this.#c=!1;return}let t=this.#n.getEditableAnnotations();for(let n of t){if(n.hide(),this.#p.isDeletedAnnotationElement(n.data.id)||e.has(n.data.id))continue;let t=await this.deserialize(n);t&&(this.addOrRebuild(t),t.enableEditing())}this.#c=!1}disable(){this.#s=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);let t=new Map,n=new Map;for(let e of this.#a.values())if(e.disableEditing(),e.annotationElementId){if(e.serialize()!==null){t.set(e.annotationElementId,e);continue}n.set(e.annotationElementId,e),this.getEditableAnnotation(e.annotationElementId)?.show(),e.remove()}if(this.#n){let e=this.#n.getEditableAnnotations();for(let r of e){let{id:e}=r.data;if(this.#p.isDeletedAnnotationElement(e))continue;let i=n.get(e);if(i){i.resetAnnotationElement(r),i.show(!1),r.show();continue}i=t.get(e),i&&(this.#p.addChangedExistingAnnotation(i),i.renderAnnotationElement(r)&&i.show(!1)),r.show()}}this.#y(),this.isEmpty&&(this.div.hidden=!0);let{classList:r}=this.div;for(let t of e.#m.values())r.remove(`${t._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#s=!1}getEditableAnnotation(e){return this.#n?.getEditableAnnotation(e)||null}setActiveEditor(e){this.#p.getActive()!==e&&this.#p.setActiveEditor(e)}enableTextSelection(){if(this.div.tabIndex=-1,this.#d?.div&&!this.#f){this.#f=new AbortController;let e=this.#p.combinedSignal(this.#f);this.#d.div.addEventListener(`pointerdown`,this.#h.bind(this),{signal:e}),this.#d.div.classList.add(`highlighting`)}}disableTextSelection(){this.div.tabIndex=0,this.#d?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#d.div.classList.remove(`highlighting`))}#h(e){this.#p.unselectAll();let{target:t}=e;if(t===this.#d.div||(t.getAttribute(`role`)===`img`||t.classList.contains(`endOfContent`))&&this.#d.div.contains(t)){let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t)return;this.#p.showAllEditors(`highlight`,!0,!0),this.#d.div.classList.add(`free`),this.toggleDrawing(),dp.startHighlighting(this,this.#p.direction===`ltr`,{target:this.#d.div,x:e.x,y:e.y}),this.#d.div.addEventListener(`pointerup`,()=>{this.#d.div.classList.remove(`free`),this.toggleDrawing(!0)},{once:!0,signal:this.#p._signal}),e.preventDefault()}}enableClick(){if(this.#r)return;this.#r=new AbortController;let e=this.#p.combinedSignal(this.#r);this.div.addEventListener(`pointerdown`,this.pointerdown.bind(this),{signal:e});let t=this.pointerup.bind(this);this.div.addEventListener(`pointerup`,t,{signal:e}),this.div.addEventListener(`pointercancel`,t,{signal:e})}disableClick(){this.#r?.abort(),this.#r=null}attach(e){this.#a.set(e.id,e);let{annotationElementId:t}=e;t&&this.#p.isDeletedAnnotationElement(t)&&this.#p.removeDeletedAnnotationElement(e)}detach(e){this.#a.delete(e.id),this.#e?.removePointerInTextLayer(e.contentDiv),!this.#s&&e.annotationElementId&&this.#p.addDeletedAnnotationElement(e)}remove(e){this.detach(e),this.#p.removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){e.parent!==this&&(e.parent&&e.annotationElementId&&(this.#p.addDeletedAnnotationElement(e.annotationElementId),Q.deleteAnnotationElement(e),e.annotationElementId=null),this.attach(e),e.parent?.detach(e),e.setParent(this),e.div&&e.isAttachedToDOM&&(e.div.remove(),this.div.append(e.div)))}add(e){if(!(e.parent===this&&e.isAttachedToDOM)){if(this.changeParent(e),this.#p.addEditor(e),this.attach(e),!e.isAttachedToDOM){let t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!this.#c),this.#p.addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){if(!e.isAttachedToDOM)return;let{activeElement:t}=document;e.div.contains(t)&&!this.#i&&(e._focusEventsAllowed=!1,this.#i=setTimeout(()=>{this.#i=null,e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener(`focusin`,()=>{e._focusEventsAllowed=!0},{once:!0,signal:this.#p._signal}),t.focus())},0)),e._structTreeParentId=this.#e?.moveElementInDOM(this.div,e.div,e.contentDiv,!0)}addOrRebuild(e){e.needsToBeRebuilt()?(e.parent||=this,e.rebuild(),e.show()):this.add(e)}addUndoableEditor(e){this.addCommands({cmd:()=>e._uiManager.rebuild(e),undo:()=>{e.remove()},mustExec:!1})}getNextId(){return this.#p.getId()}get#g(){return e.#m.get(this.#p.getMode())}combinedSignal(e){return this.#p.combinedSignal(e)}#_(e){let t=this.#g;return t?new t.prototype.constructor(e):null}canCreateNewEmptyEditor(){return this.#g?.canCreateNewEmptyEditor()}pasteEditor(e,t){this.#p.updateToolbar(e),this.#p.updateMode(e);let{offsetX:n,offsetY:r}=this.#v(),i=this.getNextId(),a=this.#_({parent:this,id:i,x:n,y:r,uiManager:this.#p,isCentered:!0,...t});a&&this.add(a)}async deserialize(t){return await e.#m.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#p)||null}createAndAddNewEditor(e,t,n={}){let r=this.getNextId(),i=this.#_({parent:this,id:r,x:e.offsetX,y:e.offsetY,uiManager:this.#p,isCentered:t,...n});return i&&this.add(i),i}#v(){let{x:e,y:t,width:n,height:r}=this.div.getBoundingClientRect(),i=Math.max(0,e),a=Math.max(0,t),o=Math.min(window.innerWidth,e+n),s=Math.min(window.innerHeight,t+r),c=(i+o)/2-e,l=(a+s)/2-t,[u,d]=this.viewport.rotation%180==0?[c,l]:[l,c];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#v(),!0)}setSelected(e){this.#p.setSelected(e)}toggleSelected(e){this.#p.toggleSelected(e)}unselect(e){this.#p.unselect(e)}pointerup(e){let{isMac:t}=_l.platform;if(!(e.button!==0||e.ctrlKey&&t)&&e.target===this.div&&this.#o&&(this.#o=!1,!(this.#g?.isDrawer&&this.#g.supportMultipleDrawings))){if(!this.#t){this.#t=!0;return}if(this.#p.getMode()===W.STAMP){this.#p.unselectAll();return}this.createAndAddNewEditor(e,!1)}}pointerdown(e){if(this.#p.getMode()===W.HIGHLIGHT&&this.enableTextSelection(),this.#o){this.#o=!1;return}let{isMac:t}=_l.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(this.#o=!0,this.#g?.isDrawer){this.startDrawingSession(e);return}let n=this.#p.getActive();this.#t=!n||n.isEmpty()}startDrawingSession(e){if(this.div.focus(),this.#l){this.#g.startDrawing(this,this.#p,!1,e);return}this.#p.setCurrentDrawingSession(this),this.#l=new AbortController;let t=this.#p.combinedSignal(this.#l);this.div.addEventListener(`blur`,({relatedTarget:e})=>{e&&!this.div.contains(e)&&(this.#u=null,this.commitOrRemove())},{signal:t}),this.#g.startDrawing(this,this.#p,!1,e)}pause(e){if(e){let{activeElement:e}=document;this.div.contains(e)&&(this.#u=e);return}this.#u&&setTimeout(()=>{this.#u?.focus(),this.#u=null},0)}endDrawingSession(e=!1){return this.#l?(this.#p.setCurrentDrawingSession(null),this.#l.abort(),this.#l=null,this.#u=null,this.#g.endDrawing(e)):null}findNewParent(e,t,n){let r=this.#p.findParent(t,n);return r===null||r===this?!1:(r.changeParent(e),!0)}commitOrRemove(){return this.#l?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#l&&this.#g.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#p.getActive()?.parent===this&&(this.#p.commitOrRemove(),this.#p.setActiveEditor(null)),this.#i&&=(clearTimeout(this.#i),null);for(let e of this.#a.values())this.#e?.removePointerInTextLayer(e.contentDiv),e.setParent(null),e.isAttachedToDOM=!1,e.div.remove();this.div=null,this.#a.clear(),this.#p.removeLayer(this)}#y(){for(let e of this.#a.values())e.isEmpty()&&e.remove()}render({viewport:e}){this.viewport=e,Wl(this.div,e);for(let e of this.#p.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:e}){this.#p.commitOrRemove(),this.#y();let t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,Wl(this.div,{rotation:n}),t!==n)for(let e of this.#a.values())e.rotate(n)}get pageDimensions(){let{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return this.#p.viewParameters.realScale}},bp=class e{#e=null;#t=0;#n=new Map;#r=new Map;constructor({pageIndex:e}){this.pageIndex=e}setParent(e){if(!this.#e){this.#e=e;return}if(this.#e!==e){if(this.#n.size>0)for(let t of this.#n.values())t.remove(),e.append(t);this.#e=e}}static get _svgFactory(){return Y(this,`_svgFactory`,new Sf)}static#i(e,[t,n,r,i]){let{style:a}=e;a.top=`${100*n}%`,a.left=`${100*t}%`,a.width=`${100*r}%`,a.height=`${100*i}%`}#a(){let t=e._svgFactory.create(1,1,!0);return this.#e.append(t),t.setAttribute(`aria-hidden`,!0),t}#o(t,n){let r=e._svgFactory.createElement(`clipPath`);t.append(r);let i=`clip_${n}`;r.setAttribute(`id`,i),r.setAttribute(`clipPathUnits`,`objectBoundingBox`);let a=e._svgFactory.createElement(`use`);return r.append(a),a.setAttribute(`href`,`#${n}`),a.classList.add(`clip`),i}#s(e,t){for(let[n,r]of Object.entries(t))r===null?e.removeAttribute(n):e.setAttribute(n,r)}draw(t,n=!1,r=!1){let i=this.#t++,a=this.#a(),o=e._svgFactory.createElement(`defs`);a.append(o);let s=e._svgFactory.createElement(`path`);o.append(s);let c=`path_p${this.pageIndex}_${i}`;s.setAttribute(`id`,c),s.setAttribute(`vector-effect`,`non-scaling-stroke`),n&&this.#r.set(i,s);let l=r?this.#o(o,c):null,u=e._svgFactory.createElement(`use`);return a.append(u),u.setAttribute(`href`,`#${c}`),this.updateProperties(a,t),this.#n.set(i,a),{id:i,clipPathId:`url(#${l})`}}drawOutline(t,n){let r=this.#t++,i=this.#a(),a=e._svgFactory.createElement(`defs`);i.append(a);let o=e._svgFactory.createElement(`path`);a.append(o);let s=`path_p${this.pageIndex}_${r}`;o.setAttribute(`id`,s),o.setAttribute(`vector-effect`,`non-scaling-stroke`);let c;if(n){let t=e._svgFactory.createElement(`mask`);a.append(t),c=`mask_p${this.pageIndex}_${r}`,t.setAttribute(`id`,c),t.setAttribute(`maskUnits`,`objectBoundingBox`);let n=e._svgFactory.createElement(`rect`);t.append(n),n.setAttribute(`width`,`1`),n.setAttribute(`height`,`1`),n.setAttribute(`fill`,`white`);let i=e._svgFactory.createElement(`use`);t.append(i),i.setAttribute(`href`,`#${s}`),i.setAttribute(`stroke`,`none`),i.setAttribute(`fill`,`black`),i.setAttribute(`fill-rule`,`nonzero`),i.classList.add(`mask`)}let l=e._svgFactory.createElement(`use`);i.append(l),l.setAttribute(`href`,`#${s}`),c&&l.setAttribute(`mask`,`url(#${c})`);let u=l.cloneNode();return i.append(u),l.classList.add(`mainOutline`),u.classList.add(`secondaryOutline`),this.updateProperties(i,t),this.#n.set(r,i),r}finalizeDraw(e,t){this.#r.delete(e),this.updateProperties(e,t)}updateProperties(t,n){if(!n)return;let{root:r,bbox:i,rootClass:a,path:o}=n,s=typeof t==`number`?this.#n.get(t):t;if(s){if(r&&this.#s(s,r),i&&e.#i(s,i),a){let{classList:e}=s;for(let[t,n]of Object.entries(a))e.toggle(t,n)}if(o){let e=s.firstChild.firstChild;this.#s(e,o)}}}updateParent(e,t){if(t===this)return;let n=this.#n.get(e);n&&(t.#e.append(n),this.#n.delete(e),t.#n.set(e,n))}remove(e){this.#r.delete(e),this.#e!==null&&(this.#n.get(e).remove(),this.#n.delete(e))}destroy(){this.#e=null;for(let e of this.#n.values())e.remove();this.#n.clear(),this.#r.clear()}};globalThis.pdfjsTestingUtils={HighlightOutliner:op},U.AbortException,U.AnnotationEditorLayer,U.AnnotationEditorParamsType,U.AnnotationEditorType,U.AnnotationEditorUIManager,U.AnnotationLayer,U.AnnotationMode,U.ColorPicker,U.DOMSVGFactory,U.DrawLayer,U.FeatureTest;var xp=U.GlobalWorkerOptions;U.ImageKind,U.InvalidPDFException,U.MissingPDFException,U.OPS,U.OutputScale,U.PDFDataRangeTransport,U.PDFDateString,U.PDFWorker,U.PasswordResponses,U.PermissionFlag,U.PixelsPerInch,U.RenderingCancelledException,U.TextLayer,U.TouchManager,U.UnexpectedResponseException,U.Util,U.VerbosityLevel,U.XfaLayer,U.build,U.createValidAbsoluteUrl,U.fetchData;var Sp=U.getDocument;U.getFilenameFromUrl,U.getPdfFilenameFromUrl,U.getXfaPageViewport,U.isDataScheme,U.isPdfFile,U.noContextMenu,U.normalizeUnicode,U.setLayerDimensions,U.shadow,U.stopEvent;var Cp=U.version,wp=null;function Tp(){let e=document.createElement(`div`);e.style.width=`1in`,document.body.append(e);let t=e.offsetWidth;return e.remove(),t}function Ep(){let e=wp??Tp();return wp=e,e/72}function Dp(e,t=500){if(typeof e!=`function`)throw TypeError(`The first argument is not a function.`);let n=null;return function(...r){n&&clearTimeout(n),n=setTimeout(()=>{n=null,e.apply(this,r)},t)}}function Op(e){return e.arrayBuffer?e.arrayBuffer():new Promise((t,n)=>{let r=new FileReader;r.addEventListener(`load`,()=>{let e=r.result;if(!(e instanceof ArrayBuffer)){n(Error(`Failed to read file as ArrayBuffer.`));return}t(e)}),r.addEventListener(`error`,n),r.readAsArrayBuffer(e)})}Ap()||(xp.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Cp}/pdf.worker.min.mjs`);function kp(){if(typeof window>`u`)return!0;try{return window.self===window.top}catch{return!1}}function Ap(){try{return typeof OffscreenCanvas<`u`&&typeof HTMLCanvasElement<`u`&&typeof HTMLCanvasElement.prototype.transferControlToOffscreen==`function`&&kp()}catch{return!1}}function jp(e,t){let n=Ep()/window.devicePixelRatio,r={...e,id:t,units:n};return Ap()?Mp(r):Np(r)}async function Mp({data:e,password:t,id:n,page:r,units:i,scale:a}){let o=new Worker(new URL(``+(typeof document>`u`&&typeof location>`u`?require("url").pathToFileURL(__dirname+`/assets/pdfjs.worker-QHzJtIzr.js`).href:new URL(`assets/pdfjs.worker-QHzJtIzr.js`,typeof document>`u`?location.href:document.currentScript&&document.currentScript.tagName.toUpperCase()===`SCRIPT`&&document.currentScript.src||document.baseURI).href),``+{}.url),{type:`module`});try{return o.postMessage({data:e,password:t,id:n,page:r,units:i,scale:a}),await new Promise((e,t)=>{let r=()=>{o.removeEventListener(`message`,i),o.removeEventListener(`error`,a)},i=i=>{if(i.data.status){if(r(),i.data.status===`success`){let{bitmap:t,width:r,height:a,pages:o}=i.data;if(t&&n){let n=document.createElement(`canvas`),i=n.getContext(`2d`);return n.width=r,n.height=a,i?.drawImage(t,0,0),t.close(),e({pages:o,canvas:n})}return e({pages:o,canvas:null})}if(i.data.status===`error`)return t(i.data.error)}},a=e=>{r(),t(Error(`Worker error: ${e.message}`))};o.addEventListener(`message`,i),o.addEventListener(`error`,a,{once:!0})})}finally{o.terminate()}}async function Np({data:e,password:t,id:n,page:r,scale:i,units:a}){let o=await Sp({data:await Op(e),password:t}).promise;try{let e=o.numPages;if(!n)return{canvas:null,pages:e};let t=await o.getPage(r),s=t.getViewport({scale:i}),c=document.createElement(`canvas`),l=c.getContext(`2d`);if(!l)throw Error(`Failed to get 2d context`);let u={canvasContext:l,viewport:s,transform:[a,0,0,a,0,0]};return c.width=Math.floor(s.width*a),c.height=Math.floor(s.height*a),await t.render(u).promise,{canvas:c,pages:e}}finally{o.destroy()}}var Pp=new Map;function Fp(e){let t=new jo(e);return Pp.set(e,t),t}function Ip(e){let t=Date.now();return{PDFId:`${e.name}-${t}`,name:e.name.replace(/.pdf/,``),updateDate:t,data:e}}async function Lp({src:e},t,n){if(!e||!n)return null;let{objects:r,options:i}=await Ys(e),a=r.filter(e=>e!==null),o=oo.groupSVGElements(a,i);for(let e of a)e.stroke=n;return o.hoverCursor=`pointer`,o.stroke=`${n}-${t}`,o}function Rp(e,t){Pp.get(e)&&Vp(e,qp(t,1/3))}async function zp(e,t){let n=Date.now(),r={PDFId:`${e.name}-${n}`,name:e.name.replace(/.png|.jpg|.jpeg/,``),updateDate:n,data:e};return t&&Bp(t,{data:e}),{...r,pages:1}}async function Bp(e,{data:t,scale:n=.5}){if(!Pp.get(e))return;let r=URL.createObjectURL(t),i=await Fs.fromURL(r);i.scale(n),Vp(e,i),URL.revokeObjectURL(r)}function Vp(e,t){let n=Pp.get(e);n&&(n.setDimensions({width:t.getScaledWidth(),height:t.getScaledHeight()}),t.set({originX:`left`,originY:`top`,left:0,top:0}),n.backgroundImage=t,n.renderAll())}function Hp(e,t){if(!t)return;let{oCoords:n}=e;if(!n)return;let{x:r,y:i}=n.tl.touchCorner.tl,{height:a,width:o,scaleY:s,scaleX:c}=t;t.top=i-a*s/2,t.left=r-o*c/2,t.setCoords()}function Up(e,t,n){!n||!e||(n.scale(1/t),Hp(e,n))}function Wp(e,t){if(!e)return;let n=e._cornerSize||6;e.borderScaleFactor=1/t,e.cornerSize=1/t*n,e.touchCornerSize=n*4*(1/t),e.setCoords()}function Gp(e){let t=Pp.get(e);t&&(t.discardActiveObject(),t.renderAll())}function Kp(e){let t=Pp.get(e);t&&(t.clear(),Pp.delete(e))}function qp(e,t){return new Fs(e,{scaleX:t,scaleY:t})}function Jp(e,t){if(!t)return;let{left:n,top:r}=e,i=t.x*e.getScaledWidth(),a=t.y*e.getScaledHeight();e.set({left:n-i,top:r-a,originX:`left`,originY:`top`})}function Yp(e,t,n){let r=e.type;return{"application/pdf":Xp,"image/png":Qp,"image/jpeg":Qp}[r]?.(e,t,n)??Promise.reject(Error(`Unsupported ${r} file type.`))}async function Xp(e,t,n){let r=Ip(e),i=await Zp({page:1,data:e,scale:.8,password:t},n);return{...r,pages:i}}async function Zp(e,t){let{canvas:n,pages:r}=await jp(e,t);return n&&t&&Rp(t,n),r}async function Qp(e,t,n){return await zp(e,n)}function $p(e,t){let n=Pp.get(e);if(!n)return;let r=n.getActiveObject();r&&(r instanceof Ca?r.forEachObject(e=>{e.set(t)}):r.set(t),n.renderAll())}async function em(e,t){let n=Pp.get(e);if(!n)return;let r=n?.getActiveObject();if(!r)return;let i=await r.clone(c);i instanceof Ca?i.forEachObject(e=>{n.add(e),t(n,e)}):(n.add(i),t(n,i)),Jp(i,{x:-.1,y:-.1}),n.setActiveObject(i)}function tm(e){let t=Pp.get(e);if(!t)return;let n=t.getActiveObject();n&&(n instanceof Ca?(n.forEachObject(e=>{t.remove(e)}),t.discardActiveObject()):t.remove(n))}function nm(e){let{id:n=``,selectionOptions:r,pointerDown:o,pointerMove:c,pointerUp:l,selectionCreated:u,selectionCleared:d}=e||{},f=(0,t.useRef)(null),p=(0,t.useRef)(null),m=(0,t.useRef)(1),h=(0,t.useRef)({...s});function g(){if(!n||Pp.has(n))return;let e=Fp(n);return e.on(`selection:created`,t=>{if(u?.(t),t.selected.length<=1)return;let n=e.getActiveObject();n&&(p.current=n,r?.value&&p.current.set(r.value),p.current._cornerSize=p.current.cornerSize,T(m.current))}),e.on(`selection:cleared`,t=>{d?.(t),D(e)}),o&&e.on(`mouse:down`,o),c&&e.on(`mouse:move`,c),l&&e.on(`mouse:up`,l),e}function _(e,t){return Yp(e,t,n)}function v(e){return Zp(e,n)}function y({data:e,scale:t=.5}){return Bp(n,{data:e,scale:t})}async function b(e,t,r){let a=Pp.get(n);if(!a)return;let o=await Fs.fromURL(e,{},{...i,...t});Jp(o,r),a.add(o),S(a,o),a.setActiveObject(o)}function x(e,t,r){let i=Pp.get(n);if(!i)return;let o=new ls(e,{...a,...t});Jp(o,r),i.add(o),S(i,o),i.setActiveObject(o)}function S(e,t){t.on(`selected`,t=>C({canvas:e,target:t.target})),t.on(`modified`,t=>C({canvas:e,target:t.target})),t.on(`scaling`,()=>D(e)),t.on(`moving`,()=>D(e)),t.on(`rotating`,()=>D(e)),t._cornerSize=t._cornerSize??t.cornerSize}async function C({canvas:e,target:t,stroke:n=h.current.stroke,uuid:r=Date.now()}){if(e.getActiveObjects().length>1||f.current?.stroke===`${n}-${r}`)return;let i=await Lp(h.current,r,n);D(e),f.current=i,p.current=t,w(e,t,r),T(m.current,!0),i&&e.add(i)}function w(e,t,n){f.current&&(f.current.on(`selected`,()=>{e.remove(t),D(e)}),f.current.on(`mouseover`,()=>{C({canvas:e,target:t,stroke:h.current.hoverStroke,uuid:n})}),f.current.on(`mouseout`,()=>{C({canvas:e,target:t,stroke:h.current.stroke,uuid:n})}))}function T(e,t=!1){let r=Pp.get(n);m.current=e,r&&(Wp(p.current,e),Up(p.current,e,f.current),!t&&r.renderAll())}function E(e){if(!e)return;h.current={...h.current,...e};let t=Pp.get(n);!f||!p.current||!t||C({target:p.current,canvas:t})}function D(e){p.current=null,f.current&&=(e.remove(f.current),null)}function O(){Gp(n)}function k(){Kp(n)}function A(e){$p(n,e)}function j(){return em(n,S)}function M(){tm(n)}return{createCanvas:g,loadFile:_,specifyPage:v,renderImage:y,addFabric:b,addTextFabric:x,clearActive:O,deleteCanvas:k,scaleFabric:T,setCloseSvgOptions:E,setActiveFabric:A,copyActiveFabric:j,deleteActiveFabric:M}}function rm(e){let n=(0,t.useRef)(0);return(0,t.useEffect)(()=>{let t=Dp(()=>{let{innerWidth:t}=globalThis;t!==n.current&&(n.current=t,e())});return n.current=window.innerWidth,window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[]),null}var im=(0,t.forwardRef)(am);function am({file:e,page:r=1,canvasId:i=`PDF-canvas`,fileZoom:a=1,fileScale:s=1,canvasScale:c=1,canvasClass:l=``,isDrop:u=!1,password:d,dropTextOptions:f,dropImageOptions:p,closeSvgOptions:m,selectionOptions:h,manualReload:g,onLoaded:_,onReload:v,onPointerDown:y,onPointerMove:b,onPointerUp:x,onSelectionCreated:S,onSelectionCleared:C},w){let T=(0,t.useRef)(null),E=`${i}-${r-1}`,D=(0,t.useMemo)(()=>a*c,[a,c]),{createCanvas:O,specifyPage:k,addFabric:A,addTextFabric:j,renderImage:M,clearActive:ee,deleteCanvas:N,scaleFabric:P,setActiveFabric:F,setCloseSvgOptions:I,copyActiveFabric:te,deleteActiveFabric:ne}=nm({id:E,selectionOptions:(0,t.useMemo)(()=>({...o,...h}),[h]),pointerDown:y,pointerMove:b,pointerUp:x,selectionCreated:S,selectionCleared:C});rm(se);async function re(){requestAnimationFrame(async()=>{if(O(),e.data?.type.startsWith(`image/`)){let t=e.data;t&&M({data:t,scale:s/3}),_?.();return}let t=e.data;t&&await k({page:r,data:t,scale:s,password:d}),_?.()})}function ie(e){if(e.preventDefault(),e.stopPropagation(),!u||!e.dataTransfer)return;let{dataTransfer:t,nativeEvent:n}=e,{offsetX:r,offsetY:i}=n,a=t.getData(`text/plain`),o=t.getData(`text/uri-list`),s=t.getData(`custom/offset`),c=s?JSON.parse(s):null,l={top:i,left:r},d={x:c?.offsetX??0,y:c?.offsetY??0};o?ae(o,l,d):a&&oe(a,l,d)}function ae(e,t,n){A(e,{...p,...t},n)}function oe(e,t,n){j(e,{...f,...t},n)}function se(){g||re(),v?.()}return(0,t.useImperativeHandle)(w,()=>({reload:re,addImage:ae,addText:oe,clearActive:ee,deleteCanvas:N,setActiveFabric:F,copyActiveFabric:te,deleteActiveFabric:ne,canvasRef:T})),(0,t.useEffect)(()=>{se()},[s,r,e,d]),(0,t.useEffect)(()=>{P(D)},[D]),(0,t.useEffect)(()=>{I(m)},[m]),(0,t.useEffect)(()=>()=>N(),[]),(0,n.jsx)(`div`,{style:{transform:`scale(${D})`},onDragOver:e=>e.preventDefault(),onDragEnter:e=>e.preventDefault(),onDrop:ie,children:(0,n.jsx)(`canvas`,{id:E,ref:T,className:l})})}e.default=im,e.loadFile=Yp,e.useFabric=nm});
|