@component-hook/pdf-canvas 1.1.1 → 1.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/react/pdf-canvas.es.js +9289 -9442
- package/dist/react/pdf-canvas.umd.js +91 -85
- package/dist/vue/pdf-canvas.es.js +8666 -8821
- package/dist/vue/pdf-canvas.umd.js +81 -75
- package/package.json +7 -7
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(at,Z){typeof exports=="object"&&typeof module<"u"?Z(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],Z):(at=typeof globalThis<"u"?globalThis:at||self,Z(at["pdf-canvas"]={},at.React))})(this,function(at,Z){"use strict";var Oc=at=>{throw TypeError(at)};var eo=(at,Z,jt)=>Z.has(at)||Oc("Cannot "+jt);var De=(at,Z,jt)=>(eo(at,Z,"read from private field"),jt?jt.call(at):Z.get(at)),hi=(at,Z,jt)=>Z.has(at)?Oc("Cannot add the same private member more than once"):Z instanceof WeakSet?Z.add(at):Z.set(at,jt),Wi=(at,Z,jt,We)=>(eo(at,Z,"write to private field"),We?We.call(at,jt):Z.set(at,jt),jt),gr=(at,Z,jt)=>(eo(at,Z,"access private method"),jt);var Dc=(at,Z,jt,We)=>({set _(gs){Wi(at,Z,gs,jt)},get _(){return De(at,Z,We)}});var hr,Fs,Ls,ri,mr,ai,vr;var jt=typeof document<"u"?document.currentScript:null,We={exports:{}},gs={};/**
|
|
2
2
|
* @license React
|
|
3
3
|
* react-jsx-runtime.production.min.js
|
|
4
4
|
*
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* This source code is licensed under the MIT license found in the
|
|
8
8
|
* LICENSE file in the root directory of this source tree.
|
|
9
|
-
*/var
|
|
9
|
+
*/var so;function Rc(){if(so)return gs;so=1;var o=Z,t=Symbol.for("react.element"),e=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,i=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,n={key:!0,ref:!0,__self:!0,__source:!0};function r(a,l,h){var c,u={},d=null,f=null;h!==void 0&&(d=""+h),l.key!==void 0&&(d=""+l.key),l.ref!==void 0&&(f=l.ref);for(c in l)s.call(l,c)&&!n.hasOwnProperty(c)&&(u[c]=l[c]);if(a&&a.defaultProps)for(c in l=a.defaultProps,l)u[c]===void 0&&(u[c]=l[c]);return{$$typeof:t,type:a,key:d,ref:f,props:u,_owner:i.current}}return gs.Fragment=e,gs.jsx=r,gs.jsxs=r,gs}var ci={};/**
|
|
10
10
|
* @license React
|
|
11
11
|
* react-jsx-runtime.development.js
|
|
12
12
|
*
|
|
@@ -14,48 +14,48 @@
|
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the MIT license found in the
|
|
16
16
|
* LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/var
|
|
18
|
-
|
|
19
|
-
`),
|
|
20
|
-
`),
|
|
21
|
-
`+
|
|
17
|
+
*/var io;function Fc(){return io||(io=1,process.env.NODE_ENV!=="production"&&function(){var o=Z,t=Symbol.for("react.element"),e=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),i=Symbol.for("react.strict_mode"),n=Symbol.for("react.profiler"),r=Symbol.for("react.provider"),a=Symbol.for("react.context"),l=Symbol.for("react.forward_ref"),h=Symbol.for("react.suspense"),c=Symbol.for("react.suspense_list"),u=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.for("react.offscreen"),g=Symbol.iterator,p="@@iterator";function v(y){if(y===null||typeof y!="object")return null;var D=g&&y[g]||y[p];return typeof D=="function"?D:null}var m=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function b(y){{for(var D=arguments.length,j=new Array(D>1?D-1:0),U=1;U<D;U++)j[U-1]=arguments[U];_("error",y,j)}}function _(y,D,j){{var U=m.ReactDebugCurrentFrame,lt=U.getStackAddendum();lt!==""&&(D+="%s",j=j.concat([lt]));var dt=j.map(function(it){return String(it)});dt.unshift("Warning: "+D),Function.prototype.apply.call(console[y],console,dt)}}var w=!1,C=!1,T=!1,E=!1,k=!1,O;O=Symbol.for("react.module.reference");function H(y){return!!(typeof y=="string"||typeof y=="function"||y===s||y===n||k||y===i||y===h||y===c||E||y===f||w||C||T||typeof y=="object"&&y!==null&&(y.$$typeof===d||y.$$typeof===u||y.$$typeof===r||y.$$typeof===a||y.$$typeof===l||y.$$typeof===O||y.getModuleId!==void 0))}function N(y,D,j){var U=y.displayName;if(U)return U;var lt=D.displayName||D.name||"";return lt!==""?j+"("+lt+")":j}function P(y){return y.displayName||"Context"}function R(y){if(y==null)return null;if(typeof y.tag=="number"&&b("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof y=="function")return y.displayName||y.name||null;if(typeof y=="string")return y;switch(y){case s:return"Fragment";case e:return"Portal";case n:return"Profiler";case i:return"StrictMode";case h:return"Suspense";case c:return"SuspenseList"}if(typeof y=="object")switch(y.$$typeof){case a:var D=y;return P(D)+".Consumer";case r:var j=y;return P(j._context)+".Provider";case l:return N(y,y.render,"ForwardRef");case u:var U=y.displayName||null;return U!==null?U:R(y.type)||"Memo";case d:{var lt=y,dt=lt._payload,it=lt._init;try{return R(it(dt))}catch{return null}}}return null}var F=Object.assign,V=0,M,L,Y,ft,bt,_t,gt;function rt(){}rt.__reactDisabledLog=!0;function Dt(){{if(V===0){M=console.log,L=console.info,Y=console.warn,ft=console.error,bt=console.group,_t=console.groupCollapsed,gt=console.groupEnd;var y={configurable:!0,enumerable:!0,value:rt,writable:!0};Object.defineProperties(console,{info:y,log:y,warn:y,error:y,group:y,groupCollapsed:y,groupEnd:y})}V++}}function ee(){{if(V--,V===0){var y={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:F({},y,{value:M}),info:F({},y,{value:L}),warn:F({},y,{value:Y}),error:F({},y,{value:ft}),group:F({},y,{value:bt}),groupCollapsed:F({},y,{value:_t}),groupEnd:F({},y,{value:gt})})}V<0&&b("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var K=m.ReactCurrentDispatcher,$;function Tt(y,D,j){{if($===void 0)try{throw Error()}catch(lt){var U=lt.stack.trim().match(/\n( *(at )?)/);$=U&&U[1]||""}return`
|
|
18
|
+
`+$+y}}var _e=!1,Nt;{var cr=typeof WeakMap=="function"?WeakMap:Map;Nt=new cr}function Gi(y,D){if(!y||_e)return"";{var j=Nt.get(y);if(j!==void 0)return j}var U;_e=!0;var lt=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var dt;dt=K.current,K.current=null,Dt();try{if(D){var it=function(){throw Error()};if(Object.defineProperty(it.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(it,[])}catch(he){U=he}Reflect.construct(y,[],it)}else{try{it.call()}catch(he){U=he}y.call(it.prototype)}}else{try{throw Error()}catch(he){U=he}y()}}catch(he){if(he&&U&&typeof he.stack=="string"){for(var et=he.stack.split(`
|
|
19
|
+
`),se=U.stack.split(`
|
|
20
|
+
`),Et=et.length-1,Rt=se.length-1;Et>=1&&Rt>=0&&et[Et]!==se[Rt];)Rt--;for(;Et>=1&&Rt>=0;Et--,Rt--)if(et[Et]!==se[Rt]){if(Et!==1||Rt!==1)do if(Et--,Rt--,Rt<0||et[Et]!==se[Rt]){var we=`
|
|
21
|
+
`+et[Et].replace(" at new "," at ");return y.displayName&&we.includes("<anonymous>")&&(we=we.replace("<anonymous>",y.displayName)),typeof y=="function"&&Nt.set(y,we),we}while(Et>=1&&Rt>=0);break}}}finally{_e=!1,K.current=dt,ee(),Error.prepareStackTrace=lt}var li=y?y.displayName||y.name:"",js=li?Tt(li):"";return typeof y=="function"&&Nt.set(y,js),js}function ur(y,D,j){return Gi(y,!1)}function dr(y){var D=y.prototype;return!!(D&&D.isReactComponent)}function Is(y,D,j){if(y==null)return"";if(typeof y=="function")return Gi(y,dr(y));if(typeof y=="string")return Tt(y);switch(y){case h:return Tt("Suspense");case c:return Tt("SuspenseList")}if(typeof y=="object")switch(y.$$typeof){case l:return ur(y.render);case u:return Is(y.type,D,j);case d:{var U=y,lt=U._payload,dt=U._init;try{return Is(dt(lt),D,j)}catch{}}}return""}var fs=Object.prototype.hasOwnProperty,vc={},bc=m.ReactDebugCurrentFrame;function fr(y){if(y){var D=y._owner,j=Is(y.type,y._source,D?D.type:null);bc.setExtraStackFrame(j)}else bc.setExtraStackFrame(null)}function Yp(y,D,j,U,lt){{var dt=Function.call.bind(fs);for(var it in y)if(dt(y,it)){var et=void 0;try{if(typeof y[it]!="function"){var se=Error((U||"React class")+": "+j+" type `"+it+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof y[it]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw se.name="Invariant Violation",se}et=y[it](D,it,U,j,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Et){et=Et}et&&!(et instanceof Error)&&(fr(lt),b("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",U||"React class",j,it,typeof et),fr(null)),et instanceof Error&&!(et.message in vc)&&(vc[et.message]=!0,fr(lt),b("Failed %s type: %s",j,et.message),fr(null))}}}var $p=Array.isArray;function Ka(y){return $p(y)}function qp(y){{var D=typeof Symbol=="function"&&Symbol.toStringTag,j=D&&y[Symbol.toStringTag]||y.constructor.name||"Object";return j}}function Kp(y){try{return yc(y),!1}catch{return!0}}function yc(y){return""+y}function _c(y){if(Kp(y))return b("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",qp(y)),yc(y)}var wc=m.ReactCurrentOwner,Jp={key:!0,ref:!0,__self:!0,__source:!0},xc,Sc;function Qp(y){if(fs.call(y,"ref")){var D=Object.getOwnPropertyDescriptor(y,"ref").get;if(D&&D.isReactWarning)return!1}return y.ref!==void 0}function Zp(y){if(fs.call(y,"key")){var D=Object.getOwnPropertyDescriptor(y,"key").get;if(D&&D.isReactWarning)return!1}return y.key!==void 0}function tm(y,D){typeof y.ref=="string"&&wc.current}function em(y,D){{var j=function(){xc||(xc=!0,b("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",D))};j.isReactWarning=!0,Object.defineProperty(y,"key",{get:j,configurable:!0})}}function sm(y,D){{var j=function(){Sc||(Sc=!0,b("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",D))};j.isReactWarning=!0,Object.defineProperty(y,"ref",{get:j,configurable:!0})}}var im=function(y,D,j,U,lt,dt,it){var et={$$typeof:t,type:y,key:D,ref:j,props:it,_owner:dt};return et._store={},Object.defineProperty(et._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(et,"_self",{configurable:!1,enumerable:!1,writable:!1,value:U}),Object.defineProperty(et,"_source",{configurable:!1,enumerable:!1,writable:!1,value:lt}),Object.freeze&&(Object.freeze(et.props),Object.freeze(et)),et};function nm(y,D,j,U,lt){{var dt,it={},et=null,se=null;j!==void 0&&(_c(j),et=""+j),Zp(D)&&(_c(D.key),et=""+D.key),Qp(D)&&(se=D.ref,tm(D,lt));for(dt in D)fs.call(D,dt)&&!Jp.hasOwnProperty(dt)&&(it[dt]=D[dt]);if(y&&y.defaultProps){var Et=y.defaultProps;for(dt in Et)it[dt]===void 0&&(it[dt]=Et[dt])}if(et||se){var Rt=typeof y=="function"?y.displayName||y.name||"Unknown":y;et&&em(it,Rt),se&&sm(it,Rt)}return im(y,et,se,lt,U,wc.current,it)}}var Ja=m.ReactCurrentOwner,Cc=m.ReactDebugCurrentFrame;function oi(y){if(y){var D=y._owner,j=Is(y.type,y._source,D?D.type:null);Cc.setExtraStackFrame(j)}else Cc.setExtraStackFrame(null)}var Qa;Qa=!1;function Za(y){return typeof y=="object"&&y!==null&&y.$$typeof===t}function Ac(){{if(Ja.current){var y=R(Ja.current.type);if(y)return`
|
|
22
22
|
|
|
23
|
-
Check the render method of \``+
|
|
23
|
+
Check the render method of \``+y+"`."}return""}}function rm(y){return""}var Tc={};function am(y){{var D=Ac();if(!D){var j=typeof y=="string"?y:y.displayName||y.name;j&&(D=`
|
|
24
24
|
|
|
25
|
-
Check the top-level render call using <`+
|
|
25
|
+
Check the top-level render call using <`+j+">.")}return D}}function Ec(y,D){{if(!y._store||y._store.validated||y.key!=null)return;y._store.validated=!0;var j=am(D);if(Tc[j])return;Tc[j]=!0;var U="";y&&y._owner&&y._owner!==Ja.current&&(U=" It was passed a child from "+R(y._owner.type)+"."),oi(y),b('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',j,U),oi(null)}}function kc(y,D){{if(typeof y!="object")return;if(Ka(y))for(var j=0;j<y.length;j++){var U=y[j];Za(U)&&Ec(U,D)}else if(Za(y))y._store&&(y._store.validated=!0);else if(y){var lt=v(y);if(typeof lt=="function"&<!==y.entries)for(var dt=lt.call(y),it;!(it=dt.next()).done;)Za(it.value)&&Ec(it.value,D)}}}function om(y){{var D=y.type;if(D==null||typeof D=="string")return;var j;if(typeof D=="function")j=D.propTypes;else if(typeof D=="object"&&(D.$$typeof===l||D.$$typeof===u))j=D.propTypes;else return;if(j){var U=R(D);Yp(j,y.props,"prop",U,y)}else if(D.PropTypes!==void 0&&!Qa){Qa=!0;var lt=R(D);b("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",lt||"Unknown")}typeof D.getDefaultProps=="function"&&!D.getDefaultProps.isReactClassApproved&&b("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function lm(y){{for(var D=Object.keys(y.props),j=0;j<D.length;j++){var U=D[j];if(U!=="children"&&U!=="key"){oi(y),b("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",U),oi(null);break}}y.ref!==null&&(oi(y),b("Invalid attribute `ref` supplied to `React.Fragment`."),oi(null))}}var Pc={};function Mc(y,D,j,U,lt,dt){{var it=H(y);if(!it){var et="";(y===void 0||typeof y=="object"&&y!==null&&Object.keys(y).length===0)&&(et+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var se=rm();se?et+=se:et+=Ac();var Et;y===null?Et="null":Ka(y)?Et="array":y!==void 0&&y.$$typeof===t?(Et="<"+(R(y.type)||"Unknown")+" />",et=" Did you accidentally export a JSX literal instead of a component?"):Et=typeof y,b("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Et,et)}var Rt=nm(y,D,j,lt,dt);if(Rt==null)return Rt;if(it){var we=D.children;if(we!==void 0)if(U)if(Ka(we)){for(var li=0;li<we.length;li++)kc(we[li],y);Object.freeze&&Object.freeze(we)}else b("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else kc(we,y)}if(fs.call(D,"key")){var js=R(y),he=Object.keys(D).filter(function(gm){return gm!=="key"}),to=he.length>0?"{key: someKey, "+he.join(": ..., ")+": ...}":"{key: someKey}";if(!Pc[js+to]){var fm=he.length>0?"{"+he.join(": ..., ")+": ...}":"{}";b(`A props object containing a "key" prop is being spread into JSX:
|
|
26
26
|
let props = %s;
|
|
27
27
|
<%s {...props} />
|
|
28
28
|
React keys must be passed directly to JSX without using spread:
|
|
29
29
|
let props = %s;
|
|
30
|
-
<%s key={someKey} {...props} />`,
|
|
31
|
-
void main(){}`),i=t.createShader(t.FRAGMENT_SHADER);return!!i&&(t.shaderSource(i,s),t.compileShader(i),!!t.getShaderParameter(i,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find(s=>this.testPrecision(e,s)),e.getExtension("WEBGL_lose_context").loseContext(),$i("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const C_={};let xm;const xi=()=>xm||(xm={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new S_,dispose(){},copyPasteData:C_}),lo=()=>xi().document,ou=()=>xi().window,Sm=()=>{var o;return Math.max((o=bt.devicePixelRatio)!==null&&o!==void 0?o:ou().devicePixelRatio,1)},Xh=new class{constructor(){E(this,"charWidthsCache",{}),E(this,"boundsOfCurveCache",{})}getFontCache(o){let{fontFamily:t,fontStyle:e,fontWeight:s}=o;t=t.toLowerCase(),this.charWidthsCache[t]||(this.charWidthsCache[t]={});const i=this.charWidthsCache[t],n="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return i[n]||(i[n]={}),i[n]}clearFontCache(o){(o=(o||"").toLowerCase())?this.charWidthsCache[o]&&delete this.charWidthsCache[o]:this.charWidthsCache={}}limitDimsByArea(o){const{perfLimitSizeTotal:t}=bt,e=Math.sqrt(t*o);return[Math.floor(e),Math.floor(t/e)]}},Pf="6.6.4";function Rr(){}const Vn=Math.PI/2,qi=2*Math.PI,Mf=Math.PI/180,He=Object.freeze([1,0,0,1,0,0]),Of=16,Wn=.4477152502,rt="center",wt="left",is="top",Df="bottom",$t="right",ze="none",Rf=/\r?\n/,Cm="moving",hu="scaling",Am="rotating",Ff="rotate",Tm="skewing",Uh="resizing",A_="modifyPoly",T_="modifyPath",lu="changed",cu="scale",Ve="scaleX",gs="scaleY",co="skewX",uo="skewY",ee="fill",We="stroke",uu="modified",fo="json",Lf="svg",W=new class{constructor(){this[fo]=new Map,this[Lf]=new Map}has(o){return this[fo].has(o)}getClass(o){const t=this[fo].get(o);if(!t)throw new wi("No class registered for ".concat(o));return t}setClass(o,t){t?this[fo].set(t,o):(this[fo].set(o.type,o),this[fo].set(o.type.toLowerCase(),o))}getSVGClass(o){return this[Lf].get(o)}setSVGClass(o,t){this[Lf].set(t??o.type.toLowerCase(),o)}},du=new class extends Array{remove(o){const t=this.indexOf(o);t>-1&&this.splice(t,1)}cancelAll(){const o=this.splice(0);return o.forEach(t=>t.abort()),o}cancelByCanvas(o){if(!o)return[];const t=this.filter(e=>{var s;return e.target===o||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===o});return t.forEach(e=>e.abort()),t}cancelByTarget(o){if(!o)return[];const t=this.filter(e=>e.target===o);return t.forEach(e=>e.abort()),t}};class E_{constructor(){E(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach(s=>{let[i,n]=s;this.on(i,n)}),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach(i=>{let[n,r]=i;s.push(this.once(n,r))}),()=>s.forEach(i=>i())}if(e){const s=this.on(t,function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()});return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach(s=>{let[i,n]=s;this._removeEventListener(i,n)}):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const Fr=(o,t)=>{const e=o.indexOf(t);return e!==-1&&o.splice(e,1),o},Ks=o=>{if(o===0)return 1;switch(Math.abs(o)/Vn){case 1:case 3:return 0;case 2:return-1}return Math.cos(o)},Js=o=>{if(o===0)return 0;const t=o/Vn,e=Math.sign(o);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(o)};class M{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;typeof t=="object"?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new M(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new M(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new M(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new M(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new M(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new M(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new M(this.x/t.x,this.y/t.y)}scalarDivide(t){return new M(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.x<t.x&&this.y<t.y}lte(t){return this.x<=t.x&&this.y<=t.y}gt(t){return this.x>t.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new M(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}midPointFrom(t){return this.lerp(t)}min(t){return new M(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new M(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new M(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:If;const s=Js(t),i=Ks(t),n=this.subtract(e);return new M(n.x*i-n.y*s,n.x*s+n.y*i).add(e)}transform(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new M(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}const If=new M(0,0),fu=o=>!!o&&Array.isArray(o._objects);function Em(o){class t extends o{constructor(){super(...arguments),E(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach(a=>this._onObjectAdded(a)),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach(a=>this._onObjectAdded(a)),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return r.forEach(h=>{const c=s.indexOf(h);c!==-1&&(s.splice(c,1),i.push(h),this._onObjectRemoved(h))}),i}forEachObject(s){this.getObjects().forEach((i,n,r)=>s(i,n,r))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter(r=>r.isType(...i))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some(n=>n instanceof t&&n.contains(s,!0))}complexity(){return this._objects.reduce((s,i)=>s+=i.complexity?i.complexity():0,0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(Fr(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Fr(this._objects,s),this._objects.push(s),this._onStackOrderChanged(s),!0)}sendObjectBackwards(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==0){const r=this.findNewLowerIndex(s,n,i);return Fr(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}bringObjectForward(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==this._objects.length-1){const r=this.findNewUpperIndex(s,n,i);return Fr(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(Fr(this._objects,s),this._objects.splice(i,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,i,n){let r;if(n){r=i;for(let a=i-1;a>=0;--a)if(s.isOverlapping(this._objects[a])){r=a;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let a=i+1;a<this._objects.length;++a)if(s.isOverlapping(this._objects[a])){r=a;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:a}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const c=[],u=new M(i,n),d=u.add(new M(r,a));for(let f=this._objects.length-1;f>=0;f--){const g=this._objects[f];g.selectable&&g.visible&&(h&&g.intersectsWithRect(u,d)||g.isContainedWithinRect(u,d)||h&&g.containsPoint(u)||h&&g.containsPoint(d))&&c.push(g)}return c}}return t}class km extends E_{_setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};for(const e in t)this.set(e,t[e])}_setObject(t){for(const e in t)this._set(e,t[e])}set(t,e){return typeof t=="object"?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return typeof e=="boolean"&&this.set(t,!e),this}get(t){return this[t]}}function Yh(o){return ou().requestAnimationFrame(o)}function Pm(o){return ou().cancelAnimationFrame(o)}let k_=0;const Gn=()=>k_++,Rs=()=>{const o=lo().createElement("canvas");if(!o||o.getContext===void 0)throw new wi("Failed to create `canvas` element");return o},Mm=()=>lo().createElement("img"),ps=o=>{const t=Rs();return t.width=o.width,t.height=o.height,t},jf=(o,t,e)=>o.toDataURL("image/".concat(t),e),Nf=(o,t,e)=>new Promise((s,i)=>{o.toBlob(s,"image/".concat(t),e)}),Ut=o=>o*Mf,Si=o=>o/Mf,Om=o=>o.every((t,e)=>t===He[e]),Ee=(o,t,e)=>new M(o).transform(t,e),ns=o=>{const t=1/(o[0]*o[3]-o[1]*o[2]),e=[t*o[3],-t*o[1],-t*o[2],t*o[0],0,0],{x:s,y:i}=new M(o[4],o[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},qt=(o,t,e)=>[o[0]*t[0]+o[2]*t[1],o[1]*t[0]+o[3]*t[1],o[0]*t[2]+o[2]*t[3],o[1]*t[2]+o[3]*t[3],e?0:o[0]*t[4]+o[2]*t[5]+o[4],e?0:o[1]*t[4]+o[3]*t[5]+o[5]],gu=(o,t)=>o.reduceRight((e,s)=>s&&e?qt(s,e,t):s||e,void 0)||He.concat(),Dm=o=>{let[t,e]=o;return Math.atan2(e,t)},Lr=o=>{const t=Dm(o),e=Math.pow(o[0],2)+Math.pow(o[1],2),s=Math.sqrt(e),i=(o[0]*o[3]-o[2]*o[1])/s,n=Math.atan2(o[0]*o[2]+o[1]*o[3],e);return{angle:Si(t),scaleX:s,scaleY:i,skewX:Si(n),skewY:0,translateX:o[4]||0,translateY:o[5]||0}},go=function(o){return[1,0,0,1,o,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function Ir(){let{angle:o=0}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{x:t=0,y:e=0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=Ut(o),i=Ks(s),n=Js(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const pu=function(o){return[o,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:o,0,0]},Rm=o=>Math.tan(Ut(o)),Bf=o=>[1,0,Rm(o),1,0,0],Hf=o=>[1,Rm(o),0,1,0,0],$h=o=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=o,a=pu(s?-t:t,i?-e:e);return n&&(a=qt(a,Bf(n),!0)),r&&(a=qt(a,Hf(r),!0)),a},Fm=o=>{const{translateX:t=0,translateY:e=0,angle:s=0}=o;let i=go(t,e);s&&(i=qt(i,Ir({angle:s})));const n=$h(o);return Om(n)||(i=qt(i,n)),i},qh=function(o){let{signal:t,crossOrigin:e=null}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(s,i){if(t&&t.aborted)return i(new kf("loadImage"));const n=Mm();let r;t&&(r=function(h){n.src="",i(h)},t.addEventListener("abort",r,{once:!0}));const a=function(){n.onload=n.onerror=null,r&&(t==null||t.removeEventListener("abort",r)),s(n)};o?(n.onload=a,n.onerror=function(){r&&(t==null||t.removeEventListener("abort",r)),i(new wi("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=o):a()})},po=function(o){let{signal:t,reviver:e=Rr}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((s,i)=>{const n=[];t&&t.addEventListener("abort",i,{once:!0}),Promise.all(o.map(r=>W.getClass(r.type).fromObject(r,{signal:t}).then(a=>(e(r,a),n.push(a),a)))).then(s).catch(r=>{n.forEach(a=>{a.dispose&&a.dispose()}),i(r)}).finally(()=>{t&&t.removeEventListener("abort",i)})})},Kh=function(o){let{signal:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((e,s)=>{const i=[];t&&t.addEventListener("abort",s,{once:!0});const n=Object.values(o).map(a=>a&&a.type&&W.has(a.type)?po([a],{signal:t}).then(h=>{let[c]=h;return i.push(c),c}):a),r=Object.keys(o);Promise.all(n).then(a=>a.reduce((h,c,u)=>(h[r[u]]=c,h),{})).then(e).catch(a=>{i.forEach(h=>{h.dispose&&h.dispose()}),s(a)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},jr=function(o){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in o&&(t[e]=o[e]),t),{})},zf=(o,t)=>Object.keys(o).reduce((e,s)=>(t(o[s],s,o)&&(e[s]=o[s]),e),{}),Dt=(o,t)=>parseFloat(Number(o).toFixed(t)),mo=o=>"matrix("+o.map(t=>Dt(t,bt.NUM_FRACTION_DIGITS)).join(" ")+")",Fs=o=>!!o&&o.toLive!==void 0,Lm=o=>!!o&&typeof o.toObject=="function",Im=o=>!!o&&o.offsetX!==void 0&&"source"in o,Nr=o=>!!o&&"multiSelectionStacking"in o;function jm(o){const t=o&&Qs(o);let e=0,s=0;if(!o||!t)return{left:e,top:s};let i=o;const n=t.documentElement,r=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(e=r.scrollLeft||n.scrollLeft||0,s=r.scrollTop||n.scrollTop||0):(e+=i.scrollLeft||0,s+=i.scrollTop||0),i.nodeType!==1||i.style.position!=="fixed"););return{left:e,top:s}}const Qs=o=>o.ownerDocument||null,Nm=o=>{var t;return((t=o.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},Bm=function(o,t,e){let{width:s,height:i}=e,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;o.width=s,o.height=i,n>1&&(o.setAttribute("width",(s*n).toString()),o.setAttribute("height",(i*n).toString()),t.scale(n,n))},Vf=(o,t)=>{let{width:e,height:s}=t;e&&(o.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(o.style.height=typeof s=="number"?"".concat(s,"px"):s)};function Hm(o){return o.onselectstart!==void 0&&(o.onselectstart=()=>!1),o.style.userSelect=ze,o}class zm{constructor(t){E(this,"_originalCanvasStyle",void 0),E(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&lo().getElementById(t)||Rs();var s;if(e.hasAttribute("data-fabric"))throw new wi("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width","".concat(e)),i.setAttribute("height","".concat(s)),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;Bm(s,i,t,e)}setCSSDimensions(t){Vf(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&Qs(t),i={left:0,top:0};if(!s)return i;const n=((e=Nm(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};i.left+=parseInt(n.borderLeftWidth,10)||0,i.top+=parseInt(n.borderTopWidth,10)||0,i.left+=parseInt(n.paddingLeft,10)||0,i.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const a=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const h=jm(t);return{left:r.left+h.left-(a.clientLeft||0)+i.left,top:r.top+h.top-(a.clientTop||0)+i.top}}(this.lower.el)}dispose(){xi().dispose(this.lower.el),delete this.lower}}const P_={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...He]};class Jh extends Em(km){get lowerCanvasEl(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.el}get contextContainer(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.ctx}static getDefaults(){return Jh.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new zm(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&($i("warn",`Canvas is trying to add an object that belongs to a different canvas.
|
|
32
|
-
Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?
|
|
30
|
+
<%s key={someKey} {...props} />`,to,js,fm,js),Pc[js+to]=!0}}return y===s?lm(Rt):om(Rt),Rt}}function hm(y,D,j){return Mc(y,D,j,!0)}function cm(y,D,j){return Mc(y,D,j,!1)}var um=cm,dm=hm;ci.Fragment=s,ci.jsx=um,ci.jsxs=dm}()),ci}var no;function Lc(){return no||(no=1,process.env.NODE_ENV==="production"?We.exports=Rc():We.exports=Fc()),We.exports}var ro=Lc();const Ic="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='20'%20cy='20'%20r='10.75'%20stroke='currentColor'%20stroke-width='2.5'/%3e%3cpath%20d='M16%2024L23.7782%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3cpath%20d='M24%2024L16.2218%2016.2218'%20stroke='currentColor'%20stroke-width='2.5'%20stroke-linecap='round'/%3e%3c/svg%3e",jc={top:100,left:50,scaleX:.5,scaleY:.5,borderColor:"black",cornerStrokeColor:"black",cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Nc={top:100,left:50,fontFamily:"helvetica",borderColor:"black",cornerStrokeColor:"black",scaleX:.7,scaleY:.7,cornerSize:6,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Bc={borderColor:"black",cornerStrokeColor:"black",cornerSize:8,selectionBackgroundColor:"rgba(245, 245, 245, 0.8)"},Hc={stroke:"#000",hoverStroke:"#B7EC5D",src:Ic},zc=["borderColor","cornerStrokeColor","cornerSize","_cornerSize","selectionBackgroundColor"];function S(o,t,e){return(t=function(s){var i=function(n,r){if(typeof n!="object"||!n)return n;var a=n[Symbol.toPrimitive];if(a!==void 0){var l=a.call(n,r);if(typeof l!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(r==="string"?String:Number)(n)}(s,"string");return typeof i=="symbol"?i:i+""}(t))in o?Object.defineProperty(o,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):o[t]=e,o}function ao(o,t){var e=Object.keys(o);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(o);t&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(o,i).enumerable})),e.push.apply(e,s)}return e}function x(o){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?ao(Object(e),!0).forEach(function(s){S(o,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(e)):ao(Object(e)).forEach(function(s){Object.defineProperty(o,s,Object.getOwnPropertyDescriptor(e,s))})}return o}function pt(o,t){if(o==null)return{};var e,s,i=function(r,a){if(r==null)return{};var l={};for(var h in r)if({}.hasOwnProperty.call(r,h)){if(a.indexOf(h)>=0)continue;l[h]=r[h]}return l}(o,t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(o);for(s=0;s<n.length;s++)e=n[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(o,e)&&(i[e]=o[e])}return i}function Re(o,t){return t||(t=o.slice(0)),Object.freeze(Object.defineProperties(o,{raw:{value:Object.freeze(t)}}))}class oo{constructor(){S(this,"browserShadowBlurConstant",1),S(this,"DPI",96),S(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),S(this,"perfLimitSizeTotal",2097152),S(this,"maxCacheSideLimit",4096),S(this,"minCacheSideLimit",256),S(this,"disableStyleCopyPaste",!1),S(this,"enableGLFiltering",!0),S(this,"textureSize",4096),S(this,"forceGLPutImageData",!1),S(this,"cachesBoundsOfCurve",!1),S(this,"fontPaths",{}),S(this,"NUM_FRACTION_DIGITS",4)}}const nt=new class extends oo{constructor(o){super(),this.configure(o)}configure(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,o)}addFonts(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths=x(x({},this.fontPaths),o)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(o=>{delete this.fontPaths[o]})}clearFonts(){this.fontPaths={}}restoreDefaults(o){const t=new oo,e=o?.reduce((s,i)=>(s[i]=t[i],s),{})||t;this.configure(e)}},Xe=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return console[o]("fabric",...e)};class Fe extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class br extends Fe{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class Vc{}class Gc extends Vc{testPrecision(t,e){const s="precision ".concat(e,` float;
|
|
31
|
+
void main(){}`),i=t.createShader(t.FRAGMENT_SHADER);return!!i&&(t.shaderSource(i,s),t.compileShader(i),!!t.getShaderParameter(i,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find(s=>this.testPrecision(e,s)),e.getExtension("WEBGL_lose_context").loseContext(),Xe("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Wc={};let lo;const Le=()=>lo||(lo={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Gc,dispose(){},copyPasteData:Wc}),Ns=()=>Le().document,ui=()=>Le().window,ho=()=>{var o;return Math.max((o=nt.devicePixelRatio)!==null&&o!==void 0?o:ui().devicePixelRatio,1)},di=new class{constructor(){S(this,"charWidthsCache",{}),S(this,"boundsOfCurveCache",{})}getFontCache(o){let{fontFamily:t,fontStyle:e,fontWeight:s}=o;t=t.toLowerCase(),this.charWidthsCache[t]||(this.charWidthsCache[t]={});const i=this.charWidthsCache[t],n="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return i[n]||(i[n]={}),i[n]}clearFontCache(o){(o=(o||"").toLowerCase())?this.charWidthsCache[o]&&delete this.charWidthsCache[o]:this.charWidthsCache={}}limitDimsByArea(o){const{perfLimitSizeTotal:t}=nt,e=Math.sqrt(t*o);return[Math.floor(e),Math.floor(t/e)]}},yr="6.7.0";function ps(){}const is=Math.PI/2,Ue=2*Math.PI,_r=Math.PI/180,Ut=Object.freeze([1,0,0,1,0,0]),wr=16,ns=.4477152502,q="center",ot="left",ie="top",xr="bottom",xt="right",Yt="none",Sr=/\r?\n/,co="moving",Xi="scaling",uo="rotating",Cr="rotate",fo="skewing",fi="resizing",Xc="modifyPoly",Uc="modifyPath",Ui="changed",Yi="scale",$t="scaleX",ce="scaleY",Bs="skewX",Hs="skewY",kt="fill",qt="stroke",$i="modified",zs="json",Ar="svg",I=new class{constructor(){this[zs]=new Map,this[Ar]=new Map}has(o){return this[zs].has(o)}getClass(o){const t=this[zs].get(o);if(!t)throw new Fe("No class registered for ".concat(o));return t}setClass(o,t){t?this[zs].set(t,o):(this[zs].set(o.type,o),this[zs].set(o.type.toLowerCase(),o))}getSVGClass(o){return this[Ar].get(o)}setSVGClass(o,t){this[Ar].set(t??o.type.toLowerCase(),o)}},qi=new class extends Array{remove(o){const t=this.indexOf(o);t>-1&&this.splice(t,1)}cancelAll(){const o=this.splice(0);return o.forEach(t=>t.abort()),o}cancelByCanvas(o){if(!o)return[];const t=this.filter(e=>{var s;return e.target===o||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===o});return t.forEach(e=>e.abort()),t}cancelByTarget(o){if(!o)return[];const t=this.filter(e=>e.target===o);return t.forEach(e=>e.abort()),t}};class Yc{constructor(){S(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach(s=>{let[i,n]=s;this.on(i,n)}),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach(i=>{let[n,r]=i;s.push(this.once(n,r))}),()=>s.forEach(i=>i())}if(e){const s=this.on(t,function(){for(var i=arguments.length,n=new Array(i),r=0;r<i;r++)n[r]=arguments[r];e.call(this,...n),s()});return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],i=s.indexOf(e);i>-1&&s.splice(i,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach(s=>{let[i,n]=s;this._removeEventListener(i,n)}):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const i=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(i)for(let n=0;n<i.length;n++)i[n].call(this,e||{})}}const ms=(o,t)=>{const e=o.indexOf(t);return e!==-1&&o.splice(e,1),o},xe=o=>{if(o===0)return 1;switch(Math.abs(o)/is){case 1:case 3:return 0;case 2:return-1}return Math.cos(o)},Se=o=>{if(o===0)return 0;const t=o/is,e=Math.sign(o);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(o)};class A{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;typeof t=="object"?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new A(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new A(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new A(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new A(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new A(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new A(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new A(this.x/t.x,this.y/t.y)}scalarDivide(t){return new A(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.x<t.x&&this.y<t.y}lte(t){return this.x<=t.x&&this.y<=t.y}gt(t){return this.x>t.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new A(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}midPointFrom(t){return this.lerp(t)}min(t){return new A(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new A(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new A(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Tr;const s=Se(t),i=xe(t),n=this.subtract(e);return new A(n.x*i-n.y*s,n.x*s+n.y*i).add(e)}transform(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new A(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}const Tr=new A(0,0),Ki=o=>!!o&&Array.isArray(o._objects);function go(o){class t extends o{constructor(){super(...arguments),S(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];const r=this._objects.push(...i);return i.forEach(a=>this._onObjectAdded(a)),r}insertAt(s){for(var i=arguments.length,n=new Array(i>1?i-1:0),r=1;r<i;r++)n[r-1]=arguments[r];return this._objects.splice(s,0,...n),n.forEach(a=>this._onObjectAdded(a)),this._objects.length}remove(){const s=this._objects,i=[];for(var n=arguments.length,r=new Array(n),a=0;a<n;a++)r[a]=arguments[a];return r.forEach(l=>{const h=s.indexOf(l);h!==-1&&(s.splice(h,1),i.push(l),this._onObjectRemoved(l))}),i}forEachObject(s){this.getObjects().forEach((i,n,r)=>s(i,n,r))}getObjects(){for(var s=arguments.length,i=new Array(s),n=0;n<s;n++)i[n]=arguments[n];return i.length===0?[...this._objects]:this._objects.filter(r=>r.isType(...i))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,i){return!!this._objects.includes(s)||!!i&&this._objects.some(n=>n instanceof t&&n.contains(s,!0))}complexity(){return this._objects.reduce((s,i)=>s+=i.complexity?i.complexity():0,0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(ms(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(ms(this._objects,s),this._objects.push(s),this._onStackOrderChanged(s),!0)}sendObjectBackwards(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==0){const r=this.findNewLowerIndex(s,n,i);return ms(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}bringObjectForward(s,i){if(!s)return!1;const n=this._objects.indexOf(s);if(n!==this._objects.length-1){const r=this.findNewUpperIndex(s,n,i);return ms(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,i){return s!==this._objects[i]&&(ms(this._objects,s),this._objects.splice(i,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,i,n){let r;if(n){r=i;for(let a=i-1;a>=0;--a)if(s.isOverlapping(this._objects[a])){r=a;break}}else r=i-1;return r}findNewUpperIndex(s,i,n){let r;if(n){r=i;for(let a=i+1;a<this._objects.length;++a)if(s.isOverlapping(this._objects[a])){r=a;break}}else r=i+1;return r}collectObjects(s){let{left:i,top:n,width:r,height:a}=s,{includeIntersecting:l=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const h=[],c=new A(i,n),u=c.add(new A(r,a));for(let d=this._objects.length-1;d>=0;d--){const f=this._objects[d];f.selectable&&f.visible&&(l&&f.intersectsWithRect(c,u)||f.isContainedWithinRect(c,u)||l&&f.containsPoint(c)||l&&f.containsPoint(u))&&h.push(f)}return h}}return t}class po extends Yc{_setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};for(const e in t)this.set(e,t[e])}_setObject(t){for(const e in t)this._set(e,t[e])}set(t,e){return typeof t=="object"?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return typeof e=="boolean"&&this.set(t,!e),this}get(t){return this[t]}}function gi(o){return ui().requestAnimationFrame(o)}function mo(o){return ui().cancelAnimationFrame(o)}let $c=0;const rs=()=>$c++,Ie=()=>{const o=Ns().createElement("canvas");if(!o||o.getContext===void 0)throw new Fe("Failed to create `canvas` element");return o},vo=()=>Ns().createElement("img"),ue=o=>{const t=Ie();return t.width=o.width,t.height=o.height,t},Er=(o,t,e)=>o.toDataURL("image/".concat(t),e),kr=(o,t,e)=>new Promise((s,i)=>{o.toBlob(s,"image/".concat(t),e)}),wt=o=>o*_r,je=o=>o/_r,bo=o=>o.every((t,e)=>t===Ut[e]),Bt=(o,t,e)=>new A(o).transform(t,e),ne=o=>{const t=1/(o[0]*o[3]-o[1]*o[2]),e=[t*o[3],-t*o[1],-t*o[2],t*o[0],0,0],{x:s,y:i}=new A(o[4],o[5]).transform(e,!0);return e[4]=-s,e[5]=-i,e},St=(o,t,e)=>[o[0]*t[0]+o[2]*t[1],o[1]*t[0]+o[3]*t[1],o[0]*t[2]+o[2]*t[3],o[1]*t[2]+o[3]*t[3],e?0:o[0]*t[4]+o[2]*t[5]+o[4],e?0:o[1]*t[4]+o[3]*t[5]+o[5]],Ji=(o,t)=>o.reduceRight((e,s)=>s&&e?St(s,e,t):s||e,void 0)||Ut.concat(),yo=o=>{let[t,e]=o;return Math.atan2(e,t)},vs=o=>{const t=yo(o),e=Math.pow(o[0],2)+Math.pow(o[1],2),s=Math.sqrt(e),i=(o[0]*o[3]-o[2]*o[1])/s,n=Math.atan2(o[0]*o[2]+o[1]*o[3],e);return{angle:je(t),scaleX:s,scaleY:i,skewX:je(n),skewY:0,translateX:o[4]||0,translateY:o[5]||0}},Vs=function(o){return[1,0,0,1,o,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function bs(){let{angle:o=0}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{x:t=0,y:e=0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=wt(o),i=xe(s),n=Se(s);return[i,n,-n,i,t?t-(i*t-n*e):0,e?e-(n*t+i*e):0]}const Qi=function(o){return[o,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:o,0,0]},_o=o=>Math.tan(wt(o)),Pr=o=>[1,0,_o(o),1,0,0],Mr=o=>[1,_o(o),0,1,0,0],pi=o=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:i=!1,skewX:n=0,skewY:r=0}=o,a=Qi(s?-t:t,i?-e:e);return n&&(a=St(a,Pr(n),!0)),r&&(a=St(a,Mr(r),!0)),a},wo=o=>{const{translateX:t=0,translateY:e=0,angle:s=0}=o;let i=Vs(t,e);s&&(i=St(i,bs({angle:s})));const n=pi(o);return bo(n)||(i=St(i,n)),i},mi=function(o){let{signal:t,crossOrigin:e=null}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(s,i){if(t&&t.aborted)return i(new br("loadImage"));const n=vo();let r;t&&(r=function(l){n.src="",i(l)},t.addEventListener("abort",r,{once:!0}));const a=function(){n.onload=n.onerror=null,r&&t?.removeEventListener("abort",r),s(n)};o?(n.onload=a,n.onerror=function(){r&&t?.removeEventListener("abort",r),i(new Fe("Error loading ".concat(n.src)))},e&&(n.crossOrigin=e),n.src=o):a()})},Gs=function(o){let{signal:t,reviver:e=ps}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((s,i)=>{const n=[];t&&t.addEventListener("abort",i,{once:!0}),Promise.all(o.map(r=>I.getClass(r.type).fromObject(r,{signal:t}).then(a=>(e(r,a),n.push(a),a)))).then(s).catch(r=>{n.forEach(a=>{a.dispose&&a.dispose()}),i(r)}).finally(()=>{t&&t.removeEventListener("abort",i)})})},vi=function(o){let{signal:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((e,s)=>{const i=[];t&&t.addEventListener("abort",s,{once:!0});const n=Object.values(o).map(a=>a&&a.type&&I.has(a.type)?Gs([a],{signal:t}).then(l=>{let[h]=l;return i.push(h),h}):a),r=Object.keys(o);Promise.all(n).then(a=>a.reduce((l,h,c)=>(l[r[c]]=h,l),{})).then(e).catch(a=>{i.forEach(l=>{l.dispose&&l.dispose()}),s(a)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},ys=function(o){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in o&&(t[e]=o[e]),t),{})},Or=(o,t)=>Object.keys(o).reduce((e,s)=>(t(o[s],s,o)&&(e[s]=o[s]),e),{}),ct=(o,t)=>parseFloat(Number(o).toFixed(t)),Ws=o=>"matrix("+o.map(t=>ct(t,nt.NUM_FRACTION_DIGITS)).join(" ")+")",pe=o=>!!o&&o.toLive!==void 0,xo=o=>!!o&&typeof o.toObject=="function",So=o=>!!o&&o.offsetX!==void 0&&"source"in o,_s=o=>!!o&&"multiSelectionStacking"in o;function Co(o){const t=o&&Ce(o);let e=0,s=0;if(!o||!t)return{left:e,top:s};let i=o;const n=t.documentElement,r=t.body||{scrollLeft:0,scrollTop:0};for(;i&&(i.parentNode||i.host)&&(i=i.parentNode||i.host,i===t?(e=r.scrollLeft||n.scrollLeft||0,s=r.scrollTop||n.scrollTop||0):(e+=i.scrollLeft||0,s+=i.scrollTop||0),i.nodeType!==1||i.style.position!=="fixed"););return{left:e,top:s}}const Ce=o=>o.ownerDocument||null,Ao=o=>{var t;return((t=o.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},To=function(o,t,e){let{width:s,height:i}=e,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;o.width=s,o.height=i,n>1&&(o.setAttribute("width",(s*n).toString()),o.setAttribute("height",(i*n).toString()),t.scale(n,n))},Dr=(o,t)=>{let{width:e,height:s}=t;e&&(o.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(o.style.height=typeof s=="number"?"".concat(s,"px"):s)};function Eo(o){return o.onselectstart!==void 0&&(o.onselectstart=()=>!1),o.style.userSelect=Yt,o}class ko{constructor(t){S(this,"_originalCanvasStyle",void 0),S(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&Ns().getElementById(t)||Ie();var s;if(e.hasAttribute("data-fabric"))throw new Fe("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width","".concat(e)),i.setAttribute("height","".concat(s)),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:i}=this.lower;To(s,i,t,e)}setCSSDimensions(t){Dr(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&Ce(t),i={left:0,top:0};if(!s)return i;const n=((e=Ao(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};i.left+=parseInt(n.borderLeftWidth,10)||0,i.top+=parseInt(n.borderTopWidth,10)||0,i.left+=parseInt(n.paddingLeft,10)||0,i.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const a=s.documentElement;t.getBoundingClientRect!==void 0&&(r=t.getBoundingClientRect());const l=Co(t);return{left:r.left+l.left-(a.clientLeft||0)+i.left,top:r.top+l.top-(a.clientTop||0)+i.top}}(this.lower.el)}dispose(){Le().dispose(this.lower.el),delete this.lower}}const qc={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...Ut]};class bi extends go(po){get lowerCanvasEl(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.el}get contextContainer(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.ctx}static getDefaults(){return bi.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new ko(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(Xe("warn",`Canvas is trying to add an object that belongs to a different canvas.
|
|
32
|
+
Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?ho():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const i=x({width:this.width,height:this.height},t);this.elements.setDimensions(i,this.getRetinaScaling()),this.hasLostContext=!0,this.width=i.width,this.height=i.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,i=[...this.viewportTransform],n=Bt(t,ne(i));i[0]=e,i[3]=e;const r=Bt(n,i);i[4]+=s.x-r.x,i[5]+=s.y-r.y,this.setViewportTransform(i)}setZoom(t){this.zoomToPoint(new A(0,0),t)}absolutePan(t){const e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new A(-t.x-this.viewportTransform[4],-t.y-this.viewportTransform[5]))}getElement(){return this.elements.lower.el}clearContext(t){t.clearRect(0,0,this.width,this.height)}getContext(){return this.elements.lower.ctx}clear(){this.remove(...this.getObjects()),this.backgroundImage=void 0,this.overlayImage=void 0,this.backgroundColor="",this.overlayColor="",this.clearContext(this.getContext()),this.fire("canvas:cleared"),this.renderOnAddRemove&&this.requestRenderAll()}renderAll(){this.cancelRequestedRender(),this.destroyed||this.renderCanvas(this.getContext(),this._objects)}renderAndReset(){this.nextRenderHandle=0,this.renderAll()}requestRenderAll(){this.nextRenderHandle||this.disposed||this.destroyed||(this.nextRenderHandle=gi(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=ne(this.viewportTransform),i=Bt({x:0,y:0},s),n=Bt({x:t,y:e},s),r=i.min(n),a=i.max(n);return this.vptCoords={tl:r,tr:new A(a.x,r.y),bl:new A(r.x,a.y),br:a}}cancelRequestedRender(){this.nextRenderHandle&&(mo(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const s=this.viewportTransform,i=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),i&&(i._set("canvas",this),i.shouldCache(),i._transformDone=!0,i.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,i)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const s=this.viewportTransform;t.save(),t.transform(...s),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let s=0,i=e.length;s<i;++s)e[s]&&e[s].render(t)}_renderBackgroundOrOverlay(t,e){const s=this["".concat(e,"Color")],i=this["".concat(e,"Image")],n=this.viewportTransform,r=this["".concat(e,"Vpt")];if(!s&&!i)return;const a=pe(s);if(s){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=a?s.toLive(t):s,r&&t.transform(...n),a){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const l=s.gradientTransform||s.patternTransform;l&&t.transform(...l)}t.fill(),t.restore()}if(i){t.save();const{skipOffscreen:l}=this;this.skipOffscreen=r,r&&t.transform(...n),i.render(t),this.skipOffscreen=l,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenter(){return{top:this.height/2,left:this.width/2}}getCenterPoint(){return new A(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new A(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new A(t.getCenterPoint().x,this.getCenterPoint().y))}centerObject(t){return this._centerObject(t,this.getCenterPoint())}viewportCenterObject(t){return this._centerObject(t,this.getVpCenter())}viewportCenterObjectH(t){return this._centerObject(t,new A(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new A(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return Bt(this.getCenterPoint(),ne(this.viewportTransform))}_centerObject(t,e){t.setXY(e,q,q),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(t){return this.toDatalessObject(t)}toObject(t){return this._toObjectMethod("toObject",t)}toJSON(){return this.toObject()}toDatalessObject(t){return this._toObjectMethod("toDatalessObject",t)}_toObjectMethod(t,e){const s=this.clipPath,i=s&&!s.excludeFromExport?this._toObject(s,t,e):null;return x(x(x({version:yr},ys(this,e)),{},{objects:this._objects.filter(n=>!n.excludeFromExport).map(n=>this._toObject(n,t,e))},this.__serializeBgOverlay(t,e)),i?{clipPath:i}:null)}_toObject(t,e,s){let i;this.includeDefaultValues||(i=t.includeDefaultValues,t.includeDefaultValues=!1);const n=t[e](s);return this.includeDefaultValues||(t.includeDefaultValues=!!i),n}__serializeBgOverlay(t,e){const s={},i=this.backgroundImage,n=this.overlayImage,r=this.backgroundColor,a=this.overlayColor;return pe(r)?r.excludeFromExport||(s.background=r.toObject(e)):r&&(s.background=r),pe(a)?a.excludeFromExport||(s.overlay=a.toObject(e)):a&&(s.overlay=a),i&&!i.excludeFromExport&&(s.backgroundImage=this._toObject(i,t,e)),n&&!n.excludeFromExport&&(s.overlayImage=this._toObject(n,t,e)),s}toSVG(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const s=[];return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push('<g clip-path="url(#'.concat(this.clipPath.clipPathId,`)" >
|
|
33
33
|
`)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
|
|
34
34
|
`),this._setSVGBgOverlayColor(s,"overlay"),this._setSVGBgOverlayImage(s,"overlayImage",e),s.push("</svg>"),s.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",`" standalone="no" ?>
|
|
35
35
|
`,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
|
36
|
-
`)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=
|
|
37
|
-
`,"<desc>Created with Fabric.js ",
|
|
36
|
+
`)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),i=e.height||"".concat(this.height),n=nt.NUM_FRACTION_DIGITS,r=e.viewBox;let a;if(r)a='viewBox="'.concat(r.x," ").concat(r.y," ").concat(r.width," ").concat(r.height,'" ');else if(this.svgViewportTransformation){const l=this.viewportTransform;a='viewBox="'.concat(ct(-l[4]/l[0],n)," ").concat(ct(-l[5]/l[3],n)," ").concat(ct(this.width/l[0],n)," ").concat(ct(this.height/l[3],n),'" ')}else a='viewBox="0 0 '.concat(this.width," ").concat(this.height,'" ');t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',i,'" ',a,`xml:space="preserve">
|
|
37
|
+
`,"<desc>Created with Fabric.js ",yr,`</desc>
|
|
38
38
|
`,`<defs>
|
|
39
39
|
`,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
|
|
40
|
-
`)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(
|
|
40
|
+
`)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(rs()),'<clipPath id="'.concat(e.clipPathId,`" >
|
|
41
41
|
`).concat(e.toClipPathSVG(t.reviver),`</clipPath>
|
|
42
|
-
`)):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this["".concat(t,"Color")];if(
|
|
42
|
+
`)):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this["".concat(t,"Color")];if(pe(e)){const s=this["".concat(t,"Vpt")],i=this.viewportTransform,n={isType:()=>!1,width:this.width/(s?i[0]:1),height:this.height/(s?i[3]:1)};return e.toSVG(n,{additionalTransform:s?Ws(i):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=nt.fontPaths;this._objects.forEach(function n(r){t.push(r),Ki(r)&&r._objects.forEach(n)}),t.forEach(n=>{if(!(r=n)||typeof r._renderText!="function")return;var r;const{styles:a,fontFamily:l}=n;!e[l]&&s[l]&&(e[l]=!0,a&&Object.values(a).forEach(h=>{Object.values(h).forEach(c=>{let{fontFamily:u=""}=c;!e[u]&&s[u]&&(e[u]=!0)})}))});const i=Object.keys(e).map(n=>` @font-face {
|
|
43
43
|
font-family: '`.concat(n,`';
|
|
44
44
|
src: url('`).concat(s[n],`');
|
|
45
45
|
}
|
|
46
46
|
`)).join("");return i?` <style type="text/css"><![CDATA[
|
|
47
47
|
`.concat(i,`]]></style>
|
|
48
|
-
`):""}_setSVGObjects(t,e){this.forEachObject(s=>{s.excludeFromExport||this._setSVGObject(t,s,e)})}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const i=this[e];i&&!i.excludeFromExport&&i.toSVG&&t.push(i.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(
|
|
48
|
+
`):""}_setSVGObjects(t,e){this.forEachObject(s=>{s.excludeFromExport||this._setSVGObject(t,s,e)})}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const i=this[e];i&&!i.excludeFromExport&&i.toSVG&&t.push(i.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(pe(s)){const i=s.repeat||"",n=this.width,r=this.height,a=this["".concat(e,"Vpt")]?Ws(ne(this.viewportTransform)):"";t.push('<rect transform="'.concat(a," translate(").concat(n/2,",").concat(r/2,')" x="').concat(s.offsetX-n/2,'" y="').concat(s.offsetY-r/2,'" width="').concat(i!=="repeat-y"&&i!=="no-repeat"||!So(s)?n:s.source.width,'" height="').concat(i!=="repeat-x"&&i!=="no-repeat"||!So(s)?r:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
|
|
49
49
|
`))}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',s,'"',`></rect>
|
|
50
|
-
`)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new wi("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[],backgroundImage:r,background:a,overlayImage:h,overlay:c,clipPath:u}=i,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([po(n,{reviver:e,signal:s}),Kh({backgroundImage:r,backgroundColor:a,overlayImage:h,overlayColor:c,clipPath:u},{signal:s})]).then(f=>{let[g,p]=f;return this.clear(),this.add(...g),this.set(i),this.set(p),this.renderOnAddRemove=d,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=ps(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return jf(this.toCanvasElement(r,t),e,s)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return Nf(this.toCanvasElement(r,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:i,top:n,filter:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const a=(e||this.width)*t,h=(s||this.height)*t,c=this.getZoom(),u=this.width,d=this.height,f=this.skipControlsDrawing,g=c*t,p=this.viewportTransform,m=[g,0,0,g,(p[4]-(i||0))*t,(p[5]-(n||0))*t],y=this.enableRetinaScaling,b=ps({width:a,height:h}),x=r?this._objects.filter(S=>r(S)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=a,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(b.getContext("2d"),x),this.viewportTransform=p,this.width=u,this.height=d,this.calcViewportBoundaries(),this.enableRetinaScaling=y,this.skipControlsDrawing=f,b}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),du.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}E(Jh,"ownDefaults",P_);const M_=["touchstart","touchmove","touchend"],Vm=o=>{const t=jm(o.target),e=function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s}(o);return new M(e.clientX+t.left,e.clientY+t.top)},mu=o=>M_.includes(o.type)||o.pointerType==="touch",Wm=o=>{o.preventDefault(),o.stopPropagation()},Ci=o=>{let t=0,e=0,s=0,i=0;for(let n=0,r=o.length;n<r;n++){const{x:a,y:h}=o[n];(a>s||!n)&&(s=a),(a<t||!n)&&(t=a),(h>i||!n)&&(i=h),(h<e||!n)&&(e=h)}return{left:t,top:e,width:s-t,height:i-e}},O_=["translateX","translateY","scaleX","scaleY"],Gm=(o,t)=>vo(o,qt(t,o.calcOwnMatrix())),vo=(o,t)=>{const e=Lr(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,a=Lt(e,O_),h=new M(s,i);o.flipX=!1,o.flipY=!1,Object.assign(o,a),o.set({scaleX:n,scaleY:r}),o.setPositionByOrigin(h,rt,rt)},Xm=o=>{o.scaleX=1,o.scaleY=1,o.skewX=0,o.skewY=0,o.flipX=!1,o.flipY=!1,o.rotate(0)},Wf=o=>({scaleX:o.scaleX,scaleY:o.scaleY,skewX:o.skewX,skewY:o.skewY,angle:o.angle,left:o.left,flipX:o.flipX,flipY:o.flipY,top:o.top}),vu=(o,t,e)=>{const s=o/2,i=t/2,n=[new M(-s,-i),new M(s,-i),new M(-s,i),new M(s,i)].map(a=>a.transform(e)),r=Ci(n);return new M(r.width,r.height)},Qh=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:He;return qt(ns(arguments.length>1&&arguments[1]!==void 0?arguments[1]:He),o)},Br=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:He,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:He;return o.transform(Qh(t,e))},Um=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:He,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:He;return o.transform(Qh(t,e),!0)},Gf=(o,t,e)=>{const s=Qh(t,e);return vo(o,qt(s,o.calcOwnMatrix())),s},Ym=(o,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(o),T(T({},t),{},{target:s})),s.fire(o,t)},D_={left:-.5,top:-.5,center:0,bottom:.5,right:.5},se=o=>typeof o=="string"?D_[o]:o-.5,bu="not-allowed";function $m(o){return se(o.originX)===se(rt)&&se(o.originY)===se(rt)}function qm(o){return .5-se(o)}const Zs=(o,t)=>o[t],Km=(o,t,e,s)=>({e:o,transform:t,pointer:new M(e,s)});function Jm(o,t){const e=o.getTotalAngle()+Si(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Xf(o,t,e,s,i){var n;let{target:r,corner:a}=o;const h=r.controls[a],c=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,u=r.padding/c,d=function(f,g,p,m){const y=f.getRelativeCenterPoint(),b=p!==void 0&&m!==void 0?f.translateToGivenOrigin(y,rt,rt,p,m):new M(f.left,f.top);return(f.angle?g.rotate(-Ut(f.angle),y):g).subtract(b)}(r,new M(s,i),t,e);return d.x>=u&&(d.x-=u),d.x<=-u&&(d.x+=u),d.y>=u&&(d.y-=u),d.y<=u&&(d.y+=u),d.x-=h.offsetX,d.y-=h.offsetY,d}const R_=(o,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,a=e-n,h=s-r,c=!Zs(i,"lockMovementX")&&i.left!==a,u=!Zs(i,"lockMovementY")&&i.top!==h;return c&&i.set(wt,a),u&&i.set(is,h),(c||u)&&Ym(Cm,Km(o,t,e,s)),c||u},Qm={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"},Uf=(o,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+6*(t-o)*e:e<.5?t:e<2/3?o+(t-o)*(2/3-e)*6:o),Zm=(o,t,e,s)=>{o/=255,t/=255,e/=255;const i=Math.max(o,t,e),n=Math.min(o,t,e);let r,a;const h=(i+n)/2;if(i===n)r=a=0;else{const c=i-n;switch(a=h>.5?c/(2-i-n):c/(i+n),i){case o:r=(t-e)/c+(t<e?6:0);break;case t:r=(e-o)/c+2;break;case e:r=(o-t)/c+4}r/=6}return[Math.round(360*r),Math.round(100*a),Math.round(100*h),s]},t0=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(o)/(o.endsWith("%")?100:1)},yu=o=>Math.min(Math.round(o),255).toString(16).toUpperCase().padStart(2,"0"),e0=o=>{let[t,e,s,i=1]=o;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class St{constructor(t){if(E(this,"isUnrecognised",!1),t)if(t instanceof St)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,s,i,n=1]=t;this.setSource([e,s,i,n])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in Qm&&(t=Qm[t]),t==="transparent"?[255,255,255,0]:St.sourceFromHex(t)||St.sourceFromRgb(t)||St.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=Zm(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=Zm(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(i,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return"".concat(yu(t)).concat(yu(e)).concat(yu(s)).concat(yu(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(e0(this.getSource())),this}toBlackWhite(t){const[e,,,s]=e0(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof St||(t=new St(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map((a,h)=>Math.round(.5*a+.5*s[h]));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return St.fromRgba(t)}static fromRgba(t){return new St(St.sourceFromRgb(t))}static sourceFromRgb(t){const e=t.match(/^rgba?\(\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d{0,3}(?:\.\d+)?%?)\s*)?\)$/i);if(e){const[s,i,n]=e.slice(1,4).map(r=>{const a=parseFloat(r);return r.endsWith("%")?Math.round(2.55*a):a});return[s,i,n,t0(e[4])]}}static fromHsl(t){return St.fromHsla(t)}static fromHsla(t){return new St(St.sourceFromHsl(t))}static sourceFromHsl(t){const e=t.match(/^hsla?\(\s*([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d*(?:\.\d+)?%?)\s*)?\)$/i);if(!e)return;const s=(St.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,a,h;if(i===0)r=a=h=n;else{const c=n<=.5?n*(i+1):n+i-n*i,u=2*n-c;r=Uf(u,c,s+1/3),a=Uf(u,c,s),h=Uf(u,c,s-1/3)}return[Math.round(255*r),Math.round(255*a),Math.round(255*h),t0(e[4])]}static fromHex(t){return new St(St.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map(h=>h+h):e.match(/.{2}/g);const[i,n,r,a=255]=s.map(h=>parseInt(h,16));return[i,n,r,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?Si(s):e.includes("turn")?360*s:s}}const Ge=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Of;const e=/\D{0,2}$/.exec(o),s=parseFloat(o),i=bt.DPI;switch(e==null?void 0:e[0]){case"mm":return s*i/25.4;case"cm":return s*i/2.54;case"in":return s*i;case"pt":return s*i/72;case"pc":return s*i/72*12;case"em":return s*t;default:return s}},Yf=o=>{const[t,e]=o.trim().split(" "),[s,i]=(n=t)&&n!==ze?[n.slice(1,4),n.slice(5,8)]:n===ze?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},Zh=function(o,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const n=new St(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(o,": ").concat(e,"; ").concat(s?"".concat(o,"-opacity: ").concat(s,"; "):""):"".concat(o,'="').concat(e,'" ').concat(s?"".concat(o,'-opacity="').concat(s,'" '):"")};class s0{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):ze,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",c=this.opacity!==void 0?this.opacity:"1",u=this.visible?"":" visibility: hidden;",d=t?"":this.getSvgFilter(),f=Zh(ee,this.fill);return[Zh(We,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",h,"; ",f,"fill-rule: ",e,"; ","opacity: ",c,";",d,u].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),i='transform="'.concat(mo(s));return"".concat(i).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=i,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:i,additionalTransform:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=e?"":'style="'.concat(this.getSvgStyles(),'" '),a=i?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,c=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",u=h&&h.absolutePositioned,d=this.stroke,f=this.fill,g=this.shadow,p=[],m=t.indexOf("COMMON_PARTS");let y;h&&(h.clipPathId="CLIPPATH_".concat(Gn()),y='<clipPath id="'.concat(h.clipPathId,`" >
|
|
51
|
-
`).concat(
|
|
52
|
-
`)),
|
|
53
|
-
`),
|
|
54
|
-
`);const
|
|
55
|
-
`),
|
|
56
|
-
`),s?s(
|
|
57
|
-
<feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(
|
|
58
|
-
<feOffset dx="`).concat(
|
|
50
|
+
`)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new Fe("`json` is undefined"));const i=typeof t=="string"?JSON.parse(t):t,{objects:n=[],backgroundImage:r,background:a,overlayImage:l,overlay:h,clipPath:c}=i,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Gs(n,{reviver:e,signal:s}),vi({backgroundImage:r,backgroundColor:a,overlayImage:l,overlayColor:h,clipPath:c},{signal:s})]).then(d=>{let[f,g]=d;return this.clear(),this.add(...f),this.set(i),this.set(g),this.renderOnAddRemove=u,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=ue(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return Er(this.toCanvasElement(r,t),e,s)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:i=1,enableRetinaScaling:n=!1}=t,r=i*(n?this.getRetinaScaling():1);return kr(this.toCanvasElement(r,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:i,top:n,filter:r}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const a=(e||this.width)*t,l=(s||this.height)*t,h=this.getZoom(),c=this.width,u=this.height,d=this.skipControlsDrawing,f=h*t,g=this.viewportTransform,p=[f,0,0,f,(g[4]-(i||0))*t,(g[5]-(n||0))*t],v=this.enableRetinaScaling,m=ue({width:a,height:l}),b=r?this._objects.filter(_=>r(_)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=a,this.height=l,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),b),this.viewportTransform=g,this.width=c,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=v,this.skipControlsDrawing=d,m}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),qi.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}S(bi,"ownDefaults",qc);const Kc=["touchstart","touchmove","touchend"],Po=o=>{const t=Co(o.target),e=function(s){const i=s.changedTouches;return i&&i[0]?i[0]:s}(o);return new A(e.clientX+t.left,e.clientY+t.top)},Zi=o=>Kc.includes(o.type)||o.pointerType==="touch",Mo=o=>{o.preventDefault(),o.stopPropagation()},Ne=o=>{let t=0,e=0,s=0,i=0;for(let n=0,r=o.length;n<r;n++){const{x:a,y:l}=o[n];(a>s||!n)&&(s=a),(a<t||!n)&&(t=a),(l>i||!n)&&(i=l),(l<e||!n)&&(e=l)}return{left:t,top:e,width:s-t,height:i-e}},Jc=["translateX","translateY","scaleX","scaleY"],Oo=(o,t)=>Xs(o,St(t,o.calcOwnMatrix())),Xs=(o,t)=>{const e=vs(t),{translateX:s,translateY:i,scaleX:n,scaleY:r}=e,a=pt(e,Jc),l=new A(s,i);o.flipX=!1,o.flipY=!1,Object.assign(o,a),o.set({scaleX:n,scaleY:r}),o.setPositionByOrigin(l,q,q)},Do=o=>{o.scaleX=1,o.scaleY=1,o.skewX=0,o.skewY=0,o.flipX=!1,o.flipY=!1,o.rotate(0)},Rr=o=>({scaleX:o.scaleX,scaleY:o.scaleY,skewX:o.skewX,skewY:o.skewY,angle:o.angle,left:o.left,flipX:o.flipX,flipY:o.flipY,top:o.top}),tn=(o,t,e)=>{const s=o/2,i=t/2,n=[new A(-s,-i),new A(s,-i),new A(-s,i),new A(s,i)].map(a=>a.transform(e)),r=Ne(n);return new A(r.width,r.height)},yi=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ut;return St(ne(arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ut),o)},ws=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ut,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ut;return o.transform(yi(t,e))},Ro=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ut,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Ut;return o.transform(yi(t,e),!0)},Fr=(o,t,e)=>{const s=yi(t,e);return Xs(o,St(s,o.calcOwnMatrix())),s},Fo=(o,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(o),x(x({},t),{},{target:s})),s.fire(o,t)},Qc={left:-.5,top:-.5,center:0,bottom:.5,right:.5},Pt=o=>typeof o=="string"?Qc[o]:o-.5,en="not-allowed";function Lo(o){return Pt(o.originX)===Pt(q)&&Pt(o.originY)===Pt(q)}function Io(o){return .5-Pt(o)}const Ae=(o,t)=>o[t],jo=(o,t,e,s)=>({e:o,transform:t,pointer:new A(e,s)});function No(o,t){const e=o.getTotalAngle()+je(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Lr(o,t,e,s,i){var n;let{target:r,corner:a}=o;const l=r.controls[a],h=((n=r.canvas)===null||n===void 0?void 0:n.getZoom())||1,c=r.padding/h,u=function(d,f,g,p){const v=d.getRelativeCenterPoint(),m=g!==void 0&&p!==void 0?d.translateToGivenOrigin(v,q,q,g,p):new A(d.left,d.top);return(d.angle?f.rotate(-wt(d.angle),v):f).subtract(m)}(r,new A(s,i),t,e);return u.x>=c&&(u.x-=c),u.x<=-c&&(u.x+=c),u.y>=c&&(u.y-=c),u.y<=c&&(u.y+=c),u.x-=l.offsetX,u.y-=l.offsetY,u}const Zc=(o,t,e,s)=>{const{target:i,offsetX:n,offsetY:r}=t,a=e-n,l=s-r,h=!Ae(i,"lockMovementX")&&i.left!==a,c=!Ae(i,"lockMovementY")&&i.top!==l;return h&&i.set(ot,a),c&&i.set(ie,l),(h||c)&&Fo(co,jo(o,t,e,s)),h||c},Bo={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#0FF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000",blanchedalmond:"#FFEBCD",blue:"#00F",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#0FF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",darkgreen:"#006400",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#F0F",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",lightgreen:"#90EE90",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#789",lightslategrey:"#789",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#0F0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#F0F",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#639",red:"#F00",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFF",whitesmoke:"#F5F5F5",yellow:"#FF0",yellowgreen:"#9ACD32"},Ir=(o,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+6*(t-o)*e:e<.5?t:e<2/3?o+(t-o)*(2/3-e)*6:o),Ho=(o,t,e,s)=>{o/=255,t/=255,e/=255;const i=Math.max(o,t,e),n=Math.min(o,t,e);let r,a;const l=(i+n)/2;if(i===n)r=a=0;else{const h=i-n;switch(a=l>.5?h/(2-i-n):h/(i+n),i){case o:r=(t-e)/h+(t<e?6:0);break;case t:r=(e-o)/h+2;break;case e:r=(o-t)/h+4}r/=6}return[Math.round(360*r),Math.round(100*a),Math.round(100*l),s]},zo=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(o)/(o.endsWith("%")?100:1)},sn=o=>Math.min(Math.round(o),255).toString(16).toUpperCase().padStart(2,"0"),Vo=o=>{let[t,e,s,i=1]=o;const n=Math.round(.3*t+.59*e+.11*s);return[n,n,n,i]};class ht{constructor(t){if(S(this,"isUnrecognised",!1),t)if(t instanceof ht)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,s,i,n=1]=t;this.setSource([e,s,i,n])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in Bo&&(t=Bo[t]),t==="transparent"?[255,255,255,0]:ht.sourceFromHex(t)||ht.sourceFromRgb(t)||ht.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=Ho(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,i]=Ho(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(i,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,i]=this.getSource();return"".concat(sn(t)).concat(sn(e)).concat(sn(s)).concat(sn(Math.round(255*i)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(Vo(this.getSource())),this}toBlackWhite(t){const[e,,,s]=Vo(this.getSource()),i=e<(t||127)?0:255;return this.setSource([i,i,i,s]),this}overlayWith(t){t instanceof ht||(t=new ht(t));const e=this.getSource(),s=t.getSource(),[i,n,r]=e.map((a,l)=>Math.round(.5*a+.5*s[l]));return this.setSource([i,n,r,e[3]]),this}static fromRgb(t){return ht.fromRgba(t)}static fromRgba(t){return new ht(ht.sourceFromRgb(t))}static sourceFromRgb(t){const e=t.match(/^rgba?\(\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d{0,3}(?:\.\d+)?%?)\s*)?\)$/i);if(e){const[s,i,n]=e.slice(1,4).map(r=>{const a=parseFloat(r);return r.endsWith("%")?Math.round(2.55*a):a});return[s,i,n,zo(e[4])]}}static fromHsl(t){return ht.fromHsla(t)}static fromHsla(t){return new ht(ht.sourceFromHsl(t))}static sourceFromHsl(t){const e=t.match(/^hsla?\(\s*([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d*(?:\.\d+)?%?)\s*)?\)$/i);if(!e)return;const s=(ht.parseAngletoDegrees(e[1])%360+360)%360/360,i=parseFloat(e[2])/100,n=parseFloat(e[3])/100;let r,a,l;if(i===0)r=a=l=n;else{const h=n<=.5?n*(i+1):n+i-n*i,c=2*n-h;r=Ir(c,h,s+1/3),a=Ir(c,h,s),l=Ir(c,h,s-1/3)}return[Math.round(255*r),Math.round(255*a),Math.round(255*l),zo(e[4])]}static fromHex(t){return new ht(ht.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map(l=>l+l):e.match(/.{2}/g);const[i,n,r,a=255]=s.map(l=>parseInt(l,16));return[i,n,r,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?je(s):e.includes("turn")?360*s:s}}const Kt=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:wr;const e=/\D{0,2}$/.exec(o),s=parseFloat(o),i=nt.DPI;switch(e?.[0]){case"mm":return s*i/25.4;case"cm":return s*i/2.54;case"in":return s*i;case"pt":return s*i/72;case"pc":return s*i/72*12;case"em":return s*t;default:return s}},jr=o=>{const[t,e]=o.trim().split(" "),[s,i]=(n=t)&&n!==Yt?[n.slice(1,4),n.slice(5,8)]:n===Yt?[n,n]:["Mid","Mid"];var n;return{meetOrSlice:e||"meet",alignX:s,alignY:i}},_i=function(o,t){let e,s,i=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const n=new ht(t),r=n.getAlpha();e=n.toRgb(),r!==1&&(s=r.toString())}else e="none";return i?"".concat(o,": ").concat(e,"; ").concat(s?"".concat(o,"-opacity: ").concat(s,"; "):""):"".concat(o,'="').concat(e,'" ').concat(s?"".concat(o,'-opacity="').concat(s,'" '):"")};class Go{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",i=this.strokeDashArray?this.strokeDashArray.join(" "):Yt,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",l=this.strokeMiterLimit?this.strokeMiterLimit:"4",h=this.opacity!==void 0?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),d=_i(kt,this.fill);return[_i(qt,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",i,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",l,"; ",d,"fill-rule: ",e,"; ","opacity: ",h,";",u,c].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),i='transform="'.concat(Ws(s));return"".concat(i).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const i=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=i,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:i,additionalTransform:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=e?"":'style="'.concat(this.getSvgStyles(),'" '),a=i?'style="'.concat(this.getSvgFilter(),'" '):"",l=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=l&&l.absolutePositioned,u=this.stroke,d=this.fill,f=this.shadow,g=[],p=t.indexOf("COMMON_PARTS");let v;l&&(l.clipPathId="CLIPPATH_".concat(rs()),v='<clipPath id="'.concat(l.clipPathId,`" >
|
|
51
|
+
`).concat(l.toClipPathSVG(s),`</clipPath>
|
|
52
|
+
`)),c&&g.push("<g ",a,this.getSvgCommons(),` >
|
|
53
|
+
`),g.push("<g ",this.getSvgTransform(!1),c?"":a+this.getSvgCommons(),` >
|
|
54
|
+
`);const m=[r,h,e?"":this.addPaintOrder()," ",n?'transform="'.concat(n,'" '):""].join("");return t[p]=m,pe(d)&&g.push(d.toSVG(this)),pe(u)&&g.push(u.toSVG(this)),f&&g.push(f.toSVG(this)),l&&g.push(v),g.push(t.join("")),g.push(`</g>
|
|
55
|
+
`),c&&g.push(`</g>
|
|
56
|
+
`),s?s(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==kt?' paint-order="'.concat(this.paintFirst,'" '):""}}function nn(o){return new RegExp("^("+o.join("|")+")\\b","i")}const xs="textDecorationThickness",Wo=["fontSize","fontWeight","fontFamily","fontStyle"],Xo=["underline","overline","linethrough"],Uo=[...Wo,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],Yo=[...Uo,...Xo,"textBackgroundColor","direction",xs],tu=[...Wo,...Xo,qt,"strokeWidth",kt,"deltaY","textBackgroundColor",xs],eu={_reNewline:Sr,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:ot,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:ot,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[xs]:66.667},Be="justify",rn="justify-left",wi="justify-right",xi="justify-center";var $o,qo,Ko;const Te=String.raw($o||($o=Re(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),Nr=String.raw(qo||(qo=Re(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),Br="http://www.w3.org/2000/svg",su=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Te+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Te+"))?\\s+(.*)"),iu={cx:ot,x:ot,r:"radius",cy:ie,y:ie,display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing","text-decoration-thickness":xs},Hr="font-size",zr="clip-path",nu=nn(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),ru=nn(["symbol","image","marker","pattern","view","svg"]),Jo=nn(["symbol","g","a","svg","clipPath","defs"]),Qo=new RegExp(String.raw(Ko||(Ko=Re(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),Te,Nr,Te,Nr,Te,Nr,Te)),au=new A(1,0),Zo=new A,Vr=(o,t)=>o.rotate(t),an=(o,t)=>new A(t).subtract(o),on=o=>o.distanceFrom(Zo),ln=(o,t)=>Math.atan2(Us(o,t),el(o,t)),tl=o=>ln(au,o),hn=o=>o.eq(Zo)?o:o.scalarDivide(on(o)),Gr=function(o){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return hn(new A(-o.y,o.x).scalarMultiply(t?1:-1))},Us=(o,t)=>o.x*t.y-o.y*t.x,el=(o,t)=>o.x*t.x+o.y*t.y,Wr=(o,t,e)=>{if(o.eq(t)||o.eq(e))return!0;const s=Us(t,e),i=Us(t,o),n=Us(e,o);return s>=0?i>=0&&n<=0:!(i<=0&&n>=0)},sl="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",il=new RegExp("(?:\\s|^)"+sl+sl+"("+Te+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Ye{constructor(t){const e=typeof t=="string"?Ye.parseShadow(t):t;Object.assign(this,Ye.ownDefaults,e),this.id=rs()}static parseShadow(t){const e=t.trim(),[,s=0,i=0,n=0]=(il.exec(e)||[]).map(r=>parseFloat(r)||0);return{color:(e.replace(il,"")||"rgb(0,0,0)").trim(),offsetX:s,offsetY:i,blur:n}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const e=Vr(new A(this.offsetX,this.offsetY),wt(-t.angle)),s=new ht(this.color);let i=40,n=40;return t.width&&t.height&&(i=100*ct((Math.abs(e.x)+this.blur)/t.width,nt.NUM_FRACTION_DIGITS)+20,n=100*ct((Math.abs(e.y)+this.blur)/t.height,nt.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(n,'%" height="').concat(100+2*n,'%" x="-').concat(i,'%" width="').concat(100+2*i,`%" >
|
|
57
|
+
<feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(ct(this.blur?this.blur/2:0,nt.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
|
|
58
|
+
<feOffset dx="`).concat(ct(e.x,nt.NUM_FRACTION_DIGITS),'" dy="').concat(ct(e.y,nt.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
|
|
59
59
|
<feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
|
|
60
60
|
<feComposite in2="oBlur" operator="in" />
|
|
61
61
|
<feMerge>
|
|
@@ -63,44 +63,44 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
63
63
|
<feMergeNode in="SourceGraphic"></feMergeNode>
|
|
64
64
|
</feMerge>
|
|
65
65
|
</filter>
|
|
66
|
-
`)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=Ki.ownDefaults;return this.includeDefaultValues?t:zf(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}E(Ki,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),E(Ki,"type","shadow"),W.setClass(Ki,"shadow");const Hr=(o,t,e)=>Math.max(o,Math.min(t,e)),B_=[is,wt,Ve,gs,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",co,uo],Ji=[ee,We,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],H_={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:wt,originY:is,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:ee,fill:"rgb(0,0,0)",fillRule:"nonzero",stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,globalCompositeOperation:"source-over",backgroundColor:"",shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},tg=(o,t,e,s)=>(o<Math.abs(t)?(o=t,s=e/4):s=t===0&&o===0?e/qi*Math.asin(1):e/qi*Math.asin(t/o),{a:o,c:t,p:e,s}),u0=(o,t,e,s,i)=>o*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*qi/e),d0=(o,t,e,s)=>-e*Math.cos(o/s*Vn)+e+t,eg=(o,t,e,s)=>(o/=s)<1/2.75?e*(7.5625*o*o)+t:o<2/2.75?e*(7.5625*(o-=1.5/2.75)*o+.75)+t:o<2.5/2.75?e*(7.5625*(o-=2.25/2.75)*o+.9375)+t:e*(7.5625*(o-=2.625/2.75)*o+.984375)+t,f0=(o,t,e,s)=>e-eg(s-o,0,e,s)+t;var z_=Object.freeze({__proto__:null,defaultEasing:d0,easeInBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*(o/=s)*o*((i+1)*o-i)+t},easeInBounce:f0,easeInCirc:(o,t,e,s)=>-e*(Math.sqrt(1-(o/=s)*o)-1)+t,easeInCubic:(o,t,e,s)=>e*(o/s)**3+t,easeInElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:a,p:h}=tg(i,e,n,1.70158);return-u0(r,a,h,o,s)+t},easeInExpo:(o,t,e,s)=>o===0?t:e*2**(10*(o/s-1))+t,easeInOutBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(o/=s/2)<1?e/2*(o*o*((1+(i*=1.525))*o-i))+t:e/2*((o-=2)*o*((1+(i*=1.525))*o+i)+2)+t},easeInOutBounce:(o,t,e,s)=>o<s/2?.5*f0(2*o,0,e,s)+t:.5*eg(2*o-s,0,e,s)+.5*e+t,easeInOutCirc:(o,t,e,s)=>(o/=s/2)<1?-e/2*(Math.sqrt(1-o**2)-1)+t:e/2*(Math.sqrt(1-(o-=2)*o)+1)+t,easeInOutCubic:(o,t,e,s)=>(o/=s/2)<1?e/2*o**3+t:e/2*((o-2)**3+2)+t,easeInOutElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:a,p:h,c}=tg(i,e,n,1.70158);return o<1?-.5*u0(r,a,h,o,s)+t:r*Math.pow(2,-10*(o-=1))*Math.sin((o*s-a)*qi/h)*.5+c+t},easeInOutExpo:(o,t,e,s)=>o===0?t:o===s?t+e:(o/=s/2)<1?e/2*2**(10*(o-1))+t:e/2*-(2**(-10*--o)+2)+t,easeInOutQuad:(o,t,e,s)=>(o/=s/2)<1?e/2*o**2+t:-e/2*(--o*(o-2)-1)+t,easeInOutQuart:(o,t,e,s)=>(o/=s/2)<1?e/2*o**4+t:-e/2*((o-=2)*o**3-2)+t,easeInOutQuint:(o,t,e,s)=>(o/=s/2)<1?e/2*o**5+t:e/2*((o-2)**5+2)+t,easeInOutSine:(o,t,e,s)=>-e/2*(Math.cos(Math.PI*o/s)-1)+t,easeInQuad:(o,t,e,s)=>e*(o/=s)*o+t,easeInQuart:(o,t,e,s)=>e*(o/=s)*o**3+t,easeInQuint:(o,t,e,s)=>e*(o/s)**5+t,easeInSine:(o,t,e,s)=>-e*Math.cos(o/s*Vn)+e+t,easeOutBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*((o=o/s-1)*o*((i+1)*o+i)+1)+t},easeOutBounce:eg,easeOutCirc:(o,t,e,s)=>e*Math.sqrt(1-(o=o/s-1)*o)+t,easeOutCubic:(o,t,e,s)=>e*((o/s-1)**3+1)+t,easeOutElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:a,p:h,c}=tg(i,e,n,1.70158);return r*2**(-10*o)*Math.sin((o*s-a)*qi/h)+c+t},easeOutExpo:(o,t,e,s)=>o===s?t+e:e*-(2**(-10*o/s)+1)+t,easeOutQuad:(o,t,e,s)=>-e*(o/=s)*(o-2)+t,easeOutQuart:(o,t,e,s)=>-e*((o=o/s-1)*o**3-1)+t,easeOutQuint:(o,t,e,s)=>e*((o/s-1)**5+1)+t,easeOutSine:(o,t,e,s)=>e*Math.sin(o/s*Vn)+t});const V_=()=>!1;class sg{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=d0,onStart:a=Rr,onChange:h=Rr,onComplete:c=Rr,abort:u=V_,target:d}=t;E(this,"_state","pending"),E(this,"durationProgress",0),E(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=a,this._onChange=h,this._onComplete=c,this._abort=u,this.target=d,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>Yh(t),this.delay):Yh(t)}tick(t){const e=(t||+new Date)-this.startTime,s=Math.min(e,this.duration);this.durationProgress=s/this.duration;const{value:i,valueProgress:n}=this.calculate(s);this.value=Object.freeze(i),this.valueProgress=n,this._state!=="aborted"&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),Yh(this.tick)))}register(){du.push(this)}unregister(){du.remove(this)}abort(){this._state="aborted",this.unregister()}}const W_=["startValue","endValue"];class G_ extends sg{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(T(T({},Lt(t,W_)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const X_=["startValue","endValue"];class U_ extends sg{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(T(T({},Lt(t,X_)),{},{startValue:e,byValue:s.map((i,n)=>i-e[n])}))}calculate(t){const e=this.startValue.map((s,i)=>this.easing(t,s,this.byValue[i],this.duration,i));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const Y_=["startValue","endValue","easing","onChange","onComplete","abort"],$_=(o,t,e,s)=>t+e*(1-Math.cos(o/s*Vn)),ig=o=>o&&((t,e,s)=>o(new St(t).toRgba(),e,s));class q_ extends sg{constructor(t){let{startValue:e,endValue:s,easing:i=$_,onChange:n,onComplete:r,abort:a}=t,h=Lt(t,Y_);const c=new St(e).getSource(),u=new St(s).getSource();super(T(T({},h),{},{startValue:c,byValue:u.map((d,f)=>d-c[f]),easing:i,onChange:ig(n),onComplete:ig(r),abort:ig(a)}))}calculate(t){const[e,s,i,n]=this.startValue.map((a,h)=>this.easing(t,a,this.byValue[h],this.duration,h)),r=[...[e,s,i].map(Math.round),Hr(0,n,1)];return{value:r,valueProgress:r.map((a,h)=>this.byValue[h]!==0?Math.abs((a-this.startValue[h])/this.byValue[h]):0).find(a=>a!==0)||0}}}function ng(o){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(o)?new U_(o):new G_(o);return t.start(),t}function g0(o){const t=new q_(o);return t.start(),t}class zt{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter(i=>!this.includes(i))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=wu(e,s),r=wu(e,t).divide(n);return i?Math.abs(r.x)===Math.abs(r.y):r.x===r.y&&r.x>=0&&r.x<=1}}static isPointInPolygon(t,e){const s=new M(t).setX(Math.min(t.x-1,...e.map(n=>n.x)));let i=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,s);if(r.includes(t))return!0;i+=+(r.status==="Intersection")}return i%2==1}static intersectLineLine(t,e,s,i){let n=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const a=e.x-t.x,h=e.y-t.y,c=i.x-s.x,u=i.y-s.y,d=t.x-s.x,f=t.y-s.y,g=c*f-u*d,p=a*f-h*d,m=u*a-c*h;if(m!==0){const y=g/m,b=p/m;return(n||0<=y&&y<=1)&&(r||0<=b&&b<=1)?new zt("Intersection").append(new M(t.x+y*a,t.y+y*h)):new zt}if(g===0||p===0){const y=n||r||zt.isPointContained(t,s,i)||zt.isPointContained(e,s,i)||zt.isPointContained(s,t,e)||zt.isPointContained(i,t,e);return new zt(y?"Coincident":void 0)}return new zt("Parallel")}static intersectSegmentLine(t,e,s,i){return zt.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return zt.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new zt,r=s.length;for(let a,h,c,u=0;u<r;u++){if(a=s[u],h=s[(u+1)%r],c=zt.intersectLineLine(t,e,a,h,i,!1),c.status==="Coincident")return c;n.append(...c.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return zt.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new zt,i=t.length,n=[];for(let r=0;r<i;r++){const a=t[r],h=t[(r+1)%i],c=zt.intersectSegmentPolygon(a,h,e);c.status==="Coincident"?(n.push(c),s.append(a,h)):s.append(...c.points)}return n.length>0&&n.length===t.length?new zt("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new M(n.x,i.y),a=new M(i.x,n.y);return zt.intersectPolygonPolygon(t,[i,r,n,a])}}class K_ extends km{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?Ee(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Ee(t,ns(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new M(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:i}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,s,i];if(this.group){const r=this.group.calcTransformMatrix();return n.map(a=>Ee(a,r))}return n}intersectsWithRect(t,e){return zt.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=zt.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return zt.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every(s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Ci(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(Ve,t),this._set(gs,t),this.setCoords()}scaleToWidth(t){const e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){const e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?Si(Dm(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||He.concat()}calcACoords(){const t=Ir({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=go(e,s),n=qt(i,t),r=this._getTransformedDimensions(),a=r.x/2,h=r.y/2;return{tl:Ee({x:-a,y:-h},n),tr:Ee({x:a,y:-h},n),bl:Ee({x:-a,y:h},n),br:Ee({x:a,y:h},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,se(this.originX),se(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),i=this.matrixCache;return i&&i.key.every((n,r)=>n===s[r])?i.value:(this.group&&(e=qt(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),i={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=Fm(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new M(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=T({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,a=e.height+i;let h;return h=e.skewX===0&&e.skewY===0?new M(r*e.scaleX,a*e.scaleY):vu(r,a,$h(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,a=t.y;const h=se(i)-se(e),c=se(n)-se(s);if(h||c){const u=this._getTransformedDimensions();r+=h*u.x,a+=c*u.y}return new M(r,a)}translateToCenterPoint(t,e,s){if(e===rt&&s===rt)return t;const i=this.translateToGivenOrigin(t,e,s,rt,rt);return this.angle?i.rotate(Ut(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,rt,rt,e,s);return this.angle?i.rotate(Ut(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Ee(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new M(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const i=this.translateToCenterPoint(t,e,s),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),wt,is)}}const J_=["type"],Q_=["extraParam"];let Qi=class Jd extends K_{static getDefaults(){return Jd.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){$i("warn","Setting type has no effect",t)}constructor(t){super(),E(this,"_cacheContext",null),Object.assign(this,Jd.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Rs(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=bt.maxCacheSideLimit,n=bt.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=bt.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[a,h]=Xh.limitDimsByArea(r),c=Hr(n,a,i),u=Hr(n,h,i);return e>c&&(t.zoomX/=e/c,t.width=c,t.capped=!0),s>u&&(t.zoomY/=s/u,t.height=u,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,i=e.y*t.y/this.scaleY;return{width:Math.ceil(s+2),height:Math.ceil(i+2),zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:i,zoomX:n,zoomY:r,x:a,y:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),c=s!==t.width||i!==t.height,u=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(c||u){s!==t.width||i!==t.height?(t.width=s,t.height=i):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const d=a/2,f=h/2;return this.cacheTranslationX=Math.round(t.width/2-d)+d,this.cacheTranslationY=Math.round(t.height/2-f)+f,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,s=this.calcTransformMatrix(!e);t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}getObjectScaling(){if(!this.group)return new M(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Lr(this.calcTransformMatrix());return new M(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),s=this.getCanvasRetinaScaling();return t.scalarMultiply(e*s)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t===0?1e-4:t}_set(t,e){t!==Ve&&t!==gs||(e=this._constrainScale(e)),t===Ve&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Ki||(e=new Ki(e));const s=this[t]!==e;return this[t]=e,s&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||s&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n}=this,{width:r,height:a}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n,width:r,height:a,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return this.stroke&&this.stroke!=="transparent"&&this.strokeWidth!==0}hasFill(){return this.fill&&this.fill!=="transparent"}needsItsOwnCache(){return!!(this.paintFirst===We&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=ps(e),i=s.getContext("2d");if(i.translate(e.cacheTranslationX,e.cacheTranslationY),i.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach(n=>{n.transform(i)}),e.parentClipPaths.push(t),t.absolutePositioned){const n=ns(this.calcTransformMatrix());i.transform(n[0],n[1],n[2],n[3],n[4],n[5])}return t.transform(i),t.drawObject(i,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const i=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,i)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,s=this._cacheContext;return!(!e||!s||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&s&&!t&&(s.save(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),s.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;const e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){const s=e.stroke;s&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,Fs(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?this._applyPatternForTransformedGradient(t,s):(t.strokeStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:s}=e;s&&(Fs(s)?(t.fillStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.fillStyle=s)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&e.length!==0&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,i=this.getCanvasRetinaScaling(),[n,,,r]=(s==null?void 0:s.viewportTransform)||He,a=n*i,h=r*i,c=e.nonScaling?new M(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*bt.browserShadowBlurConstant*(a+h)*(c.x+c.y)/4,t.shadowOffsetX=e.offsetX*a*c.x,t.shadowOffsetY=e.offsetY*h*c.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!Fs(e))return{offsetX:0,offsetY:0};const s=e.gradientTransform||e.patternTransform,i=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return e.gradientUnits==="percentage"?t.transform(this.width,0,0,this.height,i,n):t.transform(1,0,0,1,i,n),s&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),{offsetX:i,offsetY:n}}_renderPaintInOrder(t){this.paintFirst===We?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const i=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,a=i.y/this.scaleY/n,h=ps({width:Math.ceil(r),height:Math.ceil(a)}),c=h.getContext("2d");c&&(c.beginPath(),c.moveTo(0,0),c.lineTo(r,0),c.lineTo(r,a),c.lineTo(0,a),c.closePath(),c.translate(r/2,a/2),c.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(c,e),c.fillStyle=e.toLive(t),c.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=c.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new M(this.left+this.width/2,this.top+this.height/2)}clone(t){const e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){const e=this.toCanvasElement(t);return new(W.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Wf(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?Sm():1,a=(t.multiplier||1)*r,h=t.canvasProvider||(x=>new Jh(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Xm(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Gf(this,this.getViewportTransform()),this.setCoords();const c=Rs(),u=this.getBoundingRect(),d=this.shadow,f=new M;if(d){const x=d.blur,S=d.nonScaling?new M(1,1):this.getObjectScaling();f.x=2*Math.round(n(d.offsetX)+x)*n(S.x),f.y=2*Math.round(n(d.offsetY)+x)*n(S.y)}const g=u.width+f.x,p=u.height+f.y;c.width=Math.ceil(g),c.height=Math.ceil(p);const m=h(c);t.format==="jpeg"&&(m.backgroundColor="#fff"),this.setPositionByOrigin(new M(m.width/2,m.height/2),rt,rt);const y=this.canvas;m._objects=[this],this.set("canvas",m),this.setCoords();const b=m.toCanvasElement(a||1,t);return this.set("canvas",y),this.shadow=i,s&&(this.group=s),this.set(e),this.setCoords(),m._objects=[],m.destroy(),b}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return jf(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Nf(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:s,originY:i}=this;if(e){const{x:n,y:r}=this.getRelativeCenterPoint();this.originX=rt,this.originY=rt,this.left=n,this.top=r}if(this.set("angle",t),e){const{x:n,y:r}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){du.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&xi().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s},{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:a,onChange:h,onComplete:c}=s,u=T(T({},s),{},{target:this,startValue:a??i.reduce((d,f)=>d[f],this),endValue:e,abort:r==null?void 0:r.bind(this),onChange:(d,f,g)=>{i.reduce((p,m,y)=>(y===i.length-1&&(p[m]=d),p[m]),this),h&&h(d,f,g)},onComplete:(d,f,g)=>{this.setCoords(),c&&c(d,f,g)}});return n?g0(u):ng(u)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let i,n=0;n<e.length;n++){if(i=e[n],i===t)return{fork:[this,...e.slice(0,n)],otherFork:[],common:e.slice(n)};for(let r=0;r<s.length;r++){if(this===s[r])return{fork:[],otherFork:[t,...s.slice(0,r)],common:[this,...e]};if(i===s[r])return{fork:[this,...e.slice(0,n)],otherFork:[t,...s.slice(0,r)],common:e.slice(n)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const i=e.fork.pop(),n=e.otherFork.pop(),r=s._objects.indexOf(i),a=s._objects.indexOf(n);return r>-1&&r>a}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Jd.customProperties,this.constructor.customProperties||[]);let e;const s=bt.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:a,strokeDashArray:h,left:c,top:u,originX:d,originY:f,width:g,height:p,strokeWidth:m,strokeLineCap:y,strokeDashOffset:b,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:C,scaleX:k,scaleY:O,angle:P,flipX:D,flipY:R,opacity:z,visible:B,backgroundColor:F,fillRule:L,paintFirst:N,globalCompositeOperation:K,skewX:I,skewY:V}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const it=Bt=>Dt(Bt,s),Ot=T(T({},jr(this,t)),{},{type:this.constructor.type,version:Pf,originX:d,originY:f,left:it(c),top:it(u),width:it(g),height:it(p),fill:Lm(n)?n.toObject():n,stroke:Lm(r)?r.toObject():r,strokeWidth:it(m),strokeDashArray:h&&h.concat(),strokeLineCap:y,strokeDashOffset:b,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:it(C),scaleX:it(k),scaleY:it(O),angle:it(P),flipX:D,flipY:R,opacity:it(z),shadow:a&&a.toObject(),visible:B,backgroundColor:F,fillRule:L,paintFirst:N,globalCompositeOperation:K,skewX:it(I),skewY:it(V)},e?{clipPath:e}:null);return this.includeDefaultValues?Ot:this._removeDefaultValues(Ot)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return zf(t,(i,n)=>{if(n===wt||n===is||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=Lt(t,J_),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=Lt(s,Q_);return Kh(e,n).then(r=>i?(delete r[i],new this(e[i],r)):new this(r))}static fromObject(t,e){return this._fromObject(t,e)}};E(Qi,"stateProperties",B_),E(Qi,"cacheProperties",Ji),E(Qi,"ownDefaults",H_),E(Qi,"type","FabricObject"),E(Qi,"colorProperties",[ee,We,"backgroundColor"]),E(Qi,"customProperties",[]),W.setClass(Qi),W.setClass(Qi,"object");const yo=(o,t,e)=>(s,i,n,r)=>{const a=t(s,i,n,r);return a&&Ym(o,T(T({},Km(s,i,n,r)),e)),a};function _o(o){return(t,e,s,i)=>{const{target:n,originX:r,originY:a}=e,h=n.getRelativeCenterPoint(),c=n.translateToOriginPoint(h,r,a),u=o(t,e,s,i);return n.setPositionByOrigin(c,e.originX,e.originY),u}}const p0=yo(Uh,_o((o,t,e,s)=>{const i=Xf(t,t.originX,t.originY,e,s);if(se(t.originX)===se(rt)||se(t.originX)===se($t)&&i.x<0||se(t.originX)===se(wt)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),a=$m(t)?2:1,h=n.width,c=Math.abs(i.x*a/n.scaleX)-r;return n.set("width",Math.max(c,1)),h!==n.width}return!1}));function Z_(o,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=a?We:ee,c=!a&&(s.cornerStrokeColor||i.cornerStrokeColor);let u,d=t,f=e;o.save(),o.fillStyle=s.cornerColor||i.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(u=n,o.scale(1,r/n),f=e*n/r):r>n?(u=r,o.scale(n/r,1),d=t*r/n):u=n,o.beginPath(),o.arc(d,f,u/2,0,qi,!1),o[h](),c&&o.stroke(),o.restore()}function tw(o,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,h=a?We:ee,c=!a&&(s.cornerStrokeColor||i.cornerStrokeColor),u=n/2,d=r/2;o.save(),o.fillStyle=s.cornerColor||i.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",o.translate(t,e);const f=i.getTotalAngle();o.rotate(Ut(f)),o["".concat(h,"Rect")](-u,-d,n,r),c&&o.strokeRect(-u,-d,n,r),o.restore()}class ei{constructor(t){E(this,"visible",!0),E(this,"actionName",cu),E(this,"angle",0),E(this,"x",0),E(this,"y",0),E(this,"offsetX",0),E(this,"offsetY",0),E(this,"sizeX",0),E(this,"sizeY",0),E(this,"touchSizeX",0),E(this,"touchSizeY",0),E(this,"cursorStyle","crosshair"),E(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:a,br:h,bl:c}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&zt.isPointInPolygon(s,[r,a,h,c])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new M(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const a=gu([go(s,i),Ir({angle:t}),pu((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new M(-.5,-.5).transform(a),tr:new M(.5,-.5).transform(a),br:new M(.5,.5).transform(a),bl:new M(-.5,.5).transform(a)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?Z_.call(this,t,e,s,i,n):tw.call(this,t,e,s,i,n)}}const ew=(o,t,e)=>e.lockRotation?bu:t.cursorStyle,sw=yo(Am,_o((o,t,e,s)=>{let{target:i,ex:n,ey:r,theta:a,originX:h,originY:c}=t;const u=i.translateToOriginPoint(i.getRelativeCenterPoint(),h,c);if(Zs(i,"lockRotation"))return!1;const d=Math.atan2(r-u.y,n-u.x),f=Math.atan2(s-u.y,e-u.x);let g=Si(f-d+a);if(i.snapAngle&&i.snapAngle>0){const m=i.snapAngle,y=i.snapThreshold||m,b=Math.ceil(g/m)*m,x=Math.floor(g/m)*m;Math.abs(g-x)<y?g=x:Math.abs(g-b)<y&&(g=b)}g<0&&(g=360+g),g%=360;const p=i.angle!==g;return i.angle=g,p}));function m0(o,t){const e=t.canvas,s=o[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function v0(o,t,e){const s=Zs(o,"lockScalingX"),i=Zs(o,"lockScalingY");if(s&&i||!t&&(s||i)&&e||s&&t==="x"||i&&t==="y")return!0;const{width:n,height:r,strokeWidth:a}=o;return n===0&&a===0&&t!=="y"||r===0&&a===0&&t!=="x"}const iw=["e","se","s","sw","w","nw","n","ne","e"],tl=(o,t,e)=>{const s=m0(o,e);if(v0(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return bu;const i=Jm(e,t);return"".concat(iw[i],"-resize")};function rg(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,a=m0(o,n);let h,c,u,d,f,g;if(v0(n,r,a))return!1;if(t.gestureScale)c=t.scaleX*t.gestureScale,u=t.scaleY*t.gestureScale;else{if(h=Xf(t,t.originX,t.originY,e,s),f=r!=="y"?Math.sign(h.x||t.signX||1):1,g=r!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=f),t.signY||(t.signY=g),Zs(n,"lockScalingFlip")&&(t.signX!==f||t.signY!==g))return!1;if(d=n._getTransformedDimensions(),a&&!r){const y=Math.abs(h.x)+Math.abs(h.y),{original:b}=t,x=y/(Math.abs(d.x*b.scaleX/n.scaleX)+Math.abs(d.y*b.scaleY/n.scaleY));c=b.scaleX*x,u=b.scaleY*x}else c=Math.abs(h.x*n.scaleX/d.x),u=Math.abs(h.y*n.scaleY/d.y);$m(t)&&(c*=2,u*=2),t.signX!==f&&r!=="y"&&(t.originX=qm(t.originX),c*=-1,t.signX=f),t.signY!==g&&r!=="x"&&(t.originY=qm(t.originY),u*=-1,t.signY=g)}const p=n.scaleX,m=n.scaleY;return r?(r==="x"&&n.set(Ve,c),r==="y"&&n.set(gs,u)):(!Zs(n,"lockScalingX")&&n.set(Ve,c),!Zs(n,"lockScalingY")&&n.set(gs,u)),p!==n.scaleX||m!==n.scaleY}const Au=yo(hu,_o((o,t,e,s)=>rg(o,t,e,s))),nw=yo(hu,_o((o,t,e,s)=>rg(o,t,e,s,{by:"x"}))),rw=yo(hu,_o((o,t,e,s)=>rg(o,t,e,s,{by:"y"}))),aw=["target","ex","ey","skewingSide"],ag={x:{counterAxis:"y",scale:Ve,skew:co,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:gs,skew:uo,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},ow=["ns","nesw","ew","nwse"],hw=(o,t,e)=>{if(t.x!==0&&Zs(e,"lockSkewingY")||t.y!==0&&Zs(e,"lockSkewingX"))return bu;const s=Jm(e,t)%4;return"".concat(ow[s],"-resize")};function b0(o,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:a,lockSkewing:h,skew:c,flip:u}=ag[o];if(Zs(n,h))return!1;const{origin:d,flip:f}=ag[r],g=se(e[d])*(n[f]?-1:1),p=-Math.sign(g)*(n[u]?-1:1),m=.5*-((n[c]===0&&Xf(e,rt,rt,s,i)[o]>0||n[c]>0?1:-1)*p)+.5;return yo(Tm,_o((b,x,S,C)=>function(k,O,P){let{target:D,ex:R,ey:z,skewingSide:B}=O,F=Lt(O,aw);const{skew:L}=ag[k],N=P.subtract(new M(R,z)).divide(new M(D.scaleX,D.scaleY))[k],K=D[L],I=F[L],V=Math.tan(Ut(I)),it=k==="y"?D._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:D._getTransformedDimensions({scaleX:1,scaleY:1}).y,Ot=2*N*B/Math.max(it,1)+V,Bt=Si(Math.atan(Ot));D.set(L,Bt);const Xt=K!==D[L];if(Xt&&k==="y"){const{skewX:Ft,scaleX:_t}=D,ae=D._getTransformedDimensions({skewY:K}),Ze=D._getTransformedDimensions(),st=Ft!==0?ae.x/Ze.x:1;st!==1&&D.set(Ve,st*_t)}return Xt}(o,x,new M(S,C))))(t,T(T({},e),{},{[a]:m,skewingSide:p}),s,i)}const lw=(o,t,e,s)=>b0("x",o,t,e,s),cw=(o,t,e,s)=>b0("y",o,t,e,s);function Tu(o,t){return o[t.canvas.altActionKey]}const Eu=(o,t,e)=>{const s=Tu(o,e);return t.x===0?s?co:gs:t.y===0?s?uo:Ve:""},wo=(o,t,e)=>Tu(o,e)?hw(0,t,e):tl(o,t,e),y0=(o,t,e,s)=>Tu(o,t.target)?cw(o,t,e,s):nw(o,t,e,s),_0=(o,t,e,s)=>Tu(o,t.target)?lw(o,t,e,s):rw(o,t,e,s),w0=()=>({ml:new ei({x:-.5,y:0,cursorStyleHandler:wo,actionHandler:y0,getActionName:Eu}),mr:new ei({x:.5,y:0,cursorStyleHandler:wo,actionHandler:y0,getActionName:Eu}),mb:new ei({x:0,y:.5,cursorStyleHandler:wo,actionHandler:_0,getActionName:Eu}),mt:new ei({x:0,y:-.5,cursorStyleHandler:wo,actionHandler:_0,getActionName:Eu}),tl:new ei({x:-.5,y:-.5,cursorStyleHandler:tl,actionHandler:Au}),tr:new ei({x:.5,y:-.5,cursorStyleHandler:tl,actionHandler:Au}),bl:new ei({x:-.5,y:.5,cursorStyleHandler:tl,actionHandler:Au}),br:new ei({x:.5,y:.5,cursorStyleHandler:tl,actionHandler:Au}),mtr:new ei({x:0,y:-.5,actionHandler:sw,cursorStyleHandler:ew,offsetY:-40,withConnection:!0,actionName:Ff})}),uw=()=>({mr:new ei({x:.5,y:0,actionHandler:p0,cursorStyleHandler:wo,actionName:Uh}),ml:new ei({x:-.5,y:0,actionHandler:p0,cursorStyleHandler:wo,actionName:Uh})}),dw=()=>T(T({},w0()),uw());class el extends Qi{static getDefaults(){return T(T({},super.getDefaults()),el.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),el.ownDefaults),this.setOptions(t)}static createControls(){return{controls:w0()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,s=e.target,i=e.action;if(this===s&&i&&i.startsWith(cu))return!1}return super._updateCacheCanvas()}getActiveControl(){const t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const s=Object.entries(this.oCoords);for(let i=s.length-1;i>=0;i--){const[n,r]=s[i],a=this.controls[n];if(a.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:a,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=go(e.x,e.y),i=Ir({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=qt(s,i),r=qt(t,n),a=qt(r,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Lr(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const c=this._calculateCurrentDimensions(h),u={};return this.forEachControl((d,f)=>{const g=d.positionHandler(c,a,this,d);u[f]=Object.assign(g,this._calcCornerCoords(d,g))}),u}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),i=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/i[0],1/i[3]),t.rotate(Ut(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=T({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=i.borderColor,this._setLineDash(t,i.borderDashArray),this.strokeBorders(t,e),i.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:i}=this,n=T({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),a=n.hasBorders,h=n.hasControls,c=qt(r,this.calcTransformMatrix()),u=Lr(c);t.save(),t.translate(u.translateX,u.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(u.angle-=180),t.rotate(Ut(this.group?u.angle:this.angle)),a&&this.drawBorders(t,u,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=vu(this.width,this.height,$h(e)),r=this.isStrokeAccountedForInDimensions()?If:(this.strokeUniform?new M().scalarAdd(this.canvas?this.canvas.getZoom():1):new M(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);i=n.add(r).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else i=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,i,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl((i,n)=>{i.withConnection&&i.getVisibility(this,n)&&(s=!0,t.moveTo(i.x*e.x,i.y*e.y),t.lineTo(i.x*e.x+i.offsetX,i.y*e.y+i.offsetY))}),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:i,cornerDashArray:n,cornerColor:r}=this,a=T({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=a.cornerColor,this.transparentCorners||(t.strokeStyle=a.cornerStrokeColor),this._setLineDash(t,a.cornerDashArray),this.forEachControl((h,c)=>{if(h.getVisibility(this,c)){const u=this.oCoords[c];h.render(t,u.x,u.y,a,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,i]=e;return this.setControlVisible(s,i)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const i=this.width+4,n=this.height+4;return e.clearRect(-i/2,-n/2,i,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function x0(o,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(o.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),o}E(el,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class ke extends el{}x0(ke,[s0]),W.setClass(ke),W.setClass(ke,"object");const S0=(o,t,e,s)=>{const i=2*(s=Math.round(s))+1,{data:n}=o.getImageData(t-s,e-s,i,i);for(let r=3;r<n.length;r+=4)if(n[r]>0)return!1;return!0};class C0{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new M(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new M(1/this.options.scaleX,1/this.options.scaleY):new M(1,1)}createSideVector(t,e){const s=wu(t,e);return this.options.strokeUniform?s.multiply(this.scale):s}projectOrthogonally(t,e,s){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,s)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(t){const e=new M(t);return e.y+=e.x*Math.tan(Ut(this.options.skewY)),e.x+=e.y*Math.tan(Ut(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const fw=new M;class xo extends C0{static getOrthogonalRotationFactor(t,e){const s=e?Su(t,e):o0(t);return Math.abs(s)<Vn?-1:1}constructor(t,e,s,i){super(i),E(this,"AB",void 0),E(this,"AC",void 0),E(this,"alpha",void 0),E(this,"bisector",void 0),this.A=new M(t),this.B=new M(e),this.C=new M(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Su(this.AB,this.AC),this.bisector=Cu(Jf(this.AB.eq(fw)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e),n=Qf(i),r=xo.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%qi==0?[this.B]:[this.B,this.C]).forEach(e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))}),t}projectMiter(){const t=[],e=Math.abs(this.alpha),s=1/Math.sin(e/2),i=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*s),n=this.options.strokeUniform?xu(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return xu(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new M(xo.getOrthogonalRotationFactor(this.bisector),xo.getOrthogonalRotationFactor(new M(this.bisector.y,this.bisector.x)));return[new M(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new M(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{Zf(n,t,e)&&s.push(this.A.add(n))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:a,strokeUniform:h}=this.options,c=new M(Math.tan(Ut(i)),Math.tan(Ut(n))),u=this.strokeProjectionMagnitude,d=h?u/a/Math.sqrt(1/a**2+1/r**2*c.y**2):u/Math.sqrt(1+c.y**2),f=new M(Math.sqrt(Math.max(u**2-d**2,0)),d),g=h?u/Math.sqrt(1+c.x**2*(1/a)**2/(1/r+1/r*c.x*c.y)**2):u/Math.sqrt(1+c.x**2/(1+c.x*c.y)**2),p=new M(g,Math.sqrt(Math.max(u**2-g**2,0)));return[p,p.scalarMultiply(-1),f,f.scalarMultiply(-1)].map(m=>this.applySkew(h?m.multiply(this.strokeUniformScalar):m)).forEach(m=>{Zf(m,t,e)&&s.push(this.applySkew(this.A).add(m))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%qi==0,s=this.applySkew(this.A),i=t[e?0:2].subtract(s),n=t[e?1:0].subtract(s),r=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),a=bo(i,r)>0,h=a?i:n,c=a?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,c)):t.push(...this.projectRoundNoSkew(h,c)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class A0 extends C0{constructor(t,e,s){super(s),this.A=new M(t),this.T=new M(e)}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e);return this.scaleUnitVector(Qf(i),s)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){const t=[];if(!this.isSkewed()&&this.A.eq(this.T)){const e=new M(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.applySkew(this.A.add(e)),this.applySkew(this.A.subtract(e)))}else t.push(...new xo(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new M(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{const e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),s=this.scaleUnitVector(Cu(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),i=this.A.add(s);t.push(i.add(e),i.subtract(e))}return t.map(e=>this.applySkew(e))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}const T0=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(o.length===0)return s;const i=o.reduce((n,r)=>(n[n.length-1].eq(r)||n.push(new M(r)),n),[new M(o[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((a,h)=>{for(let c=a.length-1;c>=0;c--)if(h(a[c],c,a))return c;return-1})(i,a=>!a.eq(n));i.splice(r+1)}return i.forEach((n,r,a)=>{let h,c;r===0?(c=a[1],h=e?n:a[a.length-1]):r===a.length-1?(h=a[r-1],c=e?n:a[0]):(h=a[r-1],c=a[r+1]),e&&a.length===1?s.push(...new A0(n,n,t).project()):!e||r!==0&&r!==a.length-1?s.push(...new xo(n,h,c,t).project()):s.push(...new A0(n,r===0?c:h,t).project())}),s},og=o=>{const t={};return Object.keys(o).forEach(e=>{t[e]={},Object.keys(o[e]).forEach(s=>{t[e][s]=T({},o[e][s])})}),t},E0=o=>o.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">"),ku=o=>{const t=[];for(let e,s=0;s<o.length;s++)(e=gw(o,s))!==!1&&t.push(e);return t},gw=(o,t)=>{const e=o.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return o.charAt(t);if(55296<=e&&e<=56319){if(o.length<=t+1)throw"High surrogate without following low surrogate";const i=o.charCodeAt(t+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return o.charAt(t)+o.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=o.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var pw=Object.freeze({__proto__:null,capitalize:function(o){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(o.charAt(0).toUpperCase()).concat(t?o.slice(1):o.slice(1).toLowerCase())},escapeXml:E0,graphemeSplit:ku});const Pu=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return o.fill!==t.fill||o.stroke!==t.stroke||o.strokeWidth!==t.strokeWidth||o.fontSize!==t.fontSize||o.fontFamily!==t.fontFamily||o.fontWeight!==t.fontWeight||o.fontStyle!==t.fontStyle||o.textBackgroundColor!==t.textBackgroundColor||o.deltaY!==t.deltaY||e&&(o.overline!==t.overline||o.underline!==t.underline||o.linethrough!==t.linethrough)},k0=(o,t)=>{const e=t.split(`
|
|
67
|
-
`),s=[];let i=-1,n={};o=
|
|
68
|
-
`)]}static async fromElement(t,e,s){const i=Zi(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:a=0,height:h=0,visible:c=!0}=i,u=Lt(i,Lw);return new this(T(T(T({},e),u),{},{left:n,top:r,width:a,height:h,visible:!!(c&&a&&h)}))}}E(Ai,"type","Rect"),E(Ai,"cacheProperties",[...Ji,...N0]),E(Ai,"ownDefaults",{rx:0,ry:0}),E(Ai,"ATTRIBUTE_NAMES",[...Xn,"x","y","rx","ry","width","height"]),W.setClass(Ai),W.setSVGClass(Ai);const tn="initialization",Ou="added",cg="removed",Du="imperative",B0=(o,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,a=r&&r!==o?Qh(r.calcTransformMatrix(),o.calcTransformMatrix()):null,h=a?t.getRelativeCenterPoint().transform(a):t.getRelativeCenterPoint(),c=!t.isStrokeAccountedForInDimensions(),u=e&&c?Um(new M(s,s),void 0,o.calcTransformMatrix()):If,d=!e&&c?s:0,f=vu(i+d,n+d,gu([a,t.calcOwnMatrix()],!0)).add(u).scalarDivide(2);return[h.subtract(f),h.add(f)]};class Ru{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===tn||e===Du||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==tn&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===Du&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:a,height:h}=Ci(t.map(d=>B0(i,d)).reduce((d,f)=>d.concat(f),[])),c=new M(a,h),u=new M(n,r).add(c.scalarDivide(2));if(s===tn){const d=this.getInitialSize(e,{size:c,center:u});return{center:u,relativeCorrection:new M(0,0),size:d}}return{center:u.transform(i.calcOwnMatrix()),size:c}}}E(Ru,"type","strategy");class ug extends Ru{shouldPerformLayout(t){return!0}}E(ug,"type","fit-content"),W.setClass(ug);const Iw=["strategy"],jw=["target","strategy","bubbles","prevStrategy"],H0="layoutManager";class sl{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new ug;E(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=T(T({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[uu,Cm,Uh,Am,hu,Tm,lu,A_,T_].map(i=>t.on(i,n=>this.performLayout(i===uu?{type:"object_modified",trigger:i,e:n,target:s}:{type:"object_modifying",trigger:i,e:n,target:s})))}subscribe(t,e){this.unsubscribe(t,e);const s=this.attachHandlers(t,e);this._subscriptions.set(t,s)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(s=>s()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){const{target:e,type:s}=t,{canvas:i}=e;if(s===tn||s===Ou?this.subscribeTargets(t):s===cg&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===Du&&t.deep){const n=Lt(t,Iw);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(T(T({},n),{},{bubbles:!1,target:r})))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===tn?new M:e.getRelativeCenterPoint(),{center:a,correction:h=new M,relativeCorrection:c=new M}=n,u=r.subtract(a).add(h).transform(i===tn?He:ns(e.calcOwnMatrix()),!0).add(c);return{result:n,prevCenter:r,nextCenter:a,offset:u}}commitLayout(t,e){const{target:s}=t,{result:{size:i},nextCenter:n}=e;var r,a;s.set({width:i.x,height:i.y}),this.layoutObjects(t,e),t.type===tn?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*se(s.originX),top:(a=t.y)!==null&&a!==void 0?a:n.y+i.y*se(s.originY)}):(s.setPositionByOrigin(n,rt,rt),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject(i=>{i.group===s&&this.layoutObject(t,e,i)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:i}=e;s.set({left:s.left+i.x,top:s.top+i.y})}onAfterLayout(t,e){const{target:s,strategy:i,bubbles:n,prevStrategy:r}=t,a=Lt(t,jw),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const c=s.parent;n&&c!=null&&c.layoutManager&&((a.path||(a.path=[])).push(s),c.layoutManager.performLayout(T(T({},a),{},{target:c}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:H0,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}W.setClass(sl,H0);const Nw=["type","objects","layoutManager"];class Bw extends sl{performLayout(){}}class Ls extends Em(ke){static getDefaults(){return T(T({},super.getDefaults()),Ls.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),E(this,"_activeObjects",[]),E(this,"__objectSelectionTracker",void 0),E(this,"__objectSelectionDisposer",void 0),Object.assign(this,Ls.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var s;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(i=>{this.enterGroup(i,!1)}),this.layoutManager=(s=e.layoutManager)!==null&&s!==void 0?s:new sl,this.layoutManager.performLayout({type:tn,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?($i("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||($i("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((e,s,i)=>this.canEnterGroup(e)&&i.indexOf(e)===s)}add(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];const i=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...i);return this._onAfterObjectsChange(Ou,i),n}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=this._filterObjectsBeforeEnteringGroup(s),r=super.insertAt(t,...n);return this._onAfterObjectsChange(Ou,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(cg,t),t}_onObjectAdded(t){this.enterGroup(t,!0),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t,e){this.exitGroup(t,e),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onAfterObjectsChange(t,e){this.layoutManager.performLayout({type:t,targets:e,target:this})}_onStackOrderChanged(){this._set("dirty",!0)}_set(t,e){const s=this[t];return super._set(t,e),t==="canvas"&&s!==e&&(this._objects||[]).forEach(i=>{i._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:s}=e;const i=this._activeObjects;if(t)i.push(s),this._set("dirty",!0);else if(i.length>0){const n=i.indexOf(s);n>-1&&(i.splice(n,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&vo(t,qt(ns(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const s=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();s&&(s===t||t.isDescendantOf(s))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(vo(t,qt(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=ke.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let n=0;n<this._objects.length;n++){var i;const r=this._objects[n];(i=this.canvas)!==null&&i!==void 0&&i.preserveObjectStacking&&r.group!==this?(t.save(),t.transform(...ns(this.calcTransformMatrix())),r.render(t),t.restore()):r.group===this&&r.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(T({target:this,type:Du},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter(function(i){return!i.excludeFromExport}).map(function(i){const n=i.includeDefaultValues;i.includeDefaultValues=s;const r=i[t||"toObject"](e);return i.includeDefaultValues=n,r})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return T(T(T({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Ai.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const i=e.join("");return t?t(i):i}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
|
|
66
|
+
`)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=Ye.ownDefaults;return this.includeDefaultValues?t:Or(t,(s,i)=>s!==e[i])}static async fromObject(t){return new this(t)}}S(Ye,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),S(Ye,"type","shadow"),I.setClass(Ye,"shadow");const Ss=(o,t,e)=>Math.max(o,Math.min(t,e)),ou=[ie,ot,$t,ce,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Bs,Hs],$e=[kt,qt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],lu={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:ot,originY:ie,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:kt,fill:"rgb(0,0,0)",fillRule:"nonzero",stroke:null,strokeDashArray:null,strokeDashOffset:0,strokeLineCap:"butt",strokeLineJoin:"miter",strokeMiterLimit:4,globalCompositeOperation:"source-over",backgroundColor:"",shadow:null,visible:!0,includeDefaultValues:!0,excludeFromExport:!1,objectCaching:!0,clipPath:void 0,inverted:!1,absolutePositioned:!1,centeredRotation:!0,centeredScaling:!1,dirty:!0},Xr=(o,t,e,s)=>(o<Math.abs(t)?(o=t,s=e/4):s=t===0&&o===0?e/Ue*Math.asin(1):e/Ue*Math.asin(t/o),{a:o,c:t,p:e,s}),nl=(o,t,e,s,i)=>o*Math.pow(2,10*(s-=1))*Math.sin((s*i-t)*Ue/e),rl=(o,t,e,s)=>-e*Math.cos(o/s*is)+e+t,Ur=(o,t,e,s)=>(o/=s)<1/2.75?e*(7.5625*o*o)+t:o<2/2.75?e*(7.5625*(o-=1.5/2.75)*o+.75)+t:o<2.5/2.75?e*(7.5625*(o-=2.25/2.75)*o+.9375)+t:e*(7.5625*(o-=2.625/2.75)*o+.984375)+t,al=(o,t,e,s)=>e-Ur(s-o,0,e,s)+t;var hu=Object.freeze({__proto__:null,defaultEasing:rl,easeInBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*(o/=s)*o*((i+1)*o-i)+t},easeInBounce:al,easeInCirc:(o,t,e,s)=>-e*(Math.sqrt(1-(o/=s)*o)-1)+t,easeInCubic:(o,t,e,s)=>e*(o/s)**3+t,easeInElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:a,p:l}=Xr(i,e,n,1.70158);return-nl(r,a,l,o,s)+t},easeInExpo:(o,t,e,s)=>o===0?t:e*2**(10*(o/s-1))+t,easeInOutBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(o/=s/2)<1?e/2*(o*o*((1+(i*=1.525))*o-i))+t:e/2*((o-=2)*o*((1+(i*=1.525))*o+i)+2)+t},easeInOutBounce:(o,t,e,s)=>o<s/2?.5*al(2*o,0,e,s)+t:.5*Ur(2*o-s,0,e,s)+.5*e+t,easeInOutCirc:(o,t,e,s)=>(o/=s/2)<1?-e/2*(Math.sqrt(1-o**2)-1)+t:e/2*(Math.sqrt(1-(o-=2)*o)+1)+t,easeInOutCubic:(o,t,e,s)=>(o/=s/2)<1?e/2*o**3+t:e/2*((o-2)**3+2)+t,easeInOutElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s/2)===2)return t+e;n||(n=s*(.3*1.5));const{a:r,s:a,p:l,c:h}=Xr(i,e,n,1.70158);return o<1?-.5*nl(r,a,l,o,s)+t:r*Math.pow(2,-10*(o-=1))*Math.sin((o*s-a)*Ue/l)*.5+h+t},easeInOutExpo:(o,t,e,s)=>o===0?t:o===s?t+e:(o/=s/2)<1?e/2*2**(10*(o-1))+t:e/2*-(2**(-10*--o)+2)+t,easeInOutQuad:(o,t,e,s)=>(o/=s/2)<1?e/2*o**2+t:-e/2*(--o*(o-2)-1)+t,easeInOutQuart:(o,t,e,s)=>(o/=s/2)<1?e/2*o**4+t:-e/2*((o-=2)*o**3-2)+t,easeInOutQuint:(o,t,e,s)=>(o/=s/2)<1?e/2*o**5+t:e/2*((o-2)**5+2)+t,easeInOutSine:(o,t,e,s)=>-e/2*(Math.cos(Math.PI*o/s)-1)+t,easeInQuad:(o,t,e,s)=>e*(o/=s)*o+t,easeInQuart:(o,t,e,s)=>e*(o/=s)*o**3+t,easeInQuint:(o,t,e,s)=>e*(o/s)**5+t,easeInSine:(o,t,e,s)=>-e*Math.cos(o/s*is)+e+t,easeOutBack:function(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*((o=o/s-1)*o*((i+1)*o+i)+1)+t},easeOutBounce:Ur,easeOutCirc:(o,t,e,s)=>e*Math.sqrt(1-(o=o/s-1)*o)+t,easeOutCubic:(o,t,e,s)=>e*((o/s-1)**3+1)+t,easeOutElastic:(o,t,e,s)=>{const i=e;let n=0;if(o===0)return t;if((o/=s)===1)return t+e;n||(n=.3*s);const{a:r,s:a,p:l,c:h}=Xr(i,e,n,1.70158);return r*2**(-10*o)*Math.sin((o*s-a)*Ue/l)+h+t},easeOutExpo:(o,t,e,s)=>o===s?t+e:e*-(2**(-10*o/s)+1)+t,easeOutQuad:(o,t,e,s)=>-e*(o/=s)*(o-2)+t,easeOutQuart:(o,t,e,s)=>-e*((o=o/s-1)*o**3-1)+t,easeOutQuint:(o,t,e,s)=>e*((o/s-1)**5+1)+t,easeOutSine:(o,t,e,s)=>e*Math.sin(o/s*is)+t});const cu=()=>!1;class Yr{constructor(t){let{startValue:e,byValue:s,duration:i=500,delay:n=0,easing:r=rl,onStart:a=ps,onChange:l=ps,onComplete:h=ps,abort:c=cu,target:u}=t;S(this,"_state","pending"),S(this,"durationProgress",0),S(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=i,this.delay=n,this.easing=r,this._onStart=a,this._onChange=l,this._onComplete=h,this._abort=c,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>gi(t),this.delay):gi(t)}tick(t){const e=(t||+new Date)-this.startTime,s=Math.min(e,this.duration);this.durationProgress=s/this.duration;const{value:i,valueProgress:n}=this.calculate(s);this.value=Object.freeze(i),this.valueProgress=n,this._state!=="aborted"&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),gi(this.tick)))}register(){qi.push(this)}unregister(){qi.remove(this)}abort(){this._state="aborted",this.unregister()}}const uu=["startValue","endValue"];class du extends Yr{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(x(x({},pt(t,uu)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const fu=["startValue","endValue"];class gu extends Yr{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(x(x({},pt(t,fu)),{},{startValue:e,byValue:s.map((i,n)=>i-e[n])}))}calculate(t){const e=this.startValue.map((s,i)=>this.easing(t,s,this.byValue[i],this.duration,i));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const pu=["startValue","endValue","easing","onChange","onComplete","abort"],mu=(o,t,e,s)=>t+e*(1-Math.cos(o/s*is)),$r=o=>o&&((t,e,s)=>o(new ht(t).toRgba(),e,s));class vu extends Yr{constructor(t){let{startValue:e,endValue:s,easing:i=mu,onChange:n,onComplete:r,abort:a}=t,l=pt(t,pu);const h=new ht(e).getSource(),c=new ht(s).getSource();super(x(x({},l),{},{startValue:h,byValue:c.map((u,d)=>u-h[d]),easing:i,onChange:$r(n),onComplete:$r(r),abort:$r(a)}))}calculate(t){const[e,s,i,n]=this.startValue.map((a,l)=>this.easing(t,a,this.byValue[l],this.duration,l)),r=[...[e,s,i].map(Math.round),Ss(0,n,1)];return{value:r,valueProgress:r.map((a,l)=>this.byValue[l]!==0?Math.abs((a-this.startValue[l])/this.byValue[l]):0).find(a=>a!==0)||0}}}function qr(o){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(o)?new gu(o):new du(o);return t.start(),t}function ol(o){const t=new vu(o);return t.start(),t}class yt{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter(i=>!this.includes(i))),this}static isPointContained(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(i||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(i||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const n=an(e,s),r=an(e,t).divide(n);return i?Math.abs(r.x)===Math.abs(r.y):r.x===r.y&&r.x>=0&&r.x<=1}}static isPointInPolygon(t,e){const s=new A(t).setX(Math.min(t.x-1,...e.map(n=>n.x)));let i=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,s);if(r.includes(t))return!0;i+=+(r.status==="Intersection")}return i%2==1}static intersectLineLine(t,e,s,i){let n=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],r=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const a=e.x-t.x,l=e.y-t.y,h=i.x-s.x,c=i.y-s.y,u=t.x-s.x,d=t.y-s.y,f=h*d-c*u,g=a*d-l*u,p=c*a-h*l;if(p!==0){const v=f/p,m=g/p;return(n||0<=v&&v<=1)&&(r||0<=m&&m<=1)?new yt("Intersection").append(new A(t.x+v*a,t.y+v*l)):new yt}if(f===0||g===0){const v=n||r||yt.isPointContained(t,s,i)||yt.isPointContained(e,s,i)||yt.isPointContained(s,t,e)||yt.isPointContained(i,t,e);return new yt(v?"Coincident":void 0)}return new yt("Parallel")}static intersectSegmentLine(t,e,s,i){return yt.intersectLineLine(t,e,s,i,!1,!0)}static intersectSegmentSegment(t,e,s,i){return yt.intersectLineLine(t,e,s,i,!1,!1)}static intersectLinePolygon(t,e,s){let i=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const n=new yt,r=s.length;for(let a,l,h,c=0;c<r;c++){if(a=s[c],l=s[(c+1)%r],h=yt.intersectLineLine(t,e,a,l,i,!1),h.status==="Coincident")return h;n.append(...h.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,s){return yt.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new yt,i=t.length,n=[];for(let r=0;r<i;r++){const a=t[r],l=t[(r+1)%i],h=yt.intersectSegmentPolygon(a,l,e);h.status==="Coincident"?(n.push(h),s.append(a,l)):s.append(...h.points)}return n.length>0&&n.length===t.length?new yt("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const i=e.min(s),n=e.max(s),r=new A(n.x,i.y),a=new A(i.x,n.y);return yt.intersectPolygonPolygon(t,[i,r,n,a])}}class bu extends po{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?Bt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=Bt(t,ne(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new A(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:i}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,s,i];if(this.group){const r=this.group.calcTransformMatrix();return n.map(a=>Bt(a,r))}return n}intersectsWithRect(t,e){return yt.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=yt.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:s,top:i,width:n,height:r}=this.getBoundingRect();return s>=t.x&&s+n<=e.x&&i>=t.y&&i+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return yt.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every(s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Ne(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set($t,t),this._set(ce,t),this.setCoords()}scaleToWidth(t){const e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){const e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?je(yo(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||Ut.concat()}calcACoords(){const t=bs({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),i=Vs(e,s),n=St(i,t),r=this._getTransformedDimensions(),a=r.x/2,l=r.y/2;return{tl:Bt({x:-a,y:-l},n),tr:Bt({x:a,y:-l},n),bl:Bt({x:-a,y:l},n),br:Bt({x:a,y:l},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,Pt(this.originX),Pt(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),i=this.matrixCache;return i&&i.key.every((n,r)=>n===s[r])?i.value:(this.group&&(e=St(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),i={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=wo(i);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new A(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=x({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let i=s,n=0;this.strokeUniform&&(i=0,n=s);const r=e.width+i,a=e.height+i;let l;return l=e.skewX===0&&e.skewY===0?new A(r*e.scaleX,a*e.scaleY):tn(r,a,pi(e)),l.scalarAdd(n)}translateToGivenOrigin(t,e,s,i,n){let r=t.x,a=t.y;const l=Pt(i)-Pt(e),h=Pt(n)-Pt(s);if(l||h){const c=this._getTransformedDimensions();r+=l*c.x,a+=h*c.y}return new A(r,a)}translateToCenterPoint(t,e,s){if(e===q&&s===q)return t;const i=this.translateToGivenOrigin(t,e,s,q,q);return this.angle?i.rotate(wt(this.angle),t):i}translateToOriginPoint(t,e,s){const i=this.translateToGivenOrigin(t,q,q,e,s);return this.angle?i.rotate(wt(this.angle),t):i}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?Bt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new A(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const i=this.translateToCenterPoint(t,e,s),n=this.translateToOriginPoint(i,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),ot,ie)}}const yu=["type"],_u=["extraParam"];let qe=class pr extends bu{static getDefaults(){return pr.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){Xe("warn","Setting type has no effect",t)}constructor(t){super(),S(this,"_cacheContext",null),Object.assign(this,pr.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Ie(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,i=nt.maxCacheSideLimit,n=nt.minCacheSideLimit;if(e<=i&&s<=i&&e*s<=nt.perfLimitSizeTotal)return e<n&&(t.width=n),s<n&&(t.height=n),t;const r=e/s,[a,l]=di.limitDimsByArea(r),h=Ss(n,a,i),c=Ss(n,l,i);return e>h&&(t.zoomX/=e/h,t.width=h,t.capped=!0),s>c&&(t.zoomY/=s/c,t.height=c,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,i=e.y*t.y/this.scaleY;return{width:Math.ceil(s+2),height:Math.ceil(i+2),zoomX:t.x,zoomY:t.y,x:s,y:i}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:i,zoomX:n,zoomY:r,x:a,y:l}=this._limitCacheSize(this._getCacheCanvasDimensions()),h=s!==t.width||i!==t.height,c=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;if(h||c){s!==t.width||i!==t.height?(t.width=s,t.height=i):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const u=a/2,d=l/2;return this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-d)+d,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,s=this.calcTransformMatrix(!e);t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}getObjectScaling(){if(!this.group)return new A(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=vs(this.calcTransformMatrix());return new A(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),s=this.getCanvasRetinaScaling();return t.scalarMultiply(e*s)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t===0?1e-4:t}_set(t,e){t!==$t&&t!==ce||(e=this._constrainScale(e)),t===$t&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Ye||(e=new Ye(e));const s=this[t]!==e;return this[t]=e,s&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||s&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n}=this,{width:r,height:a}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:i,cacheTranslationY:n,width:r,height:a,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return this.stroke&&this.stroke!=="transparent"&&this.strokeWidth!==0}hasFill(){return this.fill&&this.fill!=="transparent"}needsItsOwnCache(){return!!(this.paintFirst===qt&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const i=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=i,this.stroke=n}createClipPathLayer(t,e){const s=ue(e),i=s.getContext("2d");if(i.translate(e.cacheTranslationX,e.cacheTranslationY),i.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach(n=>{n.transform(i)}),e.parentClipPaths.push(t),t.absolutePositioned){const n=ne(this.calcTransformMatrix());i.transform(n[0],n[1],n[2],n[3],n[4],n[5])}return t.transform(i),t.drawObject(i,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const i=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,i)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,s=this._cacheContext;return!(!e||!s||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&s&&!t&&(s.save(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),s.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;const e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){const s=e.stroke;s&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,pe(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?this._applyPatternForTransformedGradient(t,s):(t.strokeStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:s}=e;s&&(pe(s)?(t.fillStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.fillStyle=s)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&e.length!==0&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,i=this.getCanvasRetinaScaling(),[n,,,r]=s?.viewportTransform||Ut,a=n*i,l=r*i,h=e.nonScaling?new A(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*nt.browserShadowBlurConstant*(a+l)*(h.x+h.y)/4,t.shadowOffsetX=e.offsetX*a*h.x,t.shadowOffsetY=e.offsetY*l*h.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!pe(e))return{offsetX:0,offsetY:0};const s=e.gradientTransform||e.patternTransform,i=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return e.gradientUnits==="percentage"?t.transform(this.width,0,0,this.height,i,n):t.transform(1,0,0,1,i,n),s&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),{offsetX:i,offsetY:n}}_renderPaintInOrder(t){this.paintFirst===qt?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const i=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=i.x/this.scaleX/n,a=i.y/this.scaleY/n,l=ue({width:Math.ceil(r),height:Math.ceil(a)}),h=l.getContext("2d");h&&(h.beginPath(),h.moveTo(0,0),h.lineTo(r,0),h.lineTo(r,a),h.lineTo(0,a),h.closePath(),h.translate(r/2,a/2),h.scale(i.zoomX/this.scaleX/n,i.zoomY/this.scaleY/n),this._applyPatternGradientTransform(h,e),h.fillStyle=e.toLive(t),h.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/i.zoomX,n*this.scaleY/i.zoomY),t.strokeStyle=(s=h.createPattern(l,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new A(this.left+this.width/2,this.top+this.height/2)}clone(t){const e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){const e=this.toCanvasElement(t);return new(I.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Rr(this),s=this.group,i=this.shadow,n=Math.abs,r=t.enableRetinaScaling?ho():1,a=(t.multiplier||1)*r,l=t.canvasProvider||(b=>new bi(b,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Do(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Fr(this,this.getViewportTransform()),this.setCoords();const h=Ie(),c=this.getBoundingRect(),u=this.shadow,d=new A;if(u){const b=u.blur,_=u.nonScaling?new A(1,1):this.getObjectScaling();d.x=2*Math.round(n(u.offsetX)+b)*n(_.x),d.y=2*Math.round(n(u.offsetY)+b)*n(_.y)}const f=c.width+d.x,g=c.height+d.y;h.width=Math.ceil(f),h.height=Math.ceil(g);const p=l(h);t.format==="jpeg"&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new A(p.width/2,p.height/2),q,q);const v=this.canvas;p._objects=[this],this.set("canvas",p),this.setCoords();const m=p.toCanvasElement(a||1,t);return this.set("canvas",v),this.shadow=i,s&&(this.group=s),this.set(e),this.setCoords(),p._objects=[],p.destroy(),m}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Er(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return kr(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:s,originY:i}=this;if(e){const{x:n,y:r}=this.getRelativeCenterPoint();this.originX=q,this.originY=q,this.left=n,this.top=r}if(this.set("angle",t),e){const{x:n,y:r}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,i);this.left=n,this.top=r,this.originX=s,this.originY=i}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){qi.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Le().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,i)=>{let[n,r]=i;return s[n]=this._animate(n,r,e),s},{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=t.split("."),n=this.constructor.colorProperties.includes(i[i.length-1]),{abort:r,startValue:a,onChange:l,onComplete:h}=s,c=x(x({},s),{},{target:this,startValue:a??i.reduce((u,d)=>u[d],this),endValue:e,abort:r?.bind(this),onChange:(u,d,f)=>{i.reduce((g,p,v)=>(v===i.length-1&&(g[p]=u),g[p]),this),l&&l(u,d,f)},onComplete:(u,d,f)=>{this.setCoords(),h&&h(u,d,f)}});return n?ol(c):qr(c)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let i,n=0;n<e.length;n++){if(i=e[n],i===t)return{fork:[this,...e.slice(0,n)],otherFork:[],common:e.slice(n)};for(let r=0;r<s.length;r++){if(this===s[r])return{fork:[],otherFork:[t,...s.slice(0,r)],common:[this,...e]};if(i===s[r])return{fork:[this,...e.slice(0,n)],otherFork:[t,...s.slice(0,r)],common:e.slice(n)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const i=e.fork.pop(),n=e.otherFork.pop(),r=s._objects.indexOf(i),a=s._objects.indexOf(n);return r>-1&&r>a}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(pr.customProperties,this.constructor.customProperties||[]);let e;const s=nt.NUM_FRACTION_DIGITS,{clipPath:i,fill:n,stroke:r,shadow:a,strokeDashArray:l,left:h,top:c,originX:u,originY:d,width:f,height:g,strokeWidth:p,strokeLineCap:v,strokeDashOffset:m,strokeLineJoin:b,strokeUniform:_,strokeMiterLimit:w,scaleX:C,scaleY:T,angle:E,flipX:k,flipY:O,opacity:H,visible:N,backgroundColor:P,fillRule:R,paintFirst:F,globalCompositeOperation:V,skewX:M,skewY:L}=this;i&&!i.excludeFromExport&&(e=i.toObject(t.concat("inverted","absolutePositioned")));const Y=bt=>ct(bt,s),ft=x(x({},ys(this,t)),{},{type:this.constructor.type,version:yr,originX:u,originY:d,left:Y(h),top:Y(c),width:Y(f),height:Y(g),fill:xo(n)?n.toObject():n,stroke:xo(r)?r.toObject():r,strokeWidth:Y(p),strokeDashArray:l&&l.concat(),strokeLineCap:v,strokeDashOffset:m,strokeLineJoin:b,strokeUniform:_,strokeMiterLimit:Y(w),scaleX:Y(C),scaleY:Y(T),angle:Y(E),flipX:k,flipY:O,opacity:Y(H),shadow:a&&a.toObject(),visible:N,backgroundColor:P,fillRule:R,paintFirst:F,globalCompositeOperation:V,skewX:Y(M),skewY:Y(L)},e?{clipPath:e}:null);return this.includeDefaultValues?ft:this._removeDefaultValues(ft)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Or(t,(i,n)=>{if(n===ot||n===ie||n==="type")return!0;const r=s[n];return i!==r&&!(Array.isArray(i)&&Array.isArray(r)&&i.length===0&&r.length===0)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=pt(t,yu),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:i}=s,n=pt(s,_u);return vi(e,n).then(r=>i?(delete r[i],new this(e[i],r)):new this(r))}static fromObject(t,e){return this._fromObject(t,e)}};S(qe,"stateProperties",ou),S(qe,"cacheProperties",$e),S(qe,"ownDefaults",lu),S(qe,"type","FabricObject"),S(qe,"colorProperties",[kt,qt,"backgroundColor"]),S(qe,"customProperties",[]),I.setClass(qe),I.setClass(qe,"object");const Ys=(o,t,e)=>(s,i,n,r)=>{const a=t(s,i,n,r);return a&&Fo(o,x(x({},jo(s,i,n,r)),e)),a};function $s(o){return(t,e,s,i)=>{const{target:n,originX:r,originY:a}=e,l=n.getRelativeCenterPoint(),h=n.translateToOriginPoint(l,r,a),c=o(t,e,s,i);return n.setPositionByOrigin(h,e.originX,e.originY),c}}const ll=Ys(fi,$s((o,t,e,s)=>{const i=Lr(t,t.originX,t.originY,e,s);if(Pt(t.originX)===Pt(q)||Pt(t.originX)===Pt(xt)&&i.x<0||Pt(t.originX)===Pt(ot)&&i.x>0){const{target:n}=t,r=n.strokeWidth/(n.strokeUniform?n.scaleX:1),a=Lo(t)?2:1,l=n.width,h=Math.abs(i.x*a/n.scaleX)-r;return n.set("width",Math.max(h,1)),l!==n.width}return!1}));function wu(o,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,l=a?qt:kt,h=!a&&(s.cornerStrokeColor||i.cornerStrokeColor);let c,u=t,d=e;o.save(),o.fillStyle=s.cornerColor||i.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",n>r?(c=n,o.scale(1,r/n),d=e*n/r):r>n?(c=r,o.scale(n/r,1),u=t*r/n):c=n,o.beginPath(),o.arc(u,d,c/2,0,Ue,!1),o[l](),h&&o.stroke(),o.restore()}function xu(o,t,e,s,i){s=s||{};const n=this.sizeX||s.cornerSize||i.cornerSize,r=this.sizeY||s.cornerSize||i.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:i.transparentCorners,l=a?qt:kt,h=!a&&(s.cornerStrokeColor||i.cornerStrokeColor),c=n/2,u=r/2;o.save(),o.fillStyle=s.cornerColor||i.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||i.cornerStrokeColor||"",o.translate(t,e);const d=i.getTotalAngle();o.rotate(wt(d)),o["".concat(l,"Rect")](-c,-u,n,r),h&&o.strokeRect(-c,-u,n,r),o.restore()}class Ee{constructor(t){S(this,"visible",!0),S(this,"actionName",Yi),S(this,"angle",0),S(this,"x",0),S(this,"y",0),S(this,"offsetX",0),S(this,"offsetY",0),S(this,"sizeX",0),S(this,"sizeY",0),S(this,"touchSizeX",0),S(this,"touchSizeY",0),S(this,"cursorStyle","crosshair"),S(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,i){var n;let{tl:r,tr:a,br:l,bl:h}=i;return((n=e.canvas)===null||n===void 0?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&yt.isPointInPolygon(s,[r,a,l,h])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,i;return(s=(i=t._controlsVisibility)===null||i===void 0?void 0:i[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,i){return new A(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,i,n,r){const a=Ji([Vs(s,i),bs({angle:t}),Qi((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new A(-.5,-.5).transform(a),tr:new A(.5,-.5).transform(a),br:new A(.5,.5).transform(a),bl:new A(-.5,.5).transform(a)}}render(t,e,s,i,n){((i=i||{}).cornerStyle||n.cornerStyle)==="circle"?wu.call(this,t,e,s,i,n):xu.call(this,t,e,s,i,n)}}const Su=(o,t,e)=>e.lockRotation?en:t.cursorStyle,Cu=Ys(uo,$s((o,t,e,s)=>{let{target:i,ex:n,ey:r,theta:a,originX:l,originY:h}=t;const c=i.translateToOriginPoint(i.getRelativeCenterPoint(),l,h);if(Ae(i,"lockRotation"))return!1;const u=Math.atan2(r-c.y,n-c.x),d=Math.atan2(s-c.y,e-c.x);let f=je(d-u+a);if(i.snapAngle&&i.snapAngle>0){const p=i.snapAngle,v=i.snapThreshold||p,m=Math.ceil(f/p)*p,b=Math.floor(f/p)*p;Math.abs(f-b)<v?f=b:Math.abs(f-m)<v&&(f=m)}f<0&&(f=360+f),f%=360;const g=i.angle!==f;return i.angle=f,g}));function hl(o,t){const e=t.canvas,s=o[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function cl(o,t,e){const s=Ae(o,"lockScalingX"),i=Ae(o,"lockScalingY");if(s&&i||!t&&(s||i)&&e||s&&t==="x"||i&&t==="y")return!0;const{width:n,height:r,strokeWidth:a}=o;return n===0&&a===0&&t!=="y"||r===0&&a===0&&t!=="x"}const Au=["e","se","s","sw","w","nw","n","ne","e"],Si=(o,t,e)=>{const s=hl(o,e);if(cl(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return en;const i=No(e,t);return"".concat(Au[i],"-resize")};function Kr(o,t,e,s){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const n=t.target,r=i.by,a=hl(o,n);let l,h,c,u,d,f;if(cl(n,r,a))return!1;if(t.gestureScale)h=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(l=Lr(t,t.originX,t.originY,e,s),d=r!=="y"?Math.sign(l.x||t.signX||1):1,f=r!=="x"?Math.sign(l.y||t.signY||1):1,t.signX||(t.signX=d),t.signY||(t.signY=f),Ae(n,"lockScalingFlip")&&(t.signX!==d||t.signY!==f))return!1;if(u=n._getTransformedDimensions(),a&&!r){const v=Math.abs(l.x)+Math.abs(l.y),{original:m}=t,b=v/(Math.abs(u.x*m.scaleX/n.scaleX)+Math.abs(u.y*m.scaleY/n.scaleY));h=m.scaleX*b,c=m.scaleY*b}else h=Math.abs(l.x*n.scaleX/u.x),c=Math.abs(l.y*n.scaleY/u.y);Lo(t)&&(h*=2,c*=2),t.signX!==d&&r!=="y"&&(t.originX=Io(t.originX),h*=-1,t.signX=d),t.signY!==f&&r!=="x"&&(t.originY=Io(t.originY),c*=-1,t.signY=f)}const g=n.scaleX,p=n.scaleY;return r?(r==="x"&&n.set($t,h),r==="y"&&n.set(ce,c)):(!Ae(n,"lockScalingX")&&n.set($t,h),!Ae(n,"lockScalingY")&&n.set(ce,c)),g!==n.scaleX||p!==n.scaleY}const cn=Ys(Xi,$s((o,t,e,s)=>Kr(o,t,e,s))),Tu=Ys(Xi,$s((o,t,e,s)=>Kr(o,t,e,s,{by:"x"}))),Eu=Ys(Xi,$s((o,t,e,s)=>Kr(o,t,e,s,{by:"y"}))),ku=["target","ex","ey","skewingSide"],Jr={x:{counterAxis:"y",scale:$t,skew:Bs,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:ce,skew:Hs,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Pu=["ns","nesw","ew","nwse"],Mu=(o,t,e)=>{if(t.x!==0&&Ae(e,"lockSkewingY")||t.y!==0&&Ae(e,"lockSkewingX"))return en;const s=No(e,t)%4;return"".concat(Pu[s],"-resize")};function ul(o,t,e,s,i){const{target:n}=e,{counterAxis:r,origin:a,lockSkewing:l,skew:h,flip:c}=Jr[o];if(Ae(n,l))return!1;const{origin:u,flip:d}=Jr[r],f=Pt(e[u])*(n[d]?-1:1),g=-Math.sign(f)*(n[c]?-1:1),p=.5*-((n[h]===0&&Lr(e,q,q,s,i)[o]>0||n[h]>0?1:-1)*g)+.5;return Ys(fo,$s((m,b,_,w)=>function(C,T,E){let{target:k,ex:O,ey:H,skewingSide:N}=T,P=pt(T,ku);const{skew:R}=Jr[C],F=E.subtract(new A(O,H)).divide(new A(k.scaleX,k.scaleY))[C],V=k[R],M=P[R],L=Math.tan(wt(M)),Y=C==="y"?k._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:k._getTransformedDimensions({scaleX:1,scaleY:1}).y,ft=2*F*N/Math.max(Y,1)+L,bt=je(Math.atan(ft));k.set(R,bt);const _t=V!==k[R];if(_t&&C==="y"){const{skewX:gt,scaleX:rt}=k,Dt=k._getTransformedDimensions({skewY:V}),ee=k._getTransformedDimensions(),K=gt!==0?Dt.x/ee.x:1;K!==1&&k.set($t,K*rt)}return _t}(o,b,new A(_,w))))(t,x(x({},e),{},{[a]:p,skewingSide:g}),s,i)}const Ou=(o,t,e,s)=>ul("x",o,t,e,s),Du=(o,t,e,s)=>ul("y",o,t,e,s);function un(o,t){return o[t.canvas.altActionKey]}const dn=(o,t,e)=>{const s=un(o,e);return t.x===0?s?Bs:ce:t.y===0?s?Hs:$t:""},qs=(o,t,e)=>un(o,e)?Mu(0,t,e):Si(o,t,e),dl=(o,t,e,s)=>un(o,t.target)?Du(o,t,e,s):Tu(o,t,e,s),fl=(o,t,e,s)=>un(o,t.target)?Ou(o,t,e,s):Eu(o,t,e,s),gl=()=>({ml:new Ee({x:-.5,y:0,cursorStyleHandler:qs,actionHandler:dl,getActionName:dn}),mr:new Ee({x:.5,y:0,cursorStyleHandler:qs,actionHandler:dl,getActionName:dn}),mb:new Ee({x:0,y:.5,cursorStyleHandler:qs,actionHandler:fl,getActionName:dn}),mt:new Ee({x:0,y:-.5,cursorStyleHandler:qs,actionHandler:fl,getActionName:dn}),tl:new Ee({x:-.5,y:-.5,cursorStyleHandler:Si,actionHandler:cn}),tr:new Ee({x:.5,y:-.5,cursorStyleHandler:Si,actionHandler:cn}),bl:new Ee({x:-.5,y:.5,cursorStyleHandler:Si,actionHandler:cn}),br:new Ee({x:.5,y:.5,cursorStyleHandler:Si,actionHandler:cn}),mtr:new Ee({x:0,y:-.5,actionHandler:Cu,cursorStyleHandler:Su,offsetY:-40,withConnection:!0,actionName:Cr})}),Ru=()=>({mr:new Ee({x:.5,y:0,actionHandler:ll,cursorStyleHandler:qs,actionName:fi}),ml:new Ee({x:-.5,y:0,actionHandler:ll,cursorStyleHandler:qs,actionName:fi})}),Fu=()=>x(x({},gl()),Ru());class Ci extends qe{static getDefaults(){return x(x({},super.getDefaults()),Ci.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),Ci.ownDefaults),this.setOptions(t)}static createControls(){return{controls:gl()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,s=e.target,i=e.action;if(this===s&&i&&i.startsWith(Yi))return!1}return super._updateCacheCanvas()}getActiveControl(){const t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const s=Object.entries(this.oCoords);for(let i=s.length-1;i>=0;i--){const[n,r]=s[i],a=this.controls[n];if(a.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:a,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=Vs(e.x,e.y),i=bs({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=St(s,i),r=St(t,n),a=St(r,[1/t[0],0,0,1/t[3],0,0]),l=this.group?vs(this.calcTransformMatrix()):void 0;l&&(l.scaleX=Math.abs(l.scaleX),l.scaleY=Math.abs(l.scaleY));const h=this._calculateCurrentDimensions(l),c={};return this.forEachControl((u,d)=>{const f=u.positionHandler(h,a,this,u);c[d]=Object.assign(f,this._calcCornerCoords(u,f))}),c}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),i=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/i[0],1/i[3]),t.rotate(wt(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const i=x({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=i.borderColor,this._setLineDash(t,i.borderDashArray),this.strokeBorders(t,e),i.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:i}=this,n=x({hasBorders:s,hasControls:i},e),r=this.getViewportTransform(),a=n.hasBorders,l=n.hasControls,h=St(r,this.calcTransformMatrix()),c=vs(h);t.save(),t.translate(c.translateX,c.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180),t.rotate(wt(this.group?c.angle:this.angle)),a&&this.drawBorders(t,c,e),l&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let i;if(s&&s.forActiveSelection||this.group){const n=tn(this.width,this.height,pi(e)),r=this.isStrokeAccountedForInDimensions()?Tr:(this.strokeUniform?new A().scalarAdd(this.canvas?this.canvas.getZoom():1):new A(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);i=n.add(r).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else i=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,i,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl((i,n)=>{i.withConnection&&i.getVisibility(this,n)&&(s=!0,t.moveTo(i.x*e.x,i.y*e.y),t.lineTo(i.x*e.x+i.offsetX,i.y*e.y+i.offsetY))}),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:i,cornerDashArray:n,cornerColor:r}=this,a=x({cornerStrokeColor:i,cornerDashArray:n,cornerColor:r},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=a.cornerColor,this.transparentCorners||(t.strokeStyle=a.cornerStrokeColor),this._setLineDash(t,a.cornerDashArray),this.forEachControl((l,h)=>{if(l.getVisibility(this,h)){const c=this.oCoords[h];l.render(t,c.x,c.y,a,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,i]=e;return this.setControlVisible(s,i)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const i=this.width+4,n=this.height+4;return e.clearRect(-i/2,-n/2,i,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}}function pl(o,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(o.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),o}S(Ci,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class Ht extends Ci{}pl(Ht,[Go]),I.setClass(Ht),I.setClass(Ht,"object");const ml=(o,t,e,s)=>{const i=2*(s=Math.round(s))+1,{data:n}=o.getImageData(t-s,e-s,i,i);for(let r=3;r<n.length;r+=4)if(n[r]>0)return!1;return!0};class vl{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new A(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new A(1/this.options.scaleX,1/this.options.scaleY):new A(1,1)}createSideVector(t,e){const s=an(t,e);return this.options.strokeUniform?s.multiply(this.scale):s}projectOrthogonally(t,e,s){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,s)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(t){const e=new A(t);return e.y+=e.x*Math.tan(wt(this.options.skewY)),e.x+=e.y*Math.tan(wt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const Lu=new A;class Ks extends vl{static getOrthogonalRotationFactor(t,e){const s=e?ln(t,e):tl(t);return Math.abs(s)<is?-1:1}constructor(t,e,s,i){super(i),S(this,"AB",void 0),S(this,"AC",void 0),S(this,"alpha",void 0),S(this,"bisector",void 0),this.A=new A(t),this.B=new A(e),this.C=new A(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=ln(this.AB,this.AC),this.bisector=hn(Vr(this.AB.eq(Lu)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e),n=Gr(i),r=Ks.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,s*r)}projectBevel(){const t=[];return(this.alpha%Ue==0?[this.B]:[this.B,this.C]).forEach(e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))}),t}projectMiter(){const t=[],e=Math.abs(this.alpha),s=1/Math.sin(e/2),i=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*s),n=this.options.strokeUniform?on(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return on(i)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(i))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],i=new A(Ks.getOrthogonalRotationFactor(this.bisector),Ks.getOrthogonalRotationFactor(new A(this.bisector.y,this.bisector.x)));return[new A(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i),new A(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(i)].forEach(n=>{Wr(n,t,e)&&s.push(this.A.add(n))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:i,skewY:n,scaleX:r,scaleY:a,strokeUniform:l}=this.options,h=new A(Math.tan(wt(i)),Math.tan(wt(n))),c=this.strokeProjectionMagnitude,u=l?c/a/Math.sqrt(1/a**2+1/r**2*h.y**2):c/Math.sqrt(1+h.y**2),d=new A(Math.sqrt(Math.max(c**2-u**2,0)),u),f=l?c/Math.sqrt(1+h.x**2*(1/a)**2/(1/r+1/r*h.x*h.y)**2):c/Math.sqrt(1+h.x**2/(1+h.x*h.y)**2),g=new A(f,Math.sqrt(Math.max(c**2-f**2,0)));return[g,g.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(p=>this.applySkew(l?p.multiply(this.strokeUniformScalar):p)).forEach(p=>{Wr(p,t,e)&&s.push(this.applySkew(this.A).add(p))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Ue==0,s=this.applySkew(this.A),i=t[e?0:2].subtract(s),n=t[e?1:0].subtract(s),r=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),a=Us(i,r)>0,l=a?i:n,h=a?n:i;return this.isSkewed()?t.push(...this.projectRoundWithSkew(l,h)):t.push(...this.projectRoundNoSkew(l,h)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class bl extends vl{constructor(t,e,s){super(s),this.A=new A(t),this.T=new A(e)}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const i=this.createSideVector(t,e);return this.scaleUnitVector(Gr(i),s)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){const t=[];if(!this.isSkewed()&&this.A.eq(this.T)){const e=new A(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.applySkew(this.A.add(e)),this.applySkew(this.A.subtract(e)))}else t.push(...new Ks(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new A(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{const e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),s=this.scaleUnitVector(hn(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),i=this.A.add(s);t.push(i.add(e),i.subtract(e))}return t.map(e=>this.applySkew(e))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}const yl=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(o.length===0)return s;const i=o.reduce((n,r)=>(n[n.length-1].eq(r)||n.push(new A(r)),n),[new A(o[0])]);if(i.length===1)e=!0;else if(!e){const n=i[0],r=((a,l)=>{for(let h=a.length-1;h>=0;h--)if(l(a[h],h,a))return h;return-1})(i,a=>!a.eq(n));i.splice(r+1)}return i.forEach((n,r,a)=>{let l,h;r===0?(h=a[1],l=e?n:a[a.length-1]):r===a.length-1?(l=a[r-1],h=e?n:a[0]):(l=a[r-1],h=a[r+1]),e&&a.length===1?s.push(...new bl(n,n,t).project()):!e||r!==0&&r!==a.length-1?s.push(...new Ks(n,l,h,t).project()):s.push(...new bl(n,r===0?h:l,t).project())}),s},Qr=o=>{const t={};return Object.keys(o).forEach(e=>{t[e]={},Object.keys(o[e]).forEach(s=>{t[e][s]=x({},o[e][s])})}),t},_l=o=>o.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<").replace(/>/g,">");let Ai;const fn=o=>{if(Ai||Ai||(Ai="Intl"in ui()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),Ai){const t=Ai.segment(o);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return Iu(o)},Iu=o=>{const t=[];for(let e,s=0;s<o.length;s++)(e=ju(o,s))!==!1&&t.push(e);return t},ju=(o,t)=>{const e=o.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return o.charAt(t);if(55296<=e&&e<=56319){if(o.length<=t+1)throw"High surrogate without following low surrogate";const i=o.charCodeAt(t+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return o.charAt(t)+o.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=o.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var Nu=Object.freeze({__proto__:null,capitalize:function(o){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return"".concat(o.charAt(0).toUpperCase()).concat(t?o.slice(1):o.slice(1).toLowerCase())},escapeXml:_l,graphemeSplit:fn});const gn=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return o.fill!==t.fill||o.stroke!==t.stroke||o.strokeWidth!==t.strokeWidth||o.fontSize!==t.fontSize||o.fontFamily!==t.fontFamily||o.fontWeight!==t.fontWeight||o.fontStyle!==t.fontStyle||o.textDecorationThickness!==t.textDecorationThickness||o.textBackgroundColor!==t.textBackgroundColor||o.deltaY!==t.deltaY||e&&(o.overline!==t.overline||o.underline!==t.underline||o.linethrough!==t.linethrough)},wl=(o,t)=>{const e=t.split(`
|
|
67
|
+
`),s=[];let i=-1,n={};o=Qr(o);for(let r=0;r<e.length;r++){const a=fn(e[r]);if(o[r])for(let l=0;l<a.length;l++){i++;const h=o[r][l];h&&Object.keys(h).length>0&&(gn(n,h,!0)?s.push({start:i,end:i+1,style:h}):s[s.length-1].end++),n=h||{}}else i+=a.length,n={}}return s},xl=(o,t)=>{if(!Array.isArray(o))return Qr(o);const e=t.split(Sr),s={};let i=-1,n=0;for(let r=0;r<e.length;r++){const a=fn(e[r]);for(let l=0;l<a.length;l++)i++,o[n]&&o[n].start<=i&&i<o[n].end&&(s[r]=s[r]||{},s[r][l]=x({},o[n].style),i===o[n].end-1&&n++)}return s},as=["display","transform",kt,"fill-opacity","fill-rule","opacity",qt,"stroke-dasharray","stroke-linecap","stroke-dashoffset","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","id","paint-order","vector-effect","instantiated_by_use","clip-path"];function Sl(o,t){const e=o.nodeName,s=o.getAttribute("class"),i=o.getAttribute("id"),n="(?![a-zA-Z\\-]+)";let r;if(r=new RegExp("^"+e,"i"),t=t.replace(r,""),i&&t.length&&(r=new RegExp("#"+i+n,"i"),t=t.replace(r,"")),s&&t.length){const a=s.split(" ");for(let l=a.length;l--;)r=new RegExp("\\."+a[l]+n,"i"),t=t.replace(r,"")}return t.length===0}function Bu(o,t){let e=!0;const s=Sl(o,t.pop());return s&&t.length&&(e=function(i,n){let r,a=!0;for(;i.parentElement&&i.parentElement.nodeType===1&&n.length;)a&&(r=n.pop()),a=Sl(i=i.parentElement,r);return n.length===0}(o,t)),s&&e&&t.length===0}const Hu=o=>{var t;return(t=iu[o])!==null&&t!==void 0?t:o},zu=new RegExp("(".concat(Te,")"),"gi"),Vu=o=>o.replace(zu," $1 ").replace(/,/gi," ").replace(/\s+/gi," ");var Cl,Al,Tl,El,kl,Pl,Ml;const Jt="(".concat(Te,")"),Gu=String.raw(Cl||(Cl=Re(["(skewX)(",")"],["(skewX)\\(","\\)"])),Jt),Wu=String.raw(Al||(Al=Re(["(skewY)(",")"],["(skewY)\\(","\\)"])),Jt),Xu=String.raw(Tl||(Tl=Re(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),Jt,Jt,Jt),Uu=String.raw(El||(El=Re(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),Jt,Jt),Yu=String.raw(kl||(kl=Re(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),Jt,Jt),$u=String.raw(Pl||(Pl=Re(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),Jt,Jt,Jt,Jt,Jt,Jt),Zr="(?:".concat($u,"|").concat(Yu,"|").concat(Xu,"|").concat(Uu,"|").concat(Gu,"|").concat(Wu,")"),qu="(?:".concat(Zr,"*)"),Ku=String.raw(Ml||(Ml=Re(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),qu),Ju=new RegExp(Ku),Qu=new RegExp(Zr),Zu=new RegExp(Zr,"g");function pn(o){const t=[];if(!(o=Vu(o).replace(/\s*([()])\s*/gi,"$1"))||o&&!Ju.test(o))return[...Ut];for(const e of o.matchAll(Zu)){const s=Qu.exec(e[0]);if(!s)continue;let i=Ut;const n=s.filter(g=>!!g),[,r,...a]=n,[l,h,c,u,d,f]=a.map(g=>parseFloat(g));switch(r){case"translate":i=Vs(l,h);break;case Cr:i=bs({angle:l},{x:h,y:c});break;case Yi:i=Qi(l,h);break;case Bs:i=Pr(l);break;case Hs:i=Mr(l);break;case"matrix":i=[l,h,c,u,d,f]}t.push(i)}return Ji(t)}function td(o,t,e,s){const i=Array.isArray(t);let n,r=t;if(o!==kt&&o!==qt||t!==Yt){if(o==="strokeUniform")return t==="non-scaling-stroke";if(o==="strokeDashArray")r=t===Yt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(o==="transformMatrix")r=e&&e.transformMatrix?St(e.transformMatrix,pn(t)):pn(t);else if(o==="visible")r=t!==Yt&&t!=="hidden",e&&e.visible===!1&&(r=!1);else if(o==="opacity")r=parseFloat(t),e&&e.opacity!==void 0&&(r*=e.opacity);else if(o==="textAnchor")r=t==="start"?ot:t==="end"?xt:q;else if(o==="charSpacing"||o===xs)n=Kt(t,s)/s*1e3;else if(o==="paintFirst"){const a=t.indexOf(kt),l=t.indexOf(qt);r=kt,(a>-1&&l>-1&&l<a||a===-1&&l>-1)&&(r=qt)}else{if(o==="href"||o==="xlink:href"||o==="font"||o==="id")return t;if(o==="imageSmoothing")return t==="optimizeQuality";n=i?t.map(Kt):Kt(t,s)}}else r="";return!i&&isNaN(n)?r:n}function ed(o,t){const e=o.match(su);if(!e)return;const s=e[1],i=e[3],n=e[4],r=e[5],a=e[6];s&&(t.fontStyle=s),i&&(t.fontWeight=isNaN(parseFloat(i))?i:parseFloat(i)),n&&(t.fontSize=Kt(n)),a&&(t.fontFamily=a),r&&(t.lineHeight=r==="normal"?1:r)}function ta(o,t){o.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,i]=e.split(":");t[s.trim().toLowerCase()]=i.trim()})}function sd(o){const t={},e=o.getAttribute("style");return e&&(typeof e=="string"?ta(e,t):function(s,i){Object.entries(s).forEach(n=>{let[r,a]=n;a!==void 0&&(i[r.toLowerCase()]=a)})}(e,t)),t}const id={stroke:"strokeOpacity",fill:"fillOpacity"};function Ke(o,t,e){if(!o)return{};let s,i={},n=wr;o.parentNode&&Jo.test(o.parentNode.nodeName)&&(i=Ke(o.parentElement,t,e),i.fontSize&&(s=n=Kt(i.fontSize)));const r=x(x(x({},t.reduce((h,c)=>{const u=o.getAttribute(c);return u&&(h[c]=u),h},{})),function(h){let c=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const d in c)Bu(h,d.split(" "))&&(u=x(x({},u),c[d]));return u}(o,e)),sd(o));r[zr]&&o.setAttribute(zr,r[zr]),r[Hr]&&(s=Kt(r[Hr],n),r[Hr]="".concat(s));const a={};for(const h in r){const c=Hu(h),u=td(c,r[h],i,s);a[c]=u}a&&a.font&&ed(a.font,a);const l=x(x({},i),a);return Jo.test(o.nodeName)?l:function(h){const c=Ht.getDefaults();return Object.entries(id).forEach(u=>{let[d,f]=u;if(h[f]===void 0||h[d]==="")return;if(h[d]===void 0){if(!c[d])return;h[d]=c[d]}if(h[d].indexOf("url(")===0)return;const g=new ht(h[d]);h[d]=g.setAlpha(ct(g.getAlpha()*h[f],2)).toRgba()}),h}(l)}const nd=["left","top","width","height","visible"],Ol=["rx","ry"];class He extends Ht{static getDefaults(){return x(x({},super.getDefaults()),He.ownDefaults)}constructor(t){super(),Object.assign(this,He.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){const{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){const{width:e,height:s}=this,i=-e/2,n=-s/2,r=this.rx?Math.min(this.rx,e/2):0,a=this.ry?Math.min(this.ry,s/2):0,l=r!==0||a!==0;t.beginPath(),t.moveTo(i+r,n),t.lineTo(i+e-r,n),l&&t.bezierCurveTo(i+e-ns*r,n,i+e,n+ns*a,i+e,n+a),t.lineTo(i+e,n+s-a),l&&t.bezierCurveTo(i+e,n+s-ns*a,i+e-ns*r,n+s,i+e-r,n+s),t.lineTo(i+r,n+s),l&&t.bezierCurveTo(i+ns*r,n+s,i,n+s-ns*a,i,n+s-a),t.lineTo(i,n+a),l&&t.bezierCurveTo(i,n+ns*a,i+ns*r,n,i+r,n),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Ol,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:i}=this;return["<rect ","COMMON_PARTS",'x="'.concat(-t/2,'" y="').concat(-e/2,'" rx="').concat(s,'" ry="').concat(i,'" width="').concat(t,'" height="').concat(e,`" />
|
|
68
|
+
`)]}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,width:a=0,height:l=0,visible:h=!0}=i,c=pt(i,nd);return new this(x(x(x({},e),c),{},{left:n,top:r,width:a,height:l,visible:!!(h&&a&&l)}))}}S(He,"type","Rect"),S(He,"cacheProperties",[...$e,...Ol]),S(He,"ownDefaults",{rx:0,ry:0}),S(He,"ATTRIBUTE_NAMES",[...as,"x","y","rx","ry","width","height"]),I.setClass(He),I.setSVGClass(He);const Je="initialization",mn="added",ea="removed",vn="imperative",Dl=(o,t)=>{const{strokeUniform:e,strokeWidth:s,width:i,height:n,group:r}=t,a=r&&r!==o?yi(r.calcTransformMatrix(),o.calcTransformMatrix()):null,l=a?t.getRelativeCenterPoint().transform(a):t.getRelativeCenterPoint(),h=!t.isStrokeAccountedForInDimensions(),c=e&&h?Ro(new A(s,s),void 0,o.calcTransformMatrix()):Tr,u=!e&&h?s:0,d=tn(i+u,n+u,Ji([a,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[l.subtract(d),l.add(d)]};class bn{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:i}=t;return e===Je||e===vn||!!s&&i!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Je&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:i}=e;if(s===vn&&e.overrides)return e.overrides;if(t.length===0)return;const{left:n,top:r,width:a,height:l}=Ne(t.map(u=>Dl(i,u)).reduce((u,d)=>u.concat(d),[])),h=new A(a,l),c=new A(n,r).add(h.scalarDivide(2));if(s===Je){const u=this.getInitialSize(e,{size:h,center:c});return{center:c,relativeCorrection:new A(0,0),size:u}}return{center:c.transform(i.calcOwnMatrix()),size:h}}}S(bn,"type","strategy");class sa extends bn{shouldPerformLayout(t){return!0}}S(sa,"type","fit-content"),I.setClass(sa);const rd=["strategy"],ad=["target","strategy","bubbles","prevStrategy"],Rl="layoutManager";class Ti{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new sa;S(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=x(x({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[$i,co,fi,uo,Xi,fo,Ui,Xc,Uc].map(i=>t.on(i,n=>this.performLayout(i===$i?{type:"object_modified",trigger:i,e:n,target:s}:{type:"object_modifying",trigger:i,e:n,target:s})))}subscribe(t,e){this.unsubscribe(t,e);const s=this.attachHandlers(t,e);this._subscriptions.set(t,s)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(s=>s()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){const{target:e,type:s}=t,{canvas:i}=e;if(s===Je||s===mn?this.subscribeTargets(t):s===ea&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),i&&i.fire("object:layout:before",{target:e,context:t}),s===vn&&t.deep){const n=pt(t,rd);e.forEachObject(r=>r.layoutManager&&r.layoutManager.performLayout(x(x({},n),{},{bubbles:!1,target:r})))}}getLayoutResult(t){const{target:e,strategy:s,type:i}=t,n=s.calcLayoutResult(t,e.getObjects());if(!n)return;const r=i===Je?new A:e.getRelativeCenterPoint(),{center:a,correction:l=new A,relativeCorrection:h=new A}=n,c=r.subtract(a).add(l).transform(i===Je?Ut:ne(e.calcOwnMatrix()),!0).add(h);return{result:n,prevCenter:r,nextCenter:a,offset:c}}commitLayout(t,e){const{target:s}=t,{result:{size:i},nextCenter:n}=e;var r,a;s.set({width:i.x,height:i.y}),this.layoutObjects(t,e),t.type===Je?s.set({left:(r=t.x)!==null&&r!==void 0?r:n.x+i.x*Pt(s.originX),top:(a=t.y)!==null&&a!==void 0?a:n.y+i.y*Pt(s.originY)}):(s.setPositionByOrigin(n,q,q),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject(i=>{i.group===s&&this.layoutObject(t,e,i)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:i}=e;s.set({left:s.left+i.x,top:s.top+i.y})}onAfterLayout(t,e){const{target:s,strategy:i,bubbles:n,prevStrategy:r}=t,a=pt(t,ad),{canvas:l}=s;s.fire("layout:after",{context:t,result:e}),l&&l.fire("object:layout:after",{context:t,result:e,target:s});const h=s.parent;n&&h!=null&&h.layoutManager&&((a.path||(a.path=[])).push(s),h.layoutManager.performLayout(x(x({},a),{},{target:h}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Rl,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}I.setClass(Ti,Rl);const od=["type","objects","layoutManager"];class ld extends Ti{performLayout(){}}class me extends go(Ht){static getDefaults(){return x(x({},super.getDefaults()),me.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),S(this,"_activeObjects",[]),S(this,"__objectSelectionTracker",void 0),S(this,"__objectSelectionDisposer",void 0),Object.assign(this,me.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var s;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(i=>{this.enterGroup(i,!1)}),this.layoutManager=(s=e.layoutManager)!==null&&s!==void 0?s:new Ti,this.layoutManager.performLayout({type:Je,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(Xe("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(Xe("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((e,s,i)=>this.canEnterGroup(e)&&i.indexOf(e)===s)}add(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];const i=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...i);return this._onAfterObjectsChange(mn,i),n}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),i=1;i<e;i++)s[i-1]=arguments[i];const n=this._filterObjectsBeforeEnteringGroup(s),r=super.insertAt(t,...n);return this._onAfterObjectsChange(mn,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(ea,t),t}_onObjectAdded(t){this.enterGroup(t,!0),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t,e){this.exitGroup(t,e),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onAfterObjectsChange(t,e){this.layoutManager.performLayout({type:t,targets:e,target:this})}_onStackOrderChanged(){this._set("dirty",!0)}_set(t,e){const s=this[t];return super._set(t,e),t==="canvas"&&s!==e&&(this._objects||[]).forEach(i=>{i._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:s}=e;const i=this._activeObjects;if(t)i.push(s),this._set("dirty",!0);else if(i.length>0){const n=i.indexOf(s);n>-1&&(i.splice(n,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&Xs(t,St(ne(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const s=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();s&&(s===t||t.isDescendantOf(s))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(Xs(t,St(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=Ht.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let n=0;n<this._objects.length;n++){var i;const r=this._objects[n];(i=this.canvas)!==null&&i!==void 0&&i.preserveObjectStacking&&r.group!==this?(t.save(),t.transform(...ne(this.calcTransformMatrix())),r.render(t),t.restore()):r.group===this&&r.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(x({target:this,type:vn},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter(function(i){return!i.excludeFromExport}).map(function(i){const n=i.includeDefaultValues;i.includeDefaultValues=s;const r=i[t||"toObject"](e);return i.includeDefaultValues=n,r})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return x(x(x({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=He.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const i=e.join("");return t?t(i):i}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
|
|
69
69
|
`],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toSVG(t));return e.push(`</g>
|
|
70
|
-
`),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:i=[],layoutManager:n}=t,r=Lt(t,Nw);return Promise.all([po(i,e),Kh(r,e)]).then(a=>{let[h,c]=a;const u=new this(h,T(T(T({},r),c),{},{layoutManager:new Bw}));if(n){const d=W.getClass(n.type),f=W.getClass(n.strategy);u.layoutManager=new d(new f)}else u.layoutManager=new sl;return u.layoutManager.subscribeTargets({type:tn,target:u,targets:u.getObjects()}),u.setCoords(),u})}}E(Ls,"type","Group"),E(Ls,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),W.setClass(Ls);const z0=(o,t)=>Math.min(t.width/o.width,t.height/o.height),V0=(o,t)=>Math.max(t.width/o.width,t.height/o.height),dg="\\s*,?\\s*",il="".concat(dg,"(").concat(ti,")"),Hw="".concat(il).concat(il).concat(il).concat(dg,"([01])").concat(dg,"([01])").concat(il).concat(il),zw={m:"l",M:"L"},Vw=(o,t,e,s,i,n,r,a,h,c,u)=>{const d=Ks(o),f=Js(o),g=Ks(t),p=Js(t),m=e*i*g-s*n*p+r,y=s*i*g+e*n*p+a;return["C",c+h*(-e*i*f-s*n*d),u+h*(-s*i*f+e*n*d),m+h*(e*i*p+s*n*g),y+h*(s*i*p-e*n*g),m,y]},W0=(o,t,e,s)=>{const i=Math.atan2(t,o),n=Math.atan2(s,e);return n>=i?n-i:2*Math.PI-(i-n)};function fg(o,t,e,s,i,n,r,a){let h;if(bt.cachesBoundsOfCurve&&(h=[...arguments].join(),Xh.boundsOfCurveCache[h]))return Xh.boundsOfCurveCache[h];const c=Math.sqrt,u=Math.abs,d=[],f=[[0,0],[0,0]];let g=6*o-12*e+6*i,p=-3*o+9*e-9*i+3*r,m=3*e-3*o;for(let C=0;C<2;++C){if(C>0&&(g=6*t-12*s+6*n,p=-3*t+9*s-9*n+3*a,m=3*s-3*t),u(p)<1e-12){if(u(g)<1e-12)continue;const R=-m/g;0<R&&R<1&&d.push(R);continue}const k=g*g-4*m*p;if(k<0)continue;const O=c(k),P=(-g+O)/(2*p);0<P&&P<1&&d.push(P);const D=(-g-O)/(2*p);0<D&&D<1&&d.push(D)}let y=d.length;const b=y,x=X0(o,t,e,s,i,n,r,a);for(;y--;){const{x:C,y:k}=x(d[y]);f[0][y]=C,f[1][y]=k}f[0][b]=o,f[1][b]=t,f[0][b+1]=r,f[1][b+1]=a;const S=[new M(Math.min(...f[0]),Math.min(...f[1])),new M(Math.max(...f[0]),Math.max(...f[1]))];return bt.cachesBoundsOfCurve&&(Xh.boundsOfCurveCache[h]=S),S}const Ww=(o,t,e)=>{let[s,i,n,r,a,h,c,u]=e;const d=((f,g,p,m,y,b,x)=>{if(p===0||m===0)return[];let S=0,C=0,k=0;const O=Math.PI,P=x*Mf,D=Js(P),R=Ks(P),z=.5*(-R*f-D*g),B=.5*(-R*g+D*f),F=p**2,L=m**2,N=B**2,K=z**2,I=F*L-F*N-L*K;let V=Math.abs(p),it=Math.abs(m);if(I<0){const Te=Math.sqrt(1-I/(F*L));V*=Te,it*=Te}else k=(y===b?-1:1)*Math.sqrt(I/(F*N+L*K));const Ot=k*V*B/it,Bt=-k*it*z/V,Xt=R*Ot-D*Bt+.5*f,Ft=D*Ot+R*Bt+.5*g;let _t=W0(1,0,(z-Ot)/V,(B-Bt)/it),ae=W0((z-Ot)/V,(B-Bt)/it,(-z-Ot)/V,(-B-Bt)/it);b===0&&ae>0?ae-=2*O:b===1&&ae<0&&(ae+=2*O);const Ze=Math.ceil(Math.abs(ae/O*2)),st=[],nt=ae/Ze,Zt=8/3*Math.sin(nt/4)*Math.sin(nt/4)/Math.sin(nt/2);let $s=_t+nt;for(let Te=0;Te<Ze;Te++)st[Te]=Vw(_t,$s,R,D,V,it,Xt,Ft,Zt,S,C),S=st[Te][5],C=st[Te][6],_t=$s,$s+=nt;return st})(c-o,u-t,i,n,a,h,r);for(let f=0,g=d.length;f<g;f++)d[f][1]+=o,d[f][2]+=t,d[f][3]+=o,d[f][4]+=t,d[f][5]+=o,d[f][6]+=t;return d},G0=o=>{let t=0,e=0,s=0,i=0;const n=[];let r,a=0,h=0;for(const c of o){const u=[...c];let d;switch(u[0]){case"l":u[1]+=t,u[2]+=e;case"L":t=u[1],e=u[2],d=["L",t,e];break;case"h":u[1]+=t;case"H":t=u[1],d=["L",t,e];break;case"v":u[1]+=e;case"V":e=u[1],d=["L",t,e];break;case"m":u[1]+=t,u[2]+=e;case"M":t=u[1],e=u[2],s=u[1],i=u[2],d=["M",t,e];break;case"c":u[1]+=t,u[2]+=e,u[3]+=t,u[4]+=e,u[5]+=t,u[6]+=e;case"C":a=u[3],h=u[4],t=u[5],e=u[6],d=["C",u[1],u[2],a,h,t,e];break;case"s":u[1]+=t,u[2]+=e,u[3]+=t,u[4]+=e;case"S":r==="C"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=u[3],e=u[4],d=["C",a,h,u[1],u[2],t,e],a=d[3],h=d[4];break;case"q":u[1]+=t,u[2]+=e,u[3]+=t,u[4]+=e;case"Q":a=u[1],h=u[2],t=u[3],e=u[4],d=["Q",a,h,t,e];break;case"t":u[1]+=t,u[2]+=e;case"T":r==="Q"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=u[1],e=u[2],d=["Q",a,h,t,e];break;case"a":u[6]+=t,u[7]+=e;case"A":Ww(t,e,u).forEach(f=>n.push(f)),t=u[6],e=u[7];break;case"z":case"Z":t=s,e=i,d=["Z"]}d?(n.push(d),r=d[0]):r=""}return n},Fu=(o,t,e,s)=>Math.sqrt((e-o)**2+(s-t)**2),X0=(o,t,e,s,i,n,r,a)=>h=>{const c=h**3,u=(g=>3*g**2*(1-g))(h),d=(g=>3*g*(1-g)**2)(h),f=(g=>(1-g)**3)(h);return new M(r*c+i*u+e*d+o*f,a*c+n*u+s*d+t*f)},U0=o=>o**2,Y0=o=>2*o*(1-o),$0=o=>(1-o)**2,Gw=(o,t,e,s,i,n,r,a)=>h=>{const c=U0(h),u=Y0(h),d=$0(h),f=3*(d*(e-o)+u*(i-e)+c*(r-i)),g=3*(d*(s-t)+u*(n-s)+c*(a-n));return Math.atan2(g,f)},Xw=(o,t,e,s,i,n)=>r=>{const a=U0(r),h=Y0(r),c=$0(r);return new M(i*a+e*h+o*c,n*a+s*h+t*c)},Uw=(o,t,e,s,i,n)=>r=>{const a=1-r,h=2*(a*(e-o)+r*(i-e)),c=2*(a*(s-t)+r*(n-s));return Math.atan2(c,h)},q0=(o,t,e)=>{let s=new M(t,e),i=0;for(let n=1;n<=100;n+=1){const r=o(n/100);i+=Fu(s.x,s.y,r.x,r.y),s=r}return i},Yw=(o,t)=>{let e,s=0,i=0,n={x:o.x,y:o.y},r=T({},n),a=.01,h=0;const c=o.iterator,u=o.angleFinder;for(;i<t&&a>1e-4;)r=c(s),h=s,e=Fu(n.x,n.y,r.x,r.y),e+i>t?(s-=a,a/=2):(n=r,s+=a,i+=e);return T(T({},r),{},{angle:u(h)})},gg=o=>{let t,e,s=0,i=0,n=0,r=0,a=0;const h=[];for(const c of o){const u={x:i,y:n,command:c[0],length:0};switch(c[0]){case"M":e=u,e.x=r=i=c[1],e.y=a=n=c[2];break;case"L":e=u,e.length=Fu(i,n,c[1],c[2]),i=c[1],n=c[2];break;case"C":t=X0(i,n,c[1],c[2],c[3],c[4],c[5],c[6]),e=u,e.iterator=t,e.angleFinder=Gw(i,n,c[1],c[2],c[3],c[4],c[5],c[6]),e.length=q0(t,i,n),i=c[5],n=c[6];break;case"Q":t=Xw(i,n,c[1],c[2],c[3],c[4]),e=u,e.iterator=t,e.angleFinder=Uw(i,n,c[1],c[2],c[3],c[4]),e.length=q0(t,i,n),i=c[3],n=c[4];break;case"Z":e=u,e.destX=r,e.destY=a,e.length=Fu(i,n,r,a),i=r,n=a}s+=e.length,h.push(e)}return h.push({length:s,x:i,y:n}),h},K0=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:gg(o),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const i=e[s],n=t/i.length,r=o[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return T(T({},new M(i.x,i.y).lerp(new M(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return T(T({},new M(i.x,i.y).lerp(new M(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return Yw(i,t)}},$w=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),J0=new RegExp(Hw,"g"),qw=new RegExp(ti,"gi"),Kw={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Q0=o=>{var t;const e=[],s=(t=o.match($w))!==null&&t!==void 0?t:[];for(const i of s){const n=i[0];if(n==="z"||n==="Z"){e.push([n]);continue}const r=Kw[n.toLowerCase()];let a=[];if(n==="a"||n==="A"){J0.lastIndex=0;for(let h=null;h=J0.exec(i);)a.push(...h.slice(1))}else a=i.match(qw)||[];for(let h=0;h<a.length;h+=r){const c=new Array(r),u=zw[n];c[0]=h>0&&u?u:n;for(let d=0;d<r;d++)c[d+1]=parseFloat(a[h+d]);e.push(c)}}return e},Jw=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new M(o[0]),s=new M(o[1]),i=1,n=0;const r=[],a=o.length,h=a>2;let c;for(h&&(i=o[2].x<s.x?-1:o[2].x===s.x?0:1,n=o[2].y<s.y?-1:o[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),c=1;c<a;c++){if(!e.eq(s)){const u=e.midPointFrom(s);r.push(["Q",e.x,e.y,u.x,u.y])}e=o[c],c+1<o.length&&(s=o[c+1])}return h&&(i=e.x>o[c-2].x?1:e.x===o[c-2].x?0:-1,n=e.y>o[c-2].y?1:e.y===o[c-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},Z0=(o,t)=>o.map(e=>e.map((s,i)=>i===0||t===void 0?s:Dt(s,t)).join(" ")).join(" ");function Lu(o,t){const e=o.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const Qw=(o,t)=>Math.floor(Math.random()*(t-o+1))+o;function tv(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||Rr,s=new(ou()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=Rr};if(i&&i.aborted)throw new kf("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=Rr)},s.onerror=s.ontimeout=r,s.open("get",o,!0),s.send(),s}const Iu=(o,t)=>{let e=o._findCenterFromElement();o.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:a}=Lr(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(Ve,i),s.set(gs,n),s.angle=r,s.skewX=a,s.skewY=0}})(o),e=e.transform(o.transformMatrix)),delete o.transformMatrix,t&&(o.scaleX*=t.scaleX,o.scaleY*=t.scaleY,o.cropX=t.cropX,o.cropY=t.cropY,e.x+=t.offsetLeft,e.y+=t.offsetTop,o.width=t.width,o.height=t.height),o.setPositionByOrigin(e,rt,rt)};var Zw=Object.freeze({__proto__:null,addTransformToObject:Gm,animate:ng,animateColor:g0,applyTransformToObject:vo,calcAngleBetweenVectors:Su,calcDimensionsMatrix:$h,calcPlaneChangeMatrix:Qh,calcVectorRotation:o0,cancelAnimFrame:Pm,capValue:Hr,composeMatrix:Fm,copyCanvasElement:o=>{var t;const e=ps(o);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(o,0,0),e},cos:Ks,createCanvasElement:Rs,createImage:Mm,createRotateMatrix:Ir,createScaleMatrix:pu,createSkewXMatrix:Bf,createSkewYMatrix:Hf,createTranslateMatrix:go,createVector:wu,crossProduct:bo,degreesToRadians:Ut,dotProduct:h0,ease:z_,enlivenObjectEnlivables:Kh,enlivenObjects:po,findScaleToCover:V0,findScaleToFit:z0,getBoundsOfCurve:fg,getOrthonormalVector:Qf,getPathSegmentsInfo:gg,getPointOnPath:K0,getPointer:Vm,getRandomInt:Qw,getRegularPolygonPath:(o,t)=>{const e=2*Math.PI/o;let s=-Vn;o%2==0&&(s+=e/2);const i=new Array(o+1);for(let n=0;n<o;n++){const r=n*e+s,{x:a,y:h}=new M(Ks(r),Js(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",a,h]}return i[o]=["Z"],i},getSmoothPathFromPoints:Jw,getSvgAttributes:o=>{const t=["instantiated_by_use","style","id","class"];switch(o){case"linearGradient":return t.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return t.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return t.concat(["offset","stop-color","stop-opacity"])}return t},getUnitVector:Cu,groupSVGElements:(o,t)=>o&&o.length===1?o[0]:new Ls(o,t),hasStyleChanged:Pu,invertTransform:ns,isBetweenVectors:Zf,isIdentityMatrix:Om,isTouchEvent:mu,isTransparent:S0,joinPath:Z0,loadImage:qh,magnitude:xu,makeBoundingBoxFromPoints:Ci,makePathSimpler:G0,matrixToSVG:mo,mergeClipPaths:(o,t)=>{var e;let s=o,i=t;s.inverted&&!i.inverted&&(s=t,i=o),Gf(i,(e=i.group)===null||e===void 0?void 0:e.calcTransformMatrix(),s.calcTransformMatrix());const n=s.inverted&&i.inverted;return n&&(s.inverted=i.inverted=!1),new Ls([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:qt,multiplyTransformMatrixArray:gu,parsePath:Q0,parsePreserveAspectRatioAttribute:Yf,parseUnit:Ge,pick:jr,projectStrokeOnPoints:T0,qrDecompose:Lr,radiansToDegrees:Si,removeFromArray:Fr,removeTransformFromObject:(o,t)=>{const e=ns(t),s=qt(e,o.calcOwnMatrix());vo(o,s)},removeTransformMatrixForSvgParsing:Iu,request:tv,requestAnimFrame:Yh,resetObjectTransform:Xm,rotatePoint:(o,t,e)=>o.rotate(e,t),rotateVector:Jf,saveObjectTransform:Wf,sendObjectToPlane:Gf,sendPointToPlane:Br,sendVectorToPlane:Um,setStyle:Lu,sin:Js,sizeAfterTransform:vu,string:pw,stylesFromArray:P0,stylesToArray:k0,toBlob:Nf,toDataURL:jf,toFixed:Dt,transformPath:(o,t,e)=>(e&&(t=qt(t,[1,0,0,1,-e.x,-e.y])),o.map(s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:a}=Ee({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=a}return i})),transformPoint:Ee});class tx extends zm{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),E(this,"upper",void 0),E(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(s),i.parentNode&&i.parentNode.replaceChild(r,i),r.append(i,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=Rs();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){const t=lo().createElement("div");return t.setAttribute("data-fabric","wrapper"),Lu(t,{position:"relative"}),Hm(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;Lu(t,T(T({},s),{},{"touch-action":i?"manipulation":ze})),Hm(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;Bm(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Vf(this.upper.el,t),Vf(this.container,t)}cleanupDOM(t){const e=this.container,{el:s}=this.lower,{el:i}=this.upper;super.cleanupDOM(t),e.removeChild(i),e.removeChild(s),e.parentNode&&e.parentNode.replaceChild(s,e)}dispose(){super.dispose(),xi().dispose(this.upper.el),delete this.upper,delete this.container}}class ju extends Jh{constructor(){super(...arguments),E(this,"targets",[]),E(this,"_hoveredTargets",[]),E(this,"_objectsToRender",void 0),E(this,"_currentTransform",null),E(this,"_groupSelector",null),E(this,"contextTopDirty",!1)}static getDefaults(){return T(T({},super.getDefaults()),ju.ownDefaults)}get upperCanvasEl(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.el}get contextTop(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new tx(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){const t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter(e=>!e.group&&e!==t).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()}renderTop(){const t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;const e=this.getRetinaScaling(),s=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=s,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,s){const i=this.targetFindTolerance,n=this.pixelFindContext;this.clearContext(n),n.save(),n.translate(-e+i,-s+i),n.transform(...this.viewportTransform);const r=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(n),t.selectionBackgroundColor=r,n.restore();const a=Math.round(i*this.getRetinaScaling());return S0(n,a,a,a)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(s=>!!s&&t[s]===!0):t[e])}_shouldClearSelection(t,e){const s=this.getActiveObjects(),i=this._activeObject;return!!(!e||e&&i&&s.length>1&&s.indexOf(e)===-1&&i!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&i&&i!==e)}_shouldCenterTransform(t,e,s){if(!t)return;let i;return e===cu||e===Ve||e===gs||e===Uh?i=this.centeredScaling||t.centeredScaling:e===Ff&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=$t:["mr","tr","br"].includes(e)&&(s.x=wt),["tl","mt","tr"].includes(e)?s.y=Df:["bl","mb","br"].includes(e)&&(s.y=is)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?Br(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:a}=e.getActiveControl()||{},h=s&&a?(i=a.getActionHandler(t,e,a))===null||i===void 0?void 0:i.bind(a):R_,c=((g,p,m,y)=>{if(!p||!g)return"drag";const b=y.controls[p];return b.getActionName(m,b,y)})(s,r,t,e),u=t[this.centeredKey],d=this._shouldCenterTransform(e,c,u)?{x:rt,y:rt}:this._getOriginFromCorner(e,r),f={target:e,action:c,actionHandler:h,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:d.x,originY:d.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:Ut(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:u,original:T(T({},Wf(e)),{},{originX:d.x,originY:d.y})};this._currentTransform=f,this.fire("before:transform",{e:t,transform:f})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new M(e,s).transform(this.viewportTransform),a=new M(e+i,s+n).transform(this.viewportTransform),h=this.selectionLineWidth/2;let c=Math.min(r.x,a.x),u=Math.min(r.y,a.y),d=Math.max(r.x,a.x),f=Math.max(r.y,a.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(c,u,d-c,f-u)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,c+=h,u+=h,d-=h,f-=h,ke.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(c,u,d-c,f-u))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,mu(t))||i.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const n=this.targets;this.targets=[];const r=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&r&&r!==s?(this.targets=n,s):r}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,a,h,c]=s,u=Math.atan2(a.y-r.y,a.x-r.x),d=Ks(u)*n,f=Js(u)*n,g=d+f,p=d-f;s=[new M(r.x-p,r.y-g),new M(a.x+g,a.y-p),new M(h.x+p,h.y+g),new M(c.x-g,c.y+p)]}return zt.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,Br(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const i=t[s];if(this._checkTarget(i,e)){if(fu(i)&&i.subTargetCheck){const n=this._searchPossibleTargets(i._objects,e);n&&this.targets.push(n)}return i}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&fu(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!fu(r)||!r.interactive)return r}return i[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=Vm(t),r=i.width||0,a=i.height||0;r&&a||(is in i&&Df in i&&(a=Math.abs(i.top-i.bottom)),$t in i&&wt in i&&(r=Math.abs(i.right-i.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=Br(n,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(n.x/=h,n.y/=h);const c=r===0||a===0?new M(1,1):new M(s.width/r,s.height/a);return n.multiply(c)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Rs(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){const t=this._activeObject;return Nr(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],a=[];t.forEach(h=>{n.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),a.push(h))}),n.forEach(h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),r.push(h))}),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:a})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:a})),i&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),i=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),i}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,Nr(t)&&s!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){const s=this._activeObject;return!!s&&!s.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===s&&this.endCurrentTransform(t),Nr(s)&&s===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){const e=this.getActiveObjects(),s=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[s]});const i=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),i}endCurrentTransform(t){const e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){const e=this._currentTransform,s=e.target,i={e:t,target:s,transform:e,action:e.action};s._scaling&&(s._scaling=!1),s.setCoords(),e.actionPerformed&&(this.fire("object:modified",i),s.fire(uu,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;Nr(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){const e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,s){const i=this._realizeGroupTransformOnObject(t),n=super._toObject(t,e,s);return t.set(i),n}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&Nr(e)&&this._activeObject===e){const s=jr(t,["angle","flipX","flipY",wt,Ve,gs,co,uo,is]);return Gm(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}E(ju,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class ex{constructor(t){E(this,"targets",[]),E(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),Fr(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;!((e=this.target)===null||e===void 0)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}const sx=["target","oldTarget","fireCanvas","e"],ms={passive:!1},So=(o,t)=>{const e=o.getViewportPoint(t),s=o.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},Un=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.addEventListener(...e)},Is=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.removeEventListener(...e)},ix={mouse:{in:"over",out:"out",targetIn:"mouseover",targetOut:"mouseout",canvasIn:"mouse:over",canvasOut:"mouse:out"},drag:{in:"enter",out:"leave",targetIn:"dragenter",targetOut:"dragleave",canvasIn:"drag:enter",canvasOut:"drag:leave"}};class pg extends ju{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),E(this,"_isClick",void 0),E(this,"textEditingManager",new ex(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(Un,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Nm(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,ms),t(s,"".concat(i,"out"),this._onMouseOut),t(s,"".concat(i,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,ms)}removeListeners(){this.addOrRemove(Is,"remove");const t=this._getEventPrefix(),e=Qs(this.upperCanvasEl);Is(e,"".concat(t,"up"),this._onMouseUp),Is(e,"touchend",this._onTouchEnd,ms),Is(e,"".concat(t,"move"),this._onMouseMove,ms),Is(e,"touchmove",this._onMouseMove,ms),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=T({e:t},So(this,t));this.fire("mouse:out",T(T({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",T({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",T(T({},s),{},{target:i})),i&&i.fire("mouseout",T({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",T({e:t},So(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;const e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;const s={e:t,target:e};return this.fire("dragstart",s),e.fire("dragstart",s),void Un(this.upperCanvasEl,"drag",this._onDragProgress)}Wm(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e==null||e.clearContextTop(),s!==e&&(s==null||s.clearContextTop());const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),i=!0),s&&(r.save(),s.transform(r),s.renderDropTargetEffect(t),r.restore(),i=!0),r.restore(),i&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==ze,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};Is(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let a;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(a=s),s.fire(e,r));for(let h=0;h<i.length;h++){const c=i[h];c.canDrop(t)&&(a=c),c.fire(e,r)}this._renderDragEffects(t,n,a),this._dropTarget=a}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",T({e:t,target:e,subTargets:s,dragSource:this._dragSource},So(this,t)));i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&Wm(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=Qs(i);Un(r,"touchend",this._onTouchEnd,ms),e&&Un(r,"touchmove",this._onMouseMove,ms),Is(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();Is(e,"".concat(s,"move"),this._onMouseMove,ms);const i=Qs(e);Un(i,"".concat(s,"up"),this._onMouseUp),Un(i,"".concat(s,"move"),this._onMouseMove,ms)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=Qs(this.upperCanvasEl);Is(s,"touchend",this._onTouchEnd,ms),Is(s,"touchmove",this._onMouseMove,ms),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{Un(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=Qs(this.upperCanvasEl);Is(i,"".concat(s,"up"),this._onMouseUp),Is(i,"".concat(s,"move"),this._onMouseMove,ms),Un(e,"".concat(s,"move"),this._onMouseMove,ms)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,n=this._target,{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let a,h,c=!1;if(s&&(this._finalizeCurrentTransform(t),c=s.actionPerformed),!i){const u=n===this._activeObject;this.handleSelection(t),c||(c=this._shouldRender(n)||!u&&n===this._activeObject)}if(n){const u=n.findControl(this.getViewportPoint(t),mu(t)),{key:d,control:f}=u||{};if(h=d,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),c=!0;else if(f){const g=f.getMouseUpHandler(t,n,f);g&&(a=this.getScenePoint(t),g.call(f,t,s,a.x,a.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==h)){const u=s.target&&s.target.controls[s.corner],d=u&&u.getMouseUpHandler(t,s.target,u);a=a||this.getScenePoint(t),d&&d.call(u,t,s,a.x,a.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),c?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e,s){const i=this._target,n=this.targets||[],r=T(T(T({e:t,target:i,subTargets:n},So(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let a=0;a<n.length;a++)n[a]!==i&&n[a].fire("mouse".concat(e),r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const a=this.getScenePoint(t);this._groupSelector={x:a.x,y:a.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const a=e.findControl(this.getViewportPoint(t),mu(t));if(e===this._activeObject&&(a||!r)){this._setupCurrentTransform(t,e,s);const h=a?a.control:void 0,c=this.getScenePoint(t),u=h&&h.getMouseDownHandler(t,e,h);u&&u.call(h,t,this._currentTransform,c.x,c.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=Br(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let a=0;a<r;a++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[a],oldTarget:i[a]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let a=0;a<r;a++)this.fireSyntheticInOutEvents("drag",T(T({},e),{},{target:n[a],oldTarget:i[a]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,a=Lt(e,sx);const{targetIn:h,targetOut:c,canvasIn:u,canvasOut:d}=ix[t],f=i!==s;if(i&&f){const g=T(T({},a),{},{e:r,target:i,nextTarget:s},So(this,r));n&&this.fire(d,g),i.fire(c,g)}if(s&&f){const g=T(T({},a),{},{e:r,target:s,previousTarget:i},So(this,r));n&&this.fire(u,g),s.fire(h,g)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?Br(e,void 0,i.group.calcTransformMatrix()):e;s.shiftKey=t.shiftKey,s.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,s,n),s.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,s){const{action:i,actionHandler:n,target:r}=e,a=!!n&&n(t,e,s.x,s.y);a&&r.setCoords(),i==="drag"&&a&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||a}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const i=Nr(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const r=n.control;this.setCursor(r.cursorStyleHandler(t,r,e))}else e.subTargetCheck&&this.targets.concat().reverse().map(r=>{s=r.hoverCursor||s}),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,i=Nr(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||i)&&(i||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(i){const n=s.getObjects();if(e===s){const r=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(n,r)||this.searchPossibleTargets(this._objects,r))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(n,t)}else{s.isEditing&&s.exitEditing();const n=new(W.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(s,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new M(e,s),a=r.add(new M(i,n)),h=r.min(a),c=r.max(a).subtract(h),u=this.collectObjects({left:h.x,top:h.y,width:c.x,height:c.y},{includeIntersecting:!this.selectionFullyContained}),d=r.eq(a)?u[0]?[u[0]]:[]:u.length>1?u.filter(f=>!f.onSelect({e:t})).reverse():u;if(d.length===1)this.setActiveObject(d[0],t);else if(d.length>1){const f=W.getClass("ActiveSelection");this.setActiveObject(new f(d,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const ev={x1:0,y1:0,x2:0,y2:0},nx=T(T({},ev),{},{r1:0,r2:0}),Co=(o,t)=>isNaN(o)&&typeof t=="number"?t:o,rx=/^(\d+\.\d+)%|(\d+)%$/;function sv(o){return o&&rx.test(o)}function iv(o,t){const e=typeof o=="number"?o:typeof o=="string"?parseFloat(o)/(sv(o)?100:1):NaN;return Hr(0,Co(e,t),1)}const ax=/\s*;\s*/,ox=/\s*:\s*/;function hx(o,t){let e,s;const i=o.getAttribute("style");if(i){const r=i.split(ax);r[r.length-1]===""&&r.pop();for(let a=r.length;a--;){const[h,c]=r[a].split(ox).map(u=>u.trim());h==="stop-color"?e=c:h==="stop-opacity"&&(s=c)}}const n=new St(e||o.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:iv(o.getAttribute("offset"),0),color:n.toRgb(),opacity:Co(parseFloat(s||o.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function lx(o,t){const e=[],s=o.getElementsByTagName("stop"),i=iv(t,1);for(let n=s.length;n--;)e.push(hx(s[n],i));return e}function nv(o){return o.nodeName==="linearGradient"||o.nodeName==="LINEARGRADIENT"?"linear":"radial"}function rv(o){return o.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function si(o,t){return o.getAttribute(t)}function cx(o,t){return function(e,s){let i,{width:n,height:r,gradientUnits:a}=s;return Object.keys(e).reduce((h,c)=>{const u=e[c];return u==="Infinity"?i=1:u==="-Infinity"?i=0:(i=typeof u=="string"?parseFloat(u):u,typeof u=="string"&&sv(u)&&(i*=.01,a==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(i*=n),c!=="y1"&&c!=="y2"||(i*=r)))),h[c]=i,h},{})}(nv(o)==="linear"?function(e){return{x1:si(e,"x1")||0,y1:si(e,"y1")||0,x2:si(e,"x2")||"100%",y2:si(e,"y2")||0}}(o):function(e){return{x1:si(e,"fx")||si(e,"cx")||"50%",y1:si(e,"fy")||si(e,"cy")||"50%",r1:0,x2:si(e,"cx")||"50%",y2:si(e,"cy")||"50%",r2:si(e,"r")||"50%"}}(o),T(T({},t),{},{gradientUnits:rv(o)}))}class nl{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:a=0,gradientTransform:h,id:c}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:T(T({},e==="radial"?nx:ev),i),colorStops:n,offsetX:r,offsetY:a,gradientTransform:h,id:c?"".concat(c,"_").concat(Gn()):Gn()})}addColorStop(t){for(const e in t){const s=new St(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return T(T({},jr(this,t)),{},{type:this.type,coords:T({},this.coords),colorStops:this.colorStops.map(e=>T({},e)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],i=this.gradientTransform?this.gradientTransform.concat():He.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(d=>T({},d)).sort((d,f)=>d.offset-f.offset);let a=-this.offsetX,h=-this.offsetY;var c;n==="objectBoundingBox"?(a/=t.width,h/=t.height):(a+=t.width/2,h+=t.height/2),(c=t)&&typeof c._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(a-=t.pathOffset.x,h-=t.pathOffset.y),i[4]-=a,i[5]-=h;const u=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(mo(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:d,y1:f,x2:g,y2:p}=this.coords;s.push("<linearGradient ",u,' x1="',d,'" y1="',f,'" x2="',g,'" y2="',p,`">
|
|
71
|
-
`)}else if(this.type==="radial"){const{x1:
|
|
72
|
-
`),
|
|
70
|
+
`),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let i=0;i<this._objects.length;i++)e.push(" ",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:i=[],layoutManager:n}=t,r=pt(t,od);return Promise.all([Gs(i,e),vi(r,e)]).then(a=>{let[l,h]=a;const c=new this(l,x(x(x({},r),h),{},{layoutManager:new ld}));if(n){const u=I.getClass(n.type),d=I.getClass(n.strategy);c.layoutManager=new u(new d)}else c.layoutManager=new Ti;return c.layoutManager.subscribeTargets({type:Je,target:c,targets:c.getObjects()}),c.setCoords(),c})}}S(me,"type","Group"),S(me,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),I.setClass(me);const Fl=(o,t)=>Math.min(t.width/o.width,t.height/o.height),Ll=(o,t)=>Math.max(t.width/o.width,t.height/o.height),ia="\\s*,?\\s*",Ei="".concat(ia,"(").concat(Te,")"),hd="".concat(Ei).concat(Ei).concat(Ei).concat(ia,"([01])").concat(ia,"([01])").concat(Ei).concat(Ei),cd={m:"l",M:"L"},ud=(o,t,e,s,i,n,r,a,l,h,c)=>{const u=xe(o),d=Se(o),f=xe(t),g=Se(t),p=e*i*f-s*n*g+r,v=s*i*f+e*n*g+a;return["C",h+l*(-e*i*d-s*n*u),c+l*(-s*i*d+e*n*u),p+l*(e*i*g+s*n*f),v+l*(s*i*g-e*n*f),p,v]},Il=(o,t,e,s)=>{const i=Math.atan2(t,o),n=Math.atan2(s,e);return n>=i?n-i:2*Math.PI-(i-n)};function na(o,t,e,s,i,n,r,a){let l;if(nt.cachesBoundsOfCurve&&(l=[...arguments].join(),di.boundsOfCurveCache[l]))return di.boundsOfCurveCache[l];const h=Math.sqrt,c=Math.abs,u=[],d=[[0,0],[0,0]];let f=6*o-12*e+6*i,g=-3*o+9*e-9*i+3*r,p=3*e-3*o;for(let w=0;w<2;++w){if(w>0&&(f=6*t-12*s+6*n,g=-3*t+9*s-9*n+3*a,p=3*s-3*t),c(g)<1e-12){if(c(f)<1e-12)continue;const O=-p/f;0<O&&O<1&&u.push(O);continue}const C=f*f-4*p*g;if(C<0)continue;const T=h(C),E=(-f+T)/(2*g);0<E&&E<1&&u.push(E);const k=(-f-T)/(2*g);0<k&&k<1&&u.push(k)}let v=u.length;const m=v,b=Nl(o,t,e,s,i,n,r,a);for(;v--;){const{x:w,y:C}=b(u[v]);d[0][v]=w,d[1][v]=C}d[0][m]=o,d[1][m]=t,d[0][m+1]=r,d[1][m+1]=a;const _=[new A(Math.min(...d[0]),Math.min(...d[1])),new A(Math.max(...d[0]),Math.max(...d[1]))];return nt.cachesBoundsOfCurve&&(di.boundsOfCurveCache[l]=_),_}const dd=(o,t,e)=>{let[s,i,n,r,a,l,h,c]=e;const u=((d,f,g,p,v,m,b)=>{if(g===0||p===0)return[];let _=0,w=0,C=0;const T=Math.PI,E=b*_r,k=Se(E),O=xe(E),H=.5*(-O*d-k*f),N=.5*(-O*f+k*d),P=g**2,R=p**2,F=N**2,V=H**2,M=P*R-P*F-R*V;let L=Math.abs(g),Y=Math.abs(p);if(M<0){const Nt=Math.sqrt(1-M/(P*R));L*=Nt,Y*=Nt}else C=(v===m?-1:1)*Math.sqrt(M/(P*F+R*V));const ft=C*L*N/Y,bt=-C*Y*H/L,_t=O*ft-k*bt+.5*d,gt=k*ft+O*bt+.5*f;let rt=Il(1,0,(H-ft)/L,(N-bt)/Y),Dt=Il((H-ft)/L,(N-bt)/Y,(-H-ft)/L,(-N-bt)/Y);m===0&&Dt>0?Dt-=2*T:m===1&&Dt<0&&(Dt+=2*T);const ee=Math.ceil(Math.abs(Dt/T*2)),K=[],$=Dt/ee,Tt=8/3*Math.sin($/4)*Math.sin($/4)/Math.sin($/2);let _e=rt+$;for(let Nt=0;Nt<ee;Nt++)K[Nt]=ud(rt,_e,O,k,L,Y,_t,gt,Tt,_,w),_=K[Nt][5],w=K[Nt][6],rt=_e,_e+=$;return K})(h-o,c-t,i,n,a,l,r);for(let d=0,f=u.length;d<f;d++)u[d][1]+=o,u[d][2]+=t,u[d][3]+=o,u[d][4]+=t,u[d][5]+=o,u[d][6]+=t;return u},jl=o=>{let t=0,e=0,s=0,i=0;const n=[];let r,a=0,l=0;for(const h of o){const c=[...h];let u;switch(c[0]){case"l":c[1]+=t,c[2]+=e;case"L":t=c[1],e=c[2],u=["L",t,e];break;case"h":c[1]+=t;case"H":t=c[1],u=["L",t,e];break;case"v":c[1]+=e;case"V":e=c[1],u=["L",t,e];break;case"m":c[1]+=t,c[2]+=e;case"M":t=c[1],e=c[2],s=c[1],i=c[2],u=["M",t,e];break;case"c":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e,c[5]+=t,c[6]+=e;case"C":a=c[3],l=c[4],t=c[5],e=c[6],u=["C",c[1],c[2],a,l,t,e];break;case"s":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"S":r==="C"?(a=2*t-a,l=2*e-l):(a=t,l=e),t=c[3],e=c[4],u=["C",a,l,c[1],c[2],t,e],a=u[3],l=u[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":a=c[1],l=c[2],t=c[3],e=c[4],u=["Q",a,l,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":r==="Q"?(a=2*t-a,l=2*e-l):(a=t,l=e),t=c[1],e=c[2],u=["Q",a,l,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":dd(t,e,c).forEach(d=>n.push(d)),t=c[6],e=c[7];break;case"z":case"Z":t=s,e=i,u=["Z"]}u?(n.push(u),r=u[0]):r=""}return n},yn=(o,t,e,s)=>Math.sqrt((e-o)**2+(s-t)**2),Nl=(o,t,e,s,i,n,r,a)=>l=>{const h=l**3,c=(f=>3*f**2*(1-f))(l),u=(f=>3*f*(1-f)**2)(l),d=(f=>(1-f)**3)(l);return new A(r*h+i*c+e*u+o*d,a*h+n*c+s*u+t*d)},Bl=o=>o**2,Hl=o=>2*o*(1-o),zl=o=>(1-o)**2,fd=(o,t,e,s,i,n,r,a)=>l=>{const h=Bl(l),c=Hl(l),u=zl(l),d=3*(u*(e-o)+c*(i-e)+h*(r-i)),f=3*(u*(s-t)+c*(n-s)+h*(a-n));return Math.atan2(f,d)},gd=(o,t,e,s,i,n)=>r=>{const a=Bl(r),l=Hl(r),h=zl(r);return new A(i*a+e*l+o*h,n*a+s*l+t*h)},pd=(o,t,e,s,i,n)=>r=>{const a=1-r,l=2*(a*(e-o)+r*(i-e)),h=2*(a*(s-t)+r*(n-s));return Math.atan2(h,l)},Vl=(o,t,e)=>{let s=new A(t,e),i=0;for(let n=1;n<=100;n+=1){const r=o(n/100);i+=yn(s.x,s.y,r.x,r.y),s=r}return i},md=(o,t)=>{let e,s=0,i=0,n={x:o.x,y:o.y},r=x({},n),a=.01,l=0;const h=o.iterator,c=o.angleFinder;for(;i<t&&a>1e-4;)r=h(s),l=s,e=yn(n.x,n.y,r.x,r.y),e+i>t?(s-=a,a/=2):(n=r,s+=a,i+=e);return x(x({},r),{},{angle:c(l)})},ra=o=>{let t,e,s=0,i=0,n=0,r=0,a=0;const l=[];for(const h of o){const c={x:i,y:n,command:h[0],length:0};switch(h[0]){case"M":e=c,e.x=r=i=h[1],e.y=a=n=h[2];break;case"L":e=c,e.length=yn(i,n,h[1],h[2]),i=h[1],n=h[2];break;case"C":t=Nl(i,n,h[1],h[2],h[3],h[4],h[5],h[6]),e=c,e.iterator=t,e.angleFinder=fd(i,n,h[1],h[2],h[3],h[4],h[5],h[6]),e.length=Vl(t,i,n),i=h[5],n=h[6];break;case"Q":t=gd(i,n,h[1],h[2],h[3],h[4]),e=c,e.iterator=t,e.angleFinder=pd(i,n,h[1],h[2],h[3],h[4]),e.length=Vl(t,i,n),i=h[3],n=h[4];break;case"Z":e=c,e.destX=r,e.destY=a,e.length=yn(i,n,r,a),i=r,n=a}s+=e.length,l.push(e)}return l.push({length:s,x:i,y:n}),l},Gl=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ra(o),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const i=e[s],n=t/i.length,r=o[s];switch(i.command){case"M":return{x:i.x,y:i.y,angle:0};case"Z":return x(x({},new A(i.x,i.y).lerp(new A(i.destX,i.destY),n)),{},{angle:Math.atan2(i.destY-i.y,i.destX-i.x)});case"L":return x(x({},new A(i.x,i.y).lerp(new A(r[1],r[2]),n)),{},{angle:Math.atan2(r[2]-i.y,r[1]-i.x)});case"C":case"Q":return md(i,t)}},vd=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Wl=new RegExp(hd,"g"),bd=new RegExp(Te,"gi"),yd={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Xl=o=>{var t;const e=[],s=(t=o.match(vd))!==null&&t!==void 0?t:[];for(const i of s){const n=i[0];if(n==="z"||n==="Z"){e.push([n]);continue}const r=yd[n.toLowerCase()];let a=[];if(n==="a"||n==="A"){Wl.lastIndex=0;for(let l=null;l=Wl.exec(i);)a.push(...l.slice(1))}else a=i.match(bd)||[];for(let l=0;l<a.length;l+=r){const h=new Array(r),c=cd[n];h[0]=l>0&&c?c:n;for(let u=0;u<r;u++)h[u+1]=parseFloat(a[l+u]);e.push(h)}}return e},_d=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new A(o[0]),s=new A(o[1]),i=1,n=0;const r=[],a=o.length,l=a>2;let h;for(l&&(i=o[2].x<s.x?-1:o[2].x===s.x?0:1,n=o[2].y<s.y?-1:o[2].y===s.y?0:1),r.push(["M",e.x-i*t,e.y-n*t]),h=1;h<a;h++){if(!e.eq(s)){const c=e.midPointFrom(s);r.push(["Q",e.x,e.y,c.x,c.y])}e=o[h],h+1<o.length&&(s=o[h+1])}return l&&(i=e.x>o[h-2].x?1:e.x===o[h-2].x?0:-1,n=e.y>o[h-2].y?1:e.y===o[h-2].y?0:-1),r.push(["L",e.x+i*t,e.y+n*t]),r},Ul=(o,t)=>o.map(e=>e.map((s,i)=>i===0||t===void 0?s:ct(s,t)).join(" ")).join(" ");function _n(o,t){const e=o.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[i,n]=s;return e.setProperty(i,n)}))}const wd=(o,t)=>Math.floor(Math.random()*(t-o+1))+o;function Yl(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const e=t.onComplete||ps,s=new(ui()).XMLHttpRequest,i=t.signal,n=function(){s.abort()},r=function(){i&&i.removeEventListener("abort",n),s.onerror=s.ontimeout=ps};if(i&&i.aborted)throw new br("request");return i&&i.addEventListener("abort",n,{once:!0}),s.onreadystatechange=function(){s.readyState===4&&(r(),e(s),s.onreadystatechange=ps)},s.onerror=s.ontimeout=r,s.open("get",o,!0),s.send(),s}const wn=(o,t)=>{let e=o._findCenterFromElement();o.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:i,scaleY:n,angle:r,skewX:a}=vs(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set($t,i),s.set(ce,n),s.angle=r,s.skewX=a,s.skewY=0}})(o),e=e.transform(o.transformMatrix)),delete o.transformMatrix,t&&(o.scaleX*=t.scaleX,o.scaleY*=t.scaleY,o.cropX=t.cropX,o.cropY=t.cropY,e.x+=t.offsetLeft,e.y+=t.offsetTop,o.width=t.width,o.height=t.height),o.setPositionByOrigin(e,q,q)};var xd=Object.freeze({__proto__:null,addTransformToObject:Oo,animate:qr,animateColor:ol,applyTransformToObject:Xs,calcAngleBetweenVectors:ln,calcDimensionsMatrix:pi,calcPlaneChangeMatrix:yi,calcVectorRotation:tl,cancelAnimFrame:mo,capValue:Ss,composeMatrix:wo,copyCanvasElement:o=>{var t;const e=ue(o);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(o,0,0),e},cos:xe,createCanvasElement:Ie,createImage:vo,createRotateMatrix:bs,createScaleMatrix:Qi,createSkewXMatrix:Pr,createSkewYMatrix:Mr,createTranslateMatrix:Vs,createVector:an,crossProduct:Us,degreesToRadians:wt,dotProduct:el,ease:hu,enlivenObjectEnlivables:vi,enlivenObjects:Gs,findScaleToCover:Ll,findScaleToFit:Fl,getBoundsOfCurve:na,getOrthonormalVector:Gr,getPathSegmentsInfo:ra,getPointOnPath:Gl,getPointer:Po,getRandomInt:wd,getRegularPolygonPath:(o,t)=>{const e=2*Math.PI/o;let s=-is;o%2==0&&(s+=e/2);const i=new Array(o+1);for(let n=0;n<o;n++){const r=n*e+s,{x:a,y:l}=new A(xe(r),Se(r)).scalarMultiply(t);i[n]=[n===0?"M":"L",a,l]}return i[o]=["Z"],i},getSmoothPathFromPoints:_d,getSvgAttributes:o=>{const t=["instantiated_by_use","style","id","class"];switch(o){case"linearGradient":return t.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return t.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return t.concat(["offset","stop-color","stop-opacity"])}return t},getUnitVector:hn,groupSVGElements:(o,t)=>o&&o.length===1?o[0]:new me(o,t),hasStyleChanged:gn,invertTransform:ne,isBetweenVectors:Wr,isIdentityMatrix:bo,isTouchEvent:Zi,isTransparent:ml,joinPath:Ul,loadImage:mi,magnitude:on,makeBoundingBoxFromPoints:Ne,makePathSimpler:jl,matrixToSVG:Ws,mergeClipPaths:(o,t)=>{var e;let s=o,i=t;s.inverted&&!i.inverted&&(s=t,i=o),Fr(i,(e=i.group)===null||e===void 0?void 0:e.calcTransformMatrix(),s.calcTransformMatrix());const n=s.inverted&&i.inverted;return n&&(s.inverted=i.inverted=!1),new me([s],{clipPath:i,inverted:n})},multiplyTransformMatrices:St,multiplyTransformMatrixArray:Ji,parsePath:Xl,parsePreserveAspectRatioAttribute:jr,parseUnit:Kt,pick:ys,projectStrokeOnPoints:yl,qrDecompose:vs,radiansToDegrees:je,removeFromArray:ms,removeTransformFromObject:(o,t)=>{const e=ne(t),s=St(e,o.calcOwnMatrix());Xs(o,s)},removeTransformMatrixForSvgParsing:wn,request:Yl,requestAnimFrame:gi,resetObjectTransform:Do,rotatePoint:(o,t,e)=>o.rotate(e,t),rotateVector:Vr,saveObjectTransform:Rr,sendObjectToPlane:Fr,sendPointToPlane:ws,sendVectorToPlane:Ro,setStyle:_n,sin:Se,sizeAfterTransform:tn,string:Nu,stylesFromArray:xl,stylesToArray:wl,toBlob:kr,toDataURL:Er,toFixed:ct,transformPath:(o,t,e)=>(e&&(t=St(t,[1,0,0,1,-e.x,-e.y])),o.map(s=>{const i=[...s];for(let n=1;n<s.length-1;n+=2){const{x:r,y:a}=Bt({x:s[n],y:s[n+1]},t);i[n]=r,i[n+1]=a}return i})),transformPoint:Bt});class Sd extends ko{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),S(this,"upper",void 0),S(this,"container",void 0);const{el:i}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(i,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(s),i.parentNode&&i.parentNode.replaceChild(r,i),r.append(i,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=Ie();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){const t=Ns().createElement("div");return t.setAttribute("data-fabric","wrapper"),_n(t,{position:"relative"}),Eo(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:i}=e;_n(t,x(x({},s),{},{"touch-action":i?"manipulation":Yt})),Eo(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:i}=this.upper;To(s,i,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Dr(this.upper.el,t),Dr(this.container,t)}cleanupDOM(t){const e=this.container,{el:s}=this.lower,{el:i}=this.upper;super.cleanupDOM(t),e.removeChild(i),e.removeChild(s),e.parentNode&&e.parentNode.replaceChild(s,e)}dispose(){super.dispose(),Le().dispose(this.upper.el),delete this.upper,delete this.container}}class xn extends bi{constructor(){super(...arguments),S(this,"targets",[]),S(this,"_hoveredTargets",[]),S(this,"_objectsToRender",void 0),S(this,"_currentTransform",null),S(this,"_groupSelector",null),S(this,"contextTopDirty",!1)}static getDefaults(){return x(x({},super.getDefaults()),xn.ownDefaults)}get upperCanvasEl(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.el}get contextTop(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new Sd(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){const t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter(e=>!e.group&&e!==t).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()}renderTop(){const t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;const e=this.getRetinaScaling(),s=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=s,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,s){const i=this.targetFindTolerance,n=this.pixelFindContext;this.clearContext(n),n.save(),n.translate(-e+i,-s+i),n.transform(...this.viewportTransform);const r=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(n),t.selectionBackgroundColor=r,n.restore();const a=Math.round(i*this.getRetinaScaling());return ml(n,a,a,a)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(s=>!!s&&t[s]===!0):t[e])}_shouldClearSelection(t,e){const s=this.getActiveObjects(),i=this._activeObject;return!!(!e||e&&i&&s.length>1&&s.indexOf(e)===-1&&i!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&i&&i!==e)}_shouldCenterTransform(t,e,s){if(!t)return;let i;return e===Yi||e===$t||e===ce||e===fi?i=this.centeredScaling||t.centeredScaling:e===Cr&&(i=this.centeredRotation||t.centeredRotation),i?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=xt:["mr","tr","br"].includes(e)&&(s.x=ot),["tl","mt","tr"].includes(e)?s.y=xr:["bl","mb","br"].includes(e)&&(s.y=ie)),s}_setupCurrentTransform(t,e,s){var i;const n=e.group?ws(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:a}=e.getActiveControl()||{},l=s&&a?(i=a.getActionHandler(t,e,a))===null||i===void 0?void 0:i.bind(a):Zc,h=((f,g,p,v)=>{if(!g||!f)return"drag";const m=v.controls[g];return m.getActionName(p,m,v)})(s,r,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,h,c)?{x:q,y:q}:this._getOriginFromCorner(e,r),d={target:e,action:h,actionHandler:l,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:u.x,originY:u.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:wt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:c,original:x(x({},Rr(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new A(e,s).transform(this.viewportTransform),a=new A(e+i,s+n).transform(this.viewportTransform),l=this.selectionLineWidth/2;let h=Math.min(r.x,a.x),c=Math.min(r.y,a.y),u=Math.max(r.x,a.x),d=Math.max(r.y,a.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(h,c,u-h,d-c)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,h+=l,c+=l,u-=l,d-=l,Ht.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(h,c,u-h,d-c))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,i=this.getActiveObjects();if(this.targets=[],s&&i.length>=1){if(s.findControl(e,Zi(t))||i.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const n=this.targets;this.targets=[];const r=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&r&&r!==s?(this.targets=n,s):r}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const i=this.getZoom(),n=t.padding/i;if(n){const[r,a,l,h]=s,c=Math.atan2(a.y-r.y,a.x-r.x),u=xe(c)*n,d=Se(c)*n,f=u+d,g=u-d;s=[new A(r.x-g,r.y-f),new A(a.x+f,a.y-g),new A(l.x+g,l.y+f),new A(h.x-f,h.y+g)]}return yt.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,ws(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const i=t[s];if(this._checkTarget(i,e)){if(Ki(i)&&i.subTargetCheck){const n=this._searchPossibleTargets(i._objects,e);n&&this.targets.push(n)}return i}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&Ki(s)&&s.interactive&&this.targets[0]){const i=this.targets;for(let n=i.length-1;n>0;n--){const r=i[n];if(!Ki(r)||!r.interactive)return r}return i[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,i=s.getBoundingClientRect();let n=Po(t),r=i.width||0,a=i.height||0;r&&a||(ie in i&&xr in i&&(a=Math.abs(i.top-i.bottom)),xt in i&&ot in i&&(r=Math.abs(i.right-i.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=ws(n,void 0,this.viewportTransform));const l=this.getRetinaScaling();l!==1&&(n.x/=l,n.y/=l);const h=r===0||a===0?new A(1,1):new A(s.width/r,s.height/a);return n.multiply(h)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Ie(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){const t=this._activeObject;return _s(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,i=!1;const n=this.getActiveObjects(),r=[],a=[];t.forEach(l=>{n.includes(l)||(s=!0,l.fire("deselected",{e,target:l}),a.push(l))}),n.forEach(l=>{t.includes(l)||(s=!0,l.fire("selected",{e,target:l}),r.push(l))}),t.length>0&&n.length>0?(i=!0,s&&this.fire("selection:updated",{e,selected:r,deselected:a})):n.length>0?(i=!0,this.fire("selection:created",{e,selected:r})):t.length>0&&(i=!0,this.fire("selection:cleared",{e,deselected:a})),i&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),i=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),i}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,_s(t)&&s!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){const s=this._activeObject;return!!s&&!s.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===s&&this.endCurrentTransform(t),_s(s)&&s===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){const e=this.getActiveObjects(),s=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[s]});const i=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),i}endCurrentTransform(t){const e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){const e=this._currentTransform,s=e.target,i={e:t,target:s,transform:e,action:e.action};s._scaling&&(s._scaling=!1),s.setCoords(),e.actionPerformed&&(this.fire("object:modified",i),s.fire($i,i))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;_s(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){const e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,s){const i=this._realizeGroupTransformOnObject(t),n=super._toObject(t,e,s);return t.set(i),n}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&_s(e)&&this._activeObject===e){const s=ys(t,["angle","flipX","flipY",ot,$t,ce,Bs,Hs,ie]);return Oo(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const i=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(i)}}S(xn,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class Cd{constructor(t){S(this,"targets",[]),S(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:i}=t.getActiveObject()||{};i&&i.focus()},s=t.upperCanvasEl;s.addEventListener("click",e),this.__disposer=()=>s.removeEventListener("click",e)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),ms(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;!((e=this.target)===null||e===void 0)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}const Ad=["target","oldTarget","fireCanvas","e"],de={passive:!1},Js=(o,t)=>{const e=o.getViewportPoint(t),s=o.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},os=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.addEventListener(...e)},ve=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.removeEventListener(...e)},Td={mouse:{in:"over",out:"out",targetIn:"mouseover",targetOut:"mouseout",canvasIn:"mouse:over",canvasOut:"mouse:out"},drag:{in:"enter",out:"leave",targetIn:"dragenter",targetOut:"dragleave",canvasIn:"drag:enter",canvasOut:"drag:leave"}};class aa extends xn{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),S(this,"_isClick",void 0),S(this,"textEditingManager",new Cd(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(os,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,i=this._getEventPrefix();t(Ao(s),"resize",this._onResize),t(s,i+"down",this._onMouseDown),t(s,"".concat(i,"move"),this._onMouseMove,de),t(s,"".concat(i,"out"),this._onMouseOut),t(s,"".concat(i,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,de)}removeListeners(){this.addOrRemove(ve,"remove");const t=this._getEventPrefix(),e=Ce(this.upperCanvasEl);ve(e,"".concat(t,"up"),this._onMouseUp),ve(e,"touchend",this._onTouchEnd,de),ve(e,"".concat(t,"move"),this._onMouseMove,de),ve(e,"touchmove",this._onMouseMove,de),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=x({e:t},Js(this,t));this.fire("mouse:out",x(x({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",x({},s)),this._hoveredTargets.forEach(i=>{this.fire("mouse:out",x(x({},s),{},{target:i})),i&&i.fire("mouseout",x({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",x({e:t},Js(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;const e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;const s={e:t,target:e};return this.fire("dragstart",s),e.fire("dragstart",s),void os(this.upperCanvasEl,"drag",this._onDragProgress)}Mo(t)}_renderDragEffects(t,e,s){let i=!1;const n=this._dropTarget;n&&n!==e&&n!==s&&(n.clearContextTop(),i=!0),e?.clearContextTop(),s!==e&&s?.clearContextTop();const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),i=!0),s&&(r.save(),s.transform(r),s.renderDropTargetEffect(t),r.restore(),i=!0),r.restore(),i&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==Yt,s=e?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};ve(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:i}=this.findDragTargets(t),n=this._dragSource,r={e:t,target:s,subTargets:i,dragSource:n,canDrop:!1,dropTarget:void 0};let a;this.fire(e,r),this._fireEnterLeaveEvents(s,r),s&&(s.canDrop(t)&&(a=s),s.fire(e,r));for(let l=0;l<i.length;l++){const h=i[l];h.canDrop(t)&&(a=h),h.fire(e,r)}this._renderDragEffects(t,n,a),this._dropTarget=a}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),i={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",i),this._fireEnterLeaveEvents(e,i)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),i=this._basicEventHandler("drop:before",x({e:t,target:e,subTargets:s,dragSource:this._dragSource},Js(this,t)));i.didDrop=!1,i.dropTarget=void 0,this._basicEventHandler("drop",i),this.fire("drop:after",i)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],i=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&Mo(t),this._basicEventHandler("contextmenu",i),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const i=this.upperCanvasEl,n=this._getEventPrefix(),r=Ce(i);os(r,"touchend",this._onTouchEnd,de),e&&os(r,"touchmove",this._onMouseMove,de),ve(i,"".concat(n,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();ve(e,"".concat(s,"move"),this._onMouseMove,de);const i=Ce(e);os(i,"".concat(s,"up"),this._onMouseUp),os(i,"".concat(s,"move"),this._onMouseMove,de)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=Ce(this.upperCanvasEl);ve(s,"touchend",this._onTouchEnd,de),ve(s,"touchmove",this._onMouseMove,de),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{os(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const i=Ce(this.upperCanvasEl);ve(i,"".concat(s,"up"),this._onMouseUp),ve(i,"".concat(s,"move"),this._onMouseMove,de),os(e,"".concat(s,"move"),this._onMouseMove,de)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,i=this._isClick,n=this._target,{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let a,l,h=!1;if(s&&(this._finalizeCurrentTransform(t),h=s.actionPerformed),!i){const c=n===this._activeObject;this.handleSelection(t),h||(h=this._shouldRender(n)||!c&&n===this._activeObject)}if(n){const c=n.findControl(this.getViewportPoint(t),Zi(t)),{key:u,control:d}=c||{};if(l=u,n.selectable&&n!==this._activeObject&&n.activeOn==="up")this.setActiveObject(n,t),h=!0;else if(d){const f=d.getMouseUpHandler(t,n,d);f&&(a=this.getScenePoint(t),f.call(d,t,s,a.x,a.y))}n.isMoving=!1}if(s&&(s.target!==n||s.corner!==l)){const c=s.target&&s.target.controls[s.corner],u=c&&c.getMouseUpHandler(t,s.target,c);a=a||this.getScenePoint(t),u&&u.call(c,t,s,a.x,a.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),h?this.requestRenderAll():i||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:i=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let n=0;n<i.length;n++)i[n]!==s&&i[n].fire(t,e);return e}_handleEvent(t,e,s){const i=this._target,n=this.targets||[],r=x(x(x({e:t,target:i,subTargets:n},Js(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),r),i&&i.fire("mouse".concat(e),r);for(let a=0;a<n.length;a++)n[a]!==i&&n[a].fire("mouse".concat(e),r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:i}=t;if(i)return(this.fireMiddleClick&&i===1||this.fireRightClick&&i===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const a=this.getScenePoint(t);this._groupSelector={x:a.x,y:a.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const a=e.findControl(this.getViewportPoint(t),Zi(t));if(e===this._activeObject&&(a||!r)){this._setupCurrentTransform(t,e,s);const l=a?a.control:void 0,h=this.getScenePoint(t),c=l&&l.getMouseDownHandler(t,e,l);c&&c.call(l,t,this._currentTransform,h.x,h.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),n&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=ws(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let a=0;a<r;a++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[a],oldTarget:i[a]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,i=this._hoveredTargets,n=this.targets,r=Math.max(i.length,n.length);this.fireSyntheticInOutEvents("drag",x(x({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let a=0;a<r;a++)this.fireSyntheticInOutEvents("drag",x(x({},e),{},{target:n[a],oldTarget:i[a]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:i,fireCanvas:n,e:r}=e,a=pt(e,Ad);const{targetIn:l,targetOut:h,canvasIn:c,canvasOut:u}=Td[t],d=i!==s;if(i&&d){const f=x(x({},a),{},{e:r,target:i,nextTarget:s},Js(this,r));n&&this.fire(u,f),i.fire(h,f)}if(s&&d){const f=x(x({},a),{},{e:r,target:s,previousTarget:i},Js(this,r));n&&this.fire(c,f),s.fire(l,f)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,i=s.target,n=i.group?ws(e,void 0,i.group.calcTransformMatrix()):e;s.shiftKey=t.shiftKey,s.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,s,n),s.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,s){const{action:i,actionHandler:n,target:r}=e,a=!!n&&n(t,e,s.x,s.y);a&&r.setCoords(),i==="drag"&&a&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||a}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const i=_s(this._activeObject)?this._activeObject:null,n=(!i||e.group!==i)&&e.findControl(this.getViewportPoint(t));if(n){const r=n.control;this.setCursor(r.cursorStyleHandler(t,r,e))}else e.subTargetCheck&&this.targets.concat().reverse().map(r=>{s=r.hoverCursor||s}),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,i=_s(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||i)&&(i||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(i){const n=s.getObjects();if(e===s){const r=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(n,r)||this.searchPossibleTargets(this._objects,r))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(n,t)}else{s.isEditing&&s.exitEditing();const n=new(I.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(s,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:i,deltaY:n}=this._groupSelector,r=new A(e,s),a=r.add(new A(i,n)),l=r.min(a),h=r.max(a).subtract(l),c=this.collectObjects({left:l.x,top:l.y,width:h.x,height:h.y},{includeIntersecting:!this.selectionFullyContained}),u=r.eq(a)?c[0]?[c[0]]:[]:c.length>1?c.filter(d=>!d.onSelect({e:t})).reverse():c;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const d=I.getClass("ActiveSelection");this.setActiveObject(new d(u,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const $l={x1:0,y1:0,x2:0,y2:0},Ed=x(x({},$l),{},{r1:0,r2:0}),Qs=(o,t)=>isNaN(o)&&typeof t=="number"?t:o,kd=/^(\d+\.\d+)%|(\d+)%$/;function ql(o){return o&&kd.test(o)}function Kl(o,t){const e=typeof o=="number"?o:typeof o=="string"?parseFloat(o)/(ql(o)?100:1):NaN;return Ss(0,Qs(e,t),1)}const Pd=/\s*;\s*/,Md=/\s*:\s*/;function Od(o,t){let e,s;const i=o.getAttribute("style");if(i){const r=i.split(Pd);r[r.length-1]===""&&r.pop();for(let a=r.length;a--;){const[l,h]=r[a].split(Md).map(c=>c.trim());l==="stop-color"?e=h:l==="stop-opacity"&&(s=h)}}const n=new ht(e||o.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Kl(o.getAttribute("offset"),0),color:n.toRgb(),opacity:Qs(parseFloat(s||o.getAttribute("stop-opacity")||""),1)*n.getAlpha()*t}}function Dd(o,t){const e=[],s=o.getElementsByTagName("stop"),i=Kl(t,1);for(let n=s.length;n--;)e.push(Od(s[n],i));return e}function Jl(o){return o.nodeName==="linearGradient"||o.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Ql(o){return o.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function ke(o,t){return o.getAttribute(t)}function Rd(o,t){return function(e,s){let i,{width:n,height:r,gradientUnits:a}=s;return Object.keys(e).reduce((l,h)=>{const c=e[h];return c==="Infinity"?i=1:c==="-Infinity"?i=0:(i=typeof c=="string"?parseFloat(c):c,typeof c=="string"&&ql(c)&&(i*=.01,a==="pixels"&&(h!=="x1"&&h!=="x2"&&h!=="r2"||(i*=n),h!=="y1"&&h!=="y2"||(i*=r)))),l[h]=i,l},{})}(Jl(o)==="linear"?function(e){return{x1:ke(e,"x1")||0,y1:ke(e,"y1")||0,x2:ke(e,"x2")||"100%",y2:ke(e,"y2")||0}}(o):function(e){return{x1:ke(e,"fx")||ke(e,"cx")||"50%",y1:ke(e,"fy")||ke(e,"cy")||"50%",r1:0,x2:ke(e,"cx")||"50%",y2:ke(e,"cy")||"50%",r2:ke(e,"r")||"50%"}}(o),x(x({},t),{},{gradientUnits:Ql(o)}))}class ki{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:i={},colorStops:n=[],offsetX:r=0,offsetY:a=0,gradientTransform:l,id:h}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:x(x({},e==="radial"?Ed:$l),i),colorStops:n,offsetX:r,offsetY:a,gradientTransform:l,id:h?"".concat(h,"_").concat(rs()):rs()})}addColorStop(t){for(const e in t){const s=new ht(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return x(x({},ys(this,t)),{},{type:this.type,coords:x({},this.coords),colorStops:this.colorStops.map(e=>x({},e)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],i=this.gradientTransform?this.gradientTransform.concat():Ut.concat(),n=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(u=>x({},u)).sort((u,d)=>u.offset-d.offset);let a=-this.offsetX,l=-this.offsetY;var h;n==="objectBoundingBox"?(a/=t.width,l/=t.height):(a+=t.width/2,l+=t.height/2),(h=t)&&typeof h._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(a-=t.pathOffset.x,l-=t.pathOffset.y),i[4]-=a,i[5]-=l;const c=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(n,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(Ws(i),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:d,x2:f,y2:g}=this.coords;s.push("<linearGradient ",c,' x1="',u,'" y1="',d,'" x2="',f,'" y2="',g,`">
|
|
71
|
+
`)}else if(this.type==="radial"){const{x1:u,y1:d,x2:f,y2:g,r1:p,r2:v}=this.coords,m=p>v;s.push("<radialGradient ",c,' cx="',m?u:f,'" cy="',m?d:g,'" r="',m?p:v,'" fx="',m?f:u,'" fy="',m?g:d,`">
|
|
72
|
+
`),m&&(r.reverse(),r.forEach(_=>{_.offset=1-_.offset}));const b=Math.min(p,v);if(b>0){const _=b/Math.max(p,v);r.forEach(w=>{w.offset+=_*(1-w.offset)})}}return r.forEach(u=>{let{color:d,offset:f,opacity:g}=u;s.push("<stop ",'offset="',100*f+"%",'" style="stop-color:',d,g!==void 0?";stop-opacity: "+g:";",`"/>
|
|
73
73
|
`)}),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
|
|
74
|
-
`),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:a}=this.coords,
|
|
75
|
-
`)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=
|
|
76
|
-
`)]}_getOffsetTransform(){const t=
|
|
77
|
-
`];{const{radius:e}=this,s=
|
|
78
|
-
`]}}static async fromElement(t,e,s){const i=
|
|
79
|
-
`)]}static async fromElement(t,e,s){const i=
|
|
80
|
-
`)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,
|
|
81
|
-
`)]}_render(t){const e=this.points.length,s=this.pathOffset.x,i=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-i);for(let n=0;n<e;n++){const r=this.points[n];t.lineTo(r.x-s,r.y-i)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(
|
|
82
|
-
`)}const Sx=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let yg;class Pe extends fv{static getDefaults(){return T(T({},super.getDefaults()),Pe.ownDefaults)}constructor(t,e){super(),E(this,"__charBounds",[]),Object.assign(this,Pe.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=gg(t.path))}_splitText(){const t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(Ti)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,a;for(let h=0,c=this._textLines.length;h<c;h++)if((this.textAlign===Ti||h!==c-1&&!this.isEndOfWrapping(h))&&(i=0,n=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(a=this.textLines[h].match(this._reSpacesAndTabs)))){s=a.length,t=(this.width-e)/s;for(let u=0;u<=n.length;u++)r=this.__charBounds[h][u],this._reSpaceAndTab.test(n[u])?(r.width+=t,r.kernedWidth+=t,r.left+=i,i+=t):r.left+=i}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let i;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===We?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,s){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case rt:t.textBaseline="middle";break;case"ascender":t.textBaseline=is;break;case"descender":t.textBaseline=Df}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,s,i,n,r){this._renderChars(t,e,s,i,n,r)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let i=this._getTopOffset();for(let n=0,r=this._textLines.length;n<r;n++){const a=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=a;continue}const h=this._textLines[n].length,c=this._getLineLeftOffset(n);let u,d,f=0,g=0,p=this.getValueOfPropertyAt(n,0,"textBackgroundColor");for(let m=0;m<h;m++){const y=this.__charBounds[n][m];d=this.getValueOfPropertyAt(n,m,"textBackgroundColor"),this.path?(t.save(),t.translate(y.renderLeft,y.renderTop),t.rotate(y.angle),t.fillStyle=d,d&&t.fillRect(-y.width/2,-a/this.lineHeight*(1-this._fontSizeFraction),y.width,a/this.lineHeight),t.restore()):d!==p?(u=s+c+g,this.direction==="rtl"&&(u=this.width-u-f),t.fillStyle=p,p&&t.fillRect(u,i,f,a/this.lineHeight),g=y.left,f=y.width,p=d):f+=y.kernedWidth}d&&!this.path&&(u=s+c+g,this.direction==="rtl"&&(u=this.width-u-f),t.fillStyle=d,t.fillRect(u,i,f,a/this.lineHeight)),i+=a}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=Xh.getFontCache(e),r=this._getFontDeclaration(e),a=s+t,h=s&&r===this._getFontDeclaration(i),c=e.fontSize/this.CACHE_FONT_SIZE;let u,d,f,g;if(s&&n[s]!==void 0&&(f=n[s]),n[t]!==void 0&&(g=u=n[t]),h&&n[a]!==void 0&&(d=n[a],g=d-f),u===void 0||f===void 0||d===void 0){const p=function(){return yg||(yg=ps({width:0,height:0}).getContext("2d")),yg}();this._setTextStyles(p,e,!0),u===void 0&&(g=u=p.measureText(t).width,n[t]=u),f===void 0&&h&&s&&(f=p.measureText(s).width,n[s]=f),h&&d===void 0&&(d=p.measureText(a).width,n[a]=d,g=d-f)}return{width:u*c,kernedWidth:g*c}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,i=0;const n=this.pathSide===$t,r=this.path,a=this._textLines[t],h=a.length,c=new Array(h);this.__charBounds[t]=c;for(let u=0;u<h;u++){const d=a[u];s=this._getGraphemeBox(d,t,u,e),c[u]=s,i+=s.kernedWidth,e=d}if(c[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let u=0;const d=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case wt:u=n?d-i:0;break;case rt:u=(d-i)/2;break;case $t:u=n?0:d-i}u+=this.pathStartOffset*(n?-1:1);for(let f=n?h-1:0;n?f>=0:f<h;n?f--:f++)s=c[f],u>d?u%=d:u<0&&(u+=d),this._setGraphemeOnPath(u,s),u+=s.kernedWidth}return{width:i,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,i=this.path,n=K0(i.path,s,i.segmentsInfo);e.renderLeft=n.x-i.pathOffset.x,e.renderTop=n.y-i.pathOffset.y,e.angle=n.angle+(this.pathSide===$t?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),a=i?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,r,i,a);let c,u=h.kernedWidth,d=h.width;this.charSpacing!==0&&(c=this._getWidthOfCharSpacing(),d+=c,u+=c);const f={width:d,left:0,height:r.fontSize,kernedWidth:u,deltaY:r.deltaY};if(s>0&&!n){const g=this.__charBounds[e][s-1];f.left=g.left+g.width+h.kernedWidth-h.width}return f}getHeightOfLine(t){if(this.__lineHeights[t])return this.__lineHeights[t];let e=this.getHeightOfChar(t,0);for(let s=1,i=this._textLines[t].length;s<i;s++)e=Math.max(this.getHeightOfChar(t,s),e);return this.__lineHeights[t]=e*this.lineHeight*this._fontSizeMult}calcTextHeight(){let t,e=0;for(let s=0,i=this._textLines.length;s<i;s++)t=this.getHeightOfLine(s),e+=s===i-1?t/this.lineHeight:t;return e}_getLeftOffset(){return this.direction==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const i=this._getLeftOffset(),n=this._getTopOffset();for(let r=0,a=this._textLines.length;r<a;r++){const h=this.getHeightOfLine(r),c=h/this.lineHeight,u=this._getLineLeftOffset(r);this._renderTextLine(e,t,this._textLines[r],i+u,n+s+c,r),s+=h}t.restore()}_renderTextFill(t){(this.fill||this.styleHas(ee))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,s,i,n,r){const a=this.getHeightOfLine(r),h=this.textAlign.includes(Ti),c=this.path,u=!h&&this.charSpacing===0&&this.isEmptyStyles(r)&&!c,d=this.direction==="ltr",f=this.direction==="ltr"?1:-1,g=e.direction;let p,m,y,b,x,S="",C=0;if(e.save(),g!==this.direction&&(e.canvas.setAttribute("dir",d?"ltr":"rtl"),e.direction=d?"ltr":"rtl",e.textAlign=d?wt:$t),n-=a*this._fontSizeFraction/this.lineHeight,u)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let k=0,O=s.length-1;k<=O;k++)b=k===O||this.charSpacing||c,S+=s[k],y=this.__charBounds[r][k],C===0?(i+=f*(y.kernedWidth-y.width),C+=y.width):C+=y.kernedWidth,h&&!b&&this._reSpaceAndTab.test(s[k])&&(b=!0),b||(p=p||this.getCompleteStyleDeclaration(r,k),m=this.getCompleteStyleDeclaration(r,k+1),b=Pu(p,m,!1)),b&&(c?(e.save(),e.translate(y.renderLeft,y.renderTop),e.rotate(y.angle),this._renderChar(t,e,r,k,S,-C/2,0),e.restore()):(x=i,this._renderChar(t,e,r,k,S,x,n)),S="",p=m,i+=f*C,C=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=ps({width:e,height:s}),n=i.getContext("2d");return i.width=e,i.height=s,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,s),n.lineTo(0,s),n.closePath(),n.translate(e/2,s/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(i,"no-repeat")}handleFiller(t,e,s){let i,n;return Fs(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(i=-this.width/2,n=-this.height/2,t.translate(i,n),t[e]=this._applyPatternGradientTransformText(s),{offsetX:i,offsetY:n}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:i}=e;return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,i,n,r,a){const h=this._getStyleDeclaration(s,i),c=this.getCompleteStyleDeclaration(s,i),u=t==="fillText"&&c.fill,d=t==="strokeText"&&c.stroke&&c.strokeWidth;if(d||u){if(e.save(),e.font=this._getFontDeclaration(c),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(a+=h.deltaY),u){const f=this._setFillStyles(e,c);e.fillText(n,r-f.offsetX,a-f.offsetY)}if(d){const f=this._setStrokeStyles(e,c);e.strokeText(n,r-f.offsetX,a-f.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,s){const i=this.get2DCursorLocation(t,!0),n=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"fontSize"),r=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"deltaY"),a={fontSize:n*s.size,deltaY:r+n*s.baseline};this.setSelectionStyles(a,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,i=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t);let a=0;return i===Ti||i===al&&!r||i===rl&&!r||i===Bu&&!r?0:(i===rt&&(a=s/2),i===$t&&(a=s),i===al&&(a=s/2),i===rl&&(a=s),n==="rtl"&&(i===$t||i===Ti||i===rl?a=0:i===wt||i===Bu?a=-s:i!==rt&&i!==al||(a=-s/2)),a)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var i;return(i=this._getStyleDeclaration(t,e)[s])!==null&&i!==void 0?i:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const i=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),a=this.offsets[e];for(let h=0,c=this._textLines.length;h<c;h++){const u=this.getHeightOfLine(h);if(!this[e]&&!this.styleHas(e,h)){s+=u;continue}const d=this._textLines[h],f=u/this.lineHeight,g=this._getLineLeftOffset(h);let p,m,y=0,b=0,x=this.getValueOfPropertyAt(h,0,e),S=this.getValueOfPropertyAt(h,0,ee);const C=s+f*(1-this._fontSizeFraction);let k=this.getHeightOfChar(h,0),O=this.getValueOfPropertyAt(h,0,"deltaY");for(let D=0,R=d.length;D<R;D++){const z=this.__charBounds[h][D];p=this.getValueOfPropertyAt(h,D,e),m=this.getValueOfPropertyAt(h,D,ee);const B=this.getHeightOfChar(h,D),F=this.getValueOfPropertyAt(h,D,"deltaY");if(n&&p&&m)t.save(),t.fillStyle=S,t.translate(z.renderLeft,z.renderTop),t.rotate(z.angle),t.fillRect(-z.kernedWidth/2,a*B+F,z.kernedWidth,this.fontSize/15),t.restore();else if((p!==x||m!==S||B!==k||F!==O)&&b>0){let L=i+g+y;this.direction==="rtl"&&(L=this.width-L-b),x&&S&&(t.fillStyle=S,t.fillRect(L,C+a*k+O,b,this.fontSize/15)),y=z.left,b=z.width,x=p,S=m,k=B,O=F}else b+=z.kernedWidth}let P=i+g+y;this.direction==="rtl"&&(P=this.width-P-b),t.fillStyle=m,p&&m&&t.fillRect(P,C+a*k+O,b-r,this.fontSize/15),s+=u}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||Pe.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return ku(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
|
|
83
|
-
`];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return
|
|
84
|
-
`]}_getSVGTextAndBg(o,t){const e=[],s=[];let i,n=o;this.backgroundColor&&s.push(...bg(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let r=0,a=this._textLines.length;r<a;r++)i=this._getLineLeftOffset(r),this.direction==="rtl"&&(i+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",r))&&this._setSVGTextLineBg(s,r,t+i,n),this._setSVGTextLineText(e,r,t+i,n),n+=this.getHeightOfLine(r);return{textSpans:e,textBgRects:s}}_createTextCharSpan(o,t,e,s,i){const n=bt.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,o!==o.trim()||!!o.match(wx)),a=r?'style="'.concat(r,'"'):"",h=t.deltaY,c=h?' dy="'.concat(Dt(h,n),'" '):"",{angle:u,renderLeft:d,renderTop:f,width:g}=i;let p="";if(d!==void 0){const m=g/2;u&&(p=' rotate="'.concat(Dt(Si(u),n),'"'));const y=Ir({angle:Si(u)});y[4]=d,y[5]=f;const b=new M(-m,0).transform(y);e=b.x,s=b.y}return'<tspan x="'.concat(Dt(e,n),'" y="').concat(Dt(s,n),'" ').concat(c).concat(p).concat(a,">").concat(E0(o),"</tspan>")}_setSVGTextLineText(o,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Ti),r=this._textLines[t];let a,h,c,u,d,f="",g=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let p=0,m=r.length-1;p<=m;p++)d=p===m||this.charSpacing||this.path,f+=r[p],c=this.__charBounds[t][p],g===0?(e+=c.kernedWidth-c.width,g+=c.width):g+=c.kernedWidth,n&&!d&&this._reSpaceAndTab.test(r[p])&&(d=!0),d||(a=a||this.getCompleteStyleDeclaration(t,p),h=this.getCompleteStyleDeclaration(t,p+1),d=Pu(a,h,!0)),d&&(u=this._getStyleDeclaration(t,p),o.push(this._createTextCharSpan(f,u,e,s,c)),f="",a=h,this.direction==="rtl"?e-=g:e+=g,g=0)}_setSVGTextLineBg(o,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,a=0,h=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let u=0;u<i.length;u++){const{left:d,width:f,kernedWidth:g}=this.__charBounds[t][u];r=this.getValueOfPropertyAt(t,u,"textBackgroundColor"),r!==c?(c&&o.push(...bg(c,e+h,s,a,n)),h=d,a=f,c=r):a+=g}r&&o.push(...bg(c,e+h,s,a,n))}_getSVGLineTopOffset(o){let t,e=0;for(t=0;t<o;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(o){return"".concat(super.getSvgStyles(o)," white-space: pre;")}getSvgSpanStyles(o,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:a,fontWeight:h,deltaY:c}=o,u=this.getSvgTextDecoration(o);return[i?Zh(We,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",a?"font-style: ".concat(a,"; "):"",h?"font-weight: ".concat(h,"; "):"",u&&"text-decoration: ".concat(u,"; "),n?Zh(ee,n):"",c?"baseline-shift: ".concat(-c,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(o){return["overline","underline","line-through"].filter(t=>o[t.replace("-","")]).join(" ")}}]),W.setClass(Pe),W.setSVGClass(Pe);class Cx{constructor(t){E(this,"target",void 0),E(this,"__mouseDownInPlace",!1),E(this,"__dragStartFired",!1),E(this,"__isDraggingOver",!1),E(this,"__dragStartSelection",void 0),E(this,"__dragImageDisposer",void 0),E(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(s=>s()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,a=r.canvas,h=new M(r.flipX?-1:1,r.flipY?-1:1),c=r._getCursorBoundaries(i),u=new M(c.left+c.leftOffset,c.top+c.topOffset).multiply(h).transform(r.calcTransformMatrix()),d=a.getScenePoint(t).subtract(u),f=r.getCanvasRetinaScaling(),g=r.getBoundingRect(),p=u.subtract(new M(g.left,g.top)),m=a.viewportTransform,y=p.add(d).transform(m,!0),b=r.backgroundColor,x=og(r.styles);r.backgroundColor="";const S={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(S,0,i),r.setSelectionStyles(S,n,r.text.length),r.dirty=!0;const C=r.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=b,r.styles=x,r.dirty=!0,Lu(C,{position:"fixed",left:"".concat(-C.width,"px"),border:ze,width:"".concat(C.width/f,"px"),height:"".concat(C.height/f,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{C.remove()},Qs(t.target||this.target.hiddenTextarea).body.appendChild(C),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(C,y.x,y.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=T({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,a=r.canvas;let h=r.getSelectionStartFromPointer(s);const{styles:c}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},u=n[Math.max(0,n.length-1)],d=0;if(this.__dragStartSelection){const f=this.__dragStartSelection.selectionStart,g=this.__dragStartSelection.selectionEnd;h>f&&h<=g?h=f:h>g&&(h-=g-f),r.removeChars(f,g),delete this.__dragStartSelection}r._reNewline.test(u)&&(r._reNewline.test(r._text[h])||h===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,c,h),a.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(h+d,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(lu,{index:h+d,action:"drop"}),a.fire("text:changed",{target:r}),a.contextTopDirty=!0,a.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:a}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||ze;h===ze?(i.selectionStart=r,i.selectionEnd=a,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),h==="move"&&(i.removeChars(r,a),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(lu,{index:r,action:"dragend"}),n.fire("text:changed",{target:i}),n.requestRenderAll()),i.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}const gv=/[ \n\.,;!\?\-]/;class Ax extends Pe{constructor(){super(...arguments),E(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return ng({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:i,onComplete:n,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:r=>{this._currentCursorOpacity=r,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;(t=this._currentTickCompleteState)===null||t===void 0||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,s=t-1;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s--;for(;/\S/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findWordBoundaryRight(t){let e=0,s=t;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s++;for(;/\S/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}findLineBoundaryLeft(t){let e=0,s=t-1;for(;!/\n/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findLineBoundaryRight(t){let e=0,s=t;for(;!/\n/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}searchWordBoundary(t,e){const s=this._text;let i=t>0&&this._reSpace.test(s[t])&&(e===-1||!Rf.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!gv.test(n);)i+=e,n=s[i];return e===-1&&gv.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;Qs(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&i!==n||i!==s&&n!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const i=s.slice(0,t),n=this.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=s.slice(t,e);return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,s){const i=s.slice(0,t).join("").length;return t===e?{selectionStart:i,selectionEnd:i}:{selectionStart:i,selectionEnd:i+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex,r=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,a=e.leftOffset,h=this.getCanvasRetinaScaling(),c=this.canvas.upperCanvasEl,u=c.width/h,d=c.height/h,f=u-r,g=d-r,p=new M(e.left+a,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new M(c.clientWidth/u,c.clientHeight/d));return p.x<0&&(p.x=0),p.x>f&&(p.x=f),p.y<0&&(p.y=0),p.y>g&&(p.y=g),p.x+=this.canvas._offset.left,p.y+=this.canvas._offset.top,{left:"".concat(p.x,"px"),top:"".concat(p.y,"px"),fontSize:"".concat(r,"px"),charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(uu),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let a=i;a<this._unwrappedTextLines[s].length;a++)delete this.styles[s][a];if(this.styles[n])for(let a=r;a<this._unwrappedTextLines[n].length;a++){const h=this.styles[n][a];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+a-r]=h)}for(let a=s+1;a<=n;a++)delete this.styles[a];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const a=this.styles[s],h=r-i;for(let c=i;c<r;c++)delete a[c];for(const c in this.styles[s]){const u=parseInt(c,10);u>=r&&(a[u-h]=a[c],delete a[c])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,a=r===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const c=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const d in this.styles[t]){const f=parseInt(d,10);f>=e&&(h=!0,n[f-e]=this.styles[t][d],a&&e===0||delete this.styles[t][d])}let u=!1;for(h&&!a&&(this.styles[t+s]=n,u=!0),(u||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:T({},i[s-1])}:c?this.styles[t+s]={0:T({},c)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?T({},n):{};s||(s=1);for(const h in r){const c=parseInt(h,10);c>=e&&(n[c+s]=r[c],r[c-s]||delete n[c])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=T({},i[s]));return}if(!n)return;const a=n[e?e-1:1];for(;a&&s--;)this.styles[t][e+s]=T({},a)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,a=0;for(let h=0;h<t.length;h++)t[h]===`
|
|
85
|
-
`?(a++,n[a]=0):n[a]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),a&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],a),r=1;r<a;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=wt:this._selectionDirection===$t&&(this._selectionDirection=wt,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===$t?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=$t:this._selectionDirection===wt&&(this._selectionDirection=$t,this.selectionStart=e),this.selectionEnd=s)}}class Tx extends Ax{initHiddenTextarea(){const t=this.canvas&&Qs(this.canvas.getElement())||lo(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off"}).map(r=>{let[a,h]=r;return e.setAttribute(a,h)});const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(i,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(n,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map(r=>{let[a,h]=r;return e.addEventListener(a,this[h].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(lu),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const a=this._splitTextIntoLines(s).graphemeText,h=this._text.length,c=a.length,u=this.selectionStart,d=this.selectionEnd,f=u!==d;let g,p,m,y,b=c-h;const x=this.fromStringToGraphemeSelection(i,n,s),S=u>x.selectionStart;f?(p=this._text.slice(u,d),b+=d-u):c<h&&(p=S?this._text.slice(d+b,d):this._text.slice(u,u-b));const C=a.slice(x.selectionEnd-b,x.selectionEnd);if(p&&p.length&&(C.length&&(g=this.getSelectionStyles(u,u+1,!1),g=C.map(()=>g[0])),f?(m=u,y=d):S?(m=d-p.length,y=d):(m=d,y=d+p.length),this.removeStyleFromTo(m,y)),C.length){const{copyPasteData:k}=xi();e&&C.join("")===k.copiedText&&!bt.disableStyleCopyPaste&&(g=k.copiedTextStyle),this.insertNewStyleBlock(C,u,g)}r()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:s,selectionEnd:i}=e;this.compositionStart=s,this.compositionEnd=i,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=xi();t.copiedText=this.getSelectedText(),bt.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,a=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n+1,a);return this._textLines[n].slice(r).length+h+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,a=this._getWidthBeforeCursor(n,r),h=this._getIndexOnLine(n-1,a),c=this._textLines[n].slice(0,r),u=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+h-c.length+(1-u)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),a=0;for(let h=0,c=s.length;h<c;h++)if(i=this.__charBounds[t][h].width,r+=i,r>e){n=!0;const u=r-i,d=r,f=Math.abs(u-e);a=Math.abs(d-e)<f?h:h-1;break}return n||(a=s.length-1),a}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===$t);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=Hr(0,this.selectionStart,i),this.selectionEnd=Hr(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===wt?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let i;if(t.altKey)i=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this["findLineBoundary".concat(s)](this[e])}return i!==void 0&&this[e]!==i&&(this[e]=i,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=wt,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===$t&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=wt,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===wt&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=$t,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=$t,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const pv=o=>!!o.button;class Ex extends Tx{constructor(){super(...arguments),E(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 Cx(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!pv(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}mouseUpHandler(t){let{e,transform:s}=t;const i=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const n=this.canvas._activeObject;if(n&&n!==this)return}!this.editable||this.group&&!this.group.interactive||s&&s.actionPerformed||pv(e)||i||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),s=this.selectionStart,i=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(s,i,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(ns(this.calcTransformMatrix())).add(new M(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let c=0;c<this._textLines.length&&s<=e.y;c++)s+=this.getHeightOfLine(c),n=c,c>0&&(i+=this._textLines[c-1].length+this.missingNewlineOffset(c-1));let r=Math.abs(this._getLineLeftOffset(n));const a=this._textLines[n].length,h=this.__charBounds[n];for(let c=0;c<a;c++){const u=r+h[c].kernedWidth;if(e.x<=u){Math.abs(e.x-u)<=Math.abs(e.x-r)&&i++;break}r=u,i++}return Math.min(this.flipX?a-i:i,this._text.length)}}const Hu="moveCursorUp",zu="moveCursorDown",Vu="moveCursorLeft",Wu="moveCursorRight",Gu="exitEditing",mv=(o,t)=>{const e=t.getRetinaScaling();o.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;o.transform(s[0],s[1],s[2],s[3],s[4],s[5])},kx=T({selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:Gu,27:Gu,33:Hu,34:zu,35:Wu,36:Vu,37:Vu,38:Hu,39:Wu,40:zu},keysMapRtl:{9:Gu,27:Gu,33:Hu,34:zu,35:Vu,36:Wu,37:Wu,38:Hu,39:Vu,40:zu},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class nn extends Ex{static getDefaults(){return T(T({},super.getDefaults()),nn.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,T(T({},nn.ownDefaults),e)),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):(t==="canvas"&&(this.canvas instanceof pg&&this.canvas.textEditingManager.remove(this),e instanceof pg&&e.textEditingManager.add(this)),super._set(t,e))}setSelectionStart(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)}setSelectionEnd(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)}_updateAndFire(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()}_fireSelectionChanged(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart||0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionEnd,s=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,s)}setSelectionStyles(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionStart||0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,s)}get2DCursorLocation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const s=super.toCanvasElement(t);return this.isEditing=e,s}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),i=s.length>0;let n,r=t;if(i){n=ps(t.canvas),r=n.getContext("2d"),mv(r,this.canvas);const a=this.calcTransformMatrix();r.transform(a[0],a[1],a[2],a[3],a[4],a[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const a of s){const h=a.clipPath,c=ps(t.canvas),u=c.getContext("2d");if(mv(u,this.canvas),!h.absolutePositioned){const d=a.calcTransformMatrix();u.transform(d[0],d[1],d[2],d[3],d[4],d[5])}h.transform(u),h.drawObject(u,!0,{}),this.drawClipPathOnCache(r,h,c)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:s,top:i,leftOffset:n.left,topOffset:n.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:i,lineIndex:n}=this.get2DCursorLocation(t);for(let c=0;c<n;c++)e+=this.getHeightOfLine(c);const r=this._getLineLeftOffset(n),a=this.__charBounds[n][i];a&&(s=a.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===$t||this.textAlign===Ti||this.textAlign===rl?h.left*=-1:this.textAlign===wt||this.textAlign===Bu?h.left=r-(s>0?s:0):this.textAlign!==rt&&this.textAlign!==al||(h.left=r-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),a=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/a,c=this.getValueOfPropertyAt(i,n,"deltaY"),u=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(i,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:u+e.top+c,width:h,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:a,width:h,height:c}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,a,h,c)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const i=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(Ti),a=this.get2DCursorLocation(i),h=this.get2DCursorLocation(n),c=a.lineIndex,u=h.lineIndex,d=a.charIndex<0?0:a.charIndex,f=h.charIndex<0?0:h.charIndex;for(let g=c;g<=u;g++){const p=this._getLineLeftOffset(g)||0;let m=this.getHeightOfLine(g),y=0,b=0,x=0;if(g===c&&(b=this.__charBounds[c][d].left),g>=c&&g<u)x=r&&!this.isEndOfWrapping(g)?this.width:this.getLineWidth(g)||5;else if(g===u)if(f===0)x=this.__charBounds[u][f].left;else{const P=this._getWidthOfCharSpacing();x=this.__charBounds[u][f-1].left+this.__charBounds[u][f-1].width-P}y=m,(this.lineHeight<1||g===u&&this.lineHeight>1)&&(m/=this.lineHeight);let S=s.left+p+b,C=m,k=0;const O=x-b;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",C=1,k=m):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===$t||this.textAlign===Ti||this.textAlign===rl?S=this.width-S-O:this.textAlign===wt||this.textAlign===Bu?S=s.left+p-x:this.textAlign!==rt&&this.textAlign!==al||(S=s.left+p-x)),t.fillRect(S,s.top+s.topOffset+k,O,C),s.topOffset+=y}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,ee)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}E(nn,"ownDefaults",kx),E(nn,"type","IText"),W.setClass(nn),W.setClass(nn,"i-text");class Gr extends nn{static getDefaults(){return T(T({},super.getDefaults()),Gr.ownDefaults)}constructor(t,e){super(t,T(T({},Gr.ownDefaults),e))}static createControls(){return{controls:dw()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this.textAlign.includes(Ti)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,i=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)t.graphemeText[i]===`
|
|
86
|
-
`&&r>0?(s=0,i++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[i])&&r>0&&(s++,i++),n[r]={line:e,offset:s},i+=t.graphemeLines[r].length,s+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,i=t+1,n=!1;const r=this._styleMap[t],a=this._styleMap[t+1];r&&(t=r.line,s=r.offset),a&&(i=a.line,n=i===t,e=a.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const c in h)for(const u in h[c]){const d=parseInt(u,10);if(d>=s&&(!n||d<e))for(const f in h[c][u])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const i=this._styleMap[t];super._setStyleDeclaration(i.line,i.offset+e,s)}_deleteStyleDeclaration(t,e){const s=this._styleMap[t];super._deleteStyleDeclaration(s.line,s.offset+e)}_getLineStyle(t){const e=this._styleMap[t];return!!this.styles[e.line]}_setLineStyle(t){const e=this._styleMap[t];super._setLineStyle(e.line)}_wrapText(t,e){this.isWrapping=!0;const s=this.getGraphemeDataForRender(t),i=[];for(let n=0;n<s.wordsData.length;n++)i.push(...this._wrapLine(n,e,s));return this.isWrapping=!1,i}getGraphemeDataForRender(t){const e=this.splitByGrapheme,s=e?"":" ";let i=0;return{wordsData:t.map((n,r)=>{let a=0;const h=e?this.graphemeSplit(n):this.wordSplit(n);return h.length===0?[{word:[],width:0}]:h.map(c=>{const u=e?[c]:this.graphemeSplit(c),d=this._measureWord(u,r,a);return i=Math.max(d,i),a+=u.length+s.length,{word:u,width:d}})}),largestWordWidth:i}}_measureWord(t,e){let s,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,n=0;for(let r=0,a=t.length;r<a;r++)n+=this._getGraphemeBox(t[r],e,r+i,s,!0).kernedWidth,s=t[r];return n}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:i,wordsData:n}=s,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const a=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,c=[],u=h?"":" ";let d=0,f=[],g=0,p=0,m=!0;e-=r;const y=Math.max(e,i,this.dynamicMinWidth),b=n[t];let x;for(g=0,x=0;x<b.length;x++){const{word:S,width:C}=b[x];g+=S.length,d+=p+C-a,d>y&&!m?(c.push(f),f=[],d=C,m=!0):d+=a,m||h||f.push(u),f=f.concat(S),p=h?0:this._measureWord([u],t,g),g++,m=!1}return x&&c.push(f),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-a+r),c}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}E(Gr,"type","Textbox"),E(Gr,"textLayoutProperties",[...nn.textLayoutProperties,"width"]),E(Gr,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),W.setClass(Gr);class vv extends Ru{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:s}=t,{clipPath:i,group:n}=s;if(!i||!this.shouldPerformLayout(t))return;const{width:r,height:a}=Ci(B0(s,i)),h=new M(r,a);if(i.absolutePositioned)return{center:Br(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:h};{const c=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:u=new M,correction:d=new M}=this.calcBoundingBox(e,t)||{};return{center:u.add(c),correction:d.subtract(c),size:h}}return{center:s.getRelativeCenterPoint().add(c),size:h}}}}E(vv,"type","clip-path"),W.setClass(vv);class bv extends Ru{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new M(s.width||i.x,s.height||i.y)}}E(bv,"type","fixed"),W.setClass(bv);class Px extends sl{subscribeTargets(t){const e=t.target;t.targets.reduce((s,i)=>(i.parent&&s.add(i.parent),s),new Set).forEach(s=>{s.layoutManager.subscribeTargets({target:s,targets:[e]})})}unsubscribeTargets(t){const e=t.target,s=e.getObjects();t.targets.reduce((i,n)=>(n.parent&&i.add(n.parent),i),new Set).forEach(i=>{!s.some(n=>n.parent===i)&&i.layoutManager.unsubscribeTargets({target:i,targets:[e]})})}}class Xr extends Ls{static getDefaults(){return T(T({},super.getDefaults()),Xr.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,Xr.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new Px})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];this.multiSelectionStacking==="selection-order"?this.add(...e):e.forEach(i=>{const n=this._objects.findIndex(a=>a.isInFrontOf(i)),r=n===-1?this.size():n;this.insertAt(r,i)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?($i("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);const s=new Set;e.forEach(i=>{const{parent:n}=i;n&&s.add(n)}),t===cg?s.forEach(i=>{i._onAfterObjectsChange(Ou,e)}):s.forEach(i=>{i._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=T(T({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}E(Xr,"type","ActiveSelection"),E(Xr,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),W.setClass(Xr),W.setClass(Xr,"activeSelection");class Mx{constructor(){E(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const a={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach(c=>{c.applyTo(a)});const{imageData:h}=a;return h.width===s&&h.height===i||(n.width=h.width,n.height=h.height),r.putImageData(h,0,0),a}}class yv{constructor(){let{tileSize:t=bt.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};E(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),E(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=ps({width:t,height:e}),i=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});i&&(i.clearColor(0,0,0,0),this.canvas=s,this.gl=i)}applyFilters(t,e,s,i,n,r){const a=this.gl,h=n.getContext("2d");if(!a||!h)return;let c;r&&(c=this.getCachedTexture(r,e));const u={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:i,destinationWidth:s,destinationHeight:i,context:a,sourceTexture:this.createTexture(a,s,i,c?void 0:e),targetTexture:this.createTexture(a,s,i),originalTexture:c||this.createTexture(a,s,i,c?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},d=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,d),t.forEach(f=>{f&&f.applyTo(u)}),function(f){const g=f.targetCanvas,p=g.width,m=g.height,y=f.destinationWidth,b=f.destinationHeight;p===y&&m===b||(g.width=y,g.height=b)}(u),this.copyGLTo2D(a,u),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(u.sourceTexture),a.deleteTexture(u.targetTexture),a.deleteFramebuffer(d),h.setTransform(1,0,0,1,0,0),u}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,s,i,n){const{NEAREST:r,TEXTURE_2D:a,RGBA:h,UNSIGNED_BYTE:c,CLAMP_TO_EDGE:u,TEXTURE_MAG_FILTER:d,TEXTURE_MIN_FILTER:f,TEXTURE_WRAP_S:g,TEXTURE_WRAP_T:p}=t,m=t.createTexture();return t.bindTexture(a,m),t.texParameteri(a,d,n||r),t.texParameteri(a,f,n||r),t.texParameteri(a,g,u),t.texParameteri(a,p,u),i?t.texImage2D(a,0,h,h,c,i):t.texImage2D(a,0,h,e,s,0,h,c,null),m}getCachedTexture(t,e,s){const{textureCache:i}=this;if(i[t])return i[t];{const n=this.createTexture(this.gl,e.width,e.height,e,s);return n&&(i[t]=n),n}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const s=t.canvas,i=e.targetCanvas,n=i.getContext("2d");if(!n)return;n.translate(0,i.height),n.scale(1,-1);const r=s.height-i.height;n.drawImage(s,0,r,i.width,i.height,0,0,i.width,i.height)}copyGLTo2DPutImageData(t,e){const s=e.targetCanvas.getContext("2d"),i=e.destinationWidth,n=e.destinationHeight,r=i*n*4;if(!s)return;const a=new Uint8Array(this.imageBuffer,0,r),h=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,a);const c=new ImageData(h,i,n);s.putImageData(c,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let _g;function Ox(){const{WebGLProbe:o}=xi();return o.queryWebGL(Rs()),bt.enableGLFiltering&&o.isSupported(bt.textureSize)?new yv({tileSize:bt.textureSize}):new Mx}function wg(){return!_g&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(_g=Ox()),_g}const Dx=["filters","resizeFilter","src","crossOrigin","type"],_v=["cropX","cropY"];class Me extends ke{static getDefaults(){return T(T({},super.getDefaults()),Me.ownDefaults)}constructor(t,e){super(),E(this,"_lastScaleX",1),E(this,"_lastScaleY",1),E(this,"_filterScalingX",1),E(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Me.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(Gn()),this.setElement(typeof t=="string"?(this.canvas&&Qs(this.canvas.getElement())||lo()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(Me.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=wg(!1);e instanceof yv&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{const e=this[t];e&&xi().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach(s=>{s&&e.push(s.toObject())}),T(T({},super.toObject([..._v,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,i=-this.height/2;let n=[],r=[],a="",h="";if(!e)return[];if(this.hasCrop()){const c=Gn();n.push('<clipPath id="imageCrop_'+c+`">
|
|
74
|
+
`),s.join("")}toLive(t){const{x1:e,y1:s,x2:i,y2:n,r1:r,r2:a}=this.coords,l=this.type==="linear"?t.createLinearGradient(e,s,i,n):t.createRadialGradient(e,s,r,i,n,a);return this.colorStops.forEach(h=>{let{color:c,opacity:u,offset:d}=h;l.addColorStop(d,u!==void 0?new ht(c).setAlpha(u).toRgba():c)}),l}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(x(x({},t),{},{colorStops:e?e.map(i=>x({},i)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const i=Ql(t),n=e._findCenterFromElement();return new this(x({id:t.getAttribute("id")||void 0,type:Jl(t),coords:Rd(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:Dd(t,s.opacity),gradientUnits:i,gradientTransform:pn(t.getAttribute("gradientTransform")||"")},i==="pixels"?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}))}}S(ki,"type","Gradient"),I.setClass(ki,"gradient"),I.setClass(ki,"linear"),I.setClass(ki,"radial");const Fd=["type","source","patternTransform"];class oa{get type(){return"pattern"}set type(t){Xe("warn","Setting type has no effect",t)}constructor(t){S(this,"repeat","repeat"),S(this,"offsetX",0),S(this,"offsetY",0),S(this,"crossOrigin",""),this.id=rs(),Object.assign(this,t)}isImageSource(){return!!this.source&&typeof this.source.src=="string"}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const{repeat:e,crossOrigin:s}=this;return x(x({},ys(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:ct(this.offsetX,nt.NUM_FRACTION_DIGITS),offsetY:ct(this.offsetY,nt.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:s}=t;const{source:i,repeat:n,id:r}=this,a=Qs(this.offsetX/e,0),l=Qs(this.offsetY/s,0),h=n==="repeat-y"||n==="no-repeat"?1+Math.abs(a||0):Qs(i.width/e,0),c=n==="repeat-x"||n==="no-repeat"?1+Math.abs(l||0):Qs(i.height/s,0);return['<pattern id="SVGID_'.concat(r,'" x="').concat(a,'" y="').concat(l,'" width="').concat(h,'" height="').concat(c,'">'),'<image x="0" y="0" width="'.concat(i.width,'" height="').concat(i.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
|
|
75
|
+
`)}static async fromObject(t,e){let{type:s,source:i,patternTransform:n}=t,r=pt(t,Fd);const a=await mi(i,x(x({},e),{},{crossOrigin:r.crossOrigin}));return new this(x(x({},r),{},{patternTransform:n&&n.slice(0),source:a}))}}S(oa,"type","Pattern"),I.setClass(oa),I.setClass(oa,"pattern");const Ld=["path","left","top"],Id=["d"];class Cs extends Ht{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:i,top:n}=e,r=pt(e,Ld);super(),Object.assign(this,Cs.ownDefaults),this.setOptions(r),this._setPath(t||[],!0),typeof i=="number"&&this.set(ot,i),typeof n=="number"&&this.set(ie,n)}_setPath(t,e){this.path=jl(Array.isArray(t)?t:Xl(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new A(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const i of this.path)switch(i[0]){case"L":t.lineTo(i[1]+e,i[2]+s);break;case"M":t.moveTo(i[1]+e,i[2]+s);break;case"C":t.bezierCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s,i[5]+e,i[6]+s);break;case"Q":t.quadraticCurveTo(i[1]+e,i[2]+s,i[3]+e,i[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return x(x({},super.toObject(t)),{},{path:this.path.map(e=>e.slice())})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=Ul(this.path,nt.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
|
|
76
|
+
`)]}_getOffsetTransform(){const t=nt.NUM_FRACTION_DIGITS;return" translate(".concat(ct(-this.pathOffset.x,t),", ").concat(ct(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return" "+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:i}=this._calcDimensions();this.set({width:e,height:s,pathOffset:i}),t&&this.setPositionByOrigin(i,q,q)}_calcBoundsFromPath(){const t=[];let e=0,s=0,i=0,n=0;for(const r of this.path)switch(r[0]){case"L":i=r[1],n=r[2],t.push({x:e,y:s},{x:i,y:n});break;case"M":i=r[1],n=r[2],e=i,s=n;break;case"C":t.push(...na(i,n,r[1],r[2],r[3],r[4],r[5],r[6])),i=r[5],n=r[6];break;case"Q":t.push(...na(i,n,r[1],r[2],r[1],r[2],r[3],r[4])),i=r[3],n=r[4];break;case"Z":i=e,n=s}return Ne(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return x(x({},t),{},{pathOffset:new A(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s),{d:n}=i;return new this(n,x(x(x({},pt(i,Id)),e),{},{left:void 0,top:void 0}))}}S(Cs,"type","Path"),S(Cs,"cacheProperties",[...$e,"path","fillRule"]),S(Cs,"ATTRIBUTE_NAMES",[...as,"d"]),I.setClass(Cs),I.setSVGClass(Cs);const jd=["left","top","radius"],Zl=["radius","startAngle","endAngle","counterClockwise"];class Qe extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Qe.ownDefaults)}constructor(t){super(),Object.assign(this,Qe.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),t==="radius"&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,wt(this.startAngle),wt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get($t)}getRadiusY(){return this.get("radius")*this.get(ce)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Zl,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
|
|
77
|
+
`];{const{radius:e}=this,s=wt(this.startAngle),i=wt(this.endAngle),n=xe(s)*e,r=Se(s)*e,a=xe(i)*e,l=Se(i)*e,h=t>180?1:0,c=this.counterClockwise?0:1;return['<path d="M '.concat(n," ").concat(r," A ").concat(e," ").concat(e," 0 ").concat(h," ").concat(c," ").concat(a," ").concat(l,'" '),"COMMON_PARTS",` />
|
|
78
|
+
`]}}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s),{left:n=0,top:r=0,radius:a=0}=i;return new this(x(x({},pt(i,jd)),{},{radius:a,left:n-a,top:r-a}))}static fromObject(t){return super._fromObject(t)}}S(Qe,"type","Circle"),S(Qe,"cacheProperties",[...$e,...Zl]),S(Qe,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),S(Qe,"ATTRIBUTE_NAMES",["cx","cy","r",...as]),I.setClass(Qe),I.setSVGClass(Qe);const Nd=["x1","y1","x2","y2"],Bd=["x1","y1","x2","y2"],la=["x1","x2","y1","y2"];class As extends Ht{constructor(){let[t,e,s,i]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,As.ownDefaults),this.setOptions(n),this.x1=t,this.x2=s,this.y1=e,this.y2=i,this._setWidthHeight();const{left:r,top:a}=n;typeof r=="number"&&this.set(ot,r),typeof a=="number"&&this.set(ie,a)}_setWidthHeight(){const{x1:t,y1:e,x2:s,y2:i}=this;this.width=Math.abs(s-t),this.height=Math.abs(i-e);const{left:n,top:r,width:a,height:l}=Ne([{x:t,y:e},{x:s,y:i}]),h=new A(n+a/2,r+l/2);this.setPositionByOrigin(h,q,q)}_set(t,e){return super._set(t,e),la.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const s=t.strokeStyle;var i;pe(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(i=this.stroke)!==null&&i!==void 0?i:t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=s}_findCenterFromElement(){return new A((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return x(x({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:i,width:n,height:r}=this,a=t<=e?-1:1,l=s<=i?-1:1;return{x1:a*n/2,x2:a*-n/2,y1:l*r/2,y2:l*-r/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:i}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(i,`" />
|
|
79
|
+
`)]}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s),{x1:n=0,y1:r=0,x2:a=0,y2:l=0}=i;return new this([n,r,a,l],pt(i,Nd))}static fromObject(t){let{x1:e,y1:s,x2:i,y2:n}=t,r=pt(t,Bd);return this._fromObject(x(x({},r),{},{points:[e,s,i,n]}),{extraParam:"points"})}}S(As,"type","Line"),S(As,"cacheProperties",[...$e,...la]),S(As,"ATTRIBUTE_NAMES",as.concat(la)),I.setClass(As),I.setSVGClass(As);class Ts extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Ts.ownDefaults)}constructor(t){super(),Object.assign(this,Ts.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}S(Ts,"type","Triangle"),S(Ts,"ownDefaults",{width:100,height:100}),I.setClass(Ts),I.setSVGClass(Ts);const th=["rx","ry"];class Ze extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Ze.ownDefaults)}constructor(t){super(),Object.assign(this,Ze.ownDefaults),this.setOptions(t)}_set(t,e){switch(super._set(t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this}getRx(){return this.get("rx")*this.get($t)}getRy(){return this.get("ry")*this.get(ce)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...th,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
|
|
80
|
+
`)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Ue,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const i=Ke(t,this.ATTRIBUTE_NAMES,s);return i.left=(i.left||0)-i.rx,i.top=(i.top||0)-i.ry,new this(i)}}function Hd(o){if(!o)return[];const t=o.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}S(Ze,"type","Ellipse"),S(Ze,"cacheProperties",[...$e,...th]),S(Ze,"ownDefaults",{rx:0,ry:0}),S(Ze,"ATTRIBUTE_NAMES",[...as,"cx","cy","rx","ry"]),I.setClass(Ze),I.setSVGClass(Ze);const zd=["left","top"],eh={exactBoundingBox:!1};class Pe extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Pe.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),S(this,"strokeDiff",void 0),Object.assign(this,Pe.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:i}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(ot,s),typeof i=="number"&&this.set(ie,i)}isOpen(){return!0}_projectStrokeOnPoints(t){return yl(this.points,t,this.isOpen())}_calcDimensions(t){t=x({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(h=>h.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new A,strokeOffset:new A,strokeDiff:new A};const s=Ne(e),i=pi(x(x({},t),{},{scaleX:1,scaleY:1})),n=Ne(this.points.map(h=>Bt(h,i,!0))),r=new A(this.scaleX,this.scaleY);let a=s.left+s.width/2,l=s.top+s.height/2;return this.exactBoundingBox&&(a-=l*Math.tan(wt(this.skewX)),l-=a*Math.tan(wt(this.skewY))),x(x({},s),{},{pathOffset:new A(a,l),strokeOffset:new A(n.left,n.top).subtract(new A(s.left,s.top)).multiply(r),strokeDiff:new A(s.width,s.height).subtract(new A(n.width,n.height)).multiply(r)})}_findCenterFromElement(){const t=Ne(this.points);return new A(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:s,width:i,height:n,pathOffset:r,strokeOffset:a,strokeDiff:l}=this._calcDimensions();this.set({width:i,height:n,pathOffset:r,strokeOffset:a,strokeDiff:l}),t&&this.setPositionByOrigin(new A(e+i/2,s+n/2),q,q)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new A(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let r;if(Object.keys(t).some(a=>this.strokeUniform||this.constructor.layoutProperties.includes(a))){var e,s;const{width:a,height:l}=this._calcDimensions(t);r=new A((e=t.width)!==null&&e!==void 0?e:a,(s=t.height)!==null&&s!==void 0?s:l)}else{var i,n;r=new A((i=t.width)!==null&&i!==void 0?i:this.width,(n=t.height)!==null&&n!==void 0?n:this.height)}return r.multiply(new A(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const s=this.initialized&&this[t]!==e,i=super._set(t,e);return this.exactBoundingBox&&s&&((t===$t||t===ce)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),i}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return x(x({},super.toObject(t)),{},{points:this.points.map(e=>{let{x:s,y:i}=e;return{x:s,y:i}})})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,i=nt.NUM_FRACTION_DIGITS;for(let n=0,r=this.points.length;n<r;n++)t.push(ct(this.points[n].x-e,i),",",ct(this.points[n].y-s,i)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
|
|
81
|
+
`)]}_render(t){const e=this.points.length,s=this.pathOffset.x,i=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-i);for(let n=0;n<e;n++){const r=this.points[n];t.lineTo(r.x-s,r.y-i)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(Hd(t.getAttribute("points")),x(x({},pt(Ke(t,this.ATTRIBUTE_NAMES,s),zd)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}S(Pe,"ownDefaults",eh),S(Pe,"type","Polyline"),S(Pe,"layoutProperties",[Bs,Hs,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),S(Pe,"cacheProperties",[...$e,"points"]),S(Pe,"ATTRIBUTE_NAMES",[...as]),I.setClass(Pe),I.setSVGClass(Pe);class Sn extends Pe{isOpen(){return!1}}S(Sn,"ownDefaults",eh),S(Sn,"type","Polygon"),I.setClass(Sn),I.setSVGClass(Sn);class sh extends Ht{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const i in e[s])for(const n in e[s][i])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const i in s)for(const n in s[i])if(s[i][n][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,i,n=0,r=!0,a=0;for(const l in e){s=0;for(const h in e[l]){const c=e[l][h]||{};n++,c[t]!==void 0?(i?c[t]!==i&&(r=!1):i=c[t],c[t]===this[t]&&delete c[t]):r=!1,Object.keys(c).length!==0?s++:delete e[l][h]}s===0&&delete e[l]}for(let l=0;l<this._textLines.length;l++)a+=this._textLines[l].length;r&&n===a&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,i,n;for(i in e){for(n in s=e[i],s)delete s[n][t],Object.keys(s[n]).length===0&&delete s[n];Object.keys(s).length===0&&delete e[i]}}_extendStyles(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const n=Or(x(x({},this._getStyleDeclaration(s,i)),e),r=>r!==void 0);this._setStyleDeclaration(s,i,n)}getSelectionStyles(t,e,s){const i=[];for(let n=t;n<(e||t);n++)i.push(this.getStyleAtPosition(n,s));return i}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,i):this._getStyleDeclaration(s,i)}setSelectionStyles(t,e,s){for(let i=e;i<(s||e);i++)this._extendStyles(i,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const i=this.styles&&this.styles[t];return i&&(s=i[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return x(x({},ys(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}S(sh,"_styleProperties",tu);const Vd=/ +/g,Gd=/"/g;function ha(o,t,e,s,i){return" ".concat(function(n,r){let{left:a,top:l,width:h,height:c}=r,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nt.NUM_FRACTION_DIGITS;const d=_i(kt,n,!1),[f,g,p,v]=[a,l,h,c].map(m=>ct(m,u));return"<rect ".concat(d,' x="').concat(f,'" y="').concat(g,'" width="').concat(p,'" height="').concat(v,'"></rect>')}(o,{left:t,top:e,width:s,height:i}),`
|
|
82
|
+
`)}const Wd=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let ca;class zt extends sh{static getDefaults(){return x(x({},super.getDefaults()),zt.ownDefaults)}constructor(t,e){super(),S(this,"__charBounds",[]),Object.assign(this,zt.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=ra(t.path))}_splitText(){const t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(Be)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,i,n,r,a;for(let l=0,h=this._textLines.length;l<h;l++)if((this.textAlign===Be||l!==h-1&&!this.isEndOfWrapping(l))&&(i=0,n=this._textLines[l],e=this.getLineWidth(l),e<this.width&&(a=this.textLines[l].match(this._reSpacesAndTabs)))){s=a.length,t=(this.width-e)/s;for(let c=0;c<=n.length;c++)r=this.__charBounds[l][c],this._reSpaceAndTab.test(n[c])?(r.width+=t,r.kernedWidth+=t,r.left+=i,i+=t):r.left+=i}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let i;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===qt?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,s){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case q:t.textBaseline="middle";break;case"ascender":t.textBaseline=ie;break;case"descender":t.textBaseline=xr}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,s,i,n,r){this._renderChars(t,e,s,i,n,r)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let i=this._getTopOffset();for(let n=0,r=this._textLines.length;n<r;n++){const a=this.getHeightOfLine(n);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",n)){i+=a;continue}const l=this._textLines[n].length,h=this._getLineLeftOffset(n);let c,u,d=0,f=0,g=this.getValueOfPropertyAt(n,0,"textBackgroundColor");for(let p=0;p<l;p++){const v=this.__charBounds[n][p];u=this.getValueOfPropertyAt(n,p,"textBackgroundColor"),this.path?(t.save(),t.translate(v.renderLeft,v.renderTop),t.rotate(v.angle),t.fillStyle=u,u&&t.fillRect(-v.width/2,-a/this.lineHeight*(1-this._fontSizeFraction),v.width,a/this.lineHeight),t.restore()):u!==g?(c=s+h+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=g,g&&t.fillRect(c,i,d,a/this.lineHeight),f=v.left,d=v.width,g=u):d+=v.kernedWidth}u&&!this.path&&(c=s+h+f,this.direction==="rtl"&&(c=this.width-c-d),t.fillStyle=u,t.fillRect(c,i,d,a/this.lineHeight)),i+=a}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,i){const n=di.getFontCache(e),r=this._getFontDeclaration(e),a=s+t,l=s&&r===this._getFontDeclaration(i),h=e.fontSize/this.CACHE_FONT_SIZE;let c,u,d,f;if(s&&n[s]!==void 0&&(d=n[s]),n[t]!==void 0&&(f=c=n[t]),l&&n[a]!==void 0&&(u=n[a],f=u-d),c===void 0||d===void 0||u===void 0){const g=function(){return ca||(ca=ue({width:0,height:0}).getContext("2d")),ca}();this._setTextStyles(g,e,!0),c===void 0&&(f=c=g.measureText(t).width,n[t]=c),d===void 0&&l&&s&&(d=g.measureText(s).width,n[s]=d),l&&u===void 0&&(u=g.measureText(a).width,n[a]=u,f=u-d)}return{width:c*h,kernedWidth:f*h}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,i=0;const n=this.pathSide===xt,r=this.path,a=this._textLines[t],l=a.length,h=new Array(l);this.__charBounds[t]=h;for(let c=0;c<l;c++){const u=a[c];s=this._getGraphemeBox(u,t,c,e),h[c]=s,i+=s.kernedWidth,e=u}if(h[l]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let c=0;const u=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case ot:c=n?u-i:0;break;case q:c=(u-i)/2;break;case xt:c=n?0:u-i}c+=this.pathStartOffset*(n?-1:1);for(let d=n?l-1:0;n?d>=0:d<l;n?d--:d++)s=h[d],c>u?c%=u:c<0&&(c+=u),this._setGraphemeOnPath(c,s),c+=s.kernedWidth}return{width:i,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,i=this.path,n=Gl(i.path,s,i.segmentsInfo);e.renderLeft=n.x-i.pathOffset.x,e.renderTop=n.y-i.pathOffset.y,e.angle=n.angle+(this.pathSide===xt?Math.PI:0)}_getGraphemeBox(t,e,s,i,n){const r=this.getCompleteStyleDeclaration(e,s),a=i?this.getCompleteStyleDeclaration(e,s-1):{},l=this._measureChar(t,r,i,a);let h,c=l.kernedWidth,u=l.width;this.charSpacing!==0&&(h=this._getWidthOfCharSpacing(),u+=h,c+=h);const d={width:u,left:0,height:r.fontSize,kernedWidth:c,deltaY:r.deltaY};if(s>0&&!n){const f=this.__charBounds[e][s-1];d.left=f.left+f.width+l.kernedWidth-l.width}return d}getHeightOfLine(t){if(this.__lineHeights[t])return this.__lineHeights[t];let e=this.getHeightOfChar(t,0);for(let s=1,i=this._textLines[t].length;s<i;s++)e=Math.max(this.getHeightOfChar(t,s),e);return this.__lineHeights[t]=e*this.lineHeight*this._fontSizeMult}calcTextHeight(){let t,e=0;for(let s=0,i=this._textLines.length;s<i;s++)t=this.getHeightOfLine(s),e+=s===i-1?t/this.lineHeight:t;return e}_getLeftOffset(){return this.direction==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const i=this._getLeftOffset(),n=this._getTopOffset();for(let r=0,a=this._textLines.length;r<a;r++){const l=this.getHeightOfLine(r),h=l/this.lineHeight,c=this._getLineLeftOffset(r);this._renderTextLine(e,t,this._textLines[r],i+c,n+s+h,r),s+=l}t.restore()}_renderTextFill(t){(this.fill||this.styleHas(kt))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,s,i,n,r){const a=this.getHeightOfLine(r),l=this.textAlign.includes(Be),h=this.path,c=!l&&this.charSpacing===0&&this.isEmptyStyles(r)&&!h,u=this.direction==="ltr",d=this.direction==="ltr"?1:-1,f=e.direction;let g,p,v,m,b,_="",w=0;if(e.save(),f!==this.direction&&(e.canvas.setAttribute("dir",u?"ltr":"rtl"),e.direction=u?"ltr":"rtl",e.textAlign=u?ot:xt),n-=a*this._fontSizeFraction/this.lineHeight,c)return this._renderChar(t,e,r,0,s.join(""),i,n),void e.restore();for(let C=0,T=s.length-1;C<=T;C++)m=C===T||this.charSpacing||h,_+=s[C],v=this.__charBounds[r][C],w===0?(i+=d*(v.kernedWidth-v.width),w+=v.width):w+=v.kernedWidth,l&&!m&&this._reSpaceAndTab.test(s[C])&&(m=!0),m||(g=g||this.getCompleteStyleDeclaration(r,C),p=this.getCompleteStyleDeclaration(r,C+1),m=gn(g,p,!1)),m&&(h?(e.save(),e.translate(v.renderLeft,v.renderTop),e.rotate(v.angle),this._renderChar(t,e,r,C,_,-w/2,0),e.restore()):(b=i,this._renderChar(t,e,r,C,_,b,n)),_="",g=p,i+=d*w,w=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,i=ue({width:e,height:s}),n=i.getContext("2d");return i.width=e,i.height=s,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,s),n.lineTo(0,s),n.closePath(),n.translate(e/2,s/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(i,"no-repeat")}handleFiller(t,e,s){let i,n;return pe(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(i=-this.width/2,n=-this.height/2,t.translate(i,n),t[e]=this._applyPatternGradientTransformText(s),{offsetX:i,offsetY:n}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:i}=e;return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,i,n,r,a){const l=this._getStyleDeclaration(s,i),h=this.getCompleteStyleDeclaration(s,i),c=t==="fillText"&&h.fill,u=t==="strokeText"&&h.stroke&&h.strokeWidth;if(u||c){if(e.save(),e.font=this._getFontDeclaration(h),l.textBackgroundColor&&this._removeShadow(e),l.deltaY&&(a+=l.deltaY),c){const d=this._setFillStyles(e,h);e.fillText(n,r-d.offsetX,a-d.offsetY)}if(u){const d=this._setStrokeStyles(e,h);e.strokeText(n,r-d.offsetX,a-d.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,s){const i=this.get2DCursorLocation(t,!0),n=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"fontSize"),r=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"deltaY"),a={fontSize:n*s.size,deltaY:r+n*s.baseline};this.setSelectionStyles(a,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,i=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t);let a=0;return i===Be||i===xi&&!r||i===wi&&!r||i===rn&&!r?0:(i===q&&(a=s/2),i===xt&&(a=s),i===xi&&(a=s/2),i===wi&&(a=s),n==="rtl"&&(i===xt||i===Be||i===wi?a=0:i===ot||i===rn?a=-s:i!==q&&i!==xi||(a=-s/2)),a)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var i;return(i=this._getStyleDeclaration(t,e)[s])!==null&&i!==void 0?i:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const i=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),a=e==="linethrough"?.5:e==="overline"?1:0,l=this.offsets[e];for(let h=0,c=this._textLines.length;h<c;h++){const u=this.getHeightOfLine(h);if(!this[e]&&!this.styleHas(e,h)){s+=u;continue}const d=this._textLines[h],f=u/this.lineHeight,g=this._getLineLeftOffset(h);let p=0,v=0,m=this.getValueOfPropertyAt(h,0,e),b=this.getValueOfPropertyAt(h,0,kt),_=this.getValueOfPropertyAt(h,0,xs),w=m,C=b,T=_;const E=s+f*(1-this._fontSizeFraction);let k=this.getHeightOfChar(h,0),O=this.getValueOfPropertyAt(h,0,"deltaY");for(let P=0,R=d.length;P<R;P++){const F=this.__charBounds[h][P];w=this.getValueOfPropertyAt(h,P,e),C=this.getValueOfPropertyAt(h,P,kt),T=this.getValueOfPropertyAt(h,P,xs);const V=this.getHeightOfChar(h,P),M=this.getValueOfPropertyAt(h,P,"deltaY");if(n&&w&&C){const L=this.fontSize*T/1e3;t.save(),t.fillStyle=b,t.translate(F.renderLeft,F.renderTop),t.rotate(F.angle),t.fillRect(-F.kernedWidth/2,l*V+M-a*L,F.kernedWidth,L),t.restore()}else if((w!==m||C!==b||V!==k||T!==_||M!==O)&&v>0){const L=this.fontSize*_/1e3;let Y=i+g+p;this.direction==="rtl"&&(Y=this.width-Y-v),m&&b&&_&&(t.fillStyle=b,t.fillRect(Y,E+l*k+O-a*L,v,L)),p=F.left,v=F.width,m=w,_=T,b=C,k=V,O=M}else v+=F.kernedWidth}let H=i+g+p;this.direction==="rtl"&&(H=this.width-H-v),t.fillStyle=C;const N=this.fontSize*T/1e3;w&&C&&T&&t.fillRect(H,E+l*k+O-a*N,v-r,N),s+=u}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:i=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0;const r=t.includes("'")||t.includes('"')||t.includes(",")||zt.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(n?this.CACHE_FONT_SIZE:i,"px"),r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return fn(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),i=[`
|
|
83
|
+
`];let n=[];for(let r=0;r<e.length;r++)s[r]=this.graphemeSplit(e[r]),n=n.concat(s[r],i);return n.pop(),{_unwrappedLines:s,lines:e,graphemeText:n,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return x(x({},super.toObject([...Yo,...t])),{},{styles:wl(this.styles,this.text)},this.path?{path:this.path.toObject()}:{})}set(t,e){const{textLayoutProperties:s}=this.constructor;super.set(t,e);let i=!1,n=!1;if(typeof t=="object")for(const r in t)r==="path"&&this.setPathInfo(),i=i||s.includes(r),n=n||r==="path";else i=s.includes(t),n=t==="path";return n&&this.setPathInfo(),i&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,s){const i=Ke(t,zt.ATTRIBUTE_NAMES,s),n=x(x({},e),i),{textAnchor:r=ot,textDecoration:a="",dx:l=0,dy:h=0,top:c=0,left:u=0,fontSize:d=wr,strokeWidth:f=1}=n,g=pt(n,Wd),p=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),x({left:u+l,top:c+h,underline:a.includes("underline"),overline:a.includes("overline"),linethrough:a.includes("line-through"),strokeWidth:0,fontSize:d},g)),v=p.getScaledHeight()/p.height,m=((p.height+p.strokeWidth)*p.lineHeight-p.height)*v,b=p.getScaledHeight()+m;let _=0;return r===q&&(_=p.getScaledWidth()/2),r===xt&&(_=p.getScaledWidth()),p.set({left:p.left-_,top:p.top-(b-p.fontSize*(.07+p._fontSizeFraction))/p.lineHeight,strokeWidth:f}),p}static fromObject(t){return this._fromObject(x(x({},t),{},{styles:xl(t.styles||{},t.text)}),{extraParam:"text"})}}S(zt,"textLayoutProperties",Uo),S(zt,"cacheProperties",[...$e,...Yo]),S(zt,"ownDefaults",eu),S(zt,"type","Text"),S(zt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),S(zt,"ATTRIBUTE_NAMES",as.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),pl(zt,[class extends Go{_toSVG(){const o=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(o.textTop,o.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(o){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:o,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:o,withShadow:!0,additionalTransform:Ws(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(o){let{textBgRects:t,textSpans:e}=o;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ','font-family="'.concat(this.fontFamily.replace(Gd,"'"),'" '),'font-size="'.concat(this.fontSize,'" '),this.fontStyle?'font-style="'.concat(this.fontStyle,'" '):"",this.fontWeight?'font-weight="'.concat(this.fontWeight,'" '):"",s?'text-decoration="'.concat(s,'" '):"",this.direction==="rtl"?'direction="'.concat(this.direction,'" '):"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
|
|
84
|
+
`]}_getSVGTextAndBg(o,t){const e=[],s=[];let i,n=o;this.backgroundColor&&s.push(...ha(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let r=0,a=this._textLines.length;r<a;r++)i=this._getLineLeftOffset(r),this.direction==="rtl"&&(i+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",r))&&this._setSVGTextLineBg(s,r,t+i,n),this._setSVGTextLineText(e,r,t+i,n),n+=this.getHeightOfLine(r);return{textSpans:e,textBgRects:s}}_createTextCharSpan(o,t,e,s,i){const n=nt.NUM_FRACTION_DIGITS,r=this.getSvgSpanStyles(t,o!==o.trim()||!!o.match(Vd)),a=r?'style="'.concat(r,'"'):"",l=t.deltaY,h=l?' dy="'.concat(ct(l,n),'" '):"",{angle:c,renderLeft:u,renderTop:d,width:f}=i;let g="";if(u!==void 0){const p=f/2;c&&(g=' rotate="'.concat(ct(je(c),n),'"'));const v=bs({angle:je(c)});v[4]=u,v[5]=d;const m=new A(-p,0).transform(v);e=m.x,s=m.y}return'<tspan x="'.concat(ct(e,n),'" y="').concat(ct(s,n),'" ').concat(h).concat(g).concat(a,">").concat(_l(o),"</tspan>")}_setSVGTextLineText(o,t,e,s){const i=this.getHeightOfLine(t),n=this.textAlign.includes(Be),r=this._textLines[t];let a,l,h,c,u,d="",f=0;s+=i*(1-this._fontSizeFraction)/this.lineHeight;for(let g=0,p=r.length-1;g<=p;g++)u=g===p||this.charSpacing||this.path,d+=r[g],h=this.__charBounds[t][g],f===0?(e+=h.kernedWidth-h.width,f+=h.width):f+=h.kernedWidth,n&&!u&&this._reSpaceAndTab.test(r[g])&&(u=!0),u||(a=a||this.getCompleteStyleDeclaration(t,g),l=this.getCompleteStyleDeclaration(t,g+1),u=gn(a,l,!0)),u&&(c=this._getStyleDeclaration(t,g),o.push(this._createTextCharSpan(d,c,e,s,h)),d="",a=l,this.direction==="rtl"?e-=f:e+=f,f=0)}_setSVGTextLineBg(o,t,e,s){const i=this._textLines[t],n=this.getHeightOfLine(t)/this.lineHeight;let r,a=0,l=0,h=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let c=0;c<i.length;c++){const{left:u,width:d,kernedWidth:f}=this.__charBounds[t][c];r=this.getValueOfPropertyAt(t,c,"textBackgroundColor"),r!==h?(h&&o.push(...ha(h,e+l,s,a,n)),l=u,a=d,h=r):a+=f}r&&o.push(...ha(h,e+l,s,a,n))}_getSVGLineTopOffset(o){let t,e=0;for(t=0;t<o;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(o){return"".concat(super.getSvgStyles(o)," text-decoration-thickness: ").concat(ct(this.textDecorationThickness*this.getObjectScaling().y/10,nt.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(o,t){const{fontFamily:e,strokeWidth:s,stroke:i,fill:n,fontSize:r,fontStyle:a,fontWeight:l,deltaY:h,textDecorationThickness:c,linethrough:u,overline:d,underline:f}=o,g=this.getSvgTextDecoration({underline:f??this.underline,overline:d??this.overline,linethrough:u??this.linethrough}),p=c||this.textDecorationThickness;return[i?_i(qt,i):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",r?"font-size: ".concat(r,"px; "):"",a?"font-style: ".concat(a,"; "):"",l?"font-weight: ".concat(l,"; "):"",g?"text-decoration: ".concat(g,"; text-decoration-thickness: ").concat(ct(p*this.getObjectScaling().y/10,nt.NUM_FRACTION_DIGITS),"%; "):"",n?_i(kt,n):"",h?"baseline-shift: ".concat(-h,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(o){return["overline","underline","line-through"].filter(t=>o[t.replace("-","")]).join(" ")}}]),I.setClass(zt),I.setSVGClass(zt);class Xd{constructor(t){S(this,"target",void 0),S(this,"__mouseDownInPlace",!1),S(this,"__dragStartFired",!1),S(this,"__isDraggingOver",!1),S(this,"__dragStartSelection",void 0),S(this,"__dragImageDisposer",void 0),S(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(s=>s()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:i,selectionEnd:n}=e;const r=this.target,a=r.canvas,l=new A(r.flipX?-1:1,r.flipY?-1:1),h=r._getCursorBoundaries(i),c=new A(h.left+h.leftOffset,h.top+h.topOffset).multiply(l).transform(r.calcTransformMatrix()),u=a.getScenePoint(t).subtract(c),d=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),g=c.subtract(new A(f.left,f.top)),p=a.viewportTransform,v=g.add(u).transform(p,!0),m=r.backgroundColor,b=Qr(r.styles);r.backgroundColor="";const _={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(_,0,i),r.setSelectionStyles(_,n,r.text.length),r.dirty=!0;const w=r.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=m,r.styles=b,r.dirty=!0,_n(w,{position:"fixed",left:"".concat(-w.width,"px"),border:Yt,width:"".concat(w.width/d,"px"),height:"".concat(w.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{w.remove()},Ce(t.target||this.target.hiddenTextarea).body.appendChild(w),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(w,v.x,v.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},n=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r=x({text:e.text,value:n},i);t.dataTransfer.setData("text/plain",n),t.dataTransfer.setData("application/fabric",JSON.stringify({value:n,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,i=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let n=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(n&&!i){const r=this.target,a=r.canvas;let l=r.getSelectionStartFromPointer(s);const{styles:h}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},c=n[Math.max(0,n.length-1)],u=0;if(this.__dragStartSelection){const d=this.__dragStartSelection.selectionStart,f=this.__dragStartSelection.selectionEnd;l>d&&l<=f?l=d:l>f&&(l-=f-d),r.removeChars(d,f),delete this.__dragStartSelection}r._reNewline.test(c)&&(r._reNewline.test(r._text[l])||l===r._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=r,r.insertChars(n,h,l),a.setActiveObject(r),r.enterEditing(s),r.selectionStart=Math.min(l+u,r._text.length),r.selectionEnd=Math.min(r.selectionStart+n.length,r._text.length),r.hiddenTextarea.value=r.text,r._updateTextarea(),r.hiddenTextarea.focus(),r.fire(Ui,{index:l+u,action:"drop"}),a.fire("text:changed",{target:r}),a.contextTopDirty=!0,a.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const i=this.target,n=this.target.canvas,{selectionStart:r,selectionEnd:a}=this.__dragStartSelection,l=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||Yt;l===Yt?(i.selectionStart=r,i.selectionEnd=a,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),l==="move"&&(i.removeChars(r,a),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(Ui,{index:r,action:"dragend"}),n.fire("text:changed",{target:i}),n.requestRenderAll()),i.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}const ih=/[ \n\.,;!\?\-]/;class Ud extends zt{constructor(){super(...arguments),S(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:i,onComplete:n}=t;return qr({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:i,onComplete:n,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:r=>{this._currentCursorOpacity=r,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;(t=this._currentTickCompleteState)===null||t===void 0||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,s=t-1;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s--;for(;/\S/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findWordBoundaryRight(t){let e=0,s=t;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s++;for(;/\S/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}findLineBoundaryLeft(t){let e=0,s=t-1;for(;!/\n/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findLineBoundaryRight(t){let e=0,s=t;for(;!/\n/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}searchWordBoundary(t,e){const s=this._text;let i=t>0&&this._reSpace.test(s[t])&&(e===-1||!Sr.test(s[t-1]))?t-1:t,n=s[i];for(;i>0&&i<s.length&&!ih.test(n);)i+=e,n=s[i];return e===-1&&ih.test(n)&&i++,i}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),i=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;Ce(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),i=this.selectionStart,n=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&i!==n||i!==s&&n!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===i&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const i=s.slice(0,t),n=this.graphemeSplit(i).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=s.slice(t,e);return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,s){const i=s.slice(0,t).join("").length;return t===e?{selectionStart:i,selectionEnd:i}:{selectionStart:i,selectionEnd:i+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex,r=this.getValueOfPropertyAt(i,n,"fontSize")*this.lineHeight,a=e.leftOffset,l=this.getCanvasRetinaScaling(),h=this.canvas.upperCanvasEl,c=h.width/l,u=h.height/l,d=c-r,f=u-r,g=new A(e.left+a,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new A(h.clientWidth/c,h.clientHeight/u));return g.x<0&&(g.x=0),g.x>d&&(g.x=d),g.y<0&&(g.y=0),g.y>f&&(g.y=f),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:"".concat(g.x,"px"),top:"".concat(g.y,"px"),fontSize:"".concat(r,"px"),charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire($i),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:i}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(s!==n){if(this.styles[s])for(let a=i;a<this._unwrappedTextLines[s].length;a++)delete this.styles[s][a];if(this.styles[n])for(let a=r;a<this._unwrappedTextLines[n].length;a++){const l=this.styles[n][a];l&&(this.styles[s]||(this.styles[s]={}),this.styles[s][i+a-r]=l)}for(let a=s+1;a<=n;a++)delete this.styles[a];this.shiftLineStyles(n,s-n)}else if(this.styles[s]){const a=this.styles[s],l=r-i;for(let h=i;h<r;h++)delete a[h];for(const h in this.styles[s]){const c=parseInt(h,10);c>=r&&(a[c-l]=a[h],delete a[h])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const i in this.styles){const n=parseInt(i,10);n>t&&(this.styles[n+e]=s[n],s[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,s,i){const n={},r=this._unwrappedTextLines[t].length,a=r===e;let l=!1;s||(s=1),this.shiftLineStyles(t,s);const h=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const d=parseInt(u,10);d>=e&&(l=!0,n[d-e]=this.styles[t][u],a&&e===0||delete this.styles[t][u])}let c=!1;for(l&&!a&&(this.styles[t+s]=n,c=!0),(c||r>e)&&s--;s>0;)i&&i[s-1]?this.styles[t+s]={0:x({},i[s-1])}:h?this.styles[t+s]={0:x({},h)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,i){this.styles||(this.styles={});const n=this.styles[t],r=n?x({},n):{};s||(s=1);for(const l in r){const h=parseInt(l,10);h>=e&&(n[h+s]=r[h],r[h-s]||delete n[h])}if(this._forceClearCache=!0,i){for(;s--;)Object.keys(i[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=x({},i[s]));return}if(!n)return;const a=n[e?e-1:1];for(;a&&s--;)this.styles[t][e+s]=x({},a)}insertNewStyleBlock(t,e,s){const i=this.get2DCursorLocation(e,!0),n=[0];let r,a=0;for(let l=0;l<t.length;l++)t[l]===`
|
|
85
|
+
`?(a++,n[a]=0):n[a]++;for(n[0]>0&&(this.insertCharStyleObject(i.lineIndex,i.charIndex,n[0],s),s=s&&s.slice(n[0]+1)),a&&this.insertNewlineStyleObject(i.lineIndex,i.charIndex+n[0],a),r=1;r<a;r++)n[r]>0?this.insertCharStyleObject(i.lineIndex+r,0,n[r],s):s&&this.styles[i.lineIndex+r]&&s[0]&&(this.styles[i.lineIndex+r][0]=s[0]),s=s&&s.slice(n[r]+1);n[r]>0&&this.insertCharStyleObject(i.lineIndex+r,0,n[r],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;i>s&&this.removeStyleFromTo(s,i);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,s,e),this._text=[...this._text.slice(0,s),...n,...this._text.slice(i)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=ot:this._selectionDirection===xt&&(this._selectionDirection=ot,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===xt?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=xt:this._selectionDirection===ot&&(this._selectionDirection=xt,this.selectionStart=e),this.selectionEnd=s)}}class Yd extends Ud{initHiddenTextarea(){const t=this.canvas&&Ce(this.canvas.getElement())||Ns(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off"}).map(r=>{let[a,l]=r;return e.setAttribute(a,l)});const{top:s,left:i,fontSize:n}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(i,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(n,";"),(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map(r=>{let[a,l]=r;return e.addEventListener(a,this[l].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:i,selectionEnd:n}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const r=()=>{this.updateFromTextArea(),this.fire(Ui),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void r();const a=this._splitTextIntoLines(s).graphemeText,l=this._text.length,h=a.length,c=this.selectionStart,u=this.selectionEnd,d=c!==u;let f,g,p,v,m=h-l;const b=this.fromStringToGraphemeSelection(i,n,s),_=c>b.selectionStart;d?(g=this._text.slice(c,u),m+=u-c):h<l&&(g=_?this._text.slice(u+m,u):this._text.slice(c,c-m));const w=a.slice(b.selectionEnd-m,b.selectionEnd);if(g&&g.length&&(w.length&&(f=this.getSelectionStyles(c,c+1,!1),f=w.map(()=>f[0])),d?(p=c,v=u):_?(p=u-g.length,v=u):(p=u,v=u+g.length),this.removeStyleFromTo(p,v)),w.length){const{copyPasteData:C}=Le();e&&w.join("")===C.copiedText&&!nt.disableStyleCopyPaste&&(f=C.copiedTextStyle),this.insertNewStyleBlock(w,c,f)}r()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:s,selectionEnd:i}=e;this.compositionStart=s,this.compositionEnd=i,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=Le();t.copiedText=this.getSelectedText(),nt.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,i=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const r=i.charIndex,a=this._getWidthBeforeCursor(n,r),l=this._getIndexOnLine(n+1,a);return this._textLines[n].slice(r).length+l+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),i=this.get2DCursorLocation(s),n=i.lineIndex;if(n===0||t.metaKey||t.keyCode===33)return-s;const r=i.charIndex,a=this._getWidthBeforeCursor(n,r),l=this._getIndexOnLine(n-1,a),h=this._textLines[n].slice(0,r),c=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+l-h.length+(1-c)}_getIndexOnLine(t,e){const s=this._textLines[t];let i,n,r=this._getLineLeftOffset(t),a=0;for(let l=0,h=s.length;l<h;l++)if(i=this.__charBounds[t][l].width,r+=i,r>e){n=!0;const c=r-i,u=r,d=Math.abs(c-e);a=Math.abs(u-e)<d?l:l-1;break}return n||(a=s.length-1),a}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===xt);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const i=this.text.length;this.selectionStart=Ss(0,this.selectionStart,i),this.selectionEnd=Ss(0,this.selectionEnd,i),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===ot?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let i;if(t.altKey)i=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;i=this["findLineBoundary".concat(s)](this[e])}return i!==void 0&&this[e]!==i&&(this[e]=i,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=ot,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===xt&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=ot,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===ot&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=xt,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=xt,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const nh=o=>!!o.button;class $d extends Yd{constructor(){super(...arguments),S(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("mousetripleclick",this.tripleClickHandler),this.draggableTextDelegate=new Xd(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!nh(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}mouseUpHandler(t){let{e,transform:s}=t;const i=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const n=this.canvas._activeObject;if(n&&n!==this)return}!this.editable||this.group&&!this.group.interactive||s&&s.actionPerformed||nh(e)||i||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),s=this.selectionStart,i=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(s,i,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(ne(this.calcTransformMatrix())).add(new A(-this._getLeftOffset(),-this._getTopOffset()));let s=0,i=0,n=0;for(let h=0;h<this._textLines.length&&s<=e.y;h++)s+=this.getHeightOfLine(h),n=h,h>0&&(i+=this._textLines[h-1].length+this.missingNewlineOffset(h-1));let r=Math.abs(this._getLineLeftOffset(n));const a=this._textLines[n].length,l=this.__charBounds[n];for(let h=0;h<a;h++){const c=r+l[h].kernedWidth;if(e.x<=c){Math.abs(e.x-c)<=Math.abs(e.x-r)&&i++;break}r=c,i++}return Math.min(this.flipX?a-i:i,this._text.length)}}const Cn="moveCursorUp",An="moveCursorDown",Tn="moveCursorLeft",En="moveCursorRight",kn="exitEditing",rh=(o,t)=>{const e=t.getRetinaScaling();o.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;o.transform(s[0],s[1],s[2],s[3],s[4],s[5])},qd=x({selectionStart:0,selectionEnd:0,selectionColor:"rgba(17,119,255,0.3)",isEditing:!1,editable:!0,editingBorderColor:"rgba(102,153,255,0.25)",cursorWidth:2,cursorColor:"",cursorDelay:1e3,cursorDuration:600,caching:!0,hiddenTextareaContainer:null,keysMap:{9:kn,27:kn,33:Cn,34:An,35:En,36:Tn,37:Tn,38:Cn,39:En,40:An},keysMapRtl:{9:kn,27:kn,33:Cn,34:An,35:Tn,36:En,37:En,38:Cn,39:Tn,40:An},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class ts extends $d{static getDefaults(){return x(x({},super.getDefaults()),ts.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,x(x({},ts.ownDefaults),e)),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):(t==="canvas"&&(this.canvas instanceof aa&&this.canvas.textEditingManager.remove(this),e instanceof aa&&e.textEditingManager.add(this)),super._set(t,e))}setSelectionStart(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)}setSelectionEnd(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)}_updateAndFire(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()}_fireSelectionChanged(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart||0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionEnd,s=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,s)}setSelectionStyles(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionStart||0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,s)}get2DCursorLocation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const s=super.toCanvasElement(t);return this.isEditing=e,s}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),i=s.length>0;let n,r=t;if(i){n=ue(t.canvas),r=n.getContext("2d"),rh(r,this.canvas);const a=this.calcTransformMatrix();r.transform(a[0],a[1],a[2],a[3],a[4],a[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(r,e):this.renderCursor(r,e),i)for(const a of s){const l=a.clipPath,h=ue(t.canvas),c=h.getContext("2d");if(rh(c,this.canvas),!l.absolutePositioned){const u=a.calcTransformMatrix();c.transform(u[0],u[1],u[2],u[3],u[4],u[5])}l.transform(c),l.drawObject(c,!0,{}),this.drawClipPathOnCache(r,l,h)}i&&(t.setTransform(1,0,0,1,0,0),t.drawImage(n,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),i=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:s,top:i,leftOffset:n.left,topOffset:n.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:i,lineIndex:n}=this.get2DCursorLocation(t);for(let h=0;h<n;h++)e+=this.getHeightOfLine(h);const r=this._getLineLeftOffset(n),a=this.__charBounds[n][i];a&&(s=a.left),this.charSpacing!==0&&i===this._textLines[n].length&&(s-=this._getWidthOfCharSpacing());const l={top:e,left:r+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===xt||this.textAlign===Be||this.textAlign===wi?l.left*=-1:this.textAlign===ot||this.textAlign===rn?l.left=r-(s>0?s:0):this.textAlign!==q&&this.textAlign!==xi||(l.left=r-(s>0?s:0))),l}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),i=s.lineIndex,n=s.charIndex>0?s.charIndex-1:0,r=this.getValueOfPropertyAt(i,n,"fontSize"),a=this.getObjectScaling().x*this.canvas.getZoom(),l=this.cursorWidth/a,h=this.getValueOfPropertyAt(i,n,"deltaY"),c=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(i)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(i,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-l/2,top:c+e.top+h,width:l,height:r}}_renderCursor(t,e,s){const{color:i,opacity:n,left:r,top:a,width:l,height:h}=this.getCursorRenderingData(s,e);t.fillStyle=i,t.globalAlpha=n,t.fillRect(r,a,l,h)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const i=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(Be),a=this.get2DCursorLocation(i),l=this.get2DCursorLocation(n),h=a.lineIndex,c=l.lineIndex,u=a.charIndex<0?0:a.charIndex,d=l.charIndex<0?0:l.charIndex;for(let f=h;f<=c;f++){const g=this._getLineLeftOffset(f)||0;let p=this.getHeightOfLine(f),v=0,m=0,b=0;if(f===h&&(m=this.__charBounds[h][u].left),f>=h&&f<c)b=r&&!this.isEndOfWrapping(f)?this.width:this.getLineWidth(f)||5;else if(f===c)if(d===0)b=this.__charBounds[c][d].left;else{const E=this._getWidthOfCharSpacing();b=this.__charBounds[c][d-1].left+this.__charBounds[c][d-1].width-E}v=p,(this.lineHeight<1||f===c&&this.lineHeight>1)&&(p/=this.lineHeight);let _=s.left+g+m,w=p,C=0;const T=b-m;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",w=1,C=p):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===xt||this.textAlign===Be||this.textAlign===wi?_=this.width-_-T:this.textAlign===ot||this.textAlign===rn?_=s.left+g-b:this.textAlign!==q&&this.textAlign!==xi||(_=s.left+g-b)),t.fillRect(_,s.top+s.topOffset+C,T,w),s.topOffset+=v}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,kt)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}S(ts,"ownDefaults",qd),S(ts,"type","IText"),I.setClass(ts),I.setClass(ts,"i-text");class Es extends ts{static getDefaults(){return x(x({},super.getDefaults()),Es.ownDefaults)}constructor(t,e){super(t,x(x({},Es.ownDefaults),e))}static createControls(){return{controls:Fu()}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this.textAlign.includes(Be)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,i=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)t.graphemeText[i]===`
|
|
86
|
+
`&&r>0?(s=0,i++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[i])&&r>0&&(s++,i++),n[r]={line:e,offset:s},i+=t.graphemeLines[r].length,s+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,i=t+1,n=!1;const r=this._styleMap[t],a=this._styleMap[t+1];r&&(t=r.line,s=r.offset),a&&(i=a.line,n=i===t,e=a.offset);const l=t===void 0?this.styles:{line:this.styles[t]};for(const h in l)for(const c in l[h]){const u=parseInt(c,10);if(u>=s&&(!n||u<e))for(const d in l[h][c])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const i=this._styleMap[t];super._setStyleDeclaration(i.line,i.offset+e,s)}_deleteStyleDeclaration(t,e){const s=this._styleMap[t];super._deleteStyleDeclaration(s.line,s.offset+e)}_getLineStyle(t){const e=this._styleMap[t];return!!this.styles[e.line]}_setLineStyle(t){const e=this._styleMap[t];super._setLineStyle(e.line)}_wrapText(t,e){this.isWrapping=!0;const s=this.getGraphemeDataForRender(t),i=[];for(let n=0;n<s.wordsData.length;n++)i.push(...this._wrapLine(n,e,s));return this.isWrapping=!1,i}getGraphemeDataForRender(t){const e=this.splitByGrapheme,s=e?"":" ";let i=0;return{wordsData:t.map((n,r)=>{let a=0;const l=e?this.graphemeSplit(n):this.wordSplit(n);return l.length===0?[{word:[],width:0}]:l.map(h=>{const c=e?[h]:this.graphemeSplit(h),u=this._measureWord(c,r,a);return i=Math.max(u,i),a+=c.length+s.length,{word:c,width:u}})}),largestWordWidth:i}}_measureWord(t,e){let s,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,n=0;for(let r=0,a=t.length;r<a;r++)n+=this._getGraphemeBox(t[r],e,r+i,s,!0).kernedWidth,s=t[r];return n}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:i,wordsData:n}=s,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const a=this._getWidthOfCharSpacing(),l=this.splitByGrapheme,h=[],c=l?"":" ";let u=0,d=[],f=0,g=0,p=!0;e-=r;const v=Math.max(e,i,this.dynamicMinWidth),m=n[t];let b;for(f=0,b=0;b<m.length;b++){const{word:_,width:w}=m[b];f+=_.length,u+=g+w-a,u>v&&!p?(h.push(d),d=[],u=w,p=!0):u+=a,p||l||d.push(c),d=d.concat(_),g=l?0:this._measureWord([c],t,f),f++,p=!1}return b&&h.push(d),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-a+r),h}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),i=new Array(s.length);for(let n=0;n<s.length;n++)i[n]=s[n].join("");return e.lines=i,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const i=this._styleMap[e].line;t.set("".concat(i),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}S(Es,"type","Textbox"),S(Es,"textLayoutProperties",[...ts.textLayoutProperties,"width"]),S(Es,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),I.setClass(Es);class ah extends bn{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:s}=t,{clipPath:i,group:n}=s;if(!i||!this.shouldPerformLayout(t))return;const{width:r,height:a}=Ne(Dl(s,i)),l=new A(r,a);if(i.absolutePositioned)return{center:ws(i.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:l};{const h=i.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:c=new A,correction:u=new A}=this.calcBoundingBox(e,t)||{};return{center:c.add(h),correction:u.subtract(h),size:l}}return{center:s.getRelativeCenterPoint().add(h),size:l}}}}S(ah,"type","clip-path"),I.setClass(ah);class oh extends bn{getInitialSize(t,e){let{target:s}=t,{size:i}=e;return new A(s.width||i.x,s.height||i.y)}}S(oh,"type","fixed"),I.setClass(oh);class Kd extends Ti{subscribeTargets(t){const e=t.target;t.targets.reduce((s,i)=>(i.parent&&s.add(i.parent),s),new Set).forEach(s=>{s.layoutManager.subscribeTargets({target:s,targets:[e]})})}unsubscribeTargets(t){const e=t.target,s=e.getObjects();t.targets.reduce((i,n)=>(n.parent&&i.add(n.parent),i),new Set).forEach(i=>{!s.some(n=>n.parent===i)&&i.layoutManager.unsubscribeTargets({target:i,targets:[e]})})}}class ks extends me{static getDefaults(){return x(x({},super.getDefaults()),ks.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,ks.ownDefaults),this.setOptions(e);const{left:s,top:i,layoutManager:n}=e;this.groupInit(t,{left:s,top:i,layoutManager:n??new Kd})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];this.multiSelectionStacking==="selection-order"?this.add(...e):e.forEach(i=>{const n=this._objects.findIndex(a=>a.isInFrontOf(i)),r=n===-1?this.size():n;this.insertAt(r,i)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(Xe("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);const s=new Set;e.forEach(i=>{const{parent:n}=i;n&&s.add(n)}),t===ea?s.forEach(i=>{i._onAfterObjectsChange(mn,e)}):s.forEach(i=>{i._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const i=x(x({hasControls:!1},s),{},{forActiveSelection:!0});for(let n=0;n<this._objects.length;n++)this._objects[n]._renderControls(t,i);super._renderControls(t,e),t.restore()}}S(ks,"type","ActiveSelection"),S(ks,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),I.setClass(ks),I.setClass(ks,"activeSelection");class Jd{constructor(){S(this,"resources",{})}applyFilters(t,e,s,i,n){const r=n.getContext("2d");if(!r)return;r.drawImage(e,0,0,s,i);const a={sourceWidth:s,sourceHeight:i,imageData:r.getImageData(0,0,s,i),originalEl:e,originalImageData:r.getImageData(0,0,s,i),canvasEl:n,ctx:r,filterBackend:this};t.forEach(h=>{h.applyTo(a)});const{imageData:l}=a;return l.width===s&&l.height===i||(n.width=l.width,n.height=l.height),r.putImageData(l,0,0),a}}class lh{constructor(){let{tileSize:t=nt.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};S(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),S(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=ue({width:t,height:e}),i=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});i&&(i.clearColor(0,0,0,0),this.canvas=s,this.gl=i)}applyFilters(t,e,s,i,n,r){const a=this.gl,l=n.getContext("2d");if(!a||!l)return;let h;r&&(h=this.getCachedTexture(r,e));const c={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:i,destinationWidth:s,destinationHeight:i,context:a,sourceTexture:this.createTexture(a,s,i,h?void 0:e),targetTexture:this.createTexture(a,s,i),originalTexture:h||this.createTexture(a,s,i,h?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},u=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,u),t.forEach(d=>{d&&d.applyTo(c)}),function(d){const f=d.targetCanvas,g=f.width,p=f.height,v=d.destinationWidth,m=d.destinationHeight;g===v&&p===m||(f.width=v,f.height=m)}(c),this.copyGLTo2D(a,c),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(c.sourceTexture),a.deleteTexture(c.targetTexture),a.deleteFramebuffer(u),l.setTransform(1,0,0,1,0,0),c}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,s,i,n){const{NEAREST:r,TEXTURE_2D:a,RGBA:l,UNSIGNED_BYTE:h,CLAMP_TO_EDGE:c,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:f,TEXTURE_WRAP_T:g}=t,p=t.createTexture();return t.bindTexture(a,p),t.texParameteri(a,u,n||r),t.texParameteri(a,d,n||r),t.texParameteri(a,f,c),t.texParameteri(a,g,c),i?t.texImage2D(a,0,l,l,h,i):t.texImage2D(a,0,l,e,s,0,l,h,null),p}getCachedTexture(t,e,s){const{textureCache:i}=this;if(i[t])return i[t];{const n=this.createTexture(this.gl,e.width,e.height,e,s);return n&&(i[t]=n),n}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const s=t.canvas,i=e.targetCanvas,n=i.getContext("2d");if(!n)return;n.translate(0,i.height),n.scale(1,-1);const r=s.height-i.height;n.drawImage(s,0,r,i.width,i.height,0,0,i.width,i.height)}copyGLTo2DPutImageData(t,e){const s=e.targetCanvas.getContext("2d"),i=e.destinationWidth,n=e.destinationHeight,r=i*n*4;if(!s)return;const a=new Uint8Array(this.imageBuffer,0,r),l=new Uint8ClampedArray(this.imageBuffer,0,r);t.readPixels(0,0,i,n,t.RGBA,t.UNSIGNED_BYTE,a);const h=new ImageData(l,i,n);s.putImageData(h,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const i=t.getParameter(s.UNMASKED_RENDERER_WEBGL),n=t.getParameter(s.UNMASKED_VENDOR_WEBGL);i&&(e.renderer=i.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}let ua;function Qd(){const{WebGLProbe:o}=Le();return o.queryWebGL(Ie()),nt.enableGLFiltering&&o.isSupported(nt.textureSize)?new lh({tileSize:nt.textureSize}):new Jd}function da(){return!ua&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(ua=Qd()),ua}const Zd=["filters","resizeFilter","src","crossOrigin","type"],hh=["cropX","cropY"];class Vt extends Ht{static getDefaults(){return x(x({},super.getDefaults()),Vt.ownDefaults)}constructor(t,e){super(),S(this,"_lastScaleX",1),S(this,"_lastScaleY",1),S(this,"_filterScalingX",1),S(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Vt.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(rs()),this.setElement(typeof t=="string"?(this.canvas&&Ce(this.canvas.getElement())||Ns()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(Vt.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=da(!1);e instanceof lh&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{const e=this[t];e&&Le().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach(s=>{s&&e.push(s.toObject())}),x(x({},super.toObject([...hh,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,i=-this.height/2;let n=[],r=[],a="",l="";if(!e)return[];if(this.hasCrop()){const h=rs();n.push('<clipPath id="imageCrop_'+h+`">
|
|
87
87
|
`,' <rect x="'+s+'" y="'+i+'" width="'+this.width+'" height="'+this.height+`" />
|
|
88
88
|
`,`</clipPath>
|
|
89
|
-
`),a=' clip-path="url(#imageCrop_'+
|
|
90
|
-
`)),this.stroke||this.strokeDashArray){const
|
|
91
|
-
`)],this.fill=c}return n=this.paintFirst!==ee?n.concat(r,t):n.concat(t,r),n}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return qh(t,{crossOrigin:e,signal:s}).then(i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)})}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),i=s.x,n=s.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||i>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=i,void(this._lastScaleY=n);const a=ps(r),{width:h,height:c}=r;this._element=a,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,wg().applyFilters([t],r,h,c,this._element),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter(n=>n&&!n.isNeutralState()),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){const n=ps({width:s,height:i});this._element=n,this._filteredEl=n}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,s,i),this._lastScaleX=1,this._lastScaleY=1);wg().applyFilters(t,this._originalElement,s,i,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,i=this._filterScalingY,n=this.width,r=this.height,a=Math.max(this.cropX,0),h=Math.max(this.cropY,0),c=e.naturalWidth||e.width,u=e.naturalHeight||e.height,d=a*s,f=h*i,g=Math.min(n*s,c-d),p=Math.min(r*i,u-f),m=-n/2,y=-r/2,b=Math.min(n,c/s-a),x=Math.min(r,u/i-h);e&&t.drawImage(e,d,f,g,p,m,y,b,x)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=Yf(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,a=this._element.height,h=1,c=1,u=0,d=0,f=0,g=0;return!t||t.alignX===ze&&t.alignY===ze?(h=e/r,c=s/a):(t.meetOrSlice==="meet"&&(h=c=z0(this._element,i),n=(e-r*h)/2,t.alignX==="Min"&&(u=-n),t.alignX==="Max"&&(u=n),n=(s-a*c)/2,t.alignY==="Min"&&(d=-n),t.alignY==="Max"&&(d=n)),t.meetOrSlice==="slice"&&(h=c=V0(this._element,i),n=r-e/h,t.alignX==="Mid"&&(f=n/2),t.alignX==="Max"&&(f=n),n=a-s/c,t.alignY==="Mid"&&(g=n/2),t.alignY==="Max"&&(g=n),r=e/h,a=s/c)),{width:r,height:a,scaleX:h,scaleY:c,offsetLeft:u,offsetTop:d,cropX:f,cropY:g}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:a}=t,h=Lt(t,Dx);return Promise.all([qh(n,T(T({},e),{},{crossOrigin:r})),s&&po(s,e),i&&po([i],e),Kh(h,e)]).then(c=>{let[u,d=[],[f]=[],g={}]=c;return new this(u,T(T({},h),{},{src:n,filters:d,resizeFilter:f},g))})}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;return qh(t,{crossOrigin:e,signal:s}).then(n=>new this(n,i))}static async fromElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;const i=Zi(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch(n=>($i("log","Unable to parse Image",n),null))}}function xg(o){if(!j_.test(o.nodeName))return{};const t=o.getAttribute("viewBox");let e,s,i=1,n=1,r=0,a=0;const h=o.getAttribute("width"),c=o.getAttribute("height"),u=o.getAttribute("x")||0,d=o.getAttribute("y")||0,f=!(t&&r0.test(t)),g=!h||!c||h==="100%"||c==="100%";let p="",m=0,y=0;if(f&&(u||d)&&o.parentNode&&o.parentNode.nodeName!=="#document"&&(p=" translate("+Ge(u||"0")+" "+Ge(d||"0")+") ",e=(o.getAttribute("transform")||"")+p,o.setAttribute("transform",e),o.removeAttribute("x"),o.removeAttribute("y")),f&&g)return{width:0,height:0};const b={width:0,height:0};if(f)return b.width=Ge(h),b.height=Ge(c),b;const x=t.match(r0);r=-parseFloat(x[1]),a=-parseFloat(x[2]);const S=parseFloat(x[3]),C=parseFloat(x[4]);b.minX=r,b.minY=a,b.viewBoxWidth=S,b.viewBoxHeight=C,g?(b.width=S,b.height=C):(b.width=Ge(h),b.height=Ge(c),i=b.width/S,n=b.height/C);const k=Yf(o.getAttribute("preserveAspectRatio")||"");if(k.alignX!==ze&&(k.meetOrSlice==="meet"&&(n=i=i>n?n:i),k.meetOrSlice==="slice"&&(n=i=i>n?i:n),m=b.width-S*i,y=b.height-C*i,k.alignX==="Mid"&&(m/=2),k.alignY==="Mid"&&(y/=2),k.alignX==="Min"&&(m=0),k.alignY==="Min"&&(y=0)),i===1&&n===1&&r===0&&a===0&&u===0&&d===0)return b;if((u||d)&&o.parentNode.nodeName!=="#document"&&(p=" translate("+Ge(u||"0")+" "+Ge(d||"0")+") "),e=p+" matrix("+i+" 0 0 "+n+" "+(r*i+m)+" "+(a*n+y)+") ",o.nodeName==="svg"){for(s=o.ownerDocument.createElementNS($f,"g");o.firstChild;)s.appendChild(o.firstChild);o.appendChild(s)}else s=o,s.removeAttribute("x"),s.removeAttribute("y"),e=s.getAttribute("transform")+e;return s.setAttribute("transform",e),b}E(Me,"type","Image"),E(Me,"cacheProperties",[...Ji,..._v]),E(Me,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),E(Me,"CSS_CANVAS","canvas-img"),E(Me,"ATTRIBUTE_NAMES",[...Xn,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),W.setClass(Me),W.setSVGClass(Me);const Xu=o=>o.tagName.replace("svg:",""),Rx=_u(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function wv(o,t){let e,s,i,n,r=[];for(i=0,n=t.length;i<n;i++)e=t[i],s=o.getElementsByTagNameNS("http://www.w3.org/2000/svg",e),r=r.concat(Array.from(s));return r}const Fx=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Sg="xlink:href";function xv(o,t){var e;const s=((e=t.getAttribute(Sg))===null||e===void 0?void 0:e.slice(1))||"",i=o.getElementById(s);if(i&&i.getAttribute(Sg)&&xv(o,i),i&&(Fx.forEach(n=>{const r=i.getAttribute(n);!t.hasAttribute(n)&&r&&t.setAttribute(n,r)}),!t.children.length)){const n=i.cloneNode(!0);for(;n.firstChild;)t.appendChild(n.firstChild)}t.removeAttribute(Sg)}const Lx=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function Ix(o){const t=o.getElementsByTagName("style");let e,s;const i={};for(e=0,s=t.length;e<s;e++){const n=(t[e].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");n.trim()!==""&&n.split("}").filter((r,a,h)=>h.length>1&&r.trim()).forEach(r=>{if((r.match(/{/g)||[]).length>1&&r.trim().startsWith("@"))return;const a=r.split("{"),h={},c=a[1].trim().split(";").filter(function(u){return u.trim()});for(e=0,s=c.length;e<s;e++){const u=c[e].split(":"),d=u[0].trim(),f=u[1].trim();h[d]=f}(r=a[0].trim()).split(",").forEach(u=>{(u=u.replace(/^svg/i,"").trim())!==""&&(i[u]=T(T({},i[u]||{}),h))})})}return i}const Sv=o=>W.getSVGClass(Xu(o).toLowerCase());class jx{constructor(t,e,s,i,n){this.elements=t,this.options=e,this.reviver=s,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=i,this.clipPaths=n,this.gradientDefs=function(r){const a=wv(r,Lx),h={};let c=a.length;for(;c--;){const u=a[c];u.getAttribute("xlink:href")&&xv(r,u);const d=u.getAttribute("id");d&&(h[d]=u)}return h}(i),this.cssRules=Ix(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=Sv(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,ee),this.resolveGradient(s,t,We),s instanceof Me&&s._originalElement?Iu(s,s.parsePreserveAspectRatioAttribute()):Iu(s),await this.resolveClipPath(s,t),this.reviver&&this.reviver(t,s),s}return null}extractPropertyDefinition(t,e,s){const i=t[e],n=this.regexUrl;if(!n.test(i))return;n.lastIndex=0;const r=n.exec(i)[1];return n.lastIndex=0,s[r]}resolveGradient(t,e,s){const i=this.extractPropertyDefinition(t,s,this.gradientDefs);if(i){const n=e.getAttribute(s+"-opacity"),r=nl.fromElement(i,t,T(T({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e,s){const i=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(i){const n=ns(t.calcTransformMatrix()),r=i[0].parentElement;let a=e;for(;!s&&a.parentElement&&a.getAttribute("clip-path")!==t.clipPath;)a=a.parentElement;a.parentElement.appendChild(r);const h=Mu("".concat(a.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(h.join(","),")"));const c=await Promise.all(i.map(x=>Sv(x).fromElement(x,this.options,this.cssRules).then(S=>(Iu(S),S.fillRule=S.clipRule,delete S.clipRule,S)))),u=c.length===1?c[0]:new Ls(c),d=qt(n,u.calcTransformMatrix());u.clipPath&&await this.resolveClipPath(u,a,r.getAttribute("clip-path")?a:void 0);const{scaleX:f,scaleY:g,angle:p,skewX:m,translateX:y,translateY:b}=Lr(d);u.set({flipX:!1,flipY:!1}),u.set({scaleX:f,scaleY:g,angle:p,skewX:m,skewY:0}),u.setPositionByOrigin(new M(y,b),rt,rt),t.clipPath=u}else delete t.clipPath}}const Cv=o=>I_.test(Xu(o)),Cg=()=>({objects:[],elements:[],options:{},allElements:[]});async function Nx(o,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return $i("log",new kf("parseSVGDocument")),Cg();const i=o.documentElement;(function(u){const d=wv(u,["use","svg:use"]),f=["x","y","xlink:href","href","transform"];for(const g of d){const p=g.attributes,m={};for(const R of p)R.value&&(m[R.name]=R.value);const y=(m["xlink:href"]||m.href||"").slice(1);if(y==="")return;const b=u.getElementById(y);if(b===null)return;let x=b.cloneNode(!0);const S=x.attributes,C={};for(const R of S)R.value&&(C[R.name]=R.value);const{x:k=0,y:O=0,transform:P=""}=m,D="".concat(P," ").concat(C.transform||""," translate(").concat(k,", ").concat(O,")");if(xg(x),/^svg$/i.test(x.nodeName)){const R=x.ownerDocument.createElementNS($f,"g");Object.entries(C).forEach(z=>{let[B,F]=z;return R.setAttributeNS($f,B,F)}),R.append(...x.childNodes),x=R}for(const R of p){if(!R)continue;const{name:z,value:B}=R;if(!f.includes(z))if(z==="style"){const F={};lg(B,F),Object.entries(C).forEach(N=>{let[K,I]=N;F[K]=I}),lg(C.style||"",F);const L=Object.entries(F).map(N=>N.join(":")).join(";");x.setAttribute(z,L)}else!C[z]&&x.setAttribute(z,B)}x.setAttribute("transform",D),x.setAttribute("instantiated_by_use","1"),x.removeAttribute("id"),g.parentNode.replaceChild(x,g)}})(o);const n=Array.from(i.getElementsByTagName("*")),r=T(T({},xg(i)),{},{crossOrigin:e,signal:s}),a=n.filter(u=>(xg(u),Cv(u)&&!function(d){let f=d;for(;f&&(f=f.parentElement);)if(f&&f.nodeName&&Rx.test(Xu(f))&&!f.getAttribute("instantiated_by_use"))return!0;return!1}(u)));if(!a||a&&!a.length)return T(T({},Cg()),{},{options:r,allElements:n});const h={};return n.filter(u=>Xu(u)==="clipPath").forEach(u=>{u.setAttribute("originalTransform",u.getAttribute("transform")||"");const d=u.getAttribute("id");h[d]=Array.from(u.getElementsByTagName("*")).filter(f=>Cv(f))}),{objects:await new jx(a,r,t,o,h).parse(),elements:a,options:r,allElements:n}}function Bx(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{tv(o.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>Nx(s,t,e)).catch(()=>Cg())}const Uu=o=>o.webgl!==void 0,Ag="precision highp float",Hx=`
|
|
92
|
-
`.concat(
|
|
89
|
+
`),a=' clip-path="url(#imageCrop_'+h+')" '}if(this.imageSmoothing||(l=' image-rendering="optimizeSpeed"'),t.push(" <image ","COMMON_PARTS",'xlink:href="'.concat(this.getSvgSrc(!0),'" x="').concat(s-this.cropX,'" y="').concat(i-this.cropY,'" width="').concat(e.width||e.naturalWidth,'" height="').concat(e.height||e.naturalHeight,'"').concat(l).concat(a,`></image>
|
|
90
|
+
`)),this.stroke||this.strokeDashArray){const h=this.fill;this.fill=null,r=[' <rect x="'.concat(s,'" y="').concat(i,'" width="').concat(this.width,'" height="').concat(this.height,'" style="').concat(this.getSvgStyles(),`" />
|
|
91
|
+
`)],this.fill=h}return n=this.paintFirst!==kt?n.concat(r,t):n.concat(t,r),n}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return mi(t,{crossOrigin:e,signal:s}).then(i=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(i)})}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),i=s.x,n=s.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||i>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=i,void(this._lastScaleY=n);const a=ue(r),{width:l,height:h}=r;this._element=a,this._lastScaleX=t.scaleX=i,this._lastScaleY=t.scaleY=n,da().applyFilters([t],r,l,h,this._element),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter(n=>n&&!n.isNeutralState()),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(this._element===this._originalElement){const n=ue({width:s,height:i});this._element=n,this._filteredEl=n}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,s,i),this._lastScaleX=1,this._lastScaleY=1);da().applyFilters(t,this._originalElement,s,i,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,i=this._filterScalingY,n=this.width,r=this.height,a=Math.max(this.cropX,0),l=Math.max(this.cropY,0),h=e.naturalWidth||e.width,c=e.naturalHeight||e.height,u=a*s,d=l*i,f=Math.min(n*s,h-u),g=Math.min(r*i,c-d),p=-n/2,v=-r/2,m=Math.min(n,h/s-a),b=Math.min(r,c/i-l);e&&t.drawImage(e,u,d,f,g,p,v,m,b)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=jr(this.preserveAspectRatio||""),e=this.width,s=this.height,i={width:e,height:s};let n,r=this._element.width,a=this._element.height,l=1,h=1,c=0,u=0,d=0,f=0;return!t||t.alignX===Yt&&t.alignY===Yt?(l=e/r,h=s/a):(t.meetOrSlice==="meet"&&(l=h=Fl(this._element,i),n=(e-r*l)/2,t.alignX==="Min"&&(c=-n),t.alignX==="Max"&&(c=n),n=(s-a*h)/2,t.alignY==="Min"&&(u=-n),t.alignY==="Max"&&(u=n)),t.meetOrSlice==="slice"&&(l=h=Ll(this._element,i),n=r-e/l,t.alignX==="Mid"&&(d=n/2),t.alignX==="Max"&&(d=n),n=a-s/h,t.alignY==="Mid"&&(f=n/2),t.alignY==="Max"&&(f=n),r=e/l,a=s/h)),{width:r,height:a,scaleX:l,scaleY:h,offsetLeft:c,offsetTop:u,cropX:d,cropY:f}}static fromObject(t,e){let{filters:s,resizeFilter:i,src:n,crossOrigin:r,type:a}=t,l=pt(t,Zd);return Promise.all([mi(n,x(x({},e),{},{crossOrigin:r})),s&&Gs(s,e),i&&Gs([i],e),vi(l,e)]).then(h=>{let[c,u=[],[d]=[],f={}]=h;return new this(c,x(x({},l),{},{src:n,filters:u,resizeFilter:d},f))})}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;return mi(t,{crossOrigin:e,signal:s}).then(n=>new this(n,i))}static async fromElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;const i=Ke(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(i["xlink:href"]||i.href,e,i).catch(n=>(Xe("log","Unable to parse Image",n),null))}}function fa(o){if(!ru.test(o.nodeName))return{};const t=o.getAttribute("viewBox");let e,s,i=1,n=1,r=0,a=0;const l=o.getAttribute("width"),h=o.getAttribute("height"),c=o.getAttribute("x")||0,u=o.getAttribute("y")||0,d=!(t&&Qo.test(t)),f=!l||!h||l==="100%"||h==="100%";let g="",p=0,v=0;if(d&&(c||u)&&o.parentNode&&o.parentNode.nodeName!=="#document"&&(g=" translate("+Kt(c||"0")+" "+Kt(u||"0")+") ",e=(o.getAttribute("transform")||"")+g,o.setAttribute("transform",e),o.removeAttribute("x"),o.removeAttribute("y")),d&&f)return{width:0,height:0};const m={width:0,height:0};if(d)return m.width=Kt(l),m.height=Kt(h),m;const b=t.match(Qo);r=-parseFloat(b[1]),a=-parseFloat(b[2]);const _=parseFloat(b[3]),w=parseFloat(b[4]);m.minX=r,m.minY=a,m.viewBoxWidth=_,m.viewBoxHeight=w,f?(m.width=_,m.height=w):(m.width=Kt(l),m.height=Kt(h),i=m.width/_,n=m.height/w);const C=jr(o.getAttribute("preserveAspectRatio")||"");if(C.alignX!==Yt&&(C.meetOrSlice==="meet"&&(n=i=i>n?n:i),C.meetOrSlice==="slice"&&(n=i=i>n?i:n),p=m.width-_*i,v=m.height-w*i,C.alignX==="Mid"&&(p/=2),C.alignY==="Mid"&&(v/=2),C.alignX==="Min"&&(p=0),C.alignY==="Min"&&(v=0)),i===1&&n===1&&r===0&&a===0&&c===0&&u===0)return m;if((c||u)&&o.parentNode.nodeName!=="#document"&&(g=" translate("+Kt(c||"0")+" "+Kt(u||"0")+") "),e=g+" matrix("+i+" 0 0 "+n+" "+(r*i+p)+" "+(a*n+v)+") ",o.nodeName==="svg"){for(s=o.ownerDocument.createElementNS(Br,"g");o.firstChild;)s.appendChild(o.firstChild);o.appendChild(s)}else s=o,s.removeAttribute("x"),s.removeAttribute("y"),e=s.getAttribute("transform")+e;return s.setAttribute("transform",e),m}S(Vt,"type","Image"),S(Vt,"cacheProperties",[...$e,...hh]),S(Vt,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),S(Vt,"CSS_CANVAS","canvas-img"),S(Vt,"ATTRIBUTE_NAMES",[...as,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),I.setClass(Vt),I.setSVGClass(Vt);const Pn=o=>o.tagName.replace("svg:",""),tf=nn(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);function ch(o,t){let e,s,i,n,r=[];for(i=0,n=t.length;i<n;i++)e=t[i],s=o.getElementsByTagNameNS("http://www.w3.org/2000/svg",e),r=r.concat(Array.from(s));return r}const ef=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],ga="xlink:href";function uh(o,t){var e;const s=((e=t.getAttribute(ga))===null||e===void 0?void 0:e.slice(1))||"",i=o.getElementById(s);if(i&&i.getAttribute(ga)&&uh(o,i),i&&(ef.forEach(n=>{const r=i.getAttribute(n);!t.hasAttribute(n)&&r&&t.setAttribute(n,r)}),!t.children.length)){const n=i.cloneNode(!0);for(;n.firstChild;)t.appendChild(n.firstChild)}t.removeAttribute(ga)}const sf=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function nf(o){const t=o.getElementsByTagName("style");let e,s;const i={};for(e=0,s=t.length;e<s;e++){const n=(t[e].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");n.trim()!==""&&n.split("}").filter((r,a,l)=>l.length>1&&r.trim()).forEach(r=>{if((r.match(/{/g)||[]).length>1&&r.trim().startsWith("@"))return;const a=r.split("{"),l={},h=a[1].trim().split(";").filter(function(c){return c.trim()});for(e=0,s=h.length;e<s;e++){const c=h[e].split(":"),u=c[0].trim(),d=c[1].trim();l[u]=d}(r=a[0].trim()).split(",").forEach(c=>{(c=c.replace(/^svg/i,"").trim())!==""&&(i[c]=x(x({},i[c]||{}),l))})})}return i}const dh=o=>I.getSVGClass(Pn(o).toLowerCase());class rf{constructor(t,e,s,i,n){this.elements=t,this.options=e,this.reviver=s,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=i,this.clipPaths=n,this.gradientDefs=function(r){const a=ch(r,sf),l={};let h=a.length;for(;h--;){const c=a[h];c.getAttribute("xlink:href")&&uh(r,c);const u=c.getAttribute("id");u&&(l[u]=c)}return l}(i),this.cssRules=nf(i)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=dh(t);if(e){const s=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(s,t,kt),this.resolveGradient(s,t,qt),s instanceof Vt&&s._originalElement?wn(s,s.parsePreserveAspectRatioAttribute()):wn(s),await this.resolveClipPath(s,t),this.reviver&&this.reviver(t,s),s}return null}extractPropertyDefinition(t,e,s){const i=t[e],n=this.regexUrl;if(!n.test(i))return;n.lastIndex=0;const r=n.exec(i)[1];return n.lastIndex=0,s[r]}resolveGradient(t,e,s){const i=this.extractPropertyDefinition(t,s,this.gradientDefs);if(i){const n=e.getAttribute(s+"-opacity"),r=ki.fromElement(i,t,x(x({},this.options),{},{opacity:n}));t.set(s,r)}}async resolveClipPath(t,e,s){const i=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(i){const n=ne(t.calcTransformMatrix()),r=i[0].parentElement;let a=e;for(;!s&&a.parentElement&&a.getAttribute("clip-path")!==t.clipPath;)a=a.parentElement;a.parentElement.appendChild(r);const l=pn("".concat(a.getAttribute("transform")||""," ").concat(r.getAttribute("originalTransform")||""));r.setAttribute("transform","matrix(".concat(l.join(","),")"));const h=await Promise.all(i.map(b=>dh(b).fromElement(b,this.options,this.cssRules).then(_=>(wn(_),_.fillRule=_.clipRule,delete _.clipRule,_)))),c=h.length===1?h[0]:new me(h),u=St(n,c.calcTransformMatrix());c.clipPath&&await this.resolveClipPath(c,a,r.getAttribute("clip-path")?a:void 0);const{scaleX:d,scaleY:f,angle:g,skewX:p,translateX:v,translateY:m}=vs(u);c.set({flipX:!1,flipY:!1}),c.set({scaleX:d,scaleY:f,angle:g,skewX:p,skewY:0}),c.setPositionByOrigin(new A(v,m),q,q),t.clipPath=c}else delete t.clipPath}}const fh=o=>nu.test(Pn(o)),pa=()=>({objects:[],elements:[],options:{},allElements:[]});async function af(o,t){let{crossOrigin:e,signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(s&&s.aborted)return Xe("log",new br("parseSVGDocument")),pa();const i=o.documentElement;(function(c){const u=ch(c,["use","svg:use"]),d=["x","y","xlink:href","href","transform"];for(const f of u){const g=f.attributes,p={};for(const O of g)O.value&&(p[O.name]=O.value);const v=(p["xlink:href"]||p.href||"").slice(1);if(v==="")return;const m=c.getElementById(v);if(m===null)return;let b=m.cloneNode(!0);const _=b.attributes,w={};for(const O of _)O.value&&(w[O.name]=O.value);const{x:C=0,y:T=0,transform:E=""}=p,k="".concat(E," ").concat(w.transform||""," translate(").concat(C,", ").concat(T,")");if(fa(b),/^svg$/i.test(b.nodeName)){const O=b.ownerDocument.createElementNS(Br,"g");Object.entries(w).forEach(H=>{let[N,P]=H;return O.setAttributeNS(Br,N,P)}),O.append(...b.childNodes),b=O}for(const O of g){if(!O)continue;const{name:H,value:N}=O;if(!d.includes(H))if(H==="style"){const P={};ta(N,P),Object.entries(w).forEach(F=>{let[V,M]=F;P[V]=M}),ta(w.style||"",P);const R=Object.entries(P).map(F=>F.join(":")).join(";");b.setAttribute(H,R)}else!w[H]&&b.setAttribute(H,N)}b.setAttribute("transform",k),b.setAttribute("instantiated_by_use","1"),b.removeAttribute("id"),f.parentNode.replaceChild(b,f)}})(o);const n=Array.from(i.getElementsByTagName("*")),r=x(x({},fa(i)),{},{crossOrigin:e,signal:s}),a=n.filter(c=>(fa(c),fh(c)&&!function(u){let d=u;for(;d&&(d=d.parentElement);)if(d&&d.nodeName&&tf.test(Pn(d))&&!d.getAttribute("instantiated_by_use"))return!0;return!1}(c)));if(!a||a&&!a.length)return x(x({},pa()),{},{options:r,allElements:n});const l={};return n.filter(c=>Pn(c)==="clipPath").forEach(c=>{c.setAttribute("originalTransform",c.getAttribute("transform")||"");const u=c.getAttribute("id");l[u]=Array.from(c.getElementsByTagName("*")).filter(d=>fh(d))}),{objects:await new rf(a,r,t,o,l).parse(),elements:a,options:r,allElements:n}}function of(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return new Promise((s,i)=>{Yl(o.replace(/^\n\s*/,"").trim(),{onComplete:n=>{const r=n.responseXML;r&&s(r),i()},signal:e.signal})}).then(s=>af(s,t,e)).catch(()=>pa())}const Mn=o=>o.webgl!==void 0,ma="precision highp float",lf=`
|
|
92
|
+
`.concat(ma,`;
|
|
93
93
|
varying vec2 vTexCoord;
|
|
94
94
|
uniform sampler2D uTexture;
|
|
95
95
|
void main() {
|
|
96
96
|
gl_FragColor = texture2D(uTexture, vTexCoord);
|
|
97
|
-
}`),
|
|
97
|
+
}`),hf=["type"],cf=["type"],uf=new RegExp(ma,"g");class Ft{get type(){return this.constructor.type}constructor(){let t=pt(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},hf);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return lf}getVertexSource(){return`
|
|
98
98
|
attribute vec2 aPosition;
|
|
99
99
|
varying vec2 vTexCoord;
|
|
100
100
|
void main() {
|
|
101
101
|
vTexCoord = aPosition;
|
|
102
102
|
gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
|
|
103
|
-
}`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:i="highp"}}=
|
|
103
|
+
}`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:i="highp"}}=Le();i!=="highp"&&(e=e.replace(uf,ma.replace("highp",i)));const n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER),a=t.createProgram();if(!n||!r||!a)throw new Fe("Vertex, fragment shader or program creation error");if(t.shaderSource(n,s),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Fe("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new Fe("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(r)));if(t.attachShader(a,n),t.attachShader(a,r),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS))throw new Fe('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(a)));const l=this.getUniformLocations(t,a)||{};return l.uStepW=t.getUniformLocation(a,"uStepW"),l.uStepH=t.getUniformLocation(a,"uStepH"),{program:a,attributeLocations:this.getAttributeLocations(t,a),uniformLocations:l}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const s=this.constructor.uniformLocations,i={};for(let n=0;n<s.length;n++)i[s[n]]=t.getUniformLocation(e,s[n]);return i}sendAttributeData(t,e,s){const i=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(i),t.vertexAttribPointer(i,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const s=t.destinationWidth,i=t.destinationHeight;t.sourceWidth===s&&t.sourceHeight===i||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,s,i)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){Mn(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){const e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){const e=t.context,s=this.retrieveShader(t);t.pass===0&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(s.program),this.sendAttributeData(e,s.attributeLocations,t.aPosition),e.uniform1f(s.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(s.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,s.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,s){t.activeTexture(s),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const{sourceWidth:e,sourceHeight:s}=t,i=ue({width:e,height:s});t.helpLayer=i}}toObject(){const t=Object.keys(this.constructor.defaults||{});return x({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this(pt(t,cf))}}S(Ft,"type","BaseFilter"),S(Ft,"uniformLocations",[]);const df={multiply:`gl_FragColor.rgb *= uColor.rgb;
|
|
104
104
|
`,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
|
|
105
105
|
`,add:`gl_FragColor.rgb += uColor.rgb;
|
|
106
106
|
`,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
|
|
@@ -127,7 +127,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
127
127
|
`,tint:`
|
|
128
128
|
gl_FragColor.rgb *= (1.0 - uColor.a);
|
|
129
129
|
gl_FragColor.rgb += uColor.rgb;
|
|
130
|
-
`};class
|
|
130
|
+
`};class On extends Ft{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
|
|
131
131
|
precision highp float;
|
|
132
132
|
uniform sampler2D uTexture;
|
|
133
133
|
uniform vec4 uColor;
|
|
@@ -136,10 +136,10 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
136
136
|
vec4 color = texture2D(uTexture, vTexCoord);
|
|
137
137
|
gl_FragColor = color;
|
|
138
138
|
if (color.a > 0.0) {
|
|
139
|
-
`.concat(
|
|
139
|
+
`.concat(df[this.mode],`
|
|
140
140
|
}
|
|
141
141
|
}
|
|
142
|
-
`)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new
|
|
142
|
+
`)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new ht(this.color).getSource(),i=this.alpha,n=s[0]*i,r=s[1]*i,a=s[2]*i,l=1-i;for(let h=0;h<e.length;h+=4){const c=e[h],u=e[h+1],d=e[h+2];let f,g,p;switch(this.mode){case"multiply":f=c*n/255,g=u*r/255,p=d*a/255;break;case"screen":f=255-(255-c)*(255-n)/255,g=255-(255-u)*(255-r)/255,p=255-(255-d)*(255-a)/255;break;case"add":f=c+n,g=u+r,p=d+a;break;case"difference":f=Math.abs(c-n),g=Math.abs(u-r),p=Math.abs(d-a);break;case"subtract":f=c-n,g=u-r,p=d-a;break;case"darken":f=Math.min(c,n),g=Math.min(u,r),p=Math.min(d,a);break;case"lighten":f=Math.max(c,n),g=Math.max(u,r),p=Math.max(d,a);break;case"overlay":f=n<128?2*c*n/255:255-2*(255-c)*(255-n)/255,g=r<128?2*u*r/255:255-2*(255-u)*(255-r)/255,p=a<128?2*d*a/255:255-2*(255-d)*(255-a)/255;break;case"exclusion":f=n+c-2*n*c/255,g=r+u-2*r*u/255,p=a+d-2*a*d/255;break;case"tint":f=n+c*l,g=r+u*l,p=a+d*l}e[h]=f,e[h+1]=g,e[h+2]=p}}sendUniformData(t,e){const s=new ht(this.color).getSource();s[0]=this.alpha*s[0]/255,s[1]=this.alpha*s[1]/255,s[2]=this.alpha*s[2]/255,s[3]=this.alpha,t.uniform4fv(e.uColor,s)}}S(On,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),S(On,"type","BlendColor"),S(On,"uniformLocations",["uColor"]),I.setClass(On);const ff={multiply:`
|
|
143
143
|
precision highp float;
|
|
144
144
|
uniform sampler2D uTexture;
|
|
145
145
|
uniform sampler2D uImage;
|
|
@@ -165,7 +165,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
165
165
|
color.a = color2.a;
|
|
166
166
|
gl_FragColor = color;
|
|
167
167
|
}
|
|
168
|
-
`},
|
|
168
|
+
`},gf=["type","image"];class Dn extends Ft{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return ff[this.mode]}getVertexSource(){return`
|
|
169
169
|
attribute vec2 aPosition;
|
|
170
170
|
varying vec2 vTexCoord;
|
|
171
171
|
varying vec2 vTexCoord2;
|
|
@@ -175,7 +175,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
175
175
|
vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
|
|
176
176
|
gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
|
|
177
177
|
}
|
|
178
|
-
`}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:i},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=
|
|
178
|
+
`}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:i},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=Ie());const a=n.blendImage,l=a.getContext("2d");a.width!==s||a.height!==i?(a.width=s,a.height=i):l.clearRect(0,0,s,i),l.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),l.drawImage(r.getElement(),0,0,s,i);const h=l.getImageData(0,0,s,i).data;for(let c=0;c<e.length;c+=4){const u=e[c],d=e[c+1],f=e[c+2],g=e[c+3],p=h[c],v=h[c+1],m=h[c+2],b=h[c+3];switch(this.mode){case"multiply":e[c]=u*p/255,e[c+1]=d*v/255,e[c+2]=f*m/255,e[c+3]=g*b/255;break;case"mask":e[c+3]=b}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return x(x({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:i}=t,n=pt(t,gf);return Vt.fromObject(i,e).then(r=>new this(x(x({},n),{},{image:r})))}}S(Dn,"type","BlendImage"),S(Dn,"defaults",{mode:"multiply",alpha:1}),S(Dn,"uniformLocations",["uTransformMatrix","uImage"]),I.setClass(Dn);class Rn extends Ft{getFragmentSource(){return`
|
|
179
179
|
precision highp float;
|
|
180
180
|
uniform sampler2D uTexture;
|
|
181
181
|
uniform vec2 uDelta;
|
|
@@ -188,17 +188,23 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
188
188
|
}
|
|
189
189
|
void main() {
|
|
190
190
|
vec4 color = vec4(0.0);
|
|
191
|
-
float
|
|
191
|
+
float totalC = 0.0;
|
|
192
|
+
float totalA = 0.0;
|
|
192
193
|
float offset = random(v3offset);
|
|
193
194
|
for (float t = -nSamples; t <= nSamples; t++) {
|
|
194
195
|
float percent = (t + offset - 0.5) / nSamples;
|
|
196
|
+
vec4 sample = texture2D(uTexture, vTexCoord + uDelta * percent);
|
|
195
197
|
float weight = 1.0 - abs(percent);
|
|
196
|
-
|
|
197
|
-
|
|
198
|
+
float alpha = weight * sample.a;
|
|
199
|
+
color.rgb += sample.rgb * alpha;
|
|
200
|
+
color.a += alpha;
|
|
201
|
+
totalA += weight;
|
|
202
|
+
totalC += alpha;
|
|
198
203
|
}
|
|
199
|
-
gl_FragColor = color /
|
|
204
|
+
gl_FragColor.rgb = color.rgb / totalC;
|
|
205
|
+
gl_FragColor.a = color.a / totalA;
|
|
200
206
|
}
|
|
201
|
-
`}applyTo(t){
|
|
207
|
+
`}applyTo(t){Mn(t)?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;this.aspectRatio=s/i,this.horizontal=!0;let n=this.getBlurValue()*s;const r=new Uint8ClampedArray(e),a=15,l=4*s;for(let h=0;h<e.length;h+=4){let c=0,u=0,d=0,f=0,g=0;const p=h-h%l,v=p+l;for(let m=-14;m<a;m++){const b=m/a,_=4*Math.floor(n*b),w=1-Math.abs(b);let C=h+_;C<p?C=p:C>v&&(C=v);const T=e[C+3]*w;c+=e[C]*T,u+=e[C+1]*T,d+=e[C+2]*T,f+=T,g+=w}r[h]=c/f,r[h+1]=u/f,r[h+2]=d/f,r[h+3]=f/g}this.horizontal=!1,n=this.getBlurValue()*i;for(let h=0;h<r.length;h+=4){let c=0,u=0,d=0,f=0,g=0;const p=h%l,v=r.length-l+p;for(let m=-14;m<a;m++){const b=m/a,_=Math.floor(n*b)*l,w=1-Math.abs(b);let C=h+_;C<p?C=p:C>v&&(C=v);const T=r[C+3]*w;c+=r[C]*T,u+=r[C+1]*T,d+=r[C+2]*T,f+=T,g+=w}e[h]=c/f,e[h+1]=u/f,e[h+2]=d/f,e[h+3]=f/g}}sendUniformData(t,e){const s=this.chooseRightDelta();t.uniform2fv(e.uDelta,s)}isNeutralState(){return this.blur===0}getBlurValue(){let t=1;const{horizontal:e,aspectRatio:s}=this;return e?s>1&&(t=1/s):s<1&&(t=s),t*this.blur*.12}chooseRightDelta(){const t=this.getBlurValue();return this.horizontal?[t,0]:[0,t]}}S(Rn,"type","Blur"),S(Rn,"defaults",{blur:0}),S(Rn,"uniformLocations",["uDelta"]),I.setClass(Rn);class Fn extends Ft{getFragmentSource(){return`
|
|
202
208
|
precision highp float;
|
|
203
209
|
uniform sampler2D uTexture;
|
|
204
210
|
uniform float uBrightness;
|
|
@@ -208,7 +214,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
208
214
|
color.rgb += uBrightness;
|
|
209
215
|
gl_FragColor = color;
|
|
210
216
|
}
|
|
211
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.round(255*this.brightness);for(let i=0;i<e.length;i+=4)e[i]+=s,e[i+1]+=s,e[i+2]+=s}isNeutralState(){return this.brightness===0}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}
|
|
217
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.round(255*this.brightness);for(let i=0;i<e.length;i+=4)e[i]+=s,e[i+1]+=s,e[i+2]+=s}isNeutralState(){return this.brightness===0}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}S(Fn,"type","Brightness"),S(Fn,"defaults",{brightness:0}),S(Fn,"uniformLocations",["uBrightness"]),I.setClass(Fn);const gh={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Zs extends Ft{getFragmentSource(){return`
|
|
212
218
|
precision highp float;
|
|
213
219
|
uniform sampler2D uTexture;
|
|
214
220
|
varying vec2 vTexCoord;
|
|
@@ -219,7 +225,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
219
225
|
color *= uColorMatrix;
|
|
220
226
|
color += uConstants;
|
|
221
227
|
gl_FragColor = color;
|
|
222
|
-
}`}applyTo2d(t){const e=t.imageData.data,s=this.matrix,i=this.colorsOnly;for(let n=0;n<e.length;n+=4){const r=e[n],a=e[n+1],
|
|
228
|
+
}`}applyTo2d(t){const e=t.imageData.data,s=this.matrix,i=this.colorsOnly;for(let n=0;n<e.length;n+=4){const r=e[n],a=e[n+1],l=e[n+2];if(e[n]=r*s[0]+a*s[1]+l*s[2]+255*s[4],e[n+1]=r*s[5]+a*s[6]+l*s[7]+255*s[9],e[n+2]=r*s[10]+a*s[11]+l*s[12]+255*s[14],!i){const h=e[n+3];e[n]+=h*s[3],e[n+1]+=h*s[8],e[n+2]+=h*s[13],e[n+3]=r*s[15]+a*s[16]+l*s[17]+h*s[18]+255*s[19]}}}sendUniformData(t,e){const s=this.matrix,i=[s[0],s[1],s[2],s[3],s[5],s[6],s[7],s[8],s[10],s[11],s[12],s[13],s[15],s[16],s[17],s[18]],n=[s[4],s[9],s[14],s[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,i),t.uniform4fv(e.uConstants,n)}toObject(){return x(x({},super.toObject()),{},{matrix:[...this.matrix]})}}function Ps(o,t){var e;const s=(S(e=class extends Zs{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",o),S(e,"defaults",{colorsOnly:!1,matrix:t}),e);return I.setClass(s,o),s}S(Zs,"type","ColorMatrix"),S(Zs,"defaults",gh),S(Zs,"uniformLocations",["uColorMatrix","uConstants"]),I.setClass(Zs),Ps("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),Ps("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),Ps("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),Ps("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),Ps("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),Ps("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),Ps("BlackWhite",[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]);class ph extends Ft{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){Mn(t)&&(t.passes+=this.subFilters.length-1),this.subFilters.forEach(e=>{e.applyTo(t)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(t=>t.toObject())}}isNeutralState(){return!this.subFilters.some(t=>!t.isNeutralState())}static fromObject(t,e){return Promise.all((t.subFilters||[]).map(s=>I.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}S(ph,"type","Composed"),I.setClass(ph);class Ln extends Ft{getFragmentSource(){return`
|
|
223
229
|
precision highp float;
|
|
224
230
|
uniform sampler2D uTexture;
|
|
225
231
|
uniform float uContrast;
|
|
@@ -229,7 +235,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
229
235
|
float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
|
|
230
236
|
color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
|
|
231
237
|
gl_FragColor = color;
|
|
232
|
-
}`}isNeutralState(){return this.contrast===0}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.floor(255*this.contrast),i=259*(s+255)/(255*(259-s));for(let n=0;n<e.length;n+=4)e[n]=i*(e[n]-128)+128,e[n+1]=i*(e[n+1]-128)+128,e[n+2]=i*(e[n+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}
|
|
238
|
+
}`}isNeutralState(){return this.contrast===0}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.floor(255*this.contrast),i=259*(s+255)/(255*(259-s));for(let n=0;n<e.length;n+=4)e[n]=i*(e[n]-128)+128,e[n+1]=i*(e[n+1]-128)+128,e[n+2]=i*(e[n+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}S(Ln,"type","Contrast"),S(Ln,"defaults",{contrast:0}),S(Ln,"uniformLocations",["uContrast"]),I.setClass(Ln);const pf={Convolute_3_1:`
|
|
233
239
|
precision highp float;
|
|
234
240
|
uniform sampler2D uTexture;
|
|
235
241
|
uniform float uMatrix[9];
|
|
@@ -373,7 +379,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
373
379
|
gl_FragColor = color;
|
|
374
380
|
gl_FragColor.a = alpha;
|
|
375
381
|
}
|
|
376
|
-
`};class
|
|
382
|
+
`};class In extends Ft{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return pf[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,s=e.data,i=this.matrix,n=Math.round(Math.sqrt(i.length)),r=Math.floor(n/2),a=e.width,l=e.height,h=t.ctx.createImageData(a,l),c=h.data,u=this.opaque?1:0;let d,f,g,p,v,m,b,_,w,C,T,E,k;for(T=0;T<l;T++)for(C=0;C<a;C++){for(v=4*(T*a+C),d=0,f=0,g=0,p=0,k=0;k<n;k++)for(E=0;E<n;E++)b=T+k-r,m=C+E-r,b<0||b>=l||m<0||m>=a||(_=4*(b*a+m),w=i[k*n+E],d+=s[_]*w,f+=s[_+1]*w,g+=s[_+2]*w,u||(p+=s[_+3]*w));c[v]=d,c[v+1]=f,c[v+2]=g,c[v+3]=u?s[v+3]:p}t.imageData=h}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return x(x({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}S(In,"type","Convolute"),S(In,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),S(In,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),I.setClass(In);const mh="Gamma";class jn extends Ft{getFragmentSource(){return`
|
|
377
383
|
precision highp float;
|
|
378
384
|
uniform sampler2D uTexture;
|
|
379
385
|
uniform vec3 uGamma;
|
|
@@ -387,7 +393,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
387
393
|
gl_FragColor = color;
|
|
388
394
|
gl_FragColor.rgb *= color.a;
|
|
389
395
|
}
|
|
390
|
-
`}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.gamma,i=1/s[0],n=1/s[1],r=1/s[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const a=this.rgbValues;for(let
|
|
396
|
+
`}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.gamma,i=1/s[0],n=1/s[1],r=1/s[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const a=this.rgbValues;for(let l=0;l<256;l++)a.r[l]=255*Math.pow(l/255,i),a.g[l]=255*Math.pow(l/255,n),a.b[l]=255*Math.pow(l/255,r);for(let l=0;l<e.length;l+=4)e[l]=a.r[e[l]],e[l+1]=a.g[e[l+1]],e[l+2]=a.b[e[l+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return t[0]===1&&t[1]===1&&t[2]===1}toObject(){return{type:mh,gamma:this.gamma.concat()}}}S(jn,"type",mh),S(jn,"defaults",{gamma:[1,1,1]}),S(jn,"uniformLocations",["uGamma"]),I.setClass(jn);const mf={average:`
|
|
391
397
|
precision highp float;
|
|
392
398
|
uniform sampler2D uTexture;
|
|
393
399
|
varying vec2 vTexCoord;
|
|
@@ -416,7 +422,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
416
422
|
float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
|
|
417
423
|
gl_FragColor = vec4(average, average, average, col.a);
|
|
418
424
|
}
|
|
419
|
-
`};class
|
|
425
|
+
`};class Nn extends Ft{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2];switch(this.mode){case"average":s=(n+r+a)/3;break;case"lightness":s=(Math.min(n,r,a)+Math.max(n,r,a))/2;break;case"luminosity":s=.21*n+.72*r+.07*a}e[i+2]=e[i+1]=e[i]=s}}getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return mf[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}S(Nn,"type","Grayscale"),S(Nn,"defaults",{mode:"average"}),S(Nn,"uniformLocations",["uMode"]),I.setClass(Nn);const vf=x(x({},gh),{},{rotation:0});class va extends Zs{calculateMatrix(){const t=this.rotation*Math.PI,e=xe(t),s=Se(t),i=1/3,n=Math.sqrt(i)*s,r=1-e;this.matrix=[e+r/3,i*r-n,i*r+n,0,0,i*r+n,e+i*r,i*r-n,0,0,i*r-n,i*r+n,e+i*r,0,0,0,0,0,1,0]}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}S(va,"type","HueRotation"),S(va,"defaults",vf),I.setClass(va);class Bn extends Ft{applyTo2d(t){let{imageData:{data:e}}=t;for(let s=0;s<e.length;s+=4)e[s]=255-e[s],e[s+1]=255-e[s+1],e[s+2]=255-e[s+2],this.alpha&&(e[s+3]=255-e[s+3])}getFragmentSource(){return`
|
|
420
426
|
precision highp float;
|
|
421
427
|
uniform sampler2D uTexture;
|
|
422
428
|
uniform int uInvert;
|
|
@@ -434,7 +440,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
434
440
|
gl_FragColor = color;
|
|
435
441
|
}
|
|
436
442
|
}
|
|
437
|
-
`}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}
|
|
443
|
+
`}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}S(Bn,"type","Invert"),S(Bn,"defaults",{alpha:!1,invert:!0}),S(Bn,"uniformLocations",["uInvert","uAlpha"]),I.setClass(Bn);class Hn extends Ft{getFragmentSource(){return`
|
|
438
444
|
precision highp float;
|
|
439
445
|
uniform sampler2D uTexture;
|
|
440
446
|
uniform float uStepH;
|
|
@@ -449,7 +455,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
449
455
|
color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
|
|
450
456
|
gl_FragColor = color;
|
|
451
457
|
}
|
|
452
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.noise;for(let i=0;i<e.length;i+=4){const n=(.5-Math.random())*s;e[i]+=n,e[i+1]+=n,e[i+2]+=n}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return this.noise===0}}
|
|
458
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.noise;for(let i=0;i<e.length;i+=4){const n=(.5-Math.random())*s;e[i]+=n,e[i+1]+=n,e[i+2]+=n}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return this.noise===0}}S(Hn,"type","Noise"),S(Hn,"defaults",{noise:0}),S(Hn,"uniformLocations",["uNoise","uSeed"]),I.setClass(Hn);class zn extends Ft{applyTo2d(t){let{imageData:{data:e,width:s,height:i}}=t;for(let n=0;n<i;n+=this.blocksize)for(let r=0;r<s;r+=this.blocksize){const a=4*n*s+4*r,l=e[a],h=e[a+1],c=e[a+2],u=e[a+3];for(let d=n;d<Math.min(n+this.blocksize,i);d++)for(let f=r;f<Math.min(r+this.blocksize,s);f++){const g=4*d*s+4*f;e[g]=l,e[g+1]=h,e[g+2]=c,e[g+3]=u}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
|
|
453
459
|
precision highp float;
|
|
454
460
|
uniform sampler2D uTexture;
|
|
455
461
|
uniform float uBlocksize;
|
|
@@ -467,7 +473,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
|
|
|
467
473
|
vec4 color = texture2D(uTexture, squareCoords);
|
|
468
474
|
gl_FragColor = color;
|
|
469
475
|
}
|
|
470
|
-
`}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}
|
|
476
|
+
`}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}S(zn,"type","Pixelate"),S(zn,"defaults",{blocksize:4}),S(zn,"uniformLocations",["uBlocksize"]),I.setClass(zn);class Vn extends Ft{getFragmentSource(){return`
|
|
471
477
|
precision highp float;
|
|
472
478
|
uniform sampler2D uTexture;
|
|
473
479
|
uniform vec4 uLow;
|
|
@@ -479,7 +485,7 @@ void main() {
|
|
|
479
485
|
gl_FragColor.a = 0.0;
|
|
480
486
|
}
|
|
481
487
|
}
|
|
482
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new
|
|
488
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,i=new ht(this.color).getSource(),n=[i[0]-s,i[1]-s,i[2]-s],r=[i[0]+s,i[1]+s,i[2]+s];for(let a=0;a<e.length;a+=4){const l=e[a],h=e[a+1],c=e[a+2];l>n[0]&&h>n[1]&&c>n[2]&&l<r[0]&&h<r[1]&&c<r[2]&&(e[a+3]=0)}}sendUniformData(t,e){const s=new ht(this.color).getSource(),i=this.distance,n=[0+s[0]/255-i,0+s[1]/255-i,0+s[2]/255-i,1],r=[s[0]/255+i,s[1]/255+i,s[2]/255+i,1];t.uniform4fv(e.uLow,n),t.uniform4fv(e.uHigh,r)}}S(Vn,"type","RemoveColor"),S(Vn,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),S(Vn,"uniformLocations",["uLow","uHigh"]),I.setClass(Vn);class Gn extends Ft{sendUniformData(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)}getFilterWindow(){const t=this.tempScale;return Math.ceil(this.lanczosLobes/t)}getCacheKey(){const t=this.getFilterWindow();return"".concat(this.type,"_").concat(t)}getFragmentSource(){const t=this.getFilterWindow();return this.generateShader(t)}getTaps(){const t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,s=this.getFilterWindow(),i=new Array(s);for(let n=1;n<=s;n++)i[n-1]=t(n*e);return i}generateShader(t){const e=new Array(t);for(let s=1;s<=t;s++)e[s-1]="".concat(s,".0 * uDelta");return`
|
|
483
489
|
precision highp float;
|
|
484
490
|
uniform sampler2D uTexture;
|
|
485
491
|
uniform vec2 uDelta;
|
|
@@ -495,7 +501,7 @@ void main() {
|
|
|
495
501
|
`),`
|
|
496
502
|
gl_FragColor = color / sum;
|
|
497
503
|
}
|
|
498
|
-
`)}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){
|
|
504
|
+
`)}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){Mn(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<11920929e-14&&e>-11920929e-14)return 1;const s=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(s)/s}}applyTo2d(t){const e=t.imageData,s=this.scaleX,i=this.scaleY;this.rcpScaleX=1/s,this.rcpScaleY=1/i;const n=e.width,r=e.height,a=Math.round(n*s),l=Math.round(r*i);let h;h=this.resizeType==="sliceHack"?this.sliceByTwo(t,n,r,a,l):this.resizeType==="hermite"?this.hermiteFastResize(t,n,r,a,l):this.resizeType==="bilinear"?this.bilinearFiltering(t,n,r,a,l):this.resizeType==="lanczos"?this.lanczosResize(t,n,r,a,l):new ImageData(a,l),t.imageData=h}sliceByTwo(t,e,s,i,n){const r=t.imageData,a=.5;let l=!1,h=!1,c=e*a,u=s*a;const d=t.filterBackend.resources;let f=0,g=0;const p=e;let v=0;d.sliceByTwo||(d.sliceByTwo=Ie());const m=d.sliceByTwo;(m.width<1.5*e||m.height<s)&&(m.width=1.5*e,m.height=s);const b=m.getContext("2d");for(b.clearRect(0,0,1.5*e,s),b.putImageData(r,0,0),i=Math.floor(i),n=Math.floor(n);!l||!h;)e=c,s=u,i<Math.floor(c*a)?c=Math.floor(c*a):(c=i,l=!0),n<Math.floor(u*a)?u=Math.floor(u*a):(u=n,h=!0),b.drawImage(m,f,g,e,s,p,v,c,u),f=p,g=v,v+=u;return b.getImageData(f,g,i,n)}lanczosResize(t,e,s,i,n){const r=t.imageData.data,a=t.ctx.createImageData(i,n),l=a.data,h=this.lanczosCreate(this.lanczosLobes),c=this.rcpScaleX,u=this.rcpScaleY,d=2/this.rcpScaleX,f=2/this.rcpScaleY,g=Math.ceil(c*this.lanczosLobes/2),p=Math.ceil(u*this.lanczosLobes/2),v={},m={x:0,y:0},b={x:0,y:0};return function _(w){let C,T,E,k,O,H,N,P,R,F,V;for(m.x=(w+.5)*c,b.x=Math.floor(m.x),C=0;C<n;C++){for(m.y=(C+.5)*u,b.y=Math.floor(m.y),O=0,H=0,N=0,P=0,R=0,T=b.x-g;T<=b.x+g;T++)if(!(T<0||T>=e)){F=Math.floor(1e3*Math.abs(T-m.x)),v[F]||(v[F]={});for(let M=b.y-p;M<=b.y+p;M++)M<0||M>=s||(V=Math.floor(1e3*Math.abs(M-m.y)),v[F][V]||(v[F][V]=h(Math.sqrt(Math.pow(F*d,2)+Math.pow(V*f,2))/1e3)),E=v[F][V],E>0&&(k=4*(M*e+T),O+=E,H+=E*r[k],N+=E*r[k+1],P+=E*r[k+2],R+=E*r[k+3]))}k=4*(C*i+w),l[k]=H/O,l[k+1]=N/O,l[k+2]=P/O,l[k+3]=R/O}return++w<i?_(w):a}(0)}bilinearFiltering(t,e,s,i,n){let r,a,l,h,c,u,d,f,g,p,v,m,b,_=0;const w=this.rcpScaleX,C=this.rcpScaleY,T=4*(e-1),E=t.imageData.data,k=t.ctx.createImageData(i,n),O=k.data;for(d=0;d<n;d++)for(f=0;f<i;f++)for(c=Math.floor(w*f),u=Math.floor(C*d),g=w*f-c,p=C*d-u,b=4*(u*e+c),v=0;v<4;v++)r=E[b+v],a=E[b+4+v],l=E[b+T+v],h=E[b+T+4+v],m=r*(1-g)*(1-p)+a*g*(1-p)+l*p*(1-g)+h*g*p,O[_++]=m;return k}hermiteFastResize(t,e,s,i,n){const r=this.rcpScaleX,a=this.rcpScaleY,l=Math.ceil(r/2),h=Math.ceil(a/2),c=t.imageData.data,u=t.ctx.createImageData(i,n),d=u.data;for(let f=0;f<n;f++)for(let g=0;g<i;g++){const p=4*(g+f*i);let v=0,m=0,b=0,_=0,w=0,C=0,T=0;const E=(f+.5)*a;for(let k=Math.floor(f*a);k<(f+1)*a;k++){const O=Math.abs(E-(k+.5))/h,H=(g+.5)*r,N=O*O;for(let P=Math.floor(g*r);P<(g+1)*r;P++){let R=Math.abs(H-(P+.5))/l;const F=Math.sqrt(N+R*R);F>1&&F<-1||(v=2*F*F*F-3*F*F+1,v>0&&(R=4*(P+k*e),T+=v*c[R+3],b+=v,c[R+3]<255&&(v=v*c[R+3]/250),_+=v*c[R],w+=v*c[R+1],C+=v*c[R+2],m+=v))}}d[p]=_/m,d[p+1]=w/m,d[p+2]=C/m,d[p+3]=T/b}return u}}S(Gn,"type","Resize"),S(Gn,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),S(Gn,"uniformLocations",["uDelta","uTaps"]),I.setClass(Gn);class Wn extends Ft{getFragmentSource(){return`
|
|
499
505
|
precision highp float;
|
|
500
506
|
uniform sampler2D uTexture;
|
|
501
507
|
uniform float uSaturation;
|
|
@@ -509,7 +515,7 @@ void main() {
|
|
|
509
515
|
color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
|
|
510
516
|
gl_FragColor = color;
|
|
511
517
|
}
|
|
512
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2],
|
|
518
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2],l=Math.max(n,r,a);e[i]+=l!==n?(l-n)*s:0,e[i+1]+=l!==r?(l-r)*s:0,e[i+2]+=l!==a?(l-a)*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}S(Wn,"type","Saturation"),S(Wn,"defaults",{saturation:0}),S(Wn,"uniformLocations",["uSaturation"]),I.setClass(Wn);class Xn extends Ft{getFragmentSource(){return`
|
|
513
519
|
precision highp float;
|
|
514
520
|
uniform sampler2D uTexture;
|
|
515
521
|
uniform float uVibrance;
|
|
@@ -524,15 +530,15 @@ void main() {
|
|
|
524
530
|
color.b += max != color.b ? (max - color.b) * amt : 0.00;
|
|
525
531
|
gl_FragColor = color;
|
|
526
532
|
}
|
|
527
|
-
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2],h=Math.max(n,r,a),c=(n+r+a)/3,u=2*Math.abs(h-c)/255*s;e[i]+=h!==n?(h-n)*u:0,e[i+1]+=h!==r?(h-r)*u:0,e[i+2]+=h!==a?(h-a)*u:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}E(od,"type","Vibrance"),E(od,"defaults",{vibrance:0}),E(od,"uniformLocations",["uVibrance"]),W.setClass(od);let kv=null;function Kx(){const o=document.createElement("div");o.style.width="1in",document.body.append(o);const t=o.offsetWidth;return o.remove(),t}function Jx(){const o=kv??Kx();return kv=o,o/72}function Qx(o,t=500){if(typeof o!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,o.apply(this,s)},t)}}function Zx(o){return new Promise((t,e)=>{const s=window.URL.createObjectURL(o),i=new Image;i.src=s,i.addEventListener("load",async()=>{window.URL.revokeObjectURL(s),t(await tS(i))}),i.addEventListener("error",n=>{window.URL.revokeObjectURL(s),e(n)})})}function tS(o){return new Promise(t=>{const e=document.createElement("canvas"),s=e.getContext("2d"),{naturalWidth:i,naturalHeight:n}=o;e.width=i,e.height=n,s==null||s.drawImage(o,0,0,i,n),t(e.toDataURL("image/jpeg",.8))})}var ol={};ol.d=(o,t)=>{for(var e in t)ol.o(t,e)&&!ol.o(o,e)&&Object.defineProperty(o,e,{enumerable:!0,get:t[e]})},ol.o=(o,t)=>Object.prototype.hasOwnProperty.call(o,t);var tt=globalThis.pdfjsLib={};ol.d(tt,{AbortException:()=>qn,AnnotationEditorLayer:()=>lp,AnnotationEditorParamsType:()=>gt,AnnotationEditorType:()=>ot,AnnotationEditorUIManager:()=>$r,AnnotationLayer:()=>qC,AnnotationMode:()=>Yn,ColorPicker:()=>Td,DOMSVGFactory:()=>Zg,DrawLayer:()=>cp,FeatureTest:()=>Ue,GlobalWorkerOptions:()=>an,ImageKind:()=>hd,InvalidPDFException:()=>Mg,MissingPDFException:()=>ll,OPS:()=>ni,OutputScale:()=>Bg,PDFDataRangeTransport:()=>lb,PDFDateString:()=>jg,PDFWorker:()=>ko,PasswordResponses:()=>nS,PermissionFlag:()=>iS,PixelsPerInch:()=>Kn,RenderingCancelledException:()=>Lg,TextLayer:()=>pl,TouchManager:()=>bd,UnexpectedResponseException:()=>dd,Util:()=>q,VerbosityLevel:()=>ld,XfaLayer:()=>fb,build:()=>PC,createValidAbsoluteUrl:()=>hS,fetchData:()=>gd,getDocument:()=>_C,getFilenameFromUrl:()=>vS,getPdfFilenameFromUrl:()=>bS,getXfaPageViewport:()=>yS,isDataScheme:()=>pd,isPdfFile:()=>Ig,noContextMenu:()=>ri,normalizeUnicode:()=>gS,setLayerDimensions:()=>Yr,shadow:()=>ct,stopEvent:()=>bs,version:()=>kC});const Oe=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Pv=[1,0,0,1,0,0],Eg=[.001,0,0,.001,0,0],eS=1e7,kg=1.35,vs={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},Yn={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},sS="pdfjs_internal_editor_",ot={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},gt={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},iS={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},De={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},hd={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},le={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,WIDGET:20},hl={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},ld={ERRORS:0,WARNINGS:1,INFOS:5},ni={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},nS={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let cd=ld.WARNINGS;function rS(o){Number.isInteger(o)&&(cd=o)}function aS(){return cd}function ud(o){cd>=ld.INFOS&&console.log(`Info: ${o}`)}function ht(o){cd>=ld.WARNINGS&&console.log(`Warning: ${o}`)}function kt(o){throw new Error(o)}function ie(o,t){o||kt(t)}function oS(o){switch(o==null?void 0:o.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function hS(o,t=null,e=null){if(!o)return null;try{if(e&&typeof o=="string"){if(e.addDefaultProtocol&&o.startsWith("www.")){const i=o.match(/\./g);(i==null?void 0:i.length)>=2&&(o=`http://${o}`)}if(e.tryConvertEncoding)try{o=fS(o)}catch{}}const s=t?new URL(o,t):new URL(o);if(oS(s))return s}catch{}return null}function ct(o,t,e,s=!1){return Object.defineProperty(o,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const $n=function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class Mv extends $n{constructor(t,e){super(t,"PasswordException"),this.code=e}}class Pg extends $n{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class Mg extends $n{constructor(t){super(t,"InvalidPDFException")}}class ll extends $n{constructor(t){super(t,"MissingPDFException")}}class dd extends $n{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class lS extends $n{constructor(t){super(t,"FormatError")}}class qn extends $n{constructor(t){super(t,"AbortException")}}function Ov(o){(typeof o!="object"||(o==null?void 0:o.length)===void 0)&&kt("Invalid argument for bytesToString");const t=o.length,e=8192;if(t<e)return String.fromCharCode.apply(null,o);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=o.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function fd(o){typeof o!="string"&&kt("Invalid argument for stringToBytes");const t=o.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=o.charCodeAt(s)&255;return e}function cS(o){return String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,o&255)}function Og(o){const t=Object.create(null);for(const[e,s]of o)t[e]=s;return t}function uS(){const o=new Uint8Array(4);return o[0]=1,new Uint32Array(o.buffer,0,1)[0]===1}function dS(){try{return new Function(""),!0}catch{return!1}}class Ue{static get isLittleEndian(){return ct(this,"isLittleEndian",uS())}static get isEvalSupported(){return ct(this,"isEvalSupported",dS())}static get isOffscreenCanvasSupported(){return ct(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return ct(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?ct(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):ct(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,e;return ct(this,"isCSSRoundSupported",(e=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:e.call(t,"width: round(1.5px, 1px)"))}}const Dg=Array.from(Array(256).keys(),o=>o.toString(16).padStart(2,"0"));class q{static makeHexColor(t,e,s){return`#${Dg[t]}${Dg[e]}${Dg[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],r[0]),Math.min(s[1],i[1],n[1],r[1]),Math.max(s[0],i[0],n[0],r[0]),Math.max(s[1],i[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],a=(s+r)/2,h=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,c=a+h||1,u=a-h||1;return[Math.sqrt(c),Math.sqrt(u)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static bezierBoundingBox(t,e,s,i,n,r,a,h,c){return c?(c[0]=Math.min(c[0],t,a),c[1]=Math.min(c[1],e,h),c[2]=Math.max(c[2],t,a),c[3]=Math.max(c[3],e,h)):c=[Math.min(t,a),Math.min(e,h),Math.max(t,a),Math.max(e,h)],w(this,on,Cp).call(this,t,s,n,a,e,i,r,h,3*(-t+3*(s-n)+a),6*(t-2*s+n),3*(s-t),c),w(this,on,Cp).call(this,t,s,n,a,e,i,r,h,3*(-e+3*(i-r)+h),6*(e-2*i+r),3*(i-e),c),c}}on=new WeakSet,Qd=function(t,e,s,i,n,r,a,h,c,u){if(c<=0||c>=1)return;const d=1-c,f=c*c,g=f*c,p=d*(d*(d*t+3*c*e)+3*f*s)+g*i,m=d*(d*(d*n+3*c*r)+3*f*a)+g*h;u[0]=Math.min(u[0],p),u[1]=Math.min(u[1],m),u[2]=Math.max(u[2],p),u[3]=Math.max(u[3],m)},Cp=function(t,e,s,i,n,r,a,h,c,u,d,f){if(Math.abs(c)<1e-12){Math.abs(u)>=1e-12&&w(this,on,Qd).call(this,t,e,s,i,n,r,a,h,-d/u,f);return}const g=u**2-4*d*c;if(g<0)return;const p=Math.sqrt(g),m=2*c;w(this,on,Qd).call(this,t,e,s,i,n,r,a,h,(-u+p)/m,f),w(this,on,Qd).call(this,t,e,s,i,n,r,a,h,(-u-p)/m,f)},_(q,on);function fS(o){return decodeURIComponent(escape(o))}let Rg=null,Dv=null;function gS(o){return Rg||(Rg=/([\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,Dv=new Map([["ſt","ſt"]])),o.replaceAll(Rg,(t,e,s)=>e?e.normalize("NFKC"):Dv.get(s))}function pS(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const o=new Uint8Array(32);return crypto.getRandomValues(o),Ov(o)}const Fg="pdfjs_internal_id_";function mS(o){return Uint8Array.prototype.toBase64?o.toBase64():btoa(Ov(o))}typeof Promise.try!="function"&&(Promise.try=function(o,...t){return new Promise(e=>{e(o(...t))})});const rn="http://www.w3.org/2000/svg",Jr=class Jr{};Q(Jr,"CSS",96),Q(Jr,"PDF",72),Q(Jr,"PDF_TO_CSS_UNITS",Jr.CSS/Jr.PDF);let Kn=Jr;async function gd(o,t="text"){if(ul(o,document.baseURI)){const e=await fetch(o);if(!e.ok)throw new Error(e.statusText);switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",o,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"arraybuffer":case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class cl{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const h=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let u,d,f,g;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,d=0,f=0,g=1;break;case 90:u=0,d=1,f=1,g=0;break;case 270:u=0,d=-1,f=-1,g=0;break;case 0:u=1,d=0,f=0,g=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(f=-f,g=-g);let p,m,y,b;u===0?(p=Math.abs(c-t[1])*s+n,m=Math.abs(h-t[0])*s+r,y=(t[3]-t[1])*s,b=(t[2]-t[0])*s):(p=Math.abs(h-t[0])*s+n,m=Math.abs(c-t[1])*s+r,y=(t[2]-t[0])*s,b=(t[3]-t[1])*s),this.transform=[u*s,d*s,f*s,g*s,p-u*s*h-f*s*c,m-d*s*h-g*s*c],this.width=y,this.height=b}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return ct(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new cl({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return q.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=q.applyTransform([t[0],t[1]],this.transform),s=q.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return q.applyInverseTransform([t,e],this.transform)}}class Lg extends $n{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function pd(o){const t=o.length;let e=0;for(;e<t&&o[e].trim()==="";)e++;return o.substring(e,e+5).toLowerCase()==="data:"}function Ig(o){return typeof o=="string"&&/\.pdf$/i.test(o)}function vS(o){return[o]=o.split(/[#?]/,1),o.substring(o.lastIndexOf("/")+1)}function bS(o,t="document.pdf"){if(typeof o!="string")return t;if(pd(o))return ht('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(o);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class Rv{constructor(){Q(this,"started",Object.create(null));Q(this,"times",[])}time(t){t in this.started&&ht(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||ht(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
|
|
528
|
-
`);return t.join("")}}function ul(o,t){try{const{protocol:e}=t?new URL(o,t):new URL(o);return e==="http:"||e==="https:"}catch{return!1}}function ri(o){o.preventDefault()}function bs(o){o.preventDefault(),o.stopPropagation()}class jg{static toDateObject(t){if(!t||typeof t!="string")return null;l(this,_l)||v(this,_l,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?"));const e=l(this,_l).exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let h=parseInt(e[6],10);h=h>=0&&h<=59?h:0;const c=e[7]||"Z";let u=parseInt(e[8],10);u=u>=0&&u<=23?u:0;let d=parseInt(e[9],10)||0;return d=d>=0&&d<=59?d:0,c==="-"?(r+=u,a+=d):c==="+"&&(r-=u,a-=d),new Date(Date.UTC(s,i,n,r,a,h))}}_l=new WeakMap,_(jg,_l);function yS(o,{scale:t=1,rotation:e=0}){const{width:s,height:i}=o.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new cl({viewBox:n,userUnit:1,scale:t,rotation:e})}function Ng(o){if(o.startsWith("#")){const t=parseInt(o.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return o.startsWith("rgb(")?o.slice(4,-1).split(",").map(t=>parseInt(t)):o.startsWith("rgba(")?o.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(ht(`Not a valid color format: "${o}"`),[0,0,0])}function _S(o){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of o.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;o.set(e,Ng(s))}t.remove()}function It(o){const{a:t,b:e,c:s,d:i,e:n,f:r}=o.getTransform();return[t,e,s,i,n,r]}function Ei(o){const{a:t,b:e,c:s,d:i,e:n,f:r}=o.getTransform().invertSelf();return[t,e,s,i,n,r]}function Yr(o,t,e=!1,s=!0){if(t instanceof cl){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=o,a=Ue.isCSSRoundSupported,h=`var(--scale-factor) * ${i}px`,c=`var(--scale-factor) * ${n}px`,u=a?`round(down, ${h}, var(--scale-round-x, 1px))`:`calc(${h})`,d=a?`round(down, ${c}, var(--scale-round-y, 1px))`:`calc(${c})`;!e||t.rotation%180===0?(r.width=u,r.height=d):(r.width=d,r.height=u)}s&&o.setAttribute("data-main-rotation",t.rotation)}class Bg{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}const hn=class hn{constructor(t){_(this,Ye);_(this,Qn,null);_(this,Qr,null);_(this,ai);_(this,Zr,null);_(this,wl,null);v(this,ai,t),l(hn,xl)||v(hn,xl,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=v(this,Qn,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=l(this,ai)._uiManager._signal;t.addEventListener("contextmenu",ri,{signal:e}),t.addEventListener("pointerdown",w(hn,Pd,Wb),{signal:e});const s=v(this,Zr,document.createElement("div"));s.className="buttons",t.append(s);const i=l(this,ai).toolbarPosition;if(i){const{style:n}=t,r=l(this,ai)._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return w(this,Ye,Ub).call(this),t}get div(){return l(this,Qn)}hide(){var t;l(this,Qn).classList.add("hidden"),(t=l(this,Qr))==null||t.hideDropdown()}show(){var t;l(this,Qn).classList.remove("hidden"),(t=l(this,wl))==null||t.shown()}async addAltText(t){const e=await t.render();w(this,Ye,Zd).call(this,e),l(this,Zr).prepend(e,l(this,Ye,Ap)),v(this,wl,t)}addColorPicker(t){v(this,Qr,t);const e=t.renderButton();w(this,Ye,Zd).call(this,e),l(this,Zr).prepend(e,l(this,Ye,Ap))}remove(){var t;l(this,Qn).remove(),(t=l(this,Qr))==null||t.destroy(),v(this,Qr,null)}};Qn=new WeakMap,Qr=new WeakMap,ai=new WeakMap,Zr=new WeakMap,wl=new WeakMap,xl=new WeakMap,Pd=new WeakSet,Wb=function(t){t.stopPropagation()},Ye=new WeakSet,Gb=function(t){l(this,ai)._focusEventsAllowed=!1,bs(t)},Xb=function(t){l(this,ai)._focusEventsAllowed=!0,bs(t)},Zd=function(t){const e=l(this,ai)._uiManager._signal;t.addEventListener("focusin",w(this,Ye,Gb).bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",w(this,Ye,Xb).bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",ri,{signal:e})},Ub=function(){const{editorType:t,_uiManager:e}=l(this,ai),s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",l(hn,xl)[t]),w(this,Ye,Zd).call(this,s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),l(this,Zr).append(s)},Ap=function(){const t=document.createElement("div");return t.className="divider",t},_(hn,Pd),_(hn,xl,null);let Hg=hn;class wS{constructor(t){_(this,Zn);_(this,Sl,null);_(this,ta,null);_(this,ea);v(this,ea,t)}show(t,e,s){const[i,n]=w(this,Zn,$b).call(this,e,s),{style:r}=l(this,ta)||v(this,ta,w(this,Zn,Yb).call(this));t.append(l(this,ta)),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){l(this,ta).remove()}}Sl=new WeakMap,ta=new WeakMap,ea=new WeakMap,Zn=new WeakSet,Yb=function(){const t=v(this,ta,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",ri,{signal:l(this,ea)._signal});const e=v(this,Sl,document.createElement("div"));return e.className="buttons",t.append(e),w(this,Zn,qb).call(this),t},$b=function(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const a=n.x+(e?n.width:0);if(r>s){i=a,s=r;continue}e?a>i&&(i=a):a<i&&(i=a)}return[e?1-i:i,s]},qb=function(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=l(this,ea)._signal;t.addEventListener("contextmenu",ri,{signal:s}),t.addEventListener("click",()=>{l(this,ea).highlightSelection("floating_button")},{signal:s}),l(this,Sl).append(t)};function md(o,t,e){for(const s of e)t.addEventListener(s,o[s].bind(o))}class xS{constructor(){_(this,Md,0)}get id(){return`${sS}${es(this,Md)._++}`}}Md=new WeakMap;const dp=class dp{constructor(){_(this,Mo);_(this,Po,pS());_(this,Cl,0);_(this,Fe,null)}static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return ct(this,"_isSVGFittingCanvas",n)}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return w(this,Mo,tf).call(this,`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return w(this,Mo,tf).call(this,t,t)}async getFromBlob(t,e){const s=await e;return w(this,Mo,tf).call(this,t,s)}async getFromId(t){l(this,Fe)||v(this,Fe,new Map);const e=l(this,Fe).get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){l(this,Fe)||v(this,Fe,new Map);let s=l(this,Fe).get(t);if(s!=null&&s.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${l(this,Po)}_${es(this,Cl)._++}`,refCounter:1,isSvg:!1},l(this,Fe).set(t,s),l(this,Fe).set(s.id,s),s}getSvgUrl(t){const e=l(this,Fe).get(t);return e!=null&&e.isSvg?e.svgUrl:null}deleteId(t){var i;l(this,Fe)||v(this,Fe,new Map);const e=l(this,Fe).get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const n=new OffscreenCanvas(s.width,s.height);n.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=n.convertToBlob()}(i=s.close)==null||i.call(s),e.bitmap=null}isValidId(t){return t.startsWith(`image_${l(this,Po)}_`)}};Po=new WeakMap,Cl=new WeakMap,Fe=new WeakMap,Mo=new WeakSet,tf=async function(t,e){l(this,Fe)||v(this,Fe,new Map);let s=l(this,Fe).get(t);if(s===null)return null;if(s!=null&&s.bitmap)return s.refCounter+=1,s;try{s||(s={bitmap:null,id:`image_${l(this,Po)}_${es(this,Cl)._++}`,refCounter:0,isSvg:!1});let i;if(typeof e=="string"?(s.url=e,i=await gd(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=dp._isSVGFittingCanvas,r=new FileReader,a=new Image,h=new Promise((c,u)=>{a.onload=()=>{s.bitmap=a,s.isSvg=!0,c()},r.onload=async()=>{const d=s.svgUrl=r.result;a.src=await n?`${d}#svgView(preserveAspectRatio(none))`:d},a.onerror=r.onerror=u});r.readAsDataURL(i),await h}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){ht(i),s=null}return l(this,Fe).set(t,s),s&&l(this,Fe).set(s.id,s),s};let zg=dp;class SS{constructor(t=128){_(this,Jt,[]);_(this,tr,!1);_(this,Al);_(this,Wt,-1);v(this,Al,t)}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(i&&t(),l(this,tr))return;const h={cmd:t,undo:e,post:s,type:n};if(l(this,Wt)===-1){l(this,Jt).length>0&&(l(this,Jt).length=0),v(this,Wt,0),l(this,Jt).push(h);return}if(r&&l(this,Jt)[l(this,Wt)].type===n){a&&(h.undo=l(this,Jt)[l(this,Wt)].undo),l(this,Jt)[l(this,Wt)]=h;return}const c=l(this,Wt)+1;c===l(this,Al)?l(this,Jt).splice(0,1):(v(this,Wt,c),c<l(this,Jt).length&&l(this,Jt).splice(c)),l(this,Jt).push(h)}undo(){if(l(this,Wt)===-1)return;v(this,tr,!0);const{undo:t,post:e}=l(this,Jt)[l(this,Wt)];t(),e==null||e(),v(this,tr,!1),v(this,Wt,l(this,Wt)-1)}redo(){if(l(this,Wt)<l(this,Jt).length-1){v(this,Wt,l(this,Wt)+1),v(this,tr,!0);const{cmd:t,post:e}=l(this,Jt)[l(this,Wt)];t(),e==null||e(),v(this,tr,!1)}}hasSomethingToUndo(){return l(this,Wt)!==-1}hasSomethingToRedo(){return l(this,Wt)<l(this,Jt).length-1}cleanType(t){if(l(this,Wt)!==-1){for(let e=l(this,Wt);e>=0;e--)if(l(this,Jt)[e].type!==t){l(this,Jt).splice(e+1,l(this,Wt)-e),v(this,Wt,e);return}l(this,Jt).length=0,v(this,Wt,-1)}}destroy(){v(this,Jt,null)}}Jt=new WeakMap,tr=new WeakMap,Al=new WeakMap,Wt=new WeakMap;class dl{constructor(t){_(this,Od);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Ue.platform;for(const[s,i,n={}]of t)for(const r of s){const a=r.startsWith("mac+");e&&a?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!a&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(w(this,Od,Kb).call(this,e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:a=null}}=s;a&&!a(t,e)||(i.bind(t,...r,e)(),n||bs(e))}}Od=new WeakSet,Kb=function(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e};const Dd=class Dd{get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return _S(t),ct(this,"_colors",t)}convert(t){const e=Ng(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return Dd._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?q.makeHexColor(...e):t}};Q(Dd,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let Vg=Dd;const jo=class jo{constructor(t,e,s,i,n,r,a,h,c,u,d,f,g){_(this,H);_(this,Oo,new AbortController);_(this,ys,null);_(this,ce,new Map);_(this,_e,new Map);_(this,Do,null);_(this,ln,null);_(this,Ro,null);_(this,Ns,new SS);_(this,er,null);_(this,sa,null);_(this,Fo,0);_(this,ia,new Set);_(this,Pi,null);_(this,oi,null);_(this,na,new Set);Q(this,"_editorUndoBar",null);_(this,Tl,!1);_(this,El,!1);_(this,Lo,!1);_(this,kl,null);_(this,Mi,null);_(this,sr,null);_(this,Io,null);_(this,ir,!1);_(this,Oi,null);_(this,Rd,new xS);_(this,nr,!1);_(this,Pl,!1);_(this,rr,null);_(this,ra,null);_(this,Ml,null);_(this,Ol,null);_(this,ge,ot.NONE);_(this,Ct,new Set);_(this,cn,null);_(this,aa,null);_(this,Dl,null);_(this,Rl,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});_(this,ar,[0,0]);_(this,Di,null);_(this,un,null);_(this,Fl,null);_(this,Bs,null);const p=this._signal=l(this,Oo).signal;v(this,un,t),v(this,Fl,e),v(this,Do,s),this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:p}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:p}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:p}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:p}),i._on("setpreference",this.onSetPreference.bind(this),{signal:p}),i._on("switchannotationeditorparams",m=>this.updateParams(m.type,m.value),{signal:p}),w(this,H,Zb).call(this),w(this,H,iy).call(this),w(this,H,Ep).call(this),v(this,ln,n.annotationStorage),v(this,kl,n.filterFactory),v(this,aa,r),v(this,Io,a||null),v(this,Tl,h),v(this,El,c),v(this,Lo,u),v(this,Ol,d||null),this.viewParameters={realScale:Kn.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=f||null,this._supportsPinchToZoom=g!==!1}static get _keyboardManager(){const t=jo.prototype,e=r=>l(r,un).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:a})=>{if(a instanceof HTMLInputElement){const{type:h}=a;return h!=="text"&&h!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return ct(this,"_keyboardManager",new dl([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:a})=>!(a instanceof HTMLButtonElement)&&l(r,un).contains(a)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:a})=>!(a instanceof HTMLButtonElement)&&l(r,un).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}destroy(){var t,e,s,i,n;(t=l(this,Bs))==null||t.resolve(),v(this,Bs,null),(e=l(this,Oo))==null||e.abort(),v(this,Oo,null),this._signal=null;for(const r of l(this,_e).values())r.destroy();l(this,_e).clear(),l(this,ce).clear(),l(this,na).clear(),v(this,ys,null),l(this,Ct).clear(),l(this,Ns).destroy(),(s=l(this,Do))==null||s.destroy(),(i=l(this,Oi))==null||i.hide(),v(this,Oi,null),l(this,Mi)&&(clearTimeout(l(this,Mi)),v(this,Mi,null)),l(this,Di)&&(clearTimeout(l(this,Di)),v(this,Di,null)),(n=this._editorUndoBar)==null||n.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return l(this,Ol)}get useNewAltTextFlow(){return l(this,El)}get useNewAltTextWhenAddingImage(){return l(this,Lo)}get hcmFilter(){return ct(this,"hcmFilter",l(this,aa)?l(this,kl).addHCMFilter(l(this,aa).foreground,l(this,aa).background):"none")}get direction(){return ct(this,"direction",getComputedStyle(l(this,un)).direction)}get highlightColors(){return ct(this,"highlightColors",l(this,Io)?new Map(l(this,Io).split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return ct(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),v(this,sa,t)}setMainHighlightColorPicker(t){v(this,Ml,t)}editAltText(t,e=!1){var s;(s=l(this,Do))==null||s.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":v(this,Lo,e);break}}onPageChanging({pageNumber:t}){v(this,Fo,t-1)}focusMainContainer(){l(this,un).focus()}findParent(t,e){for(const s of l(this,_e).values()){const{x:i,y:n,width:r,height:a}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+a)return s}return null}disableUserSelect(t=!1){l(this,Fl).classList.toggle("noUserSelect",t)}addShouldRescale(t){l(this,na).add(t)}removeShouldRescale(t){l(this,na).delete(t)}onScaleChanging({scale:t}){var e;this.commitOrRemove(),this.viewParameters.realScale=t*Kn.PDF_TO_CSS_UNITS;for(const s of l(this,na))s.onScaleChanging();(e=l(this,sa))==null||e.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,a=e.toString(),c=w(this,H,ef).call(this,e).closest(".textLayer"),u=this.getSelectionBoxes(c);if(!u)return;e.empty();const d=w(this,H,Tp).call(this,c),f=l(this,ge)===ot.NONE,g=()=>{d==null||d.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:u,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:a}),f&&this.showAllEditors("highlight",!0,!0)};if(f){this.switchToMode(ot.HIGHLIGHT,g);return}g()}addToAnnotationStorage(t){!t.isEmpty()&&l(this,ln)&&!l(this,ln).has(t.id)&&l(this,ln).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,l(this,ir)&&(v(this,ir,!1),w(this,H,sf).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of l(this,Ct))if(e.div.contains(t)){v(this,ra,[e,t]),e._focusEventsAllowed=!1;break}}focus(){if(!l(this,ra))return;const[t,e]=l(this,ra);v(this,ra,null),e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}addEditListeners(){w(this,H,Ep).call(this),w(this,H,kp).call(this)}removeEditListeners(){w(this,H,sy).call(this),w(this,H,Pp).call(this)}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of l(this,oi))if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of l(this,oi))if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){var s;if(t.preventDefault(),(s=l(this,ys))==null||s.commitOrRemove(),!this.hasSelection)return;const e=[];for(const i of l(this,Ct)){const n=i.serialize(!0);n&&e.push(n)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of l(this,oi))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){ht(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const h of s){const c=await i.deserialize(h);if(!c)return;n.push(c)}const r=()=>{for(const h of n)w(this,H,Mp).call(this,h);w(this,H,Op).call(this,n)},a=()=>{for(const h of n)h.remove()};this.addCommands({cmd:r,undo:a,mustExec:!0})}catch(n){ht(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),l(this,ge)!==ot.NONE&&!this.isEditorHandlingKeyboard&&jo._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,l(this,ir)&&(v(this,ir,!1),w(this,H,sf).call(this,"main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}setEditingState(t){t?(w(this,H,ty).call(this),w(this,H,kp).call(this),w(this,H,ss).call(this,{isEditing:l(this,ge)!==ot.NONE,isEmpty:w(this,H,Yc).call(this),hasSomethingToUndo:l(this,Ns).hasSomethingToUndo(),hasSomethingToRedo:l(this,Ns).hasSomethingToRedo(),hasSelectedEditor:!1})):(w(this,H,ey).call(this),w(this,H,Pp).call(this),w(this,H,ss).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!l(this,oi)){v(this,oi,t);for(const e of l(this,oi))w(this,H,Nn).call(this,e.defaultPropertiesToUpdate)}}getId(){return l(this,Rd).id}get currentLayer(){return l(this,_e).get(l(this,Fo))}getLayer(t){return l(this,_e).get(t)}get currentPageIndex(){return l(this,Fo)}addLayer(t){l(this,_e).set(t.pageIndex,t),l(this,nr)?t.enable():t.disable()}removeLayer(t){l(this,_e).delete(t.pageIndex)}async updateMode(t,e=null,s=!1){var i;if(l(this,ge)!==t&&!(l(this,Bs)&&(await l(this,Bs).promise,!l(this,Bs)))){if(v(this,Bs,Promise.withResolvers()),v(this,ge,t),t===ot.NONE){this.setEditingState(!1),w(this,H,ry).call(this),(i=this._editorUndoBar)==null||i.hide(),l(this,Bs).resolve();return}this.setEditingState(!0),await w(this,H,ny).call(this),this.unselectAll();for(const n of l(this,_e).values())n.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),l(this,Bs).resolve();return}for(const n of l(this,ce).values())n.annotationElementId===e?(this.setSelected(n),n.enterInEditMode()):n.unselect();l(this,Bs).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==l(this,ge)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){var s;if(l(this,oi)){switch(t){case gt.CREATE:this.currentLayer.addNewEditor();return;case gt.HIGHLIGHT_DEFAULT_COLOR:(s=l(this,Ml))==null||s.updateColor(e);break;case gt.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(l(this,Dl)||v(this,Dl,new Map)).set(t,e),this.showAllEditors("highlight",e);break}for(const i of l(this,Ct))i.updateParams(t,e);for(const i of l(this,oi))i.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){var n;for(const r of l(this,ce).values())r.editorType===t&&r.show(e);(((n=l(this,Dl))==null?void 0:n.get(gt.HIGHLIGHT_SHOW_ALL))??!0)!==e&&w(this,H,Nn).call(this,[[gt.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(l(this,Pl)!==t){v(this,Pl,t);for(const e of l(this,_e).values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}getEditors(t){const e=[];for(const s of l(this,ce).values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return l(this,ce).get(t)}addEditor(t){l(this,ce).set(t.id,t)}removeEditor(t){var e;t.div.contains(document.activeElement)&&(l(this,Mi)&&clearTimeout(l(this,Mi)),v(this,Mi,setTimeout(()=>{this.focusMainContainer(),v(this,Mi,null)},0))),l(this,ce).delete(t.id),this.unselect(t),(!t.annotationElementId||!l(this,ia).has(t.annotationElementId))&&((e=l(this,ln))==null||e.remove(t.id))}addDeletedAnnotationElement(t){l(this,ia).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return l(this,ia).has(t)}removeDeletedAnnotationElement(t){l(this,ia).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){l(this,ys)!==t&&(v(this,ys,t),t&&w(this,H,Nn).call(this,t.propertiesToUpdate))}updateUI(t){l(this,H,ay)===t&&w(this,H,Nn).call(this,t.propertiesToUpdate)}updateUIForDefaultProperties(t){w(this,H,Nn).call(this,t.defaultPropertiesToUpdate)}toggleSelected(t){if(l(this,Ct).has(t)){l(this,Ct).delete(t),t.unselect(),w(this,H,ss).call(this,{hasSelectedEditor:this.hasSelection});return}l(this,Ct).add(t),t.select(),w(this,H,Nn).call(this,t.propertiesToUpdate),w(this,H,ss).call(this,{hasSelectedEditor:!0})}setSelected(t){var e;(e=l(this,sa))==null||e.commitOrRemove();for(const s of l(this,Ct))s!==t&&s.unselect();l(this,Ct).clear(),l(this,Ct).add(t),t.select(),w(this,H,Nn).call(this,t.propertiesToUpdate),w(this,H,ss).call(this,{hasSelectedEditor:!0})}isSelected(t){return l(this,Ct).has(t)}get firstSelectedEditor(){return l(this,Ct).values().next().value}unselect(t){t.unselect(),l(this,Ct).delete(t),w(this,H,ss).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return l(this,Ct).size!==0}get isEnterHandled(){return l(this,Ct).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){var t;l(this,Ns).undo(),w(this,H,ss).call(this,{hasSomethingToUndo:l(this,Ns).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:w(this,H,Yc).call(this)}),(t=this._editorUndoBar)==null||t.hide()}redo(){l(this,Ns).redo(),w(this,H,ss).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:l(this,Ns).hasSomethingToRedo(),isEmpty:w(this,H,Yc).call(this)})}addCommands(t){l(this,Ns).add(t),w(this,H,ss).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:w(this,H,Yc).call(this)})}cleanUndoStack(t){l(this,Ns).cleanType(t)}delete(){var n;this.commitOrRemove();const t=(n=this.currentLayer)==null?void 0:n.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...l(this,Ct)],s=()=>{var r;(r=this._editorUndoBar)==null||r.show(i,e.length===1?e[0].editorType:e.length);for(const a of e)a.remove()},i=()=>{for(const r of e)w(this,H,Mp).call(this,r)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){var t;(t=l(this,ys))==null||t.commitOrRemove()}hasSomethingToControl(){return l(this,ys)||this.hasSelection}selectAll(){for(const t of l(this,Ct))t.commit();w(this,H,Op).call(this,l(this,ce).values())}unselectAll(){var t;if(!(l(this,ys)&&(l(this,ys).commitOrRemove(),l(this,ge)!==ot.NONE))&&!((t=l(this,sa))!=null&&t.commitOrRemove())&&this.hasSelection){for(const e of l(this,Ct))e.unselect();l(this,Ct).clear(),w(this,H,ss).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;l(this,ar)[0]+=t,l(this,ar)[1]+=e;const[i,n]=l(this,ar),r=[...l(this,Ct)],a=1e3;l(this,Di)&&clearTimeout(l(this,Di)),v(this,Di,setTimeout(()=>{v(this,Di,null),l(this,ar)[0]=l(this,ar)[1]=0,this.addCommands({cmd:()=>{for(const h of r)l(this,ce).has(h.id)&&h.translateInPage(i,n)},undo:()=>{for(const h of r)l(this,ce).has(h.id)&&h.translateInPage(-i,-n)},mustExec:!1})},a));for(const h of r)h.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),v(this,Pi,new Map);for(const t of l(this,Ct))l(this,Pi).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!l(this,Pi))return!1;this.disableUserSelect(!1);const t=l(this,Pi);v(this,Pi,null);let e=!1;for(const[{x:i,y:n,pageIndex:r},a]of t)a.newX=i,a.newY=n,a.newPageIndex=r,e||(e=i!==a.savedX||n!==a.savedY||r!==a.savedPageIndex);if(!e)return!1;const s=(i,n,r,a)=>{if(l(this,ce).has(i.id)){const h=l(this,_e).get(a);h?i._setParentAndPosition(h,n,r):(i.pageIndex=a,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:a}]of t)s(i,n,r,a)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:a}]of t)s(i,n,r,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(l(this,Pi))for(const s of l(this,Pi).keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){var t;return((t=this.getActive())==null?void 0:t.shouldGetKeyboardEvents())||l(this,Ct).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return l(this,ys)===t}getActive(){return l(this,ys)}getMode(){return l(this,ge)}get imageManager(){return ct(this,"imageManager",new zg)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let c=0,u=e.rangeCount;c<u;c++)if(!t.contains(e.getRangeAt(c).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(c,u,d,f)=>({x:(u-i)/r,y:1-(c+d-s)/n,width:f/r,height:d/n});break;case"180":a=(c,u,d,f)=>({x:1-(c+d-s)/n,y:1-(u+f-i)/r,width:d/n,height:f/r});break;case"270":a=(c,u,d,f)=>({x:1-(u+f-i)/r,y:(c-s)/n,width:f/r,height:d/n});break;default:a=(c,u,d,f)=>({x:(c-s)/n,y:(u-i)/r,width:d/n,height:f/r});break}const h=[];for(let c=0,u=e.rangeCount;c<u;c++){const d=e.getRangeAt(c);if(!d.collapsed)for(const{x:f,y:g,width:p,height:m}of d.getClientRects())p===0||m===0||h.push(a(f,g,p,m))}return h.length===0?null:h}addChangedExistingAnnotation({annotationElementId:t,id:e}){(l(this,Ro)||v(this,Ro,new Map)).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){var e;(e=l(this,Ro))==null||e.delete(t)}renderAnnotationElement(t){var i;const e=(i=l(this,Ro))==null?void 0:i.get(t.data.id);if(!e)return;const s=l(this,ln).getRawValue(e);s&&(l(this,ge)===ot.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}};Oo=new WeakMap,ys=new WeakMap,ce=new WeakMap,_e=new WeakMap,Do=new WeakMap,ln=new WeakMap,Ro=new WeakMap,Ns=new WeakMap,er=new WeakMap,sa=new WeakMap,Fo=new WeakMap,ia=new WeakMap,Pi=new WeakMap,oi=new WeakMap,na=new WeakMap,Tl=new WeakMap,El=new WeakMap,Lo=new WeakMap,kl=new WeakMap,Mi=new WeakMap,sr=new WeakMap,Io=new WeakMap,ir=new WeakMap,Oi=new WeakMap,Rd=new WeakMap,nr=new WeakMap,Pl=new WeakMap,rr=new WeakMap,ra=new WeakMap,Ml=new WeakMap,Ol=new WeakMap,ge=new WeakMap,Ct=new WeakMap,cn=new WeakMap,aa=new WeakMap,Dl=new WeakMap,Rl=new WeakMap,ar=new WeakMap,Di=new WeakMap,un=new WeakMap,Fl=new WeakMap,Bs=new WeakMap,H=new WeakSet,ef=function({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t},Tp=function(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of l(this,_e).values())if(s.hasTextLayer(t))return s;return null},Jb=function(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=w(this,H,ef).call(this,t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(l(this,Oi)||v(this,Oi,new wS(this)),l(this,Oi).show(s,i,this.direction==="ltr"))},Qb=function(){var n,r,a;const t=document.getSelection();if(!t||t.isCollapsed){l(this,cn)&&((n=l(this,Oi))==null||n.hide(),v(this,cn,null),w(this,H,ss).call(this,{hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===l(this,cn))return;const i=w(this,H,ef).call(this,t).closest(".textLayer");if(!i){l(this,cn)&&((r=l(this,Oi))==null||r.hide(),v(this,cn,null),w(this,H,ss).call(this,{hasSelectedText:!1}));return}if((a=l(this,Oi))==null||a.hide(),v(this,cn,e),w(this,H,ss).call(this,{hasSelectedText:!0}),!(l(this,ge)!==ot.HIGHLIGHT&&l(this,ge)!==ot.NONE)&&(l(this,ge)===ot.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),v(this,ir,this.isShiftKeyDown),!this.isShiftKeyDown)){const h=l(this,ge)===ot.HIGHLIGHT?w(this,H,Tp).call(this,i):null;h==null||h.toggleDrawing();const c=new AbortController,u=this.combinedSignal(c),d=f=>{f.type==="pointerup"&&f.button!==0||(c.abort(),h==null||h.toggleDrawing(!0),f.type==="pointerup"&&w(this,H,sf).call(this,"main_toolbar"))};window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("blur",d,{signal:u})}},sf=function(t=""){l(this,ge)===ot.HIGHLIGHT?this.highlightSelection(t):l(this,Tl)&&w(this,H,Jb).call(this)},Zb=function(){document.addEventListener("selectionchange",w(this,H,Qb).bind(this),{signal:this._signal})},ty=function(){if(l(this,sr))return;v(this,sr,new AbortController);const t=this.combinedSignal(l(this,sr));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},ey=function(){var t;(t=l(this,sr))==null||t.abort(),v(this,sr,null)},Ep=function(){if(l(this,rr))return;v(this,rr,new AbortController);const t=this.combinedSignal(l(this,rr));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},sy=function(){var t;(t=l(this,rr))==null||t.abort(),v(this,rr,null)},kp=function(){if(l(this,er))return;v(this,er,new AbortController);const t=this.combinedSignal(l(this,er));document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})},Pp=function(){var t;(t=l(this,er))==null||t.abort(),v(this,er,null)},iy=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},ss=function(t){Object.entries(t).some(([s,i])=>l(this,Rl)[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(l(this,Rl),t)}),l(this,ge)===ot.HIGHLIGHT&&t.hasSelectedEditor===!1&&w(this,H,Nn).call(this,[[gt.HIGHLIGHT_FREE,!0]]))},Nn=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},ny=async function(){if(!l(this,nr)){v(this,nr,!0);const t=[];for(const e of l(this,_e).values())t.push(e.enable());await Promise.all(t);for(const e of l(this,ce).values())e.enable()}},ry=function(){if(this.unselectAll(),l(this,nr)){v(this,nr,!1);for(const t of l(this,_e).values())t.disable();for(const t of l(this,ce).values())t.disable()}},Mp=function(t){const e=l(this,_e).get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},ay=function(){let t=null;for(t of l(this,Ct));return t},Yc=function(){if(l(this,ce).size===0)return!0;if(l(this,ce).size===1)for(const t of l(this,ce).values())return t.isEmpty();return!1},Op=function(t){for(const e of l(this,Ct))e.unselect();l(this,Ct).clear();for(const e of t)e.isEmpty()||(l(this,Ct).add(e),e.select());w(this,H,ss).call(this,{hasSelectedEditor:this.hasSelection})},Q(jo,"TRANSLATE_SMALL",1),Q(jo,"TRANSLATE_BIG",10);let $r=jo;const $e=class $e{constructor(t){_(this,li);_(this,pe,null);_(this,Ri,!1);_(this,hi,null);_(this,No,null);_(this,Fi,null);_(this,_s,null);_(this,Bo,!1);_(this,Li,null);_(this,ls,null);_(this,dn,null);_(this,oa,null);_(this,Ii,!1);v(this,ls,t),v(this,Ii,t._uiManager.useNewAltTextFlow),l($e,or)||v($e,or,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(t){$e._l10n??($e._l10n=t)}async render(){const t=v(this,hi,document.createElement("button"));t.className="altText",t.tabIndex="0";const e=v(this,No,document.createElement("span"));t.append(e),l(this,Ii)?(t.classList.add("new"),t.setAttribute("data-l10n-id",l($e,or).missing),e.setAttribute("data-l10n-id",l($e,or)["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=l(this,ls)._uiManager._signal;t.addEventListener("contextmenu",ri,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),l(this,ls)._uiManager.editAltText(l(this,ls)),l(this,Ii)&&l(this,ls)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:l(this,li,$c)}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(v(this,Bo,!0),i(n))},{signal:s}),await w(this,li,nf).call(this),t}finish(){l(this,hi)&&(l(this,hi).focus({focusVisible:l(this,Bo)}),v(this,Bo,!1))}isEmpty(){return l(this,Ii)?l(this,pe)===null:!l(this,pe)&&!l(this,Ri)}hasData(){return l(this,Ii)?l(this,pe)!==null||!!l(this,dn):this.isEmpty()}get guessedText(){return l(this,dn)}async setGuessedText(t){l(this,pe)===null&&(v(this,dn,t),v(this,oa,await $e._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),w(this,li,nf).call(this))}toggleAltTextBadge(t=!1){var e;if(!l(this,Ii)||l(this,pe)){(e=l(this,Li))==null||e.remove(),v(this,Li,null);return}if(!l(this,Li)){const s=v(this,Li,document.createElement("div"));s.className="noAltTextBadge",l(this,ls).div.append(s)}l(this,Li).classList.toggle("hidden",!t)}serialize(t){let e=l(this,pe);return!t&&l(this,dn)===e&&(e=l(this,oa)),{altText:e,decorative:l(this,Ri),guessedText:l(this,dn),textWithDisclaimer:l(this,oa)}}get data(){return{altText:l(this,pe),decorative:l(this,Ri)}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(v(this,dn,s),v(this,oa,i)),!(l(this,pe)===t&&l(this,Ri)===e)&&(n||(v(this,pe,t),v(this,Ri,e)),w(this,li,nf).call(this))}toggle(t=!1){l(this,hi)&&(!t&&l(this,_s)&&(clearTimeout(l(this,_s)),v(this,_s,null)),l(this,hi).disabled=!t)}shown(){l(this,ls)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:l(this,li,$c)}})}destroy(){var t,e;(t=l(this,hi))==null||t.remove(),v(this,hi,null),v(this,No,null),v(this,Fi,null),(e=l(this,Li))==null||e.remove(),v(this,Li,null)}};pe=new WeakMap,Ri=new WeakMap,hi=new WeakMap,No=new WeakMap,Fi=new WeakMap,_s=new WeakMap,Bo=new WeakMap,Li=new WeakMap,ls=new WeakMap,dn=new WeakMap,oa=new WeakMap,Ii=new WeakMap,or=new WeakMap,li=new WeakSet,$c=function(){return l(this,pe)&&"added"||l(this,pe)===null&&this.guessedText&&"review"||"missing"},nf=async function(){var i,n,r;const t=l(this,hi);if(!t)return;if(l(this,Ii)){if(t.classList.toggle("done",!!l(this,pe)),t.setAttribute("data-l10n-id",l($e,or)[l(this,li,$c)]),(i=l(this,No))==null||i.setAttribute("data-l10n-id",l($e,or)[`${l(this,li,$c)}-label`]),!l(this,pe)){(n=l(this,Fi))==null||n.remove();return}}else{if(!l(this,pe)&&!l(this,Ri)){t.classList.remove("done"),(r=l(this,Fi))==null||r.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=l(this,Fi);if(!e){v(this,Fi,e=document.createElement("span")),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${l(this,ls).id}`;const a=100,h=l(this,ls)._uiManager._signal;h.addEventListener("abort",()=>{clearTimeout(l(this,_s)),v(this,_s,null)},{once:!0}),t.addEventListener("mouseenter",()=>{v(this,_s,setTimeout(()=>{v(this,_s,null),l(this,Fi).classList.add("show"),l(this,ls)._reportTelemetry({action:"alt_text_tooltip"})},a))},{signal:h}),t.addEventListener("mouseleave",()=>{var c;l(this,_s)&&(clearTimeout(l(this,_s)),v(this,_s,null)),(c=l(this,Fi))==null||c.classList.remove("show")},{signal:h})}l(this,Ri)?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=l(this,pe)),e.parentNode||t.append(e);const s=l(this,ls).getImageForAltText();s==null||s.setAttribute("aria-describedby",e.id)},_($e,or,null),Q($e,"_l10n",null);let vd=$e;const fp=class fp{constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){_(this,gn);_(this,Ll);_(this,ha,!1);_(this,Il,null);_(this,jl);_(this,Nl);_(this,Bl);_(this,Hl);_(this,Ho);_(this,fn,null);_(this,la);_(this,hr,null);v(this,Ll,t),v(this,Il,s),v(this,jl,e),v(this,Nl,i),v(this,Bl,n),v(this,Hl,r),v(this,la,new AbortController),v(this,Ho,AbortSignal.any([a,l(this,la).signal])),t.addEventListener("touchstart",w(this,gn,oy).bind(this),{passive:!1,signal:l(this,Ho)})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return ct(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}destroy(){var t;(t=l(this,la))==null||t.abort(),v(this,la,null)}};Ll=new WeakMap,ha=new WeakMap,Il=new WeakMap,jl=new WeakMap,Nl=new WeakMap,Bl=new WeakMap,Hl=new WeakMap,Ho=new WeakMap,fn=new WeakMap,la=new WeakMap,hr=new WeakMap,gn=new WeakSet,oy=function(t){var i,n,r;if((i=l(this,jl))!=null&&i.call(this)||t.touches.length<2)return;if(!l(this,hr)){v(this,hr,new AbortController);const a=AbortSignal.any([l(this,Ho),l(this,hr).signal]),h=l(this,Ll),c={signal:a,passive:!1};h.addEventListener("touchmove",w(this,gn,hy).bind(this),c),h.addEventListener("touchend",w(this,gn,Dp).bind(this),c),h.addEventListener("touchcancel",w(this,gn,Dp).bind(this),c),(n=l(this,Nl))==null||n.call(this)}if(bs(t),t.touches.length!==2||(r=l(this,Il))!=null&&r.call(this)){v(this,fn,null);return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),v(this,fn,{touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY})},hy=function(t){var C;if(!l(this,fn)||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:a}=s,h=l(this,fn),{touch0X:c,touch0Y:u,touch1X:d,touch1Y:f}=h,g=d-c,p=f-u,m=r-i,y=a-n,b=Math.hypot(m,y)||1,x=Math.hypot(g,p)||1;if(!l(this,ha)&&Math.abs(x-b)<=fp.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(h.touch0X=i,h.touch0Y=n,h.touch1X=r,h.touch1Y=a,t.preventDefault(),!l(this,ha)){v(this,ha,!0);return}const S=[(i+r)/2,(n+a)/2];(C=l(this,Bl))==null||C.call(this,S,x,b)},Dp=function(t){var e;l(this,hr).abort(),v(this,hr,null),(e=l(this,Hl))==null||e.call(this),l(this,fn)&&(t.preventDefault(),v(this,fn,null),v(this,ha,!1))};let bd=fp;const lt=class lt{constructor(t){_(this,J);_(this,ca,null);_(this,ci,null);_(this,Rt,null);_(this,zo,!1);_(this,lr,null);_(this,zl,"");_(this,ua,!1);_(this,we,null);_(this,da,null);_(this,pn,null);_(this,cr,null);_(this,Vl,"");_(this,fa,!1);_(this,ws,null);_(this,Wl,!1);_(this,ga,!1);_(this,mn,!1);_(this,ji,null);_(this,Vo,0);_(this,Wo,0);_(this,Hs,null);_(this,pa,null);Q(this,"_editToolbar",null);Q(this,"_initialOptions",Object.create(null));Q(this,"_initialData",null);Q(this,"_isVisible",!0);Q(this,"_uiManager",null);Q(this,"_focusEventsAllowed",!0);_(this,Gl,!1);_(this,Fd,lt._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[a,h]=this.parentDimensions;this.x=t.x/a,this.y=t.y/h,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=lt.prototype._resizeWithKeyboard,e=$r.TRANSLATE_SMALL,s=$r.TRANSLATE_BIG;return ct(this,"_resizerKeyboardManager",new dl([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],lt.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return ct(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new CS({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(lt._l10n??(lt._l10n=t),lt._l10nResizer||(lt._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),lt._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);lt._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){kt("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return l(this,Gl)}set _isDraggable(t){var e;v(this,Gl,t),(e=this.div)==null||e.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=l(this,Fd)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):w(this,J,qc).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(l(this,fa)?v(this,fa,!1):this.parent.setSelected(this))}focusout(t){var s;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const e=t.relatedTarget;e!=null&&e.closest(`#${this.id}`)||(t.preventDefault(),(s=this.parent)!=null&&s.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}translate(t,e){w(this,J,Rp).call(this,this.parentDimensions,t,e)}translateInPage(t,e){l(this,ws)||v(this,ws,[this.x,this.y,this.width,this.height]),w(this,J,Rp).call(this,this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){l(this,ws)||v(this,ws,[this.x,this.y,this.width,this.height]);const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:d,y:f}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,f)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[h,c]=this.getBaseTranslation();r+=h,a+=c;const{style:u}=s;u.left=`${(100*r).toFixed(2)}%`,u.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!l(this,ws)&&(l(this,ws)[0]!==this.x||l(this,ws)[1]!==this.y)}get _hasBeenResized(){return!!l(this,ws)&&(l(this,ws)[2]!==this.width||l(this,ws)[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=lt,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:a,height:h}=this;if(a*=s,h*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-a,n)),r=Math.max(0,Math.min(i-h,r));break;case 90:n=Math.max(0,Math.min(s-h,n)),r=Math.min(i,Math.max(a,r));break;case 180:n=Math.min(s,Math.max(a,n)),r=Math.min(i,Math.max(h,r));break;case 270:n=Math.min(s,Math.max(h,n)),r=Math.max(0,Math.min(i-a,r));break}this.x=n/=s,this.y=r/=i;const[c,u]=this.getBaseTranslation();n+=c,r+=u,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(t,e){var s;return w(s=lt,Xl,Fp).call(s,t,e,this.parentRotation)}pageTranslationToScreen(t,e){var s;return w(s=lt,Xl,Fp).call(s,t,e,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,l(this,ua)||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!l(this,ua)&&e.endsWith("%");if(i&&n)return;const[r,a]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!l(this,ua)&&!n&&(t.height=`${(100*parseFloat(e)/a).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}_onResized(){}static _round(t){return Math.round(t*1e4)/1e4}_onResizing(){}altTextFinish(){var t;(t=l(this,Rt))==null||t.finish()}async addEditToolbar(){return this._editToolbar||l(this,ga)?this._editToolbar:(this._editToolbar=new Hg(this),this.div.append(this._editToolbar.render()),l(this,Rt)&&await this._editToolbar.addAltText(l(this,Rt)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=l(this,Rt))==null||t.destroy())}addContainer(t){var s;const e=(s=this._editToolbar)==null?void 0:s.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){l(this,Rt)||(vd.initialize(lt._l10n),v(this,Rt,new vd(this)),l(this,ca)&&(l(this,Rt).data=l(this,ca),v(this,ca,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=l(this,Rt))==null?void 0:t.data}set altTextData(t){l(this,Rt)&&(l(this,Rt).data=t)}get guessedAltText(){var t;return(t=l(this,Rt))==null?void 0:t.guessedText}async setGuessedAltText(t){var e;await((e=l(this,Rt))==null?void 0:e.setGuessedText(t))}serializeAltText(t){var e;return(e=l(this,Rt))==null?void 0:e.serialize(t)}hasAltText(){return!!l(this,Rt)&&!l(this,Rt).isEmpty()}hasAltTextData(){var t;return((t=l(this,Rt))==null?void 0:t.hasData())??!1}render(){var n;this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=l(this,zo)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),w(this,J,Np).call(this);const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),md(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(l(this,pa)||v(this,pa,new bd({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:w(this,J,uy).bind(this),onPinching:w(this,J,dy).bind(this),onPinchEnd:w(this,J,fy).bind(this),signal:this._uiManager._signal}))),(n=this._uiManager._editorUndoBar)==null||n.hide(),this.div}pointerdown(t){const{isMac:e}=Ue.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(v(this,fa,!0),this._isDraggable){w(this,J,gy).call(this,t);return}w(this,J,jp).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}_onStartDragging(){}_onStopDragging(){}moveInDOM(){l(this,ji)&&clearTimeout(l(this,ji)),v(this,ji,setTimeout(()=>{var t;v(this,ji,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[a,h]=this.pageTranslation,c=t/i,u=e/i,d=this.x*n,f=this.y*r,g=this.width*n,p=this.height*r;switch(s){case 0:return[d+c+a,r-f-u-p+h,d+c+g+a,r-f-u+h];case 90:return[d+u+a,r-f+c+h,d+u+p+a,r-f+c+g+h];case 180:return[d-c-g+a,r-f+u+h,d-c+a,r-f+u+p+h];case 270:return[d-u-p+a,r-f-c-g+h,d-u+a,r-f-c+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,a=n-s,h=r-i;switch(this.rotation){case 0:return[s,e-r,a,h];case 90:return[s,e-i,h,a];case 180:return[n,e-i,a,h];case 270:return[n,e-r,h,a];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){v(this,ga,!0)}disableEditMode(){v(this,ga,!1)}isInEditMode(){return l(this,ga)}shouldGetKeyboardEvents(){return l(this,mn)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}rebuild(){w(this,J,Np).call(this)}rotate(t){}resize(){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,e=null){kt("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,v(i,ca,t.accessibilityData);const[n,r]=i.pageDimensions,[a,h,c,u]=i.getRectInCurrentCoords(t.rect,r);return i.x=a/n,i.y=h/r,i.width=c/n,i.height=u/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t,e;if((t=l(this,cr))==null||t.abort(),v(this,cr,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),l(this,ji)&&(clearTimeout(l(this,ji)),v(this,ji,null)),w(this,J,qc).call(this),this.removeEditToolbar(),l(this,Hs)){for(const s of l(this,Hs).values())clearTimeout(s);v(this,Hs,null)}this.parent=null,(e=l(this,pa))==null||e.destroy(),v(this,pa,null)}get isResizable(){return!1}makeResizable(){this.isResizable&&(w(this,J,ly).call(this),l(this,we).classList.remove("hidden"),md(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),v(this,pn,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const e=l(this,we).children;if(!l(this,ci)){v(this,ci,Array.from(e));const r=w(this,J,py).bind(this),a=w(this,J,my).bind(this),h=this._uiManager._signal;for(const c of l(this,ci)){const u=c.getAttribute("data-resizer-name");c.setAttribute("role","spinbutton"),c.addEventListener("keydown",r,{signal:h}),c.addEventListener("blur",a,{signal:h}),c.addEventListener("focus",w(this,J,vy).bind(this,u),{signal:h}),c.setAttribute("data-l10n-id",lt._l10nResizer[u])}}const s=l(this,ci)[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(l(this,ci).length/4);if(n!==i){if(n<i)for(let a=0;a<i-n;a++)l(this,we).append(l(this,we).firstChild);else if(n>i)for(let a=0;a<n-i;a++)l(this,we).firstChild.before(l(this,we).lastChild);let r=0;for(const a of e){const c=l(this,ci)[r++].getAttribute("data-resizer-name");a.setAttribute("data-l10n-id",lt._l10nResizer[c])}}w(this,J,Bp).call(this,0),v(this,mn,!0),l(this,we).firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}_resizeWithKeyboard(t,e){l(this,mn)&&w(this,J,Ip).call(this,l(this,Vl),{deltaX:t,deltaY:e,fromKeyboard:!0})}_stopResizingWithKeyboard(){w(this,J,qc).call(this),this.div.focus()}select(){var t,e,s;if(this.makeResizable(),(t=this.div)==null||t.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{var i,n;(i=this.div)!=null&&i.classList.contains("selectedEditor")&&((n=this._editToolbar)==null||n.show())});return}(e=this._editToolbar)==null||e.show(),(s=l(this,Rt))==null||s.toggleAltTextBadge(!1)}unselect(){var t,e,s,i,n;(t=l(this,we))==null||t.classList.add("hidden"),(e=this.div)==null||e.classList.remove("selectedEditor"),(s=this.div)!=null&&s.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(i=this._editToolbar)==null||i.hide(),(n=l(this,Rt))==null||n.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return l(this,Wl)}set isEditing(t){v(this,Wl,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){v(this,ua,!0);const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){l(this,Hs)||v(this,Hs,new Map);const{action:s}=t;let i=l(this,Hs).get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),l(this,Hs).delete(s),l(this,Hs).size===0&&v(this,Hs,null)},lt._telemetryTimeout),l(this,Hs).set(s,i);return}t.type||(t.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),v(this,zo,!1)}disable(){this.div&&(this.div.tabIndex=-1),v(this,zo,!0)}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;(e==null?void 0:e.nodeName)==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}};ca=new WeakMap,ci=new WeakMap,Rt=new WeakMap,zo=new WeakMap,lr=new WeakMap,zl=new WeakMap,ua=new WeakMap,we=new WeakMap,da=new WeakMap,pn=new WeakMap,cr=new WeakMap,Vl=new WeakMap,fa=new WeakMap,ws=new WeakMap,Wl=new WeakMap,ga=new WeakMap,mn=new WeakMap,ji=new WeakMap,Vo=new WeakMap,Wo=new WeakMap,Hs=new WeakMap,pa=new WeakMap,Gl=new WeakMap,Fd=new WeakMap,J=new WeakSet,Rp=function([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()},Xl=new WeakSet,Fp=function(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}},rf=function(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}},ly=function(){if(l(this,we))return;v(this,we,document.createElement("div")),l(this,we).classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");l(this,we).append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",w(this,J,cy).bind(this,s),{signal:e}),i.addEventListener("contextmenu",ri,{signal:e}),i.tabIndex=-1}this.div.prepend(l(this,we))},cy=function(t,e){var u;e.preventDefault();const{isMac:s}=Ue.platform;if(e.button!==0||e.ctrlKey&&s)return;(u=l(this,Rt))==null||u.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,v(this,da,[e.screenX,e.screenY]);const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",w(this,J,Ip).bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",bs,{passive:!1,signal:r}),window.addEventListener("contextmenu",ri,{signal:r}),v(this,pn,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const a=this.parent.div.style.cursor,h=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const c=()=>{var d;n.abort(),this.parent.togglePointerEvents(!0),(d=l(this,Rt))==null||d.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=h,w(this,J,af).call(this)};window.addEventListener("pointerup",c,{signal:r}),window.addEventListener("blur",c,{signal:r})},Lp=function(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()},af=function(){if(!l(this,pn))return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=l(this,pn);v(this,pn,null);const n=this.x,r=this.y,a=this.width,h=this.height;n===t&&r===e&&a===s&&h===i||this.addCommands({cmd:w(this,J,Lp).bind(this,n,r,a,h),undo:w(this,J,Lp).bind(this,t,e,s,i),mustExec:!0})},Ip=function(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,a=this.width,h=this.height,c=lt.MIN_SIZE/s,u=lt.MIN_SIZE/i,d=w(this,J,rf).call(this,this.rotation),f=(I,V)=>[d[0]*I+d[2]*V,d[1]*I+d[3]*V],g=w(this,J,rf).call(this,360-this.rotation),p=(I,V)=>[g[0]*I+g[2]*V,g[1]*I+g[3]*V];let m,y,b=!1,x=!1;switch(t){case"topLeft":b=!0,m=(I,V)=>[0,0],y=(I,V)=>[I,V];break;case"topMiddle":m=(I,V)=>[I/2,0],y=(I,V)=>[I/2,V];break;case"topRight":b=!0,m=(I,V)=>[I,0],y=(I,V)=>[0,V];break;case"middleRight":x=!0,m=(I,V)=>[I,V/2],y=(I,V)=>[0,V/2];break;case"bottomRight":b=!0,m=(I,V)=>[I,V],y=(I,V)=>[0,0];break;case"bottomMiddle":m=(I,V)=>[I/2,V],y=(I,V)=>[I/2,0];break;case"bottomLeft":b=!0,m=(I,V)=>[0,V],y=(I,V)=>[I,0];break;case"middleLeft":x=!0,m=(I,V)=>[0,V/2],y=(I,V)=>[I,V/2];break}const S=m(a,h),C=y(a,h);let k=f(...C);const O=lt._round(n+k[0]),P=lt._round(r+k[1]);let D=1,R=1,z,B;if(e.fromKeyboard)({deltaX:z,deltaY:B}=e);else{const{screenX:I,screenY:V}=e,[it,Ot]=l(this,da);[z,B]=this.screenToPageTranslation(I-it,V-Ot),l(this,da)[0]=I,l(this,da)[1]=V}if([z,B]=p(z/s,B/i),b){const I=Math.hypot(a,h);D=R=Math.max(Math.min(Math.hypot(C[0]-S[0]-z,C[1]-S[1]-B)/I,1/a,1/h),c/a,u/h)}else x?D=Math.max(c,Math.min(1,Math.abs(C[0]-S[0]-z)))/a:R=Math.max(u,Math.min(1,Math.abs(C[1]-S[1]-B)))/h;const F=lt._round(a*D),L=lt._round(h*R);k=f(...y(F,L));const N=O-k[0],K=P-k[1];l(this,ws)||v(this,ws,[this.x,this.y,this.width,this.height]),this.width=F,this.height=L,this.x=N,this.y=K,this.setDims(s*F,i*L),this.fixAndSetPosition(),this._onResizing()},uy=function(){var t;v(this,pn,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height}),(t=l(this,Rt))==null||t.toggle(!1),this.parent.togglePointerEvents(!1)},dy=function(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=w(this,J,rf).call(this,this.rotation),a=(O,P)=>[r[0]*O+r[2]*P,r[1]*O+r[3]*P],[h,c]=this.parentDimensions,u=this.x,d=this.y,f=this.width,g=this.height,p=lt.MIN_SIZE/h,m=lt.MIN_SIZE/c;n=Math.max(Math.min(n,1/f,1/g),p/f,m/g);const y=lt._round(f*n),b=lt._round(g*n);if(y===f&&b===g)return;l(this,ws)||v(this,ws,[u,d,f,g]);const x=a(f/2,g/2),S=lt._round(u+x[0]),C=lt._round(d+x[1]),k=a(y/2,b/2);this.x=S-k[0],this.y=C-k[1],this.width=y,this.height=b,this.setDims(h*y,c*b),this.fixAndSetPosition(),this._onResizing()},fy=function(){var t;(t=l(this,Rt))==null||t.toggle(!0),this.parent.togglePointerEvents(!0),w(this,J,af).call(this)},jp=function(t){const{isMac:e}=Ue.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)},gy=function(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},a=c=>{i.abort(),v(this,lr,null),v(this,fa,!1),this._uiManager.endDragSession()||w(this,J,jp).call(this,c),s&&this._onStopDragging()};e&&(v(this,Vo,t.clientX),v(this,Wo,t.clientY),v(this,lr,t.pointerId),v(this,zl,t.pointerType),window.addEventListener("pointermove",c=>{s||(s=!0,this._onStartDragging());const{clientX:u,clientY:d,pointerId:f}=c;if(f!==l(this,lr)){bs(c);return}const[g,p]=this.screenToPageTranslation(u-l(this,Vo),d-l(this,Wo));v(this,Vo,u),v(this,Wo,d),this._uiManager.dragSelectedEditors(g,p)},r),window.addEventListener("touchmove",bs,r),window.addEventListener("pointerdown",c=>{c.pointerType===l(this,zl)&&(l(this,pa)||c.isPrimary)&&a(c),bs(c)},r));const h=c=>{if(!l(this,lr)||l(this,lr)===c.pointerId){a(c);return}bs(c)};window.addEventListener("pointerup",h,{signal:n}),window.addEventListener("blur",h,{signal:n})},Np=function(){if(l(this,cr)||!this.div)return;v(this,cr,new AbortController);const t=this._uiManager.combinedSignal(l(this,cr));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},py=function(t){lt._resizerKeyboardManager.exec(this,t)},my=function(t){var e;l(this,mn)&&((e=t.relatedTarget)==null?void 0:e.parentNode)!==l(this,we)&&w(this,J,qc).call(this)},vy=function(t){v(this,Vl,l(this,mn)?t:"")},Bp=function(t){if(l(this,ci))for(const e of l(this,ci))e.tabIndex=t},qc=function(){v(this,mn,!1),w(this,J,Bp).call(this,-1),w(this,J,af).call(this)},_(lt,Xl),Q(lt,"_l10n",null),Q(lt,"_l10nResizer",null),Q(lt,"_borderLineWidth",-1),Q(lt,"_colorManager",new Vg),Q(lt,"_zIndex",1),Q(lt,"_telemetryTimeout",1e3);let Vt=lt;class CS extends Vt{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Fv=3285377520,js=4294901760,ki=65535;class Lv{constructor(t){this.h1=t?t&4294967295:Fv,this.h2=t?t&4294967295:Fv}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let m=0,y=t.length;m<y;m++){const b=t.charCodeAt(m);b<=255?e[s++]=b:(e[s++]=b>>>8,e[s++]=b&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let a=0,h=0,c=this.h1,u=this.h2;const d=3432918353,f=461845907,g=d&ki,p=f&ki;for(let m=0;m<i;m++)m&1?(a=r[m],a=a*d&js|a*g&ki,a=a<<15|a>>>17,a=a*f&js|a*p&ki,c^=a,c=c<<13|c>>>19,c=c*5+3864292196):(h=r[m],h=h*d&js|h*g&ki,h=h<<15|h>>>17,h=h*f&js|h*p&ki,u^=h,u=u<<13|u>>>19,u=u*5+3864292196);switch(a=0,n){case 3:a^=e[i*4+2]<<16;case 2:a^=e[i*4+1]<<8;case 1:a^=e[i*4],a=a*d&js|a*g&ki,a=a<<15|a>>>17,a=a*f&js|a*p&ki,i&1?c^=a:u^=a}this.h1=c,this.h2=u}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&js|t*36045&ki,e=e*4283543511&js|((e<<16|t>>>16)*2950163797&js)>>>16,t^=e>>>1,t=t*444984403&js|t*60499&ki,e=e*3301882366&js|((e<<16|t>>>16)*3120437893&js)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Wg=Object.freeze({map:null,hash:"",transfer:void 0});class Gg{constructor(){_(this,Ld);_(this,ma,!1);_(this,va,null);_(this,me,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=l(this,me).get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return l(this,me).get(t)}remove(t){if(l(this,me).delete(t),l(this,me).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of l(this,me).values())if(e instanceof Vt)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=l(this,me).get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,l(this,me).set(t,e);i&&w(this,Ld,by).call(this),e instanceof Vt&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return l(this,me).has(t)}getAll(){return l(this,me).size>0?Og(l(this,me)):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return l(this,me).size}resetModified(){l(this,ma)&&(v(this,ma,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Iv(this)}get serializable(){if(l(this,me).size===0)return Wg;const t=new Map,e=new Lv,s=[],i=Object.create(null);let n=!1;for(const[r,a]of l(this,me)){const h=a instanceof Vt?a.serialize(!1,i):a;h&&(t.set(r,h),e.update(`${r}:${JSON.stringify(h)}`),n||(n=!!h.bitmap))}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Wg}get editorStats(){let t=null;const e=new Map;for(const s of l(this,me).values()){if(!(s instanceof Vt))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||(t=Object.create(null));const r=t[n]||(t[n]=new Map);for(const[a,h]of Object.entries(i)){if(a==="type")continue;let c=r.get(a);c||(c=new Map,r.set(a,c));const u=c.get(h)??0;c.set(h,u+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){v(this,va,null)}get modifiedIds(){if(l(this,va))return l(this,va);const t=[];for(const e of l(this,me).values())!(e instanceof Vt)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return v(this,va,{ids:new Set(t),hash:t.join(",")})}}ma=new WeakMap,va=new WeakMap,me=new WeakMap,Ld=new WeakSet,by=function(){l(this,ma)||(v(this,ma,!0),typeof this.onSetModified=="function"&&this.onSetModified())};class Iv extends Gg{constructor(e){super();_(this,Ul);const{map:s,hash:i,transfer:n}=e.serializable,r=structuredClone(s,n?{transfer:n}:null);v(this,Ul,{map:r,hash:i,transfer:n})}get print(){kt("Should not call PrintAnnotationStorage.print")}get serializable(){return l(this,Ul)}get modifiedIds(){return ct(this,"modifiedIds",{ids:new Set,hash:""})}}Ul=new WeakMap;class AS{constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){_(this,Go,new Set);this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),l(this,Go).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||l(this,Go).has(t.loadedName))){if(ie(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),l(this,Go).add(s),e==null||e(t)}catch{ht(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}kt("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw ht(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){var e;const t=!!((e=this._document)!=null&&e.fonts);return ct(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Oe||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),ct(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(ie(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return ct(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(C,k){return C.charCodeAt(k)<<24|C.charCodeAt(k+1)<<16|C.charCodeAt(k+2)<<8|C.charCodeAt(k+3)&255}function i(C,k,O,P){const D=C.substring(0,k),R=C.substring(k+O);return D+P+R}let n,r;const a=this._document.createElement("canvas");a.width=1,a.height=1;const h=a.getContext("2d");let c=0;function u(C,k){if(++c>30){ht("Load test font never loaded."),k();return}if(h.font="30px "+C,h.fillText(".",0,20),h.getImageData(0,0,1,1).data[3]>0){k();return}setTimeout(u.bind(null,C,k))}const d=`lt${Date.now()}${this.loadTestFontId++}`;let f=this._loadTestFont;f=i(f,976,d.length,d);const p=16,m=1482184792;let y=s(f,p);for(n=0,r=d.length-3;n<r;n+=4)y=y-m+s(d,n)|0;n<d.length&&(y=y-m+s(d+"XXX",n)|0),f=i(f,p,4,cS(y));const b=`url(data:font/opentype;base64,${btoa(f)});`,x=`@font-face {font-family:"${d}";src:${b}}`;this.insertRule(x);const S=this._document.createElement("div");S.style.visibility="hidden",S.style.width=S.style.height="10px",S.style.position="absolute",S.style.top=S.style.left="0px";for(const C of[t.loadedName,d]){const k=this._document.createElement("span");k.textContent="Hi",k.style.fontFamily=C,S.append(k)}this._document.body.append(S),u(d,()=>{S.remove(),e.complete()})}}Go=new WeakMap;class TS{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}createNativeFontFace(){var e;if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const s={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(s.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,s)}return(e=this._inspectFont)==null||e.call(this,this),t}createFontFaceRule(){var s;if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${mS(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let i=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(i+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${i}src:${t}}`}return(s=this._inspectFont)==null||s.call(this,this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){ht(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const yd={DATA:1,ERROR:2},ne={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function jv(){}function rs(o){if(o instanceof qn||o instanceof Mg||o instanceof ll||o instanceof Mv||o instanceof dd||o instanceof Pg)return o;switch(o instanceof Error||typeof o=="object"&&o!==null||kt('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),o.name){case"AbortException":return new qn(o.message);case"InvalidPDFException":return new Mg(o.message);case"MissingPDFException":return new ll(o.message);case"PasswordException":return new Mv(o.message,o.code);case"UnexpectedResponseException":return new dd(o.message,o.status);case"UnknownErrorException":return new Pg(o.message,o.details)}return new Pg(o.message,o.toString())}class fl{constructor(t,e,s){_(this,zs);_(this,Xo,new AbortController);this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",w(this,zs,yy).bind(this),{signal:l(this,Xo).signal})}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,a=this.targetName,h=this.comObj;return new ReadableStream({start:c=>{const u=Promise.withResolvers();return this.streamControllers[n]={controller:c,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},h.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:c.desiredSize},i),u.promise},pull:c=>{const u=Promise.withResolvers();return this.streamControllers[n].pullCall=u,h.postMessage({sourceName:r,targetName:a,stream:ne.PULL,streamId:n,desiredSize:c.desiredSize}),u.promise},cancel:c=>{ie(c instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[n].cancelCall=u,this.streamControllers[n].isClosed=!0,h.postMessage({sourceName:r,targetName:a,stream:ne.CANCEL,streamId:n,reason:rs(c)}),u.promise}},s)}destroy(){var t;(t=l(this,Xo))==null||t.abort(),v(this,Xo,null)}}Xo=new WeakMap,zs=new WeakSet,yy=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){w(this,zs,wy).call(this,t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===yd.DATA)i.resolve(t.data);else if(t.callback===yd.ERROR)i.reject(rs(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:yd.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:yd.ERROR,callbackId:t.callbackId,reason:rs(r)})});return}if(t.streamId){w(this,zs,_y).call(this,t);return}e(t.data)},_y=function(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],h={enqueue(c,u=1,d){if(this.isCancelled)return;const f=this.desiredSize;this.desiredSize-=u,f>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:ne.ENQUEUE,streamId:e,chunk:c},d)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:ne.CLOSE,streamId:e}),delete r.streamSinks[e])},error(c){ie(c instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:ne.ERROR,streamId:e,reason:rs(c)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};h.sinkCapability.resolve(),h.ready=h.sinkCapability.promise,this.streamSinks[e]=h,Promise.try(a,t.data,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ne.START_COMPLETE,streamId:e,success:!0})},function(c){n.postMessage({sourceName:s,targetName:i,stream:ne.START_COMPLETE,streamId:e,reason:rs(c)})})},wy=function(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case ne.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(rs(t.reason));break;case ne.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(rs(t.reason));break;case ne.PULL:if(!a){n.postMessage({sourceName:s,targetName:i,stream:ne.PULL_COMPLETE,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||jv).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ne.PULL_COMPLETE,streamId:e,success:!0})},function(c){n.postMessage({sourceName:s,targetName:i,stream:ne.PULL_COMPLETE,streamId:e,reason:rs(c)})});break;case ne.ENQUEUE:if(ie(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case ne.CLOSE:if(ie(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),w(this,zs,of).call(this,r,e);break;case ne.ERROR:ie(r,"error should have stream controller"),r.controller.error(rs(t.reason)),w(this,zs,of).call(this,r,e);break;case ne.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(rs(t.reason)),w(this,zs,of).call(this,r,e);break;case ne.CANCEL:if(!a)break;const h=rs(t.reason);Promise.try(a.onCancel||jv,h).then(function(){n.postMessage({sourceName:s,targetName:i,stream:ne.CANCEL_COMPLETE,streamId:e,success:!0})},function(c){n.postMessage({sourceName:s,targetName:i,stream:ne.CANCEL_COMPLETE,streamId:e,reason:rs(c)})}),a.sinkCapability.reject(h),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}},of=async function(t,e){var s,i,n;await Promise.allSettled([(s=t.startCall)==null?void 0:s.promise,(i=t.pullCall)==null?void 0:i.promise,(n=t.cancelCall)==null?void 0:n.promise]),delete this.streamControllers[e]};class Nv{constructor({enableHWA:t=!1}){_(this,Yl,!1);v(this,Yl,t)}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!l(this,Yl)})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){kt("Abstract method `_createCanvas` called.")}}Yl=new WeakMap;class ES extends Nv{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class Bv{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){kt("Abstract method `_fetch` called.")}}class Hv extends Bv{async _fetch(t){const e=await gd(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):fd(e)}}class zv{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class kS extends zv{constructor({docId:e,ownerDocument:s=globalThis.document}){super();_(this,G);_(this,ba);_(this,Uo);_(this,vn);_(this,bn);_(this,Le);_(this,ya);_(this,_a,0);v(this,bn,e),v(this,Le,s)}addFilter(e){if(!e)return"none";let s=l(this,G,Be).get(e);if(s)return s;const[i,n,r]=w(this,G,hf).call(this,e),a=e.length===1?i:`${i}${n}${r}`;if(s=l(this,G,Be).get(a),s)return l(this,G,Be).set(e,s),s;const h=`g_${l(this,bn)}_transfer_map_${es(this,_a)._++}`,c=w(this,G,Bh).call(this,h);l(this,G,Be).set(e,c),l(this,G,Be).set(a,c);const u=w(this,G,Hh).call(this,h);return w(this,G,Qc).call(this,i,n,r,u),c}addHCMFilter(e,s){var p;const i=`${e}-${s}`,n="base";let r=l(this,G,Kc).get(n);if((r==null?void 0:r.key)===i||(r?((p=r.filter)==null||p.remove(),r.key=i,r.url="none",r.filter=null):(r={key:i,url:"none",filter:null},l(this,G,Kc).set(n,r)),!e||!s))return r.url;const a=w(this,G,Zc).call(this,e);e=q.makeHexColor(...a);const h=w(this,G,Zc).call(this,s);if(s=q.makeHexColor(...h),l(this,G,Nh).style.color="",e==="#000000"&&s==="#ffffff"||e===s)return r.url;const c=new Array(256);for(let m=0;m<=255;m++){const y=m/255;c[m]=y<=.03928?y/12.92:((y+.055)/1.055)**2.4}const u=c.join(","),d=`g_${l(this,bn)}_hcm_filter`,f=r.filter=w(this,G,Hh).call(this,d);w(this,G,Qc).call(this,u,u,u,f),w(this,G,Hp).call(this,f);const g=(m,y)=>{const b=a[m]/255,x=h[m]/255,S=new Array(y+1);for(let C=0;C<=y;C++)S[C]=b+C/y*(x-b);return S.join(",")};return w(this,G,Qc).call(this,g(0,5),g(1,5),g(2,5),f),r.url=w(this,G,Bh).call(this,d),r.url}addAlphaFilter(e){let s=l(this,G,Be).get(e);if(s)return s;const[i]=w(this,G,hf).call(this,[e]),n=`alpha_${i}`;if(s=l(this,G,Be).get(n),s)return l(this,G,Be).set(e,s),s;const r=`g_${l(this,bn)}_alpha_map_${es(this,_a)._++}`,a=w(this,G,Bh).call(this,r);l(this,G,Be).set(e,a),l(this,G,Be).set(n,a);const h=w(this,G,Hh).call(this,r);return w(this,G,zp).call(this,i,h),a}addLuminosityFilter(e){let s=l(this,G,Be).get(e||"luminosity");if(s)return s;let i,n;if(e?([i]=w(this,G,hf).call(this,[e]),n=`luminosity_${i}`):n="luminosity",s=l(this,G,Be).get(n),s)return l(this,G,Be).set(e,s),s;const r=`g_${l(this,bn)}_luminosity_map_${es(this,_a)._++}`,a=w(this,G,Bh).call(this,r);l(this,G,Be).set(e,a),l(this,G,Be).set(n,a);const h=w(this,G,Hh).call(this,r);return w(this,G,xy).call(this,h),e&&w(this,G,zp).call(this,i,h),a}addHighlightHCMFilter(e,s,i,n,r){var x;const a=`${s}-${i}-${n}-${r}`;let h=l(this,G,Kc).get(e);if((h==null?void 0:h.key)===a||(h?((x=h.filter)==null||x.remove(),h.key=a,h.url="none",h.filter=null):(h={key:a,url:"none",filter:null},l(this,G,Kc).set(e,h)),!s||!i))return h.url;const[c,u]=[s,i].map(w(this,G,Zc).bind(this));let d=Math.round(.2126*c[0]+.7152*c[1]+.0722*c[2]),f=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[g,p]=[n,r].map(w(this,G,Zc).bind(this));f<d&&([d,f,g,p]=[f,d,p,g]),l(this,G,Nh).style.color="";const m=(S,C,k)=>{const O=new Array(256),P=(f-d)/k,D=S/255,R=(C-S)/(255*k);let z=0;for(let B=0;B<=k;B++){const F=Math.round(d+B*P),L=D+B*R;for(let N=z;N<=F;N++)O[N]=L;z=F+1}for(let B=z;B<256;B++)O[B]=O[z-1];return O.join(",")},y=`g_${l(this,bn)}_hcm_${e}_filter`,b=h.filter=w(this,G,Hh).call(this,y);return w(this,G,Hp).call(this,b),w(this,G,Qc).call(this,m(g[0],p[0],5),m(g[1],p[1],5),m(g[2],p[2],5),b),h.url=w(this,G,Bh).call(this,y),h.url}destroy(e=!1){var s,i,n,r;e&&((s=l(this,ya))!=null&&s.size)||((i=l(this,vn))==null||i.parentNode.parentNode.remove(),v(this,vn,null),(n=l(this,Uo))==null||n.clear(),v(this,Uo,null),(r=l(this,ya))==null||r.clear(),v(this,ya,null),v(this,_a,0))}}ba=new WeakMap,Uo=new WeakMap,vn=new WeakMap,bn=new WeakMap,Le=new WeakMap,ya=new WeakMap,_a=new WeakMap,G=new WeakSet,Be=function(){return l(this,Uo)||v(this,Uo,new Map)},Kc=function(){return l(this,ya)||v(this,ya,new Map)},Nh=function(){if(!l(this,vn)){const e=l(this,Le).createElement("div"),{style:s}=e;s.visibility="hidden",s.contain="strict",s.width=s.height=0,s.position="absolute",s.top=s.left=0,s.zIndex=-1;const i=l(this,Le).createElementNS(rn,"svg");i.setAttribute("width",0),i.setAttribute("height",0),v(this,vn,l(this,Le).createElementNS(rn,"defs")),e.append(i),i.append(l(this,vn)),l(this,Le).body.append(e)}return l(this,vn)},hf=function(e){if(e.length===1){const c=e[0],u=new Array(256);for(let f=0;f<256;f++)u[f]=c[f]/255;const d=u.join(",");return[d,d,d]}const[s,i,n]=e,r=new Array(256),a=new Array(256),h=new Array(256);for(let c=0;c<256;c++)r[c]=s[c]/255,a[c]=i[c]/255,h[c]=n[c]/255;return[r.join(","),a.join(","),h.join(",")]},Bh=function(e){if(l(this,ba)===void 0){v(this,ba,"");const s=l(this,Le).URL;s!==l(this,Le).baseURI&&(pd(s)?ht('#createUrl: ignore "data:"-URL for performance reasons.'):v(this,ba,s.split("#",1)[0]))}return`url(${l(this,ba)}#${e})`},xy=function(e){const s=l(this,Le).createElementNS(rn,"feColorMatrix");s.setAttribute("type","matrix"),s.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),e.append(s)},Hp=function(e){const s=l(this,Le).createElementNS(rn,"feColorMatrix");s.setAttribute("type","matrix"),s.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),e.append(s)},Hh=function(e){const s=l(this,Le).createElementNS(rn,"filter");return s.setAttribute("color-interpolation-filters","sRGB"),s.setAttribute("id",e),l(this,G,Nh).append(s),s},Jc=function(e,s,i){const n=l(this,Le).createElementNS(rn,s);n.setAttribute("type","discrete"),n.setAttribute("tableValues",i),e.append(n)},Qc=function(e,s,i,n){const r=l(this,Le).createElementNS(rn,"feComponentTransfer");n.append(r),w(this,G,Jc).call(this,r,"feFuncR",e),w(this,G,Jc).call(this,r,"feFuncG",s),w(this,G,Jc).call(this,r,"feFuncB",i)},zp=function(e,s){const i=l(this,Le).createElementNS(rn,"feComponentTransfer");s.append(i),w(this,G,Jc).call(this,i,"feFuncA",e)},Zc=function(e){return l(this,G,Nh).style.color=e,Ng(getComputedStyle(l(this,G,Nh)).getPropertyValue("color"))};class Vv{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){kt("Abstract method `_fetch` called.")}}class Wv extends Vv{async _fetch(t){const e=await gd(t,"arraybuffer");return new Uint8Array(e)}}Oe&&ht("Please use the `legacy` build in Node.js environments.");async function Gv(o){const e=await process.getBuiltinModule("fs").promises.readFile(o);return new Uint8Array(e)}class PS extends zv{}class MS extends Nv{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:Ht&&Ht.tagName.toUpperCase()==="SCRIPT"&&Ht.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class OS extends Bv{async _fetch(t){return Gv(t)}}class DS extends Vv{async _fetch(t){return Gv(t)}}const Re={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Xg(o,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),o.clip(i)}class Ug{getPattern(){kt("Abstract method `getPattern` called.")}}class RS extends Ug{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===Re.STROKE||i===Re.FILL){const r=e.current.getClippedPathBoundingBox(i,It(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,h=Math.ceil(r[3]-r[1])||1,c=e.cachedCanvases.getCanvas("pattern",a,h),u=c.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-r[0],-r[1]),s=q.transform(s,[1,0,0,1,r[0],r[1]]),u.transform(...e.baseTransform),this.matrix&&u.transform(...this.matrix),Xg(u,this._bbox),u.fillStyle=this._createGradient(u),u.fill(),n=t.createPattern(c.canvas,"no-repeat");const d=new DOMMatrix(s);n.setTransform(d)}else Xg(t,this._bbox),n=this._createGradient(t);return n}}function Yg(o,t,e,s,i,n,r,a){const h=t.coords,c=t.colors,u=o.data,d=o.width*4;let f;h[e+1]>h[s+1]&&(f=e,e=s,s=f,f=n,n=r,r=f),h[s+1]>h[i+1]&&(f=s,s=i,i=f,f=r,r=a,a=f),h[e+1]>h[s+1]&&(f=e,e=s,s=f,f=n,n=r,r=f);const g=(h[e]+t.offsetX)*t.scaleX,p=(h[e+1]+t.offsetY)*t.scaleY,m=(h[s]+t.offsetX)*t.scaleX,y=(h[s+1]+t.offsetY)*t.scaleY,b=(h[i]+t.offsetX)*t.scaleX,x=(h[i+1]+t.offsetY)*t.scaleY;if(p>=x)return;const S=c[n],C=c[n+1],k=c[n+2],O=c[r],P=c[r+1],D=c[r+2],R=c[a],z=c[a+1],B=c[a+2],F=Math.round(p),L=Math.round(x);let N,K,I,V,it,Ot,Bt,Xt;for(let Ft=F;Ft<=L;Ft++){if(Ft<y){const nt=Ft<p?0:(p-Ft)/(p-y);N=g-(g-m)*nt,K=S-(S-O)*nt,I=C-(C-P)*nt,V=k-(k-D)*nt}else{let nt;Ft>x?nt=1:y===x?nt=0:nt=(y-Ft)/(y-x),N=m-(m-b)*nt,K=O-(O-R)*nt,I=P-(P-z)*nt,V=D-(D-B)*nt}let _t;Ft<p?_t=0:Ft>x?_t=1:_t=(p-Ft)/(p-x),it=g-(g-b)*_t,Ot=S-(S-R)*_t,Bt=C-(C-z)*_t,Xt=k-(k-B)*_t;const ae=Math.round(Math.min(N,it)),Ze=Math.round(Math.max(N,it));let st=d*Ft+ae*4;for(let nt=ae;nt<=Ze;nt++)_t=(N-nt)/(N-it),_t<0?_t=0:_t>1&&(_t=1),u[st++]=K-(K-Ot)*_t|0,u[st++]=I-(I-Bt)*_t|0,u[st++]=V-(V-Xt)*_t|0,u[st++]=255}}function FS(o,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const a=t.verticesPerRow,h=Math.floor(s.length/a)-1,c=a-1;for(n=0;n<h;n++){let u=n*a;for(let d=0;d<c;d++,u++)Yg(o,e,s[u],s[u+1],s[u+a],i[u],i[u+1],i[u+a]),Yg(o,e,s[u+a+1],s[u+1],s[u+a],i[u+a+1],i[u+1],i[u+a])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)Yg(o,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class LS extends Ug{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const a=Math.floor(this._bounds[0]),h=Math.floor(this._bounds[1]),c=Math.ceil(this._bounds[2])-a,u=Math.ceil(this._bounds[3])-h,d=Math.min(Math.ceil(Math.abs(c*t[0]*1.1)),3e3),f=Math.min(Math.ceil(Math.abs(u*t[1]*1.1)),3e3),g=c/d,p=u/f,m={coords:this._coords,colors:this._colors,offsetX:-a,offsetY:-h,scaleX:1/g,scaleY:1/p},y=d+2*2,b=f+2*2,x=s.getCanvas("mesh",y,b),S=x.context,C=S.createImageData(d,f);if(e){const O=C.data;for(let P=0,D=O.length;P<D;P+=4)O[P]=e[0],O[P+1]=e[1],O[P+2]=e[2],O[P+3]=255}for(const O of this._figures)FS(C,O,m);return S.putImageData(C,2,2),{canvas:x.canvas,offsetX:a-2*g,offsetY:h-2*p,scaleX:g,scaleY:p}}getPattern(t,e,s,i){Xg(t,this._bbox);let n;if(i===Re.SHADING)n=q.singularValueDecompose2dScale(It(t));else if(n=q.singularValueDecompose2dScale(e.baseTransform),this.matrix){const a=q.singularValueDecompose2dScale(this.matrix);n=[n[0]*a[0],n[1]*a[1]]}const r=this._createMeshCanvas(n,i===Re.SHADING?null:this._background,e.cachedCanvases);return i!==Re.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class IS extends Ug{getPattern(){return"hotpink"}}function jS(o){switch(o[0]){case"RadialAxial":return new RS(o);case"Mesh":return new LS(o);case"Dummy":return new IS}throw new Error(`Unknown IR type: ${o[0]}`)}const Xv={COLORED:1,UNCOLORED:2},Id=class Id{constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:a}=this;let{xstep:h,ystep:c}=this;h=Math.abs(h),c=Math.abs(c),ud("TilingType: "+n);const u=e[0],d=e[1],f=e[2],g=e[3],p=f-u,m=g-d,y=q.singularValueDecompose2dScale(this.matrix),b=q.singularValueDecompose2dScale(this.baseTransform),x=y[0]*b[0],S=y[1]*b[1];let C=p,k=m,O=!1,P=!1;const D=Math.ceil(h*x),R=Math.ceil(c*S),z=Math.ceil(p*x),B=Math.ceil(m*S);D>=z?C=h:O=!0,R>=B?k=c:P=!0;const F=this.getSizeAndScale(C,this.ctx.canvas.width,x),L=this.getSizeAndScale(k,this.ctx.canvas.height,S),N=t.cachedCanvases.getCanvas("pattern",F.size,L.size),K=N.context,I=a.createCanvasGraphics(K);if(I.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(I,i,r),K.translate(-F.scale*u,-L.scale*d),I.transform(F.scale,0,0,L.scale,0,0),K.save(),this.clipBbox(I,u,d,f,g),I.baseTransform=It(I.ctx),I.executeOperatorList(s),I.endDrawing(),K.restore(),O||P){const V=N.canvas;O&&(C=h),P&&(k=c);const it=this.getSizeAndScale(C,this.ctx.canvas.width,x),Ot=this.getSizeAndScale(k,this.ctx.canvas.height,S),Bt=it.size,Xt=Ot.size,Ft=t.cachedCanvases.getCanvas("pattern-workaround",Bt,Xt),_t=Ft.context,ae=O?Math.floor(p/h):0,Ze=P?Math.floor(m/c):0;for(let st=0;st<=ae;st++)for(let nt=0;nt<=Ze;nt++)_t.drawImage(V,Bt*st,Xt*nt,Bt,Xt,0,0,Bt,Xt);return{canvas:Ft.canvas,scaleX:it.scale,scaleY:Ot.scale,offsetX:u,offsetY:d}}return{canvas:N.canvas,scaleX:F.scale,scaleY:L.scale,offsetX:u,offsetY:d}}getSizeAndScale(t,e,s){const i=Math.max(Id.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,a=n-s;t.ctx.rect(e,s,r,a),t.current.updateRectMinMax(It(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case Xv.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case Xv.UNCOLORED:const a=q.makeHexColor(s[0],s[1],s[2]);i.fillStyle=a,i.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new lS(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Re.SHADING&&(n=q.transform(n,e.baseTransform),this.matrix&&(n=q.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let a=new DOMMatrix(n);a=a.translate(r.offsetX,r.offsetY),a=a.scale(1/r.scaleX,1/r.scaleY);const h=t.createPattern(r.canvas,"repeat");return h.setTransform(a),h}};Q(Id,"MAX_PATTERN_SIZE",3e3);let $g=Id;function NS({src:o,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const a=Ue.isLittleEndian?4278190080:255,[h,c]=r?[n,a]:[a,n],u=s>>3,d=s&7,f=o.length;e=new Uint32Array(e.buffer);let g=0;for(let p=0;p<i;p++){for(const y=t+u;t<y;t++){const b=t<f?o[t]:255;e[g++]=b&128?c:h,e[g++]=b&64?c:h,e[g++]=b&32?c:h,e[g++]=b&16?c:h,e[g++]=b&8?c:h,e[g++]=b&4?c:h,e[g++]=b&2?c:h,e[g++]=b&1?c:h}if(d===0)continue;const m=t<f?o[t++]:255;for(let y=0;y<d;y++)e[g++]=m&1<<7-y?c:h}return{srcPos:t,destPos:g}}const Uv=16,Yv=100,BS=15,$v=10,qv=1e3,as=16;function HS(o,t){if(o._removeMirroring)throw new Error("Context is already forwarding operations.");o.__originalSave=o.save,o.__originalRestore=o.restore,o.__originalRotate=o.rotate,o.__originalScale=o.scale,o.__originalTranslate=o.translate,o.__originalTransform=o.transform,o.__originalSetTransform=o.setTransform,o.__originalResetTransform=o.resetTransform,o.__originalClip=o.clip,o.__originalMoveTo=o.moveTo,o.__originalLineTo=o.lineTo,o.__originalBezierCurveTo=o.bezierCurveTo,o.__originalRect=o.rect,o.__originalClosePath=o.closePath,o.__originalBeginPath=o.beginPath,o._removeMirroring=()=>{o.save=o.__originalSave,o.restore=o.__originalRestore,o.rotate=o.__originalRotate,o.scale=o.__originalScale,o.translate=o.__originalTranslate,o.transform=o.__originalTransform,o.setTransform=o.__originalSetTransform,o.resetTransform=o.__originalResetTransform,o.clip=o.__originalClip,o.moveTo=o.__originalMoveTo,o.lineTo=o.__originalLineTo,o.bezierCurveTo=o.__originalBezierCurveTo,o.rect=o.__originalRect,o.closePath=o.__originalClosePath,o.beginPath=o.__originalBeginPath,delete o._removeMirroring},o.save=function(){t.save(),this.__originalSave()},o.restore=function(){t.restore(),this.__originalRestore()},o.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},o.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},o.transform=function(s,i,n,r,a,h){t.transform(s,i,n,r,a,h),this.__originalTransform(s,i,n,r,a,h)},o.setTransform=function(s,i,n,r,a,h){t.setTransform(s,i,n,r,a,h),this.__originalSetTransform(s,i,n,r,a,h)},o.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},o.rotate=function(s){t.rotate(s),this.__originalRotate(s)},o.clip=function(s){t.clip(s),this.__originalClip(s)},o.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},o.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},o.bezierCurveTo=function(e,s,i,n,r,a){t.bezierCurveTo(e,s,i,n,r,a),this.__originalBezierCurveTo(e,s,i,n,r,a)},o.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},o.closePath=function(){t.closePath(),this.__originalClosePath()},o.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class zS{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function _d(o,t,e,s,i,n,r,a,h,c){const[u,d,f,g,p,m]=It(o);if(d===0&&f===0){const x=r*u+p,S=Math.round(x),C=a*g+m,k=Math.round(C),O=(r+h)*u+p,P=Math.abs(Math.round(O)-S)||1,D=(a+c)*g+m,R=Math.abs(Math.round(D)-k)||1;return o.setTransform(Math.sign(u),0,0,Math.sign(g),S,k),o.drawImage(t,e,s,i,n,0,0,P,R),o.setTransform(u,d,f,g,p,m),[P,R]}if(u===0&&g===0){const x=a*f+p,S=Math.round(x),C=r*d+m,k=Math.round(C),O=(a+c)*f+p,P=Math.abs(Math.round(O)-S)||1,D=(r+h)*d+m,R=Math.abs(Math.round(D)-k)||1;return o.setTransform(0,Math.sign(d),Math.sign(f),0,S,k),o.drawImage(t,e,s,i,n,0,0,R,P),o.setTransform(u,d,f,g,p,m),[R,P]}o.drawImage(t,e,s,i,n,r,a,h,c);const y=Math.hypot(u,d),b=Math.hypot(f,g);return[y*h,b*c]}function VS(o){const{width:t,height:e}=o;if(t>qv||e>qv)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),a,h,c;const u=t+7&-8;let d=new Uint8Array(u*e),f=0;for(const b of o.data){let x=128;for(;x>0;)d[f++]=b&x?0:255,x>>=1}let g=0;for(f=0,d[f]!==0&&(r[0]=1,++g),h=1;h<t;h++)d[f]!==d[f+1]&&(r[h]=d[f]?2:1,++g),f++;for(d[f]!==0&&(r[h]=2,++g),a=1;a<e;a++){f=a*u,c=a*n,d[f-u]!==d[f]&&(r[c]=d[f]?1:8,++g);let b=(d[f]?4:0)+(d[f-u]?8:0);for(h=1;h<t;h++)b=(b>>2)+(d[f+1]?4:0)+(d[f-u+1]?8:0),i[b]&&(r[c+h]=i[b],++g),f++;if(d[f-u]!==d[f]&&(r[c+h]=d[f]?2:4,++g),g>s)return null}for(f=u*(e-1),c=a*n,d[f]!==0&&(r[c]=8,++g),h=1;h<t;h++)d[f]!==d[f+1]&&(r[c+h]=d[f]?4:8,++g),f++;if(d[f]!==0&&(r[c+h]=4,++g),g>s)return null;const p=new Int32Array([0,n,-1,0,-n,0,0,0,1]),m=new Path2D;for(a=0;g&&a<=e;a++){let b=a*n;const x=b+t;for(;b<x&&!r[b];)b++;if(b===x)continue;m.moveTo(b%n,a);const S=b;let C=r[b];do{const k=p[C];do b+=k;while(!r[b]);const O=r[b];O!==5&&O!==10?(C=O,r[b]=0):(C=O&51*C>>4,r[b]&=C>>2|C<<2),m.lineTo(b%n,b/n|0),r[b]||--g}while(S!==b);--a}return d=null,r=null,function(b){b.save(),b.scale(1/t,-1/e),b.translate(0,-e),b.fill(m),b.beginPath(),b.restore()}}class Kv{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=Pv,this.textMatrixScale=1,this.fontMatrix=Eg,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=De.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=q.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=q.applyTransform(e,t),i=q.applyTransform(e.slice(2),t),n=q.applyTransform([e[0],e[3]],t),r=q.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],r[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],r[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],r[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],r[1])}updateScalingPathMinMax(t,e){q.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,a,h,c,u){const d=q.bezierBoundingBox(e,s,i,n,r,a,h,c,u);u||this.updateRectMinMax(t,d)}getPathBoundingBox(t=Re.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Re.STROKE){e||kt("Stroke bounding box must include transform.");const i=q.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,r=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=r,s[2]+=n,s[3]+=r}return s}updateClipFromPath(){const t=q.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=Re.FILL,e=null){return q.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function Jv(o,t){if(t instanceof ImageData){o.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%as,n=(e-i)/as,r=i===0?n:n+1,a=o.createImageData(s,as);let h=0,c;const u=t.data,d=a.data;let f,g,p,m;if(t.kind===hd.GRAYSCALE_1BPP){const y=u.byteLength,b=new Uint32Array(d.buffer,0,d.byteLength>>2),x=b.length,S=s+7>>3,C=4294967295,k=Ue.isLittleEndian?4278190080:255;for(f=0;f<r;f++){for(p=f<n?as:i,c=0,g=0;g<p;g++){const O=y-h;let P=0;const D=O>S?s:O*8-7,R=D&-8;let z=0,B=0;for(;P<R;P+=8)B=u[h++],b[c++]=B&128?C:k,b[c++]=B&64?C:k,b[c++]=B&32?C:k,b[c++]=B&16?C:k,b[c++]=B&8?C:k,b[c++]=B&4?C:k,b[c++]=B&2?C:k,b[c++]=B&1?C:k;for(;P<D;P++)z===0&&(B=u[h++],z=128),b[c++]=B&z?C:k,z>>=1}for(;c<x;)b[c++]=0;o.putImageData(a,0,f*as)}}else if(t.kind===hd.RGBA_32BPP){for(g=0,m=s*as*4,f=0;f<n;f++)d.set(u.subarray(h,h+m)),h+=m,o.putImageData(a,0,g),g+=as;f<r&&(m=s*i*4,d.set(u.subarray(h,h+m)),o.putImageData(a,0,g))}else if(t.kind===hd.RGB_24BPP)for(p=as,m=s*p,f=0;f<r;f++){for(f>=n&&(p=i,m=s*p),c=0,g=m;g--;)d[c++]=u[h++],d[c++]=u[h++],d[c++]=u[h++],d[c++]=255;o.putImageData(a,0,f*as)}else throw new Error(`bad image kind: ${t.kind}`)}function Qv(o,t){if(t.bitmap){o.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%as,n=(e-i)/as,r=i===0?n:n+1,a=o.createImageData(s,as);let h=0;const c=t.data,u=a.data;for(let d=0;d<r;d++){const f=d<n?as:i;({srcPos:h}=NS({src:c,srcPos:h,dest:u,width:s,height:f,nonBlackColor:0})),o.putImageData(a,0,d*as)}}function gl(o,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)o[s]!==void 0&&(t[s]=o[s]);o.setLineDash!==void 0&&(t.setLineDash(o.getLineDash()),t.lineDashOffset=o.lineDashOffset)}function wd(o){if(o.strokeStyle=o.fillStyle="#000000",o.fillRule="nonzero",o.globalAlpha=1,o.lineWidth=1,o.lineCap="butt",o.lineJoin="miter",o.miterLimit=10,o.globalCompositeOperation="source-over",o.font="10px sans-serif",o.setLineDash!==void 0&&(o.setLineDash([]),o.lineDashOffset=0),!Oe){const{filter:t}=o;t!=="none"&&t!==""&&(o.filter="none")}}function Zv(o,t){if(t)return!0;const e=q.singularValueDecompose2dScale(o);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*Kn.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const WS=["butt","round","square"],GS=["miter","round","bevel"],XS={},tb={},gp=class gp{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:a=null},h,c){_(this,ui);this.ctx=t,this.current=new Kv(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=r,this.cachedCanvases=new zS(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=h,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=c,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=a,s){const h=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=h.canvas,this.ctx=h.context,this.ctx.save(),this.ctx.transform(...It(this.compositeCtx))}this.ctx.save(),wd(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=It(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let a=e||0;const h=n.length;if(h===a)return a;const c=h-a>$v&&typeof s=="function",u=c?Date.now()+BS:0;let d=0;const f=this.commonObjs,g=this.objs;let p;for(;;){if(i!==void 0&&a===i.nextBreakPoint)return i.breakIt(a,s),a;if(p=r[a],p!==ni.dependency)this[p].apply(this,n[a]);else for(const m of n[a]){const y=m.startsWith("g_")?f:g;if(!y.has(m))return y.get(m,s),a}if(a++,a===h)return a;if(c&&++d>$v){if(Date.now()>u)return s(),a;d=0}}}endDrawing(){w(this,ui,Vp).call(this),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),w(this,ui,Wp).call(this)}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),a=s,h=i,c="prescale1",u,d;for(;n>2&&a>1||r>2&&h>1;){let f=a,g=h;n>2&&a>1&&(f=a>=16384?Math.floor(a/2)-1||1:Math.ceil(a/2),n/=a/f),r>2&&h>1&&(g=h>=16384?Math.floor(h/2)-1||1:Math.ceil(h)/2,r/=h/g),u=this.cachedCanvases.getCanvas(c,f,g),d=u.context,d.clearRect(0,0,f,g),d.drawImage(t,0,0,a,h,0,0,f,g),t=u.canvas,a=f,h=g,c=c==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:a,paintHeight:h}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,a=It(e);let h,c,u,d;if((t.bitmap||t.data)&&t.count>1){const D=t.bitmap||t.data.buffer;c=JSON.stringify(r?a:[a.slice(0,4),n]),h=this._cachedBitmapsMap.get(D),h||(h=new Map,this._cachedBitmapsMap.set(D,h));const R=h.get(c);if(R&&!r){const z=Math.round(Math.min(a[0],a[2])+a[4]),B=Math.round(Math.min(a[1],a[3])+a[5]);return{canvas:R,offsetX:z,offsetY:B}}u=R}u||(d=this.cachedCanvases.getCanvas("maskCanvas",s,i),Qv(d.context,t));let f=q.transform(a,[1/s,0,0,-1/i,0,0]);f=q.transform(f,[1,0,0,1,0,-i]);const[g,p,m,y]=q.getAxialAlignedBoundingBox([0,0,s,i],f),b=Math.round(m-g)||1,x=Math.round(y-p)||1,S=this.cachedCanvases.getCanvas("fillCanvas",b,x),C=S.context,k=g,O=p;C.translate(-k,-O),C.transform(...f),u||(u=this._scaleImage(d.canvas,Ei(C)),u=u.img,h&&r&&h.set(c,u)),C.imageSmoothingEnabled=Zv(It(C),t.interpolate),_d(C,u,0,0,u.width,u.height,0,0,s,i),C.globalCompositeOperation="source-in";const P=q.transform(Ei(C),[1,0,0,1,-k,-O]);return C.fillStyle=r?n.getPattern(e,this,P,Re.FILL):n,C.fillRect(0,0,s,i),h&&!r&&(this.cachedCanvases.delete("fillCanvas"),h.set(c,S.canvas)),{canvas:S.canvas,offsetX:Math.round(k),offsetY:Math.round(O)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=WS[t]}setLineJoin(t){this.ctx.lineJoin=GS[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...It(this.suspendedCtx)),gl(this.suspendedCtx,n),HS(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),gl(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],a=i[2]-n,h=i[3]-r;a===0||h===0||(this.genericComposeSMask(e.context,s,a,h,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,a,h,c,u,d){let f=t.canvas,g=h-u,p=c-d;if(r){const y=q.makeHexColor(...r);if(g<0||p<0||g+s>f.width||p+i>f.height){const b=this.cachedCanvases.getCanvas("maskExtension",s,i),x=b.context;x.drawImage(f,-g,-p),x.globalCompositeOperation="destination-atop",x.fillStyle=y,x.fillRect(0,0,s,i),x.globalCompositeOperation="source-over",f=b.canvas,g=p=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const b=new Path2D;b.rect(g,p,s,i),t.clip(b),t.globalCompositeOperation="destination-atop",t.fillStyle=y,t.fillRect(g,p,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&a?e.filter=this.filterFactory.addAlphaFilter(a):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(a));const m=new Path2D;m.rect(h,c,s,i),e.clip(m),e.globalCompositeOperation="destination-in",e.drawImage(f,g,p,s,i,h,c,s,i),e.restore()}save(){this.inSMaskMode?(gl(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),gl(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,a=n.y,h,c;const u=It(i),d=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,f=d?s.slice(0):null;for(let g=0,p=0,m=t.length;g<m;g++)switch(t[g]|0){case ni.rectangle:r=e[p++],a=e[p++];const y=e[p++],b=e[p++],x=r+y,S=a+b;i.moveTo(r,a),y===0||b===0?i.lineTo(x,S):(i.lineTo(x,a),i.lineTo(x,S),i.lineTo(r,S)),d||n.updateRectMinMax(u,[r,a,x,S]),i.closePath();break;case ni.moveTo:r=e[p++],a=e[p++],i.moveTo(r,a),d||n.updatePathMinMax(u,r,a);break;case ni.lineTo:r=e[p++],a=e[p++],i.lineTo(r,a),d||n.updatePathMinMax(u,r,a);break;case ni.curveTo:h=r,c=a,r=e[p+4],a=e[p+5],i.bezierCurveTo(e[p],e[p+1],e[p+2],e[p+3],r,a),n.updateCurvePathMinMax(u,h,c,e[p],e[p+1],e[p+2],e[p+3],r,a,f),p+=6;break;case ni.curveTo2:h=r,c=a,i.bezierCurveTo(r,a,e[p],e[p+1],e[p+2],e[p+3]),n.updateCurvePathMinMax(u,h,c,r,a,e[p],e[p+1],e[p+2],e[p+3],f),r=e[p+2],a=e[p+3],p+=4;break;case ni.curveTo3:h=r,c=a,r=e[p+2],a=e[p+3],i.bezierCurveTo(e[p],e[p+1],r,a,r,a),n.updateCurvePathMinMax(u,h,c,e[p],e[p+1],r,a,r,a,f),p+=4;break;case ni.closePath:i.closePath();break}d&&n.updateScalingPathMinMax(u,f),n.setCurrentPoint(r,a)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&(s!=null&&s.getPattern)?(e.save(),e.strokeStyle=s.getPattern(e,this,Ei(e),Re.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,Ei(e),Re.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=XS}eoClip(){this.pendingClip=tb}beginText(){this.current.textMatrix=Pv,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:a,fontSize:h,path:c}of t)s.addPath(c,new DOMMatrix(n).preMultiplySelf(i).translate(r,a).scale(h,-h));e.clip(s),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){var u;const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||Eg,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&ht("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=((u=s.systemFontInfo)==null?void 0:u.css)||`"${n}", ${s.fallbackName}`;let a="normal";s.black?a="900":s.bold&&(a="bold");const h=s.italic?"italic":"normal";let c=e;e<Uv?c=Uv:e>Yv&&(c=Yv),this.current.fontSizeScale=e/c,this.ctx.font=`${h} ${a} ${c}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,e,s,i,n){const r=this.ctx,a=this.current,h=a.font,c=a.textRenderingMode,u=a.fontSize/a.fontSizeScale,d=c&De.FILL_STROKE_MASK,f=!!(c&De.ADD_TO_PATH_FLAG),g=a.patternFill&&!h.missingFile,p=a.patternStroke&&!h.missingFile;let m;if((h.disableFontFace||f||g||p)&&(m=h.getPathGenerator(this.commonObjs,t)),h.disableFontFace||g||p){if(r.save(),r.translate(e,s),r.scale(u,-u),d===De.FILL||d===De.FILL_STROKE)if(i){const y=r.getTransform();r.setTransform(...i),r.fill(w(this,ui,Gp).call(this,m,y,i))}else r.fill(m);if(d===De.STROKE||d===De.FILL_STROKE)if(n){const y=r.getTransform();r.setTransform(...n),r.stroke(w(this,ui,Gp).call(this,m,y,n))}else r.lineWidth/=u,r.stroke(m);r.restore()}else(d===De.FILL||d===De.FILL_STROKE)&&r.fillText(t,e,s),(d===De.STROKE||d===De.FILL_STROKE)&&r.strokeText(t,e,s);f&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:It(r),x:e,y:s,fontSize:u,path:m})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return ct(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,a=e.charSpacing,h=e.wordSpacing,c=e.fontDirection,u=e.textHScale*c,d=t.length,f=s.vertical,g=f?1:-1,p=s.defaultVMetrics,m=i*e.fontMatrix[0],y=e.textRenderingMode===De.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),c>0?n.scale(u,-1):n.scale(u,1);let b,x;if(e.patternFill){n.save();const P=e.fillColor.getPattern(n,this,Ei(n),Re.FILL);b=It(n),n.restore(),n.fillStyle=P}if(e.patternStroke){n.save();const P=e.strokeColor.getPattern(n,this,Ei(n),Re.STROKE);x=It(n),n.restore(),n.strokeStyle=P}let S=e.lineWidth;const C=e.textMatrixScale;if(C===0||S===0){const P=e.textRenderingMode&De.FILL_STROKE_MASK;(P===De.STROKE||P===De.FILL_STROKE)&&(S=this.getSinglePixelWidth())}else S/=C;if(r!==1&&(n.scale(r,r),S/=r),n.lineWidth=S,s.isInvalidPDFjsFont){const P=[];let D=0;for(const R of t)P.push(R.unicode),D+=R.width;n.fillText(P.join(""),0,0),e.x+=D*m*u,n.restore(),this.compose();return}let k=0,O;for(O=0;O<d;++O){const P=t[O];if(typeof P=="number"){k+=g*P*i/1e3;continue}let D=!1;const R=(P.isSpace?h:0)+a,z=P.fontChar,B=P.accent;let F,L,N=P.width;if(f){const I=P.vmetric||p,V=-(P.vmetric?I[1]:N*.5)*m,it=I[2]*m;N=I?-I[0]:N,F=V/r,L=(k+it)/r}else F=k/r,L=0;if(s.remeasure&&N>0){const I=n.measureText(z).width*1e3/i*r;if(N<I&&this.isFontSubpixelAAEnabled){const V=N/I;D=!0,n.save(),n.scale(V,1),F/=V}else N!==I&&(F+=(N-I)/2e3*i/r)}if(this.contentVisible&&(P.isInFont||s.missingFile)){if(y&&!B)n.fillText(z,F,L);else if(this.paintChar(z,F,L,b,x),B){const I=F+i*B.offset.x/r,V=L-i*B.offset.y/r;this.paintChar(B.fontChar,I,V,b,x)}}const K=f?N*m-R*c:N*m+R*c;k+=K,D&&n.restore()}f?e.y-=k:e.x+=k*u,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,a=i.vertical?1:-1,h=s.charSpacing,c=s.wordSpacing,u=s.textHScale*r,d=s.fontMatrix||Eg,f=t.length,g=s.textRenderingMode===De.INVISIBLE;let p,m,y,b;if(!(g||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(u,r),p=0;p<f;++p){if(m=t[p],typeof m=="number"){b=a*m*n/1e3,this.ctx.translate(b,0),s.x+=b*u;continue}const x=(m.isSpace?c:0)+h,S=i.charProcOperatorList[m.operatorListId];if(!S){ht(`Type3 character "${m.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=m,this.save(),e.scale(n,n),e.transform(...d),this.executeOperatorList(S),this.restore()),y=q.applyTransform([m.width,0],d)[0]*n+x,e.translate(y,0),s.x+=y*u}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,r){this.ctx.rect(s,i,n-s,r-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||It(this.ctx),n={createCanvasGraphics:r=>new gp(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new $g(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=q.makeHexColor(t,e,s),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=q.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=jS(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,Ei(e),Re.SHADING);const i=Ei(e);if(i){const{width:n,height:r}=e.canvas,[a,h,c,u]=q.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(a,h,c-a,u-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){kt("Should not call beginInlineImage")}beginImageData(){kt("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=It(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(It(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||ud("TODO: Support non-isolated groups."),t.knockout&&ht("Knockout groups not supported.");const s=It(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=q.getAxialAlignedBoundingBox(t.bbox,It(e));const n=[0,0,e.canvas.width,e.canvas.height];i=q.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),a=Math.floor(i[1]),h=Math.max(Math.ceil(i[2])-r,1),c=Math.max(Math.ceil(i[3])-a,1);this.current.startNewPathAndClipBox([0,0,h,c]);let u="groupAt"+this.groupLevel;t.smask&&(u+="_smask_"+this.smaskCounter++%2);const d=this.cachedCanvases.getCanvas(u,h,c),f=d.context;f.translate(-r,-a),f.transform(...s),t.smask?this.smaskStack.push({canvas:d.canvas,context:f,offsetX:r,offsetY:a,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(r,a),e.save()),gl(e,f),this.ctx=f,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=It(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=q.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(w(this,ui,Vp).call(this),wd(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=a;const[h,c]=q.singularValueDecompose2dScale(It(this.ctx)),{viewportScale:u}=this,d=Math.ceil(r*this.outputScaleX*u),f=Math.ceil(a*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(d,f);const{canvas:g,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,g),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(h,0,0,-c,0,a*c),wd(this.ctx)}else wd(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new Kv(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),w(this,ui,Wp).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=VS(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const a=this.ctx;a.save();const h=It(a);a.transform(e,s,i,n,0,0);const c=this._createMaskCanvas(t);a.setTransform(1,0,0,1,c.offsetX-h[4],c.offsetY-h[5]);for(let u=0,d=r.length;u<d;u+=2){const f=q.transform(h,[e,s,i,n,r[u],r[u+1]]),[g,p]=q.applyTransform([0,0],f);a.drawImage(c.canvas,g,p)}a.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:r,width:a,height:h,transform:c}=n,u=this.cachedCanvases.getCanvas("maskCanvas",a,h),d=u.context;d.save();const f=this.getObject(r,n);Qv(d,f),d.globalCompositeOperation="source-in",d.fillStyle=i?s.getPattern(d,this,Ei(e),Re.FILL):s,d.fillRect(0,0,a,h),d.restore(),e.save(),e.transform(...c),e.scale(1,-1),_d(e,u.canvas,0,0,a,h,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){ht("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){ht("Dependent image isn't ready yet");return}const r=n.width,a=n.height,h=[];for(let c=0,u=i.length;c<u;c+=2)h.push({transform:[e,0,0,s,i[c],i[c+1]],x:0,y:0,w:r,h:a});this.paintInlineImageXObjectGroup(n,h)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!Oe){const{filter:a}=i;a!=="none"&&a!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const h=this.cachedCanvases.getCanvas("inlineImage",e,s).context;Jv(h,t),n=this.applyTransferMapsToCanvas(h)}const r=this._scaleImage(n,Ei(i));i.imageSmoothingEnabled=Zv(It(i),t.interpolate),_d(i,r.img,0,0,r.paintWidth,r.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,r=t.height,h=this.cachedCanvases.getCanvas("inlineImage",n,r).context;Jv(h,t),i=this.applyTransferMapsToCanvas(h)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),_d(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===tb?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=It(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,a;if(s===0&&i===0){const h=Math.abs(e),c=Math.abs(n);if(h===c)if(t===0)r=a=1/h;else{const u=h*t;r=a=u<1?1/u:1}else if(t===0)r=1/h,a=1/c;else{const u=h*t,d=c*t;r=u<1?1/u:1,a=d<1?1/d:1}}else{const h=Math.abs(e*n-s*i),c=Math.hypot(e,s),u=Math.hypot(i,n);if(t===0)r=u/h,a=c/h;else{const d=t*h;r=u>d?u/d:1,a=c>d?c/d:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const a=Math.max(i,n);e.setLineDash(r.map(h=>h/a)),e.lineDashOffset/=a}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};ui=new WeakSet,Vp=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)},Wp=function(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}},Gp=function(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i};let To=gp;for(const o in ni)To.prototype[o]!==void 0&&(To.prototype[ni[o]]=To.prototype[o]);class an{static get workerPort(){return l(this,$l)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");v(this,$l,t)}static get workerSrc(){return l(this,ql)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");v(this,ql,t)}}$l=new WeakMap,ql=new WeakMap,_(an,$l,null),_(an,ql,"");class US{constructor({parsedData:t,rawData:e}){_(this,wa);_(this,Kl);v(this,wa,t),v(this,Kl,e)}getRaw(){return l(this,Kl)}get(t){return l(this,wa).get(t)??null}getAll(){return Og(l(this,wa))}has(t){return l(this,wa).has(t)}}wa=new WeakMap,Kl=new WeakMap;const Eo=Symbol("INTERNAL");class YS{constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){_(this,Jl,!1);_(this,Ql,!1);_(this,Zl,!1);_(this,Yo,!0);v(this,Jl,!!(t&vs.DISPLAY)),v(this,Ql,!!(t&vs.PRINT)),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(l(this,Zl))return l(this,Yo);if(!l(this,Yo))return!1;const{print:t,view:e}=this.usage;return l(this,Jl)?(e==null?void 0:e.viewState)!=="OFF":l(this,Ql)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,e,s=!1){t!==Eo&&kt("Internal method `_setVisible` called."),v(this,Zl,s),v(this,Yo,e)}}Jl=new WeakMap,Ql=new WeakMap,Zl=new WeakMap,Yo=new WeakMap;class $S{constructor(t,e=vs.DISPLAY){_(this,tc);_(this,ur,null);_(this,At,new Map);_(this,$o,null);_(this,qo,null);if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,v(this,qo,t.order);for(const s of t.groups)l(this,At).set(s.id,new YS(e,s));if(t.baseState==="OFF")for(const s of l(this,At).values())s._setVisible(Eo,!1);for(const s of t.on)l(this,At).get(s)._setVisible(Eo,!0);for(const s of t.off)l(this,At).get(s)._setVisible(Eo,!1);v(this,$o,this.getHash())}}isVisible(t){if(l(this,At).size===0)return!0;if(!t)return ud("Optional content group not defined."),!0;if(t.type==="OCG")return l(this,At).has(t.id)?l(this,At).get(t.id).visible:(ht(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return w(this,tc,Xp).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(l(this,At).get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(!l(this,At).get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(!l(this,At).get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!l(this,At).has(e))return ht(`Optional content group not found: ${e}`),!0;if(l(this,At).get(e).visible)return!1}return!0}return ht(`Unknown optional content policy ${t.policy}.`),!0}return ht(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){var n;const i=l(this,At).get(t);if(!i){ht(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const r of i.rbGroups)for(const a of r)a!==t&&((n=l(this,At).get(a))==null||n._setVisible(Eo,!1,!0));i._setVisible(Eo,!!e,!0),v(this,ur,null)}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=l(this,At).get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}v(this,ur,null)}get hasInitialVisibility(){return l(this,$o)===null||this.getHash()===l(this,$o)}getOrder(){return l(this,At).size?l(this,qo)?l(this,qo).slice():[...l(this,At).keys()]:null}getGroups(){return l(this,At).size>0?Og(l(this,At)):null}getGroup(t){return l(this,At).get(t)||null}getHash(){if(l(this,ur)!==null)return l(this,ur);const t=new Lv;for(const[e,s]of l(this,At))t.update(`${e}:${s.visible}`);return v(this,ur,t.hexdigest())}}ur=new WeakMap,At=new WeakMap,$o=new WeakMap,qo=new WeakMap,tc=new WeakSet,Xp=function(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=w(this,tc,Xp).call(this,n);else if(l(this,At).has(n))r=l(this,At).get(n).visible;else return ht(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"};class qS{constructor(t,{disableRange:e=!1,disableStream:s=!1}){ie(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:a}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=a,(n==null?void 0:n.length)>0){const h=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(h)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((h,c)=>{this._onReceiveData({begin:h,chunk:c})}),t.addProgressListener((h,c)=>{this._onProgress({loaded:h,total:c})}),t.addProgressiveReadListener(h=>{this._onReceiveData({chunk:h})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});ie(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}_onProgress(t){var e,s,i,n;t.total===void 0?(s=(e=this._rangeReaders[0])==null?void 0:e.onProgress)==null||s.call(e,{loaded:t.loaded}):(n=(i=this._fullRequestReader)==null?void 0:i.onProgress)==null||n.call(i,{loaded:t.loaded,total:t.total})}_onProgressiveDone(){var t;(t=this._fullRequestReader)==null||t.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){ie(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new KS(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new JS(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeReaders.slice(0))s.cancel(t);this._pdfDataRangeTransport.abort()}}class KS{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Ig(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class JS{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function QS(o){let t=!0,e=s("filename\\*","i").exec(o);if(e){e=e[1];let u=a(e);return u=unescape(u),u=h(u),u=c(u),n(u)}if(e=r(o),e){const u=c(e);return n(u)}if(e=s("filename","i").exec(o),e){e=e[1];let u=a(e);return u=c(u),n(u)}function s(u,d){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',d)}function i(u,d){if(u){if(!/^[\x00-\xFF]+$/.test(d))return d;try{const f=new TextDecoder(u,{fatal:!0}),g=fd(d);d=f.decode(g),t=!1}catch{}}return d}function n(u){return t&&/[\x80-\xff]/.test(u)&&(u=i("utf-8",u),t&&(u=i("iso-8859-1",u))),u}function r(u){const d=[];let f;const g=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(f=g.exec(u))!==null;){let[,m,y,b]=f;if(m=parseInt(m,10),m in d){if(m===0)break;continue}d[m]=[y,b]}const p=[];for(let m=0;m<d.length&&m in d;++m){let[y,b]=d[m];b=a(b),y&&(b=unescape(b),m===0&&(b=h(b))),p.push(b)}return p.join("")}function a(u){if(u.startsWith('"')){const d=u.slice(1).split('\\"');for(let f=0;f<d.length;++f){const g=d[f].indexOf('"');g!==-1&&(d[f]=d[f].slice(0,g),d.length=f+1),d[f]=d[f].replaceAll(/\\(.)/g,"$1")}u=d.join('"')}return u}function h(u){const d=u.indexOf("'");if(d===-1)return u;const f=u.slice(0,d),p=u.slice(d+1).replace(/^[^']*'/,"");return i(f,p)}function c(u){return!u.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(u)?u:u.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(d,f,g,p){if(g==="q"||g==="Q")return p=p.replaceAll("_"," "),p=p.replaceAll(/=([0-9a-fA-F]{2})/g,function(m,y){return String.fromCharCode(parseInt(y,16))}),i(f,p);try{p=atob(p)}catch{}return i(f,p)})}return""}function eb(o,t){const e=new Headers;if(!o||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function xd(o){try{return new URL(o).origin}catch{}return null}function sb({responseHeaders:o,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(o.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||o.get("Accept-Ranges")!=="bytes"||(o.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function ib(o){const t=o.get("Content-Disposition");if(t){let e=QS(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Ig(e))return e}return null}function Sd(o,t){return o===404||o===0&&t.startsWith("file:")?new ll('Missing PDF "'+t+'".'):new dd(`Unexpected server response (${o}) while retrieving PDF "${t}".`,o)}function nb(o){return o===200||o===206}function rb(o,t,e){return{method:"GET",headers:o,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function ab(o){return o instanceof Uint8Array?o.buffer:o instanceof ArrayBuffer?o:(ht(`getArrayBuffer - unexpected data format: ${o}`),new Uint8Array(o).buffer)}class ob{constructor(t){Q(this,"_responseOrigin",null);this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=eb(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return ie(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new ZS(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new tC(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeRequestReaders.slice(0))s.cancel(t)}}class ZS{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers),i=e.url;fetch(i,rb(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=xd(n.url),!nb(n.status))throw Sd(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:a,suggestedLength:h}=sb({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=a,this._contentLength=h||this._contentLength,this._filename=ib(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new qn("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded,total:this._contentLength}),{value:ab(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}class tC{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,rb(n,this._withCredentials,this._abortController)).then(a=>{const h=xd(a.url);if(h!==t._responseOrigin)throw new Error(`Expected range response-origin "${h}" to match "${t._responseOrigin}".`);if(!nb(a.status))throw Sd(a.status,r);this._readCapability.resolve(),this._reader=a.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:ab(t),done:!1})}cancel(t){var e;(e=this._reader)==null||e.cancel(t),this._abortController.abort()}}const qg=200,Kg=206;function eC(o){const t=o.response;return typeof t!="string"?t:fd(t).buffer}class sC{constructor({url:t,httpHeaders:e,withCredentials:s}){Q(this,"_responseOrigin",null);this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=eb(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=Kg):i.expectedStatus=qg,e.responseType="arraybuffer",ie(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){var i;const s=this.pendingRequests[t];s&&((i=s.onProgress)==null||i.call(s,e))}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){s.onError(i.status);return}const n=i.status||qg;if(!(n===qg&&s.expectedStatus===Kg)&&n!==s.expectedStatus){s.onError(i.status);return}const a=eC(i);if(n===Kg){const h=i.getResponseHeader("Content-Range"),c=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);c?s.onDone({begin:parseInt(c[1],10),chunk:a}):(ht('Missing or invalid "Content-Range" header.'),s.onError(0))}else a?s.onDone({begin:0,chunk:a}):s.onError(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class iC{constructor(t){this._source=t,this._manager=new sC(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return ie(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new nC(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new rC(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeRequestReaders.slice(0))s.cancel(t)}}class nC{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=xd(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(a=>{const[h,...c]=a.split(": ");return[h,c.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=sb({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=ib(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=Sd(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){var e;(e=this.onProgress)==null||e.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class rC{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){var e;const t=xd((e=this._manager.getRequestXhr(this._requestId))==null?void 0:e.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){var t;(t=this.onClosed)==null||t.call(this,this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??(this._storedError=Sd(t,this._url));for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){var e;this.isStreamingSupported||(e=this.onProgress)==null||e.call(this,{loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const aC=/^[a-z][a-z0-9\-+.]+:/i;function oC(o){if(aC.test(o))return new URL(o);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(o))}class hC{constructor(t){this.source=t,this.url=oC(t.url),ie(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return ie(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new lC(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new cC(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){var e;(e=this._fullRequestReader)==null||e.cancel(t);for(const s of this._rangeRequestReaders.slice(0))s.cancel(t)}}class lC{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();const s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new ll(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new qn("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class cC{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){var s;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(s=this.onProgress)==null||s.call(this,{loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const uC=1e5,os=30,dC=.8,ue=class ue{constructor({textContentSource:t,container:e,viewport:s}){_(this,_n);_(this,dr,Promise.withResolvers());_(this,cs,null);_(this,ec,!1);_(this,sc,!!((Eb=globalThis.FontInspector)!=null&&Eb.enabled));_(this,xa,null);_(this,yn,null);_(this,ic,0);_(this,nc,0);_(this,Sa,null);_(this,Ko,null);_(this,Jo,0);_(this,fr,0);_(this,Qo,Object.create(null));_(this,rc,[]);_(this,Zo,null);_(this,Ca,[]);_(this,ac,new WeakMap);_(this,oc,null);var h;if(t instanceof ReadableStream)v(this,Zo,t);else if(typeof t=="object")v(this,Zo,new ReadableStream({start(c){c.enqueue(t),c.close()}}));else throw new Error('No "textContentSource" parameter specified.');v(this,cs,v(this,Ko,e)),v(this,fr,s.scale*(globalThis.devicePixelRatio||1)),v(this,Jo,s.rotation),v(this,yn,{div:null,properties:null,ctx:null});const{pageWidth:i,pageHeight:n,pageX:r,pageY:a}=s.rawDims;v(this,oc,[1,0,0,-1,-r,a+n]),v(this,nc,i),v(this,ic,n),w(h=ue,xs,Ay).call(h),Yr(e,s),l(this,dr).promise.finally(()=>{l(ue,th).delete(this),v(this,yn,null),v(this,Qo,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Ue.platform;return ct(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{l(this,Sa).read().then(({value:e,done:s})=>{if(s){l(this,dr).resolve();return}l(this,xa)??v(this,xa,e.lang),Object.assign(l(this,Qo),e.styles),w(this,_n,Sy).call(this,e.items),t()},l(this,dr).reject)};return v(this,Sa,l(this,Zo).getReader()),l(ue,th).add(this),t(),l(this,dr).promise}update({viewport:t,onBefore:e=null}){var n;const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==l(this,Jo)&&(e==null||e(),v(this,Jo,i),Yr(l(this,Ko),{rotation:i})),s!==l(this,fr)){e==null||e(),v(this,fr,s);const r={div:null,properties:null,ctx:w(n=ue,xs,lf).call(n,l(this,xa))};for(const a of l(this,Ca))r.properties=l(this,ac).get(a),r.div=a,w(this,_n,Up).call(this,r)}}cancel(){var e;const t=new qn("TextLayer task cancelled.");(e=l(this,Sa))==null||e.cancel(t).catch(()=>{}),v(this,Sa,null),l(this,dr).reject(t)}get textDivs(){return l(this,Ca)}get textContentItemsStr(){return l(this,rc)}static cleanup(){if(!(l(this,th).size>0)){l(this,Aa).clear();for(const{canvas:t}of l(this,Ta).values())t.remove();l(this,Ta).clear()}}};dr=new WeakMap,cs=new WeakMap,ec=new WeakMap,sc=new WeakMap,xa=new WeakMap,yn=new WeakMap,ic=new WeakMap,nc=new WeakMap,Sa=new WeakMap,Ko=new WeakMap,Jo=new WeakMap,fr=new WeakMap,Qo=new WeakMap,rc=new WeakMap,Zo=new WeakMap,Ca=new WeakMap,ac=new WeakMap,oc=new WeakMap,Aa=new WeakMap,Ta=new WeakMap,hc=new WeakMap,gr=new WeakMap,th=new WeakMap,_n=new WeakSet,Sy=function(t){var i,n;if(l(this,ec))return;(n=l(this,yn)).ctx??(n.ctx=w(i=ue,xs,lf).call(i,l(this,xa)));const e=l(this,Ca),s=l(this,rc);for(const r of t){if(e.length>uC){ht("Ignoring additional textDivs for performance reasons."),v(this,ec,!0);return}if(r.str===void 0){if(r.type==="beginMarkedContentProps"||r.type==="beginMarkedContent"){const a=l(this,cs);v(this,cs,document.createElement("span")),l(this,cs).classList.add("markedContent"),r.id!==null&&l(this,cs).setAttribute("id",`${r.id}`),a.append(l(this,cs))}else r.type==="endMarkedContent"&&v(this,cs,l(this,cs).parentNode);continue}s.push(r.str),w(this,_n,Cy).call(this,r)}},Cy=function(t){var m;const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};l(this,Ca).push(e);const i=q.transform(l(this,oc),t.transform);let n=Math.atan2(i[1],i[0]);const r=l(this,Qo)[t.fontName];r.vertical&&(n+=Math.PI/2);let a=l(this,sc)&&r.fontSubstitution||r.fontFamily;a=ue.fontFamilyMap.get(a)||a;const h=Math.hypot(i[2],i[3]),c=h*w(m=ue,xs,Ty).call(m,a,l(this,xa));let u,d;n===0?(u=i[4],d=i[5]-c):(u=i[4]+c*Math.sin(n),d=i[5]-c*Math.cos(n));const f="calc(var(--scale-factor)*",g=e.style;l(this,cs)===l(this,Ko)?(g.left=`${(100*u/l(this,nc)).toFixed(2)}%`,g.top=`${(100*d/l(this,ic)).toFixed(2)}%`):(g.left=`${f}${u.toFixed(2)}px)`,g.top=`${f}${d.toFixed(2)}px)`),g.fontSize=`${f}${(l(ue,gr)*h).toFixed(2)}px)`,g.fontFamily=a,s.fontSize=h,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,l(this,sc)&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let p=!1;if(t.str.length>1)p=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const y=Math.abs(t.transform[0]),b=Math.abs(t.transform[3]);y!==b&&Math.max(y,b)/Math.min(y,b)>1.5&&(p=!0)}if(p&&(s.canvasWidth=r.vertical?t.height:t.width),l(this,ac).set(e,s),l(this,yn).div=e,l(this,yn).properties=s,w(this,_n,Up).call(this,l(this,yn)),s.hasText&&l(this,cs).append(e),s.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),l(this,cs).append(y)}},Up=function(t){var a;const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(l(ue,gr)>1&&(r=`scale(${1/l(ue,gr)})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:h}=n,{canvasWidth:c,fontSize:u}=s;w(a=ue,xs,Yp).call(a,i,u*l(this,fr),h);const{width:d}=i.measureText(e.textContent);d>0&&(r=`scaleX(${c*l(this,fr)/d}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)},xs=new WeakSet,lf=function(t=null){let e=l(this,Ta).get(t||(t=""));if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),l(this,Ta).set(t,e),l(this,hc).set(e,{size:0,family:""})}return e},Yp=function(t,e,s){const i=l(this,hc).get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)},Ay=function(){if(l(this,gr)!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),v(this,gr,t.getBoundingClientRect().height),t.remove()},Ty=function(t,e){const s=l(this,Aa).get(t);if(s)return s;const i=w(this,xs,lf).call(this,e);i.canvas.width=i.canvas.height=os,w(this,xs,Yp).call(this,i,os,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,a=Math.abs(n.fontBoundingBoxDescent);if(r){const u=r/(r+a);return l(this,Aa).set(t,u),i.canvas.width=i.canvas.height=0,u}i.strokeStyle="red",i.clearRect(0,0,os,os),i.strokeText("g",0,0);let h=i.getImageData(0,0,os,os).data;a=0;for(let u=h.length-1-3;u>=0;u-=4)if(h[u]>0){a=Math.ceil(u/4/os);break}i.clearRect(0,0,os,os),i.strokeText("A",0,os),h=i.getImageData(0,0,os,os).data,r=0;for(let u=0,d=h.length;u<d;u+=4)if(h[u]>0){r=os-Math.floor(u/4/os);break}i.canvas.width=i.canvas.height=0;const c=r?r/(r+a):dC;return l(this,Aa).set(t,c),c},_(ue,xs),_(ue,Aa,new Map),_(ue,Ta,new Map),_(ue,hc,new WeakMap),_(ue,gr,null),_(ue,th,new Set);let pl=ue;class ml{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){var h;if(!n)return;let r=null;const a=n.name;if(a==="#text")r=n.value;else if(ml.shouldBuildText(a))(h=n==null?void 0:n.attributes)!=null&&h.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const c of n.children)i(c)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const fC=65536,gC=100,pC=5e3,mC=Oe?MS:ES,vC=Oe?OS:Hv,bC=Oe?PS:kS,yC=Oe?DS:Wv;function _C(o={}){typeof o=="string"||o instanceof URL?o={url:o}:(o instanceof ArrayBuffer||ArrayBuffer.isView(o))&&(o={data:o});const t=new Jg,{docId:e}=t,s=o.url?wC(o.url):null,i=o.data?xC(o.data):null,n=o.httpHeaders||null,r=o.withCredentials===!0,a=o.password??null,h=o.range instanceof lb?o.range:null,c=Number.isInteger(o.rangeChunkSize)&&o.rangeChunkSize>0?o.rangeChunkSize:fC;let u=o.worker instanceof ko?o.worker:null;const d=o.verbosity,f=typeof o.docBaseUrl=="string"&&!pd(o.docBaseUrl)?o.docBaseUrl:null,g=typeof o.cMapUrl=="string"?o.cMapUrl:null,p=o.cMapPacked!==!1,m=o.CMapReaderFactory||vC,y=typeof o.standardFontDataUrl=="string"?o.standardFontDataUrl:null,b=o.StandardFontDataFactory||yC,x=o.stopAtErrors!==!0,S=Number.isInteger(o.maxImageSize)&&o.maxImageSize>-1?o.maxImageSize:-1,C=o.isEvalSupported!==!1,k=typeof o.isOffscreenCanvasSupported=="boolean"?o.isOffscreenCanvasSupported:!Oe,O=typeof o.isImageDecoderSupported=="boolean"?o.isImageDecoderSupported:!Oe&&(Ue.platform.isFirefox||!globalThis.chrome),P=Number.isInteger(o.canvasMaxAreaInBytes)?o.canvasMaxAreaInBytes:-1,D=typeof o.disableFontFace=="boolean"?o.disableFontFace:Oe,R=o.fontExtraProperties===!0,z=o.enableXfa===!0,B=o.ownerDocument||globalThis.document,F=o.disableRange===!0,L=o.disableStream===!0,N=o.disableAutoFetch===!0,K=o.pdfBug===!0,I=o.CanvasFactory||mC,V=o.FilterFactory||bC,it=o.enableHWA===!0,Ot=h?h.length:o.length??NaN,Bt=typeof o.useSystemFonts=="boolean"?o.useSystemFonts:!Oe&&!D,Xt=typeof o.useWorkerFetch=="boolean"?o.useWorkerFetch:m===Hv&&b===Wv&&g&&y&&ul(g,document.baseURI)&&ul(y,document.baseURI),Ft=null;rS(d);const _t={canvasFactory:new I({ownerDocument:B,enableHWA:it}),filterFactory:new V({docId:e,ownerDocument:B}),cMapReaderFactory:Xt?null:new m({baseUrl:g,isCompressed:p}),standardFontDataFactory:Xt?null:new b({baseUrl:y})};if(!u){const st={verbosity:d,port:an.workerPort};u=st.port?ko.fromPort(st):new ko(st),t._worker=u}const ae={docId:e,apiVersion:"4.10.38",data:i,password:a,disableAutoFetch:N,rangeChunkSize:c,length:Ot,docBaseUrl:f,enableXfa:z,evaluatorOptions:{maxImageSize:S,disableFontFace:D,ignoreErrors:x,isEvalSupported:C,isOffscreenCanvasSupported:k,isImageDecoderSupported:O,canvasMaxAreaInBytes:P,fontExtraProperties:R,useSystemFonts:Bt,cMapUrl:Xt?g:null,standardFontDataUrl:Xt?y:null}},Ze={disableFontFace:D,fontExtraProperties:R,ownerDocument:B,pdfBug:K,styleElement:Ft,loadingParams:{disableAutoFetch:N,enableXfa:z}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const st=u.messageHandler.sendWithPromise("GetDocRequest",ae,i?[i.buffer]:null);let nt;if(h)nt=new qS(h,{disableRange:F,disableStream:L});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Zt;if(Oe)if(ul(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");Zt=ob}else Zt=hC;else Zt=ul(s)?ob:iC;nt=new Zt({url:s,length:Ot,httpHeaders:n,withCredentials:r,rangeChunkSize:c,disableRange:F,disableStream:L})}return st.then(Zt=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const $s=new fl(e,Zt,u.port),Te=new TC($s,t,nt,Ze,_t);t._transport=Te,$s.send("Ready",null)})}).catch(t._capability.reject),t}function wC(o){if(o instanceof URL)return o.href;try{return new URL(o,window.location).href}catch{if(Oe&&typeof o=="string")return o}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function xC(o){if(Oe&&typeof Buffer<"u"&&o instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(o instanceof Uint8Array&&o.byteLength===o.buffer.byteLength)return o;if(typeof o=="string")return fd(o);if(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="object"&&!isNaN(o==null?void 0:o.length))return new Uint8Array(o);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function hb(o){return typeof o=="object"&&Number.isInteger(o==null?void 0:o.num)&&o.num>=0&&Number.isInteger(o==null?void 0:o.gen)&&o.gen>=0}const Nd=class Nd{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${es(Nd,jd)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){var t,e,s,i;this.destroyed=!0;try{(t=this._worker)!=null&&t.port&&(this._worker._pendingDestroy=!0),await((e=this._transport)==null?void 0:e.destroy())}catch(n){throw(s=this._worker)!=null&&s.port&&delete this._worker._pendingDestroy,n}this._transport=null,(i=this._worker)==null||i.destroy(),this._worker=null}};jd=new WeakMap,_(Nd,jd,0);let Jg=Nd;class lb{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){kt("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class SC{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return ct(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class CC{constructor(t,e,s,i=!1){_(this,Vs);_(this,pr,null);_(this,wn,!1);this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new Rv:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new cb,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new cl({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return ct(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var t;return((t=this._transport._htmlForXfa)==null?void 0:t.children[this._pageIndex])||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=Yn.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:a=null,annotationCanvasMap:h=null,pageColors:c=null,printAnnotationStorage:u=null,isEditing:d=!1}){var C,k;(C=this._stats)==null||C.time("Overall");const f=this._transport.getRenderingIntent(s,i,u,d),{renderingIntent:g,cacheKey:p}=f;v(this,wn,!1),w(this,Vs,cf).call(this),a||(a=this._transport.getOptionalContentConfig(g));let m=this._intentStates.get(p);m||(m=Object.create(null),this._intentStates.set(p,m)),m.streamReaderCancelTimeout&&(clearTimeout(m.streamReaderCancelTimeout),m.streamReaderCancelTimeout=null);const y=!!(g&vs.PRINT);m.displayReadyCapability||(m.displayReadyCapability=Promise.withResolvers(),m.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(k=this._stats)==null||k.time("Page Request"),this._pumpOperatorList(f));const b=O=>{var P;m.renderTasks.delete(x),(this._maybeCleanupAfterRender||y)&&v(this,wn,!0),w(this,Vs,zh).call(this,!y),O?(x.capability.reject(O),this._abortOperatorList({intentState:m,reason:O instanceof Error?O:new Error(O)})):x.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(P=globalThis.Stats)!=null&&P.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},x=new Qg({callback:b,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:h,operatorList:m.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!y,pdfBug:this._pdfBug,pageColors:c});(m.renderTasks||(m.renderTasks=new Set)).add(x);const S=x.task;return Promise.all([m.displayReadyCapability.promise,a]).then(([O,P])=>{var D;if(this.destroyed){b();return}if((D=this._stats)==null||D.time("Rendering"),!(P.renderingIntent&g))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");x.initializeGraphics({transparency:O,optionalContentConfig:P}),x.operatorListChanged()}).catch(b),S}getOperatorList({intent:t="display",annotationMode:e=Yn.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){var c;function n(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(h))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let a=this._intentStates.get(r.cacheKey);a||(a=Object.create(null),this._intentStates.set(r.cacheKey,a));let h;return a.opListReadCapability||(h=Object.create(null),h.operatorListChanged=n,a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||(a.renderTasks=new Set)).add(h),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(c=this._stats)==null||c.time("Page Request"),this._pumpOperatorList(r)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>ml.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:h,done:c}){if(c){s(a);return}a.lang??(a.lang=h.lang),Object.assign(a.styles,h.styles),a.items.push(...h.items),n()},i)}const r=e.getReader(),a={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),v(this,wn,!1),w(this,Vs,cf).call(this),Promise.all(t)}cleanup(t=!1){v(this,wn,!0);const e=w(this,Vs,zh).call(this,!1);return t&&e&&this._stats&&(this._stats=new Rv),e}_startRenderPage(t,e){var i,n;const s=this._intentStates.get(e);s&&((i=this._stats)==null||i.timeEnd("Page Request"),(n=s.displayReadyCapability)==null||n.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&w(this,Vs,zh).call(this,!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,h=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),c=this._intentStates.get(e);c.streamReader=h;const u=()=>{h.read().then(({value:d,done:f})=>{if(f){c.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(d,c),u())},d=>{if(c.streamReader=null,!this._transport.destroyed){if(c.operatorList){c.operatorList.lastChunk=!0;for(const f of c.renderTasks)f.operatorListChanged();w(this,Vs,zh).call(this,!0)}if(c.displayReadyCapability)c.displayReadyCapability.reject(d);else if(c.opListReadCapability)c.opListReadCapability.reject(d);else throw d}})};u()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof Lg){let i=gC;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}if(t.streamReader.cancel(new qn(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}pr=new WeakMap,wn=new WeakMap,Vs=new WeakSet,zh=function(t=!1){if(w(this,Vs,cf).call(this),!l(this,wn)||this.destroyed)return!1;if(t)return v(this,pr,setTimeout(()=>{v(this,pr,null),w(this,Vs,zh).call(this,!1)},pC)),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),v(this,wn,!1),!0},cf=function(){l(this,pr)&&(clearTimeout(l(this,pr)),v(this,pr,null))};class AC{constructor(){_(this,xn,new Map);_(this,Bd,Promise.resolve())}postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};l(this,Bd).then(()=>{for(const[i]of l(this,xn))i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if((s==null?void 0:s.signal)instanceof AbortSignal){const{signal:n}=s;if(n.aborted){ht("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}l(this,xn).set(e,i)}removeEventListener(t,e){const s=l(this,xn).get(e);s==null||s(),l(this,xn).delete(e)}terminate(){for(const[,t]of l(this,xn))t==null||t();l(this,xn).clear()}}xn=new WeakMap,Bd=new WeakMap;const jt=class jt{constructor({name:t=null,port:e=null,verbosity:s=aS()}={}){_(this,eh);var i;if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if((i=l(jt,ka))!=null&&i.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(l(jt,ka)||v(jt,ka,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new fl("main","worker",t),this._messageHandler.on("ready",function(){}),w(this,eh,uf).call(this)}_initialize(){if(l(jt,Ea)||l(jt,sh,df)){this._setupFakeWorker();return}let{workerSrc:t}=jt;try{jt._isSameOrigin(window.location.href,t)||(t=jt._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new fl("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",a=>{if(n.abort(),this.destroyed||!a){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,w(this,eh,uf).call(this)}),s.on("ready",a=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const a=new Uint8Array;s.send("test",a,[a.buffer])};r();return}catch{ud("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){l(jt,Ea)||(ht("Setting up fake worker."),v(jt,Ea,!0)),jt._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new AC;this._port=e;const s=`fake${es(jt,Hd)._++}`,i=new fl(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new fl(s,s+"_worker",e),w(this,eh,uf).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t,e,s;this.destroyed=!0,(t=this._webWorker)==null||t.terminate(),this._webWorker=null,(e=l(jt,ka))==null||e.delete(this._port),this._port=null,(s=this._messageHandler)==null||s.destroy(),this._messageHandler=null}static fromPort(t){var s;if(!(t!=null&&t.port))throw new Error("PDFWorker.fromPort - invalid method signature.");const e=(s=l(this,ka))==null?void 0:s.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new jt(t)}static get workerSrc(){if(an.workerSrc)return an.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return ct(this,"_setupFakeWorkerGlobal",(async()=>l(this,sh,df)?l(this,sh,df):(await import(this.workerSrc)).WorkerMessageHandler)())}};Hd=new WeakMap,Ea=new WeakMap,ka=new WeakMap,eh=new WeakSet,uf=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},sh=new WeakSet,df=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},_(jt,sh),_(jt,Hd,0),_(jt,Ea,!1),_(jt,ka),Oe&&(v(jt,Ea,!0),an.workerSrc||(an.workerSrc="./pdf.worker.mjs")),jt._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},jt._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let ko=jt;class TC{constructor(t,e,s,i,n){_(this,Pa);_(this,Sn,new Map);_(this,Ni,new Map);_(this,ih,new Map);_(this,nh,new Map);_(this,Cn,null);this.messageHandler=t,this.loadingTask=e,this.commonObjs=new cb,this.fontLoader=new AS({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}get annotationStorage(){return ct(this,"annotationStorage",new Gg)}getRenderingIntent(t,e=Yn.ENABLE,s=null,i=!1,n=!1){let r=vs.DISPLAY,a=Wg;switch(t){case"any":r=vs.ANY;break;case"display":break;case"print":r=vs.PRINT;break;default:ht(`getRenderingIntent - invalid intent: ${t}`)}const h=r&vs.PRINT&&s instanceof Iv?s:this.annotationStorage;switch(e){case Yn.DISABLE:r+=vs.ANNOTATIONS_DISABLE;break;case Yn.ENABLE:break;case Yn.ENABLE_FORMS:r+=vs.ANNOTATIONS_FORMS;break;case Yn.ENABLE_STORAGE:r+=vs.ANNOTATIONS_STORAGE,a=h.serializable;break;default:ht(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=vs.IS_EDITING),n&&(r+=vs.OPLIST);const{ids:c,hash:u}=h.modifiedIds,d=[r,a.hash,u];return{renderingIntent:r,cacheKey:d.join("_"),annotationStorageSerializable:a,modifiedIds:c}}destroy(){var s;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(s=l(this,Cn))==null||s.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const i of l(this,Ni).values())t.push(i._destroy());l(this,Ni).clear(),l(this,ih).clear(),l(this,nh).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{var i,n;this.commonObjs.clear(),this.fontLoader.clear(),l(this,Sn).clear(),this.filterFactory.destroy(),pl.cleanup(),(i=this._networkStream)==null||i.cancelAllRequests(new qn("Worker was terminated.")),(n=this.messageHandler)==null||n.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{ie(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:r}){if(r){i.close();return}ie(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",async s=>{var a;await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&((a=e.onProgress)==null||a.call(e,this._lastProgress)),this._fullReader.onProgress=h=>{var c;(c=e.onProgress)==null||c.call(e,{loaded:h.loaded,total:h.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{ie(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:a}){if(a){i.close();return}ie(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new SC(s,this))}),t.on("DocException",s=>{e._capability.reject(rs(s))}),t.on("PasswordRequest",s=>{v(this,Cn,Promise.withResolvers());try{if(!e.onPassword)throw rs(s);const i=n=>{n instanceof Error?l(this,Cn).reject(n):l(this,Cn).resolve({password:n})};e.onPassword(i,s.code)}catch(i){l(this,Cn).reject(i)}return l(this,Cn).promise}),t.on("DataLoaded",s=>{var i;(i=e.onProgress)==null||i.call(e,{loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;l(this,Ni).get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{var r;if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:a,fontExtraProperties:h,pdfBug:c}=this._params;if("error"in n){const g=n.error;ht(`Error during font loading: ${g}`),this.commonObjs.resolve(s,g);break}const u=c&&((r=globalThis.FontInspector)!=null&&r.enabled)?(g,p)=>globalThis.FontInspector.fontAdded(g,p):null,d=new TS(n,{disableFontFace:a,fontExtraProperties:h,inspectFont:u});this.fontLoader.bind(d).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!h&&d.data&&(d.data=null),this.commonObjs.resolve(s,d)});break;case"CopyLocalImage":const{imageRef:f}=n;ie(f,"The imageRef must be defined.");for(const g of l(this,Ni).values())for(const[,p]of g.objs)if((p==null?void 0:p.ref)===f)return p.dataLen?(this.commonObjs.resolve(s,structuredClone(p)),p.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{var h;if(this.destroyed)return;const a=l(this,Ni).get(i);if(!a.objs.has(s)){if(a._intentStates.size===0){(h=r==null?void 0:r.bitmap)==null||h.close();return}switch(n){case"Image":a.objs.resolve(s,r),(r==null?void 0:r.dataLen)>eS&&(a._maybeCleanupAfterRender=!0);break;case"Pattern":a.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{var i;this.destroyed||(i=e.onProgress)==null||i.call(e,{loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var s;this.annotationStorage.size<=0&&ht("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((s=this._fullReader)==null?void 0:s.filename)??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=l(this,ih).get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&l(this,nh).set(n.refStr,t);const r=new CC(e,n,this,this._params.pdfBug);return l(this,Ni).set(e,r),r});return l(this,ih).set(e,i),i}getPageIndex(t){return hb(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return w(this,Pa,tu).call(this,"GetFieldObjects")}hasJSActions(){return w(this,Pa,tu).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return w(this,Pa,tu).call(this,"GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return w(this,Pa,tu).call(this,"GetOptionalContentConfig").then(e=>new $S(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=l(this,Sn).get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>{var n,r;return{info:i[0],metadata:i[1]?new US(i[1]):null,contentDispositionFilename:((n=this._fullReader)==null?void 0:n.filename)??null,contentLength:((r=this._fullReader)==null?void 0:r.contentLength)??null}});return l(this,Sn).set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of l(this,Ni).values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),l(this,Sn).clear(),this.filterFactory.destroy(!0),pl.cleanup()}}cachedPageNumber(t){if(!hb(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return l(this,nh).get(e)??null}}Sn=new WeakMap,Ni=new WeakMap,ih=new WeakMap,nh=new WeakMap,Cn=new WeakMap,Pa=new WeakSet,tu=function(t,e=null){const s=l(this,Sn).get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return l(this,Sn).set(t,i),i};const vl=Symbol("INITIAL_DATA");class cb{constructor(){_(this,lc);_(this,Ss,Object.create(null))}get(t,e=null){if(e){const i=w(this,lc,$p).call(this,t);return i.promise.then(()=>e(i.data)),null}const s=l(this,Ss)[t];if(!s||s.data===vl)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=l(this,Ss)[t];return!!e&&e.data!==vl}delete(t){const e=l(this,Ss)[t];return!e||e.data===vl?!1:(delete l(this,Ss)[t],!0)}resolve(t,e=null){const s=w(this,lc,$p).call(this,t);s.data=e,s.resolve()}clear(){var t;for(const e in l(this,Ss)){const{data:s}=l(this,Ss)[e];(t=s==null?void 0:s.bitmap)==null||t.close()}v(this,Ss,Object.create(null))}*[Symbol.iterator](){for(const t in l(this,Ss)){const{data:e}=l(this,Ss)[t];e!==vl&&(yield[t,e])}}}Ss=new WeakMap,lc=new WeakSet,$p=function(t){var e;return(e=l(this,Ss))[t]||(e[t]={...Promise.withResolvers(),data:vl})};class EC{constructor(t){_(this,mr,null);v(this,mr,t),this.onContinue=null}get promise(){return l(this,mr).capability.promise}cancel(t=0){l(this,mr).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=l(this,mr).operatorList;if(!t)return!1;const{annotationCanvasMap:e}=l(this,mr);return t.form||t.canvas&&(e==null?void 0:e.size)>0}}mr=new WeakMap;const Oa=class Oa{constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:a,canvasFactory:h,filterFactory:c,useRequestAnimationFrame:u=!1,pdfBug:d=!1,pageColors:f=null}){_(this,vr,null);this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=h,this.filterFactory=c,this._pdfBug=d,this.pageColors=f,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new EC(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){var a,h;if(this.cancelled)return;if(this._canvas){if(l(Oa,Ma).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");l(Oa,Ma).add(this._canvas)}this._pdfBug&&((a=globalThis.StepperManager)!=null&&a.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:r}=this.params;this.gfx=new To(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,(h=this.graphicsReadyCallback)==null||h.call(this)}cancel(t=null,e=0){var s;this.running=!1,this.cancelled=!0,(s=this.gfx)==null||s.endDrawing(),l(this,vr)&&(window.cancelAnimationFrame(l(this,vr)),v(this,vr,null)),l(Oa,Ma).delete(this._canvas),this.callback(t||new Lg(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){var t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?v(this,vr,window.requestAnimationFrame(()=>{v(this,vr,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),l(Oa,Ma).delete(this._canvas),this.callback())))}};vr=new WeakMap,Ma=new WeakMap,_(Oa,Ma,new WeakSet);let Qg=Oa;const kC="4.10.38",PC="f9bea397f";function ub(o){return Math.floor(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0")}function bl(o){return Math.max(0,Math.min(255,255*o))}class db{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=bl(t),[t,t,t]}static G_HTML([t]){const e=ub(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(bl)}static RGB_HTML(t){return`#${t.map(ub).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[bl(1-Math.min(1,t+i)),bl(1-Math.min(1,s+i)),bl(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,a=Math.min(i,n,r);return["CMYK",i,n,r,a]}}class MC{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){kt("Abstract method `_createSVG` called.")}}class Zg extends MC{_createSVG(t){return document.createElementNS(rn,t)}}class fb{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",a=>{i.setValue(e,{value:a.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",a=>{i.setValue(e,{value:a.target.checked?a.target.getAttribute("xfaOn"):a.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",a=>{i.setValue(e,{value:a.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const a of s.children)a.attributes.value===r.value?a.attributes.selected=!0:a.attributes.hasOwnProperty("selected")&&delete a.attributes.selected}t.addEventListener("input",a=>{const h=a.target.options,c=h.selectedIndex===-1?"":h[h.selectedIndex].value;i.setValue(e,{value:c})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[h,c]of Object.entries(r))if(c!=null)switch(h){case"class":c.length&&t.setAttribute(h,c.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",c);break;case"style":Object.assign(t.style,c);break;case"textContent":t.textContent=c;break;default:(!a||h!=="href"&&h!=="newWindow")&&t.setAttribute(h,c)}a&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){var d,f;const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const a=n!=="richText",h=t.div;if(h.append(r),t.viewport){const g=`matrix(${t.viewport.transform.join(",")})`;h.style.transform=g}a&&h.setAttribute("class","xfaLayer xfaFont");const c=[];if(i.children.length===0){if(i.value){const g=document.createTextNode(i.value);r.append(g),a&&ml.shouldBuildText(i.name)&&c.push(g)}return{textDivs:c}}const u=[[i,-1,r]];for(;u.length>0;){const[g,p,m]=u.at(-1);if(p+1===g.children.length){u.pop();continue}const y=g.children[++u.at(-1)[1]];if(y===null)continue;const{name:b}=y;if(b==="#text"){const S=document.createTextNode(y.value);c.push(S),m.append(S);continue}const x=(d=y==null?void 0:y.attributes)!=null&&d.xmlns?document.createElementNS(y.attributes.xmlns,b):document.createElement(b);if(m.append(x),y.attributes&&this.setAttributes({html:x,element:y,storage:e,intent:n,linkService:s}),((f=y.children)==null?void 0:f.length)>0)u.push([y,-1,x]);else if(y.value){const S=document.createTextNode(y.value);a&&ml.shouldBuildText(b)&&c.push(S),x.append(S)}}for(const g of h.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))g.setAttribute("readOnly",!0);return{textDivs:c}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const yl=1e3,OC=9,qr=new WeakSet;function Jn(o){return{width:o[2]-o[0],height:o[3]-o[1]}}class DC{static create(t){switch(t.data.annotationType){case le.LINK:return new gb(t);case le.TEXT:return new RC(t);case le.WIDGET:switch(t.data.fieldType){case"Tx":return new FC(t);case"Btn":return t.data.radioButton?new pb(t):t.data.checkBox?new IC(t):new jC(t);case"Ch":return new NC(t);case"Sig":return new LC(t)}return new Kr(t);case le.POPUP:return new tp(t);case le.FREETEXT:return new mb(t);case le.LINE:return new HC(t);case le.SQUARE:return new zC(t);case le.CIRCLE:return new VC(t);case le.POLYLINE:return new vb(t);case le.CARET:return new GC(t);case le.INK:return new ep(t);case le.POLYGON:return new WC(t);case le.HIGHLIGHT:return new bb(t);case le.UNDERLINE:return new XC(t);case le.SQUIGGLY:return new UC(t);case le.STRIKEOUT:return new YC(t);case le.STAMP:return new yb(t);case le.FILEATTACHMENT:return new $C(t);default:return new Kt(t)}}}const pp=class pp{constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){_(this,cc);_(this,Da,null);_(this,rh,!1);_(this,ah,null);this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t!=null&&t.str||e!=null&&e.str||s!=null&&s.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return pp._hasPopupData(this.data)}updateEdited(t){var s;if(!this.container)return;l(this,Da)||v(this,Da,{rect:this.data.rect.slice(0)});const{rect:e}=t;e&&w(this,cc,qp).call(this,e),(s=l(this,ah))==null||s.popup.updateEdited(t)}resetEdited(){var t;l(this,Da)&&(w(this,cc,qp).call(this,l(this,Da).rect),(t=l(this,ah))==null||t.popup.resetEdited(),v(this,Da,null))}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Kr||(n.tabIndex=yl);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof tp){const{rotation:m}=e;return!e.hasOwnCanvas&&m!==0&&this.setRotation(m,n),n}const{width:a,height:h}=Jn(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const m=e.borderStyle.horizontalCornerRadius,y=e.borderStyle.verticalCornerRadius;if(m>0||y>0){const x=`calc(${m}px * var(--scale-factor)) / calc(${y}px * var(--scale-factor))`;r.borderRadius=x}else if(this instanceof pb){const x=`calc(${a}px * var(--scale-factor)) / calc(${h}px * var(--scale-factor))`;r.borderRadius=x}switch(e.borderStyle.style){case hl.SOLID:r.borderStyle="solid";break;case hl.DASHED:r.borderStyle="dashed";break;case hl.BEVELED:ht("Unimplemented border style: beveled");break;case hl.INSET:ht("Unimplemented border style: inset");break;case hl.UNDERLINE:r.borderBottomStyle="solid";break}const b=e.borderColor||null;b?(v(this,rh,!0),r.borderColor=q.makeHexColor(b[0]|0,b[1]|0,b[2]|0)):r.borderWidth=0}const c=q.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:u,pageHeight:d,pageX:f,pageY:g}=i.rawDims;r.left=`${100*(c[0]-f)/u}%`,r.top=`${100*(c[1]-g)/d}%`;const{rotation:p}=e;return e.hasOwnCanvas||p===0?(r.width=`${100*a/u}%`,r.height=`${100*h/d}%`):this.setRotation(p,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:r}=Jn(this.data.rect);let a,h;t%180===0?(a=100*n/s,h=100*r/i):(a=100*r/s,h=100*n/i),e.style.width=`${a}%`,e.style.height=`${h}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],a=n.slice(1);i.target.style[s]=db[`${r}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[s]:db[`${r}_rgb`](a)})};return ct(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail)){const n=t[i]||s[i];n==null||n(e)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const a={detail:{[i]:n},target:t};r(a),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(m=>Math.fround(m));if(t.length===8){const[m,y,b,x]=t.subarray(2,6);if(i===m&&n===y&&e===b&&s===x)return}const{style:r}=this.container;let a;if(l(this,rh)){const{borderColor:m,borderWidth:y}=r;r.borderWidth=0,a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${m}" stroke-width="${y}">`],this.container.classList.add("hasBorder")}const h=i-e,c=n-s,{svgFactory:u}=this,d=u.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0);const f=u.createElement("defs");d.append(f);const g=u.createElement("clipPath"),p=`clippath_${this.data.id}`;g.setAttribute("id",p),g.setAttribute("clipPathUnits","objectBoundingBox"),f.append(g);for(let m=2,y=t.length;m<y;m+=8){const b=t[m],x=t[m+1],S=t[m+2],C=t[m+3],k=u.createElement("rect"),O=(S-e)/h,P=(n-x)/c,D=(b-S)/h,R=(x-C)/c;k.setAttribute("x",O),k.setAttribute("y",P),k.setAttribute("width",D),k.setAttribute("height",R),g.append(k),a==null||a.push(`<rect vector-effect="non-scaling-stroke" x="${O}" y="${P}" width="${D}" height="${R}"/>`)}l(this,rh)&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(d),this.container.style.clipPath=`url(#${p})`}_createPopup(){const{data:t}=this,e=v(this,ah,new tp({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(e.render())}render(){kt("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:a}of i){if(n===-1||r===e)continue;const h=typeof a=="string"?a:null,c=document.querySelector(`[data-element-id="${r}"]`);if(c&&!qr.has(c)){ht(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:h,domElement:c})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&qr.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){var t;this.container&&(this.container.hidden=!1),(t=this.popup)==null||t.maybeShow()}hide(){var t;this.container&&(this.container.hidden=!0),(t=this.popup)==null||t.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{var s;(s=this.linkService.eventBus)==null||s.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}};Da=new WeakMap,rh=new WeakMap,ah=new WeakMap,cc=new WeakSet,qp=function(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:h}}}}=this;s==null||s.splice(0,4,...t);const{width:c,height:u}=Jn(t);e.left=`${100*(t[0]-a)/n}%`,e.top=`${100*(r-t[3]+h)/r}%`,i===0?(e.width=`${100*c/n}%`,e.height=`${100*u/r}%`):this.setRotation(i)};let Kt=pp;class gb extends Kt{constructor(e,s=null){super(e,{isRenderable:!0,ignoreBorder:!!(s!=null&&s.ignoreBorder),createQuadrilaterals:!0});_(this,Cs);this.isTooltipOnly=e.data.isTooltipOnly}render(){const{data:e,linkService:s}=this,i=document.createElement("a");i.setAttribute("data-element-id",e.id);let n=!1;return e.url?(s.addLinkAttributes(i,e.url,e.newWindow),n=!0):e.action?(this._bindNamedAction(i,e.action),n=!0):e.attachment?(w(this,Cs,Ey).call(this,i,e.attachment,e.attachmentDest),n=!0):e.setOCGState?(w(this,Cs,ky).call(this,i,e.setOCGState),n=!0):e.dest?(this._bindLink(i,e.dest),n=!0):(e.actions&&(e.actions.Action||e.actions["Mouse Up"]||e.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(i,e),n=!0),e.resetForm?(this._bindResetFormAction(i,e.resetForm),n=!0):this.isTooltipOnly&&!n&&(this._bindLink(i,""),n=!0)),this.container.classList.add("linkAnnotation"),n&&this.container.append(i),this.container}_bindLink(e,s){e.href=this.linkService.getDestinationHash(s),e.onclick=()=>(s&&this.linkService.goToDestination(s),!1),(s||s==="")&&w(this,Cs,ao).call(this)}_bindNamedAction(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeNamedAction(s),!1),w(this,Cs,ao).call(this)}_bindJSAction(e,s){e.href=this.linkService.getAnchorUrl("");const i=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const n of Object.keys(s.actions)){const r=i.get(n);r&&(e[r]=()=>{var a;return(a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:s.id,name:n}}),!1})}e.onclick||(e.onclick=()=>!1),w(this,Cs,ao).call(this)}_bindResetFormAction(e,s){const i=e.onclick;if(i||(e.href=this.linkService.getAnchorUrl("")),w(this,Cs,ao).call(this),!this._fieldObjects){ht('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(e.onclick=()=>!1);return}e.onclick=()=>{var d;i==null||i();const{fields:n,refs:r,include:a}=s,h=[];if(n.length!==0||r.length!==0){const f=new Set(r);for(const g of n){const p=this._fieldObjects[g]||[];for(const{id:m}of p)f.add(m)}for(const g of Object.values(this._fieldObjects))for(const p of g)f.has(p.id)===a&&h.push(p)}else for(const f of Object.values(this._fieldObjects))h.push(...f);const c=this.annotationStorage,u=[];for(const f of h){const{id:g}=f;switch(u.push(g),f.type){case"text":{const m=f.defaultValue||"";c.setValue(g,{value:m});break}case"checkbox":case"radiobutton":{const m=f.defaultValue===f.exportValues;c.setValue(g,{value:m});break}case"combobox":case"listbox":{const m=f.defaultValue||"";c.setValue(g,{value:m});break}default:continue}const p=document.querySelector(`[data-element-id="${g}"]`);if(p){if(!qr.has(p)){ht(`_bindResetFormAction - element not allowed: ${g}`);continue}}else continue;p.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((d=this.linkService.eventBus)==null||d.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}Cs=new WeakSet,ao=function(){this.container.setAttribute("data-internal-link","")},Ey=function(e,s,i=null){e.href=this.linkService.getAnchorUrl(""),s.description&&(e.title=s.description),e.onclick=()=>{var n;return(n=this.downloadManager)==null||n.openOrDownloadData(s.content,s.filename,i),!1},w(this,Cs,ao).call(this)},ky=function(e,s){e.href=this.linkService.getAnchorUrl(""),e.onclick=()=>(this.linkService.executeSetOCGState(s),!1),w(this,Cs,ao).call(this)};class RC extends Kt{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Kr extends Kt{render(){return this.container}showElementAndHideCanvas(t){var e;this.data.hasOwnCanvas&&(((e=t.previousSibling)==null?void 0:e.nodeName)==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Ue.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{var a;(a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{var a;if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&((a=this.linkService.eventBus)==null||a.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}}))})}_setEventListeners(t,e,s,i){var n,r,a;for(const[h,c]of s)(c==="Action"||(n=this.data.actions)!=null&&n[c])&&((c==="Focus"||c==="Blur")&&(e||(e={focused:!1})),this._setEventListener(t,e,h,c,i),c==="Focus"&&!((r=this.data.actions)!=null&&r.Blur)?this._setEventListener(t,e,"blur","Blur",null):c==="Blur"&&!((a=this.data.actions)!=null&&a.Focus)&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":q.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||OC,n=t.style;let r;const a=2,h=c=>Math.round(10*c)/10;if(this.data.multiLine){const c=Math.abs(this.data.rect[3]-this.data.rect[1]-a),u=Math.round(c/(kg*i))||1,d=c/u;r=Math.min(i,h(d/kg))}else{const c=Math.abs(this.data.rect[3]-this.data.rect[1]-a);r=Math.min(i,h(c/kg))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=q.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class FC extends Kr{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){var i,n;const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const r=t.getValue(e,{value:this.data.fieldValue});let a=r.value||"";const h=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;h&&a.length>h&&(a=a.slice(0,h));let c=r.formattedValue||((i=this.data.textContent)==null?void 0:i.join(`
|
|
529
|
-
`))||null;c&&this.data.comb&&(c=c.replaceAll(/\s+/g,""));const u={userValue:a,formattedValue:c,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=c??a,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",c??a),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),qr.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=yl,this._setRequired(s,this.data.required),h&&(s.maxLength=h),s.addEventListener("input",f=>{t.setValue(e,{value:f.target.value}),this.setPropertyOnSiblings(s,"value",f.target.value,"value"),u.formattedValue=null}),s.addEventListener("resetform",f=>{const g=this.data.defaultFieldValue??"";s.value=u.userValue=g,u.formattedValue=null});let d=f=>{const{formattedValue:g}=u;g!=null&&(f.target.value=g),f.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",g=>{var m;if(u.focused)return;const{target:p}=g;u.userValue&&(p.value=u.userValue),u.lastCommittedValue=p.value,u.commitKey=1,(m=this.data.actions)!=null&&m.Focus||(u.focused=!0)}),s.addEventListener("updatefromsandbox",g=>{this.showElementAndHideCanvas(g.target);const p={value(m){u.userValue=m.detail.value??"",t.setValue(e,{value:u.userValue.toString()}),m.target.value=u.userValue},formattedValue(m){const{formattedValue:y}=m.detail;u.formattedValue=y,y!=null&&m.target!==document.activeElement&&(m.target.value=y),t.setValue(e,{formattedValue:y})},selRange(m){m.target.setSelectionRange(...m.detail.selRange)},charLimit:m=>{var S;const{charLimit:y}=m.detail,{target:b}=m;if(y===0){b.removeAttribute("maxLength");return}b.setAttribute("maxLength",y);let x=u.userValue;!x||x.length<=y||(x=x.slice(0,y),b.value=u.userValue=x,t.setValue(e,{value:x}),(S=this.linkService.eventBus)==null||S.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:x,willCommit:!0,commitKey:1,selStart:b.selectionStart,selEnd:b.selectionEnd}}))}};this._dispatchEventFromSandbox(p,g)}),s.addEventListener("keydown",g=>{var y;u.commitKey=1;let p=-1;if(g.key==="Escape"?p=0:g.key==="Enter"&&!this.data.multiLine?p=2:g.key==="Tab"&&(u.commitKey=3),p===-1)return;const{value:m}=g.target;u.lastCommittedValue!==m&&(u.lastCommittedValue=m,u.userValue=m,(y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:m,willCommit:!0,commitKey:p,selStart:g.target.selectionStart,selEnd:g.target.selectionEnd}}))});const f=d;d=null,s.addEventListener("blur",g=>{var m,y;if(!u.focused||!g.relatedTarget)return;(m=this.data.actions)!=null&&m.Blur||(u.focused=!1);const{value:p}=g.target;u.userValue=p,u.lastCommittedValue!==p&&((y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:p,willCommit:!0,commitKey:u.commitKey,selStart:g.target.selectionStart,selEnd:g.target.selectionEnd}})),f(g)}),(n=this.data.actions)!=null&&n.Keystroke&&s.addEventListener("beforeinput",g=>{var k;u.lastCommittedValue=null;const{data:p,target:m}=g,{value:y,selectionStart:b,selectionEnd:x}=m;let S=b,C=x;switch(g.inputType){case"deleteWordBackward":{const O=y.substring(0,b).match(/\w*[^\w]*$/);O&&(S-=O[0].length);break}case"deleteWordForward":{const O=y.substring(b).match(/^[^\w]*\w*/);O&&(C+=O[0].length);break}case"deleteContentBackward":b===x&&(S-=1);break;case"deleteContentForward":b===x&&(C+=1);break}g.preventDefault(),(k=this.linkService.eventBus)==null||k.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:y,change:p||"",willCommit:!1,selStart:S,selEnd:C}})}),this._setEventListeners(s,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],g=>g.target.value)}if(d&&s.addEventListener("blur",d),this.data.comb){const g=(this.data.rect[2]-this.data.rect[0])/h;s.classList.add("comb"),s.style.letterSpacing=`calc(${g}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class LC extends Kr{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class IC extends Kr{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return qr.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=yl,n.addEventListener("change",r=>{const{name:a,checked:h}=r.target;for(const c of this._getElementsByName(a,s)){const u=h&&c.exportValue===e.exportValue;c.domElement&&(c.domElement.checked=u),t.setValue(c.id,{value:u})}t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue||"Off";r.target.checked=a===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const a={value(h){h.target.checked=h.detail.value!=="Off",t.setValue(s,{value:h.target.checked})}};this._dispatchEventFromSandbox(a,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class pb extends Kr{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if(typeof i=="string"&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(qr.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=yl,n.addEventListener("change",r=>{const{name:a,checked:h}=r.target;for(const c of this._getElementsByName(a,s))t.setValue(c.id,{value:!1});t.setValue(s,{value:h})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue;r.target.checked=a!=null&&a===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",a=>{const h={value:c=>{const u=r===c.detail.value;for(const d of this._getElementsByName(c.target.name)){const f=u&&d.id===s;d.domElement&&(d.domElement.checked=f),t.setValue(d.id,{value:f})}}};this._dispatchEventFromSandbox(h,a)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class jC extends gb{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),t}}class NC extends Kr{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");qr.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=yl;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",u=>{const d=this.data.defaultFieldValue;for(const f of i.options)f.selected=f.value===d});for(const u of this.data.options){const d=document.createElement("option");d.textContent=u.displayValue,d.value=u.exportValue,s.value.includes(u.exportValue)&&(d.setAttribute("selected",!0),n=!1),i.append(d)}let r=null;if(n){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),i.prepend(u),r=()=>{u.remove(),i.removeEventListener("input",r),r=null},i.addEventListener("input",r)}const a=u=>{const d=u?"value":"textContent",{options:f,multiple:g}=i;return g?Array.prototype.filter.call(f,p=>p.selected).map(p=>p[d]):f.selectedIndex===-1?null:f[f.selectedIndex][d]};let h=a(!1);const c=u=>{const d=u.target.options;return Array.prototype.map.call(d,f=>({displayValue:f.textContent,exportValue:f.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",u=>{const d={value(f){r==null||r();const g=f.detail.value,p=new Set(Array.isArray(g)?g:[g]);for(const m of i.options)m.selected=p.has(m.value);t.setValue(e,{value:a(!0)}),h=a(!1)},multipleSelection(f){i.multiple=!0},remove(f){const g=i.options,p=f.detail.remove;g[p].selected=!1,i.remove(p),g.length>0&&Array.prototype.findIndex.call(g,y=>y.selected)===-1&&(g[0].selected=!0),t.setValue(e,{value:a(!0),items:c(f)}),h=a(!1)},clear(f){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),h=a(!1)},insert(f){const{index:g,displayValue:p,exportValue:m}=f.detail.insert,y=i.children[g],b=document.createElement("option");b.textContent=p,b.value=m,y?y.before(b):i.append(b),t.setValue(e,{value:a(!0),items:c(f)}),h=a(!1)},items(f){const{items:g}=f.detail;for(;i.length!==0;)i.remove(0);for(const p of g){const{displayValue:m,exportValue:y}=p,b=document.createElement("option");b.textContent=m,b.value=y,i.append(b)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:a(!0),items:c(f)}),h=a(!1)},indices(f){const g=new Set(f.detail.indices);for(const p of f.target.options)p.selected=g.has(p.index);t.setValue(e,{value:a(!0)}),h=a(!1)},editable(f){f.target.disabled=!f.detail.editable}};this._dispatchEventFromSandbox(d,u)}),i.addEventListener("input",u=>{var g;const d=a(!0),f=a(!1);t.setValue(e,{value:d}),u.preventDefault(),(g=this.linkService.eventBus)==null||g.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:h,change:f,changeEx:d,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):i.addEventListener("input",function(u){t.setValue(e,{value:a(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class tp extends Kt{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Kt._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new BC({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const s of this.elements)s.popup=t,s.container.ariaHasPopup="dialog",e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${Fg}${s}`).join(",")),this.container}}class BC{constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:a,parent:h,rect:c,parentRect:u,open:d}){_(this,Tt);_(this,oh,w(this,Tt,Oy).bind(this));_(this,zd,w(this,Tt,Jp).bind(this));_(this,Vd,w(this,Tt,pf).bind(this));_(this,hh,w(this,Tt,gf).bind(this));_(this,Ra,null);_(this,Yt,null);_(this,An,null);_(this,lh,null);_(this,uc,null);_(this,dc,null);_(this,ch,null);_(this,Tn,!1);_(this,di,null);_(this,En,null);_(this,fc,null);_(this,kn,null);_(this,gc,null);_(this,Fa,null);_(this,La,!1);var f;v(this,Yt,t),v(this,gc,i),v(this,An,r),v(this,kn,a),v(this,dc,h),v(this,Ra,e),v(this,fc,c),v(this,ch,u),v(this,uc,s),v(this,lh,jg.toDateObject(n)),this.trigger=s.flatMap(g=>g.getElementsToTriggerPopup());for(const g of this.trigger)g.addEventListener("click",l(this,hh)),g.addEventListener("mouseenter",l(this,Vd)),g.addEventListener("mouseleave",l(this,zd)),g.classList.add("popupTriggerArea");for(const g of s)(f=g.container)==null||f.addEventListener("keydown",l(this,oh));l(this,Yt).hidden=!0,d&&w(this,Tt,gf).call(this)}render(){if(l(this,di))return;const t=v(this,di,document.createElement("div"));if(t.className="popup",l(this,Ra)){const n=t.style.outlineColor=q.makeHexColor(...l(this,Ra));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=q.makeHexColor(...l(this,Ra).map(a=>Math.floor(.7*(255-a)+a)))}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),{dir:s.dir,str:s.textContent}=l(this,gc),t.append(e),l(this,lh)){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:l(this,lh).valueOf()})),e.append(n)}const i=l(this,Tt,ff);if(i)fb.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(l(this,An));t.append(n)}l(this,Yt).append(t)}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let n=0,r=i.length;n<r;++n){const a=i[n];s.append(document.createTextNode(a)),n<r-1&&s.append(document.createElement("br"))}return s}updateEdited({rect:t,popupContent:e}){var s;l(this,Fa)||v(this,Fa,{contentsObj:l(this,An),richText:l(this,kn)}),t&&v(this,En,null),e&&(v(this,kn,w(this,Tt,My).call(this,e)),v(this,An,null)),(s=l(this,di))==null||s.remove(),v(this,di,null)}resetEdited(){var t;l(this,Fa)&&({contentsObj:es(this,An)._,richText:es(this,kn)._}=l(this,Fa),v(this,Fa,null),(t=l(this,di))==null||t.remove(),v(this,di,null),v(this,En,null))}forceHide(){v(this,La,this.isVisible),l(this,La)&&(l(this,Yt).hidden=!0)}maybeShow(){l(this,La)&&(l(this,di)||w(this,Tt,pf).call(this),v(this,La,!1),l(this,Yt).hidden=!1)}get isVisible(){return l(this,Yt).hidden===!1}}oh=new WeakMap,zd=new WeakMap,Vd=new WeakMap,hh=new WeakMap,Ra=new WeakMap,Yt=new WeakMap,An=new WeakMap,lh=new WeakMap,uc=new WeakMap,dc=new WeakMap,ch=new WeakMap,Tn=new WeakMap,di=new WeakMap,En=new WeakMap,fc=new WeakMap,kn=new WeakMap,gc=new WeakMap,Fa=new WeakMap,La=new WeakMap,Tt=new WeakSet,ff=function(){const t=l(this,kn),e=l(this,An);return t!=null&&t.str&&(!(e!=null&&e.str)||e.str===t.str)&&l(this,kn).html||null},Kp=function(){var t,e,s;return((s=(e=(t=l(this,Tt,ff))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.fontSize)||0},Py=function(){var t,e,s;return((s=(e=(t=l(this,Tt,ff))==null?void 0:t.attributes)==null?void 0:e.style)==null?void 0:s.color)||null},My=function(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:l(this,Tt,Py),fontSize:l(this,Tt,Kp)?`calc(${l(this,Tt,Kp)}px * var(--scale-factor))`:""}};for(const n of t.split(`
|
|
530
|
-
`))e.push({name:"span",value:n,attributes:i});return s},Oy=function(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&l(this,Tn))&&w(this,Tt,gf).call(this)},Dy=function(){if(l(this,En)!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=l(this,dc);let r=!!l(this,ch),a=r?l(this,ch):l(this,fc);for(const p of l(this,uc))if(!a||q.intersect(p.data.rect,a)!==null){a=p.data.rect,r=!0;break}const h=q.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),u=r?a[2]-a[0]+5:0,d=h[0]+u,f=h[1];v(this,En,[100*(d-i)/e,100*(f-n)/s]);const{style:g}=l(this,Yt);g.left=`${l(this,En)[0]}%`,g.top=`${l(this,En)[1]}%`},gf=function(){v(this,Tn,!l(this,Tn)),l(this,Tn)?(w(this,Tt,pf).call(this),l(this,Yt).addEventListener("click",l(this,hh)),l(this,Yt).addEventListener("keydown",l(this,oh))):(w(this,Tt,Jp).call(this),l(this,Yt).removeEventListener("click",l(this,hh)),l(this,Yt).removeEventListener("keydown",l(this,oh)))},pf=function(){l(this,di)||this.render(),this.isVisible?l(this,Tn)&&l(this,Yt).classList.add("focused"):(w(this,Tt,Dy).call(this),l(this,Yt).hidden=!1,l(this,Yt).style.zIndex=parseInt(l(this,Yt).style.zIndex)+1e3)},Jp=function(){l(this,Yt).classList.remove("focused"),!(l(this,Tn)||!this.isVisible)&&(l(this,Yt).hidden=!0,l(this,Yt).style.zIndex=parseInt(l(this,Yt).style.zIndex)-1e3)};class mb extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=ot.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class HC extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,pc,null)}render(){this.container.classList.add("lineAnnotation");const e=this.data,{width:s,height:i}=Jn(e.rect),n=this.svgFactory.create(s,i,!0),r=v(this,pc,this.svgFactory.createElement("svg:line"));return r.setAttribute("x1",e.rect[2]-e.lineCoordinates[0]),r.setAttribute("y1",e.rect[3]-e.lineCoordinates[1]),r.setAttribute("x2",e.rect[2]-e.lineCoordinates[2]),r.setAttribute("y2",e.rect[3]-e.lineCoordinates[3]),r.setAttribute("stroke-width",e.borderStyle.width||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),n.append(r),this.container.append(n),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return l(this,pc)}addHighlightArea(){this.container.classList.add("highlightArea")}}pc=new WeakMap;class zC extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,mc,null)}render(){this.container.classList.add("squareAnnotation");const e=this.data,{width:s,height:i}=Jn(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,a=v(this,mc,this.svgFactory.createElement("svg:rect"));return a.setAttribute("x",r/2),a.setAttribute("y",r/2),a.setAttribute("width",s-r),a.setAttribute("height",i-r),a.setAttribute("stroke-width",r||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),n.append(a),this.container.append(n),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return l(this,mc)}addHighlightArea(){this.container.classList.add("highlightArea")}}mc=new WeakMap;class VC extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,vc,null)}render(){this.container.classList.add("circleAnnotation");const e=this.data,{width:s,height:i}=Jn(e.rect),n=this.svgFactory.create(s,i,!0),r=e.borderStyle.width,a=v(this,vc,this.svgFactory.createElement("svg:ellipse"));return a.setAttribute("cx",s/2),a.setAttribute("cy",i/2),a.setAttribute("rx",s/2-r/2),a.setAttribute("ry",i/2-r/2),a.setAttribute("stroke-width",r||1),a.setAttribute("stroke","transparent"),a.setAttribute("fill","transparent"),n.append(a),this.container.append(n),!e.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return l(this,vc)}addHighlightArea(){this.container.classList.add("highlightArea")}}vc=new WeakMap;class vb extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,bc,null);this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,vertices:s,borderStyle:i,popupRef:n}}=this;if(!s)return this.container;const{width:r,height:a}=Jn(e),h=this.svgFactory.create(r,a,!0);let c=[];for(let d=0,f=s.length;d<f;d+=2){const g=s[d]-e[0],p=e[3]-s[d+1];c.push(`${g},${p}`)}c=c.join(" ");const u=v(this,bc,this.svgFactory.createElement(this.svgElementName));return u.setAttribute("points",c),u.setAttribute("stroke-width",i.width||1),u.setAttribute("stroke","transparent"),u.setAttribute("fill","transparent"),h.append(u),this.container.append(h),!n&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return l(this,bc)}addHighlightArea(){this.container.classList.add("highlightArea")}}bc=new WeakMap;class WC extends vb{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class GC extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class ep extends Kt{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0});_(this,_c);_(this,yc,null);_(this,Ia,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?ot.HIGHLIGHT:ot.INK}render(){this.container.classList.add(this.containerClassName);const{data:{rect:e,rotation:s,inkLists:i,borderStyle:n,popupRef:r}}=this,{transform:a,width:h,height:c}=w(this,_c,Qp).call(this,s,e),u=this.svgFactory.create(h,c,!0),d=v(this,yc,this.svgFactory.createElement("svg:g"));u.append(d),d.setAttribute("stroke-width",n.width||1),d.setAttribute("stroke-linecap","round"),d.setAttribute("stroke-linejoin","round"),d.setAttribute("stroke-miterlimit",10),d.setAttribute("stroke","transparent"),d.setAttribute("fill","transparent"),d.setAttribute("transform",a);for(let f=0,g=i.length;f<g;f++){const p=this.svgFactory.createElement(this.svgElementName);l(this,Ia).push(p),p.setAttribute("points",i[f].join(",")),d.append(p)}return!r&&this.hasPopupData&&this._createPopup(),this.container.append(u),this._editOnDoubleClick(),this.container}updateEdited(e){super.updateEdited(e);const{thickness:s,points:i,rect:n}=e,r=l(this,yc);if(s>=0&&r.setAttribute("stroke-width",s||1),i)for(let a=0,h=l(this,Ia).length;a<h;a++)l(this,Ia)[a].setAttribute("points",i[a].join(","));if(n){const{transform:a,width:h,height:c}=w(this,_c,Qp).call(this,this.data.rotation,n);r.parentElement.setAttribute("viewBox",`0 0 ${h} ${c}`),r.setAttribute("transform",a)}}getElementsToTriggerPopup(){return l(this,Ia)}addHighlightArea(){this.container.classList.add("highlightArea")}}yc=new WeakMap,Ia=new WeakMap,_c=new WeakSet,Qp=function(e,s){switch(e){case 90:return{transform:`rotate(90) translate(${-s[0]},${s[1]}) scale(1,-1)`,width:s[3]-s[1],height:s[2]-s[0]};case 180:return{transform:`rotate(180) translate(${-s[2]},${s[1]}) scale(1,-1)`,width:s[2]-s[0],height:s[3]-s[1]};case 270:return{transform:`rotate(270) translate(${-s[2]},${s[3]}) scale(1,-1)`,width:s[3]-s[1],height:s[2]-s[0]};default:return{transform:`translate(${-s[0]},${s[3]}) scale(1,-1)`,width:s[2]-s[0],height:s[3]-s[1]}}};class bb extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=ot.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class XC extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class UC extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class YC extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class yb extends Kt{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=ot.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class $C extends Kt{constructor(e){var i;super(e,{isRenderable:!0});_(this,xc);_(this,wc,null);const{file:s}=this.data;this.filename=s.filename,this.content=s.content,(i=this.linkService.eventBus)==null||i.dispatch("fileattachmentannotation",{source:this,...s})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:e,data:s}=this;let i;s.hasAppearance||s.fillAlpha===0?i=document.createElement("div"):(i=document.createElement("img"),i.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(s.name)?"paperclip":"pushpin"}.svg`,s.fillAlpha&&s.fillAlpha<1&&(i.style=`filter: opacity(${Math.round(s.fillAlpha*100)}%);`)),i.addEventListener("dblclick",w(this,xc,Zp).bind(this)),v(this,wc,i);const{isMac:n}=Ue.platform;return e.addEventListener("keydown",r=>{r.key==="Enter"&&(n?r.metaKey:r.ctrlKey)&&w(this,xc,Zp).call(this)}),!s.popupRef&&this.hasPopupData?this._createPopup():i.classList.add("popupTriggerArea"),e.append(i),e}getElementsToTriggerPopup(){return l(this,wc)}addHighlightArea(){this.container.classList.add("highlightArea")}}wc=new WeakMap,xc=new WeakSet,Zp=function(){var e;(e=this.downloadManager)==null||e.openOrDownloadData(this.content,this.filename)};class qC{constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:a}){_(this,Ba);_(this,Sc,null);_(this,ja,null);_(this,Na,new Map);_(this,Cc,null);this.div=t,v(this,Sc,e),v(this,ja,s),v(this,Cc,a||null),this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return l(this,Na).size>0}async render(t){var r;const{annotations:e}=t,s=this.div;Yr(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new Zg,annotationStorage:t.annotationStorage||new Gg,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const a of e){if(a.noHTML)continue;const h=a.annotationType===le.POPUP;if(h){const d=i.get(a.id);if(!d)continue;n.elements=d}else{const{width:d,height:f}=Jn(a.rect);if(d<=0||f<=0)continue}n.data=a;const c=DC.create(n);if(!c.isRenderable)continue;if(!h&&a.popupRef){const d=i.get(a.popupRef);d?d.push(c):i.set(a.popupRef,[c])}const u=c.render();a.hidden&&(u.style.visibility="hidden"),await w(this,Ba,Ry).call(this,u,a.id),c._isEditable&&(l(this,Na).set(c.data.id,c),(r=this._annotationEditorUIManager)==null||r.renderAnnotationElement(c))}w(this,Ba,tm).call(this)}update({viewport:t}){const e=this.div;this.viewport=t,Yr(e,{rotation:t.rotation}),w(this,Ba,tm).call(this),e.hidden=!1}getEditableAnnotations(){return Array.from(l(this,Na).values())}getEditableAnnotation(t){return l(this,Na).get(t)}}Sc=new WeakMap,ja=new WeakMap,Na=new WeakMap,Cc=new WeakMap,Ba=new WeakSet,Ry=async function(t,e){var r,a;const s=t.firstChild||t,i=s.id=`${Fg}${e}`,n=await((r=l(this,Cc))==null?void 0:r.getAriaAttributes(i));if(n)for(const[h,c]of n)s.setAttribute(h,c);this.div.append(t),(a=l(this,Sc))==null||a.moveElementInDOM(this.div,t,s,!1)},tm=function(){if(!l(this,ja))return;const t=this.div;for(const[e,s]of l(this,ja)){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}l(this,ja).clear()};const Cd=/\r\n?|\n/g,Mt=class Mt extends Vt{constructor(e){super({...e,name:"freeTextEditor"});_(this,re);_(this,fi);_(this,As,"");_(this,Ac,`${this.id}-editor`);_(this,Ha,null);_(this,Ts);v(this,fi,e.color||Mt._defaultColor||Vt._defaultLineColor),v(this,Ts,e.fontSize||Mt._defaultFontSize)}static get _keyboardManager(){const e=Mt.prototype,s=r=>r.isEmpty(),i=$r.TRANSLATE_SMALL,n=$r.TRANSLATE_BIG;return ct(this,"_keyboardManager",new dl([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],e.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],e.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],e._translateEmpty,{args:[-i,0],checker:s}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],e._translateEmpty,{args:[-n,0],checker:s}],[["ArrowRight","mac+ArrowRight"],e._translateEmpty,{args:[i,0],checker:s}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],e._translateEmpty,{args:[n,0],checker:s}],[["ArrowUp","mac+ArrowUp"],e._translateEmpty,{args:[0,-i],checker:s}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],e._translateEmpty,{args:[0,-n],checker:s}],[["ArrowDown","mac+ArrowDown"],e._translateEmpty,{args:[0,i],checker:s}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],e._translateEmpty,{args:[0,n],checker:s}]]))}static initialize(e,s){Vt.initialize(e,s);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(e,s){switch(e){case gt.FREETEXT_SIZE:Mt._defaultFontSize=s;break;case gt.FREETEXT_COLOR:Mt._defaultColor=s;break}}updateParams(e,s){switch(e){case gt.FREETEXT_SIZE:w(this,re,Fy).call(this,s);break;case gt.FREETEXT_COLOR:w(this,re,Ly).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[gt.FREETEXT_SIZE,Mt._defaultFontSize],[gt.FREETEXT_COLOR,Mt._defaultColor||Vt._defaultLineColor]]}get propertiesToUpdate(){return[[gt.FREETEXT_SIZE,l(this,Ts)],[gt.FREETEXT_COLOR,l(this,fi)]]}_translateEmpty(e,s){this._uiManager.translateSelectedEditors(e,s,!0)}getInitialTranslation(){const e=this.parentScale;return[-Mt._internalPadding*e,-(Mt._internalPadding+l(this,Ts))*e]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(ot.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),v(this,Ha,new AbortController);const e=this._uiManager.combinedSignal(l(this,Ha));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:e}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:e}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:e}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:e}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:e})}disableEditMode(){var e;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",l(this,Ac)),this._isDraggable=!0,(e=l(this,Ha))==null||e.abort(),v(this,Ha,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(e){this._focusEventsAllowed&&(super.focusin(e),e.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(e){var s;this.width||(this.enableEditMode(),e&&this.editorDiv.focus(),(s=this._initialOptions)!=null&&s.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const e=l(this,As),s=v(this,As,w(this,re,Iy).call(this).trimEnd());if(e===s)return;const i=n=>{if(v(this,As,n),!n){this.remove();return}w(this,re,bf).call(this),this._uiManager.rebuild(this),w(this,re,mf).call(this)};this.addCommands({cmd:()=>{i(s)},undo:()=>{i(e)},mustExec:!1}),w(this,re,mf).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(e){this.enterInEditMode()}keydown(e){e.target===this.div&&e.key==="Enter"&&(this.enterInEditMode(),e.preventDefault())}editorDivKeydown(e){Mt._keyboardManager.exec(this,e)}editorDivFocus(e){this.isEditing=!0}editorDivBlur(e){this.isEditing=!1}editorDivInput(e){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let e,s;this.width&&(e=this.x,s=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",l(this,Ac)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:i}=this.editorDiv;if(i.fontSize=`calc(${l(this,Ts)}px * var(--scale-factor))`,i.color=l(this,fi),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),md(this,this.div,["dblclick","keydown"]),this.width){const[n,r]=this.parentDimensions;if(this.annotationElementId){const{position:a}=this._initialData;let[h,c]=this.getInitialTranslation();[h,c]=this.pageTranslationToScreen(h,c);const[u,d]=this.pageDimensions,[f,g]=this.pageTranslation;let p,m;switch(this.rotation){case 0:p=e+(a[0]-f)/u,m=s+this.height-(a[1]-g)/d;break;case 90:p=e+(a[0]-f)/u,m=s-(a[1]-g)/d,[h,c]=[c,-h];break;case 180:p=e-this.width+(a[0]-f)/u,m=s-(a[1]-g)/d,[h,c]=[-h,-c];break;case 270:p=e+(a[0]-f-this.height*d)/u,m=s+(a[1]-g-this.width*u)/d,[h,c]=[-c,h];break}this.setAt(p*n,m*r,h,c)}else this.setAt(e*n,s*r,this.width*n,this.height*r);w(this,re,bf).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(e){var p,m,y;const s=e.clipboardData||window.clipboardData,{types:i}=s;if(i.length===1&&i[0]==="text/plain")return;e.preventDefault();const n=w(p=Mt,Pn,em).call(p,s.getData("text")||"").replaceAll(Cd,`
|
|
531
|
-
`);if(
|
|
532
|
-
`)
|
|
533
|
-
`)
|
|
534
|
-
`)}
|
|
535
|
-
`)
|
|
536
|
-
`)){const
|
|
537
|
-
`)
|
|
538
|
-
`)){const s=document.createElement("div");s.append(e?document.createTextNode(e):document.createElement("br")),this.editorDiv.append(s)}},jy=function(){return l(this,As).replaceAll(" "," ")},em=function(e){return e.replaceAll(" "," ")},Ny=function(e){const{value:s,fontSize:i,color:n,pageIndex:r}=this._initialData;return this._hasBeenMoved||e.value!==s||e.fontSize!==i||e.color.some((a,h)=>a!==n[h])||e.pageIndex!==r},_(Mt,Pn),Q(Mt,"_freeTextDefaultContent",""),Q(Mt,"_internalPadding",0),Q(Mt,"_defaultColor",null),Q(Mt,"_defaultFontSize",10),Q(Mt,"_type","freetext"),Q(Mt,"_editorType",ot.FREETEXT);let sp=Mt;class U{toSVGPath(){kt("Abstract method `toSVGPath` must be implemented.")}get box(){kt("Abstract getter `box` must be implemented.")}serialize(t,e){kt("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||(r=new Float32Array(t.length));for(let a=0,h=t.length;a<h;a+=2)r[a]=e+t[a]*i,r[a+1]=s+t[a+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||(r=new Float32Array(t.length));for(let a=0,h=t.length;a<h;a+=2)r[a]=e+t[a+1]*i,r[a+1]=s+t[a]*n;return r}static _translate(t,e,s,i){i||(i=new Float32Array(t.length));for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}Q(U,"PRECISION",1e-4);const Mn=class Mn{constructor({x:t,y:e},s,i,n,r,a=0){_(this,de);_(this,Es);_(this,gi,[]);_(this,uh);_(this,dh);_(this,Bi,[]);_(this,ut,new Float32Array(18));_(this,za);_(this,Va);_(this,Tc);_(this,Ec);_(this,fh);_(this,gh);_(this,br,[]);v(this,Es,s),v(this,gh,n*i),v(this,dh,r),l(this,ut).set([NaN,NaN,NaN,NaN,t,e],6),v(this,uh,a),v(this,Ec,l(Mn,kc)*i),v(this,Tc,l(Mn,Gd)*i),v(this,fh,i),l(this,br).push(t,e)}isEmpty(){return isNaN(l(this,ut)[8])}add({x:t,y:e}){var R;v(this,za,t),v(this,Va,e);const[s,i,n,r]=l(this,Es);let[a,h,c,u]=l(this,ut).subarray(8,12);const d=t-c,f=e-u,g=Math.hypot(d,f);if(g<l(this,Tc))return!1;const p=g-l(this,Ec),m=p/g,y=m*d,b=m*f;let x=a,S=h;a=c,h=u,c+=y,u+=b,(R=l(this,br))==null||R.push(t,e);const C=-b/p,k=y/p,O=C*l(this,gh),P=k*l(this,gh);return l(this,ut).set(l(this,ut).subarray(2,8),0),l(this,ut).set([c+O,u+P],4),l(this,ut).set(l(this,ut).subarray(14,18),12),l(this,ut).set([c-O,u-P],16),isNaN(l(this,ut)[6])?(l(this,Bi).length===0&&(l(this,ut).set([a+O,h+P],2),l(this,Bi).push(NaN,NaN,NaN,NaN,(a+O-s)/n,(h+P-i)/r),l(this,ut).set([a-O,h-P],14),l(this,gi).push(NaN,NaN,NaN,NaN,(a-O-s)/n,(h-P-i)/r)),l(this,ut).set([x,S,a,h,c,u],6),!this.isEmpty()):(l(this,ut).set([x,S,a,h,c,u],6),Math.abs(Math.atan2(S-h,x-a)-Math.atan2(b,y))<Math.PI/2?([a,h,c,u]=l(this,ut).subarray(2,6),l(this,Bi).push(NaN,NaN,NaN,NaN,((a+c)/2-s)/n,((h+u)/2-i)/r),[a,h,x,S]=l(this,ut).subarray(14,18),l(this,gi).push(NaN,NaN,NaN,NaN,((x+a)/2-s)/n,((S+h)/2-i)/r),!0):([x,S,a,h,c,u]=l(this,ut).subarray(0,6),l(this,Bi).push(((x+5*a)/6-s)/n,((S+5*h)/6-i)/r,((5*a+c)/6-s)/n,((5*h+u)/6-i)/r,((a+c)/2-s)/n,((h+u)/2-i)/r),[c,u,a,h,x,S]=l(this,ut).subarray(12,18),l(this,gi).push(((x+5*a)/6-s)/n,((S+5*h)/6-i)/r,((5*a+c)/6-s)/n,((5*h+u)/6-i)/r,((a+c)/2-s)/n,((h+u)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=l(this,Bi),e=l(this,gi);if(isNaN(l(this,ut)[6])&&!this.isEmpty())return w(this,de,By).call(this);const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);w(this,de,zy).call(this,s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return w(this,de,Hy).call(this,s),s.join(" ")}newFreeDrawOutline(t,e,s,i,n,r){return new _b(t,e,s,i,n,r)}getOutlines(){var d;const t=l(this,Bi),e=l(this,gi),s=l(this,ut),[i,n,r,a]=l(this,Es),h=new Float32Array((((d=l(this,br))==null?void 0:d.length)??0)+2);for(let f=0,g=h.length-2;f<g;f+=2)h[f]=(l(this,br)[f]-i)/r,h[f+1]=(l(this,br)[f+1]-n)/a;if(h[h.length-2]=(l(this,za)-i)/r,h[h.length-1]=(l(this,Va)-n)/a,isNaN(s[6])&&!this.isEmpty())return w(this,de,Vy).call(this,h);const c=new Float32Array(l(this,Bi).length+24+l(this,gi).length);let u=t.length;for(let f=0;f<u;f+=2){if(isNaN(t[f])){c[f]=c[f+1]=NaN;continue}c[f]=t[f],c[f+1]=t[f+1]}u=w(this,de,Gy).call(this,c,u);for(let f=e.length-6;f>=6;f-=6)for(let g=0;g<6;g+=2){if(isNaN(e[f+g])){c[u]=c[u+1]=NaN,u+=2;continue}c[u]=e[f+g],c[u+1]=e[f+g+1],u+=2}return w(this,de,Wy).call(this,c,u),this.newFreeDrawOutline(c,h,l(this,Es),l(this,fh),l(this,uh),l(this,dh))}};Es=new WeakMap,gi=new WeakMap,uh=new WeakMap,dh=new WeakMap,Bi=new WeakMap,ut=new WeakMap,za=new WeakMap,Va=new WeakMap,Tc=new WeakMap,Ec=new WeakMap,fh=new WeakMap,gh=new WeakMap,br=new WeakMap,kc=new WeakMap,Wd=new WeakMap,Gd=new WeakMap,de=new WeakSet,eu=function(){const t=l(this,ut).subarray(4,6),e=l(this,ut).subarray(16,18),[s,i,n,r]=l(this,Es);return[(l(this,za)+(t[0]-e[0])/2-s)/n,(l(this,Va)+(t[1]-e[1])/2-i)/r,(l(this,za)+(e[0]-t[0])/2-s)/n,(l(this,Va)+(e[1]-t[1])/2-i)/r]},By=function(){const[t,e,s,i]=l(this,Es),[n,r,a,h]=w(this,de,eu).call(this);return`M${(l(this,ut)[2]-t)/s} ${(l(this,ut)[3]-e)/i} L${(l(this,ut)[4]-t)/s} ${(l(this,ut)[5]-e)/i} L${n} ${r} L${a} ${h} L${(l(this,ut)[16]-t)/s} ${(l(this,ut)[17]-e)/i} L${(l(this,ut)[14]-t)/s} ${(l(this,ut)[15]-e)/i} Z`},Hy=function(t){const e=l(this,gi);t.push(`L${e[4]} ${e[5]} Z`)},zy=function(t){const[e,s,i,n]=l(this,Es),r=l(this,ut).subarray(4,6),a=l(this,ut).subarray(16,18),[h,c,u,d]=w(this,de,eu).call(this);t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${h} ${c} L${u} ${d} L${(a[0]-e)/i} ${(a[1]-s)/n}`)},Vy=function(t){const e=l(this,ut),[s,i,n,r]=l(this,Es),[a,h,c,u]=w(this,de,eu).call(this),d=new Float32Array(36);return d.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,a,h,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(d,t,l(this,Es),l(this,fh),l(this,uh),l(this,dh))},Wy=function(t,e){const s=l(this,gi);return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6},Gy=function(t,e){const s=l(this,ut).subarray(4,6),i=l(this,ut).subarray(16,18),[n,r,a,h]=l(this,Es),[c,u,d,f]=w(this,de,eu).call(this);return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/h,NaN,NaN,NaN,NaN,c,u,NaN,NaN,NaN,NaN,d,f,NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/h],e),e+=24},_(Mn,kc,8),_(Mn,Wd,2),_(Mn,Gd,l(Mn,kc)+l(Mn,Wd));let Ad=Mn;class _b extends U{constructor(e,s,i,n,r,a){super();_(this,Xd);_(this,ph);_(this,Wa,new Float32Array(4));_(this,On);_(this,Pc);_(this,ks);_(this,Mc);_(this,Qt);v(this,Qt,e),v(this,ks,s),v(this,ph,i),v(this,Mc,n),v(this,On,r),v(this,Pc,a),this.lastPoint=[NaN,NaN],w(this,Xd,Xy).call(this,a);const[h,c,u,d]=l(this,Wa);for(let f=0,g=e.length;f<g;f+=2)e[f]=(e[f]-h)/u,e[f+1]=(e[f+1]-c)/d;for(let f=0,g=s.length;f<g;f+=2)s[f]=(s[f]-h)/u,s[f+1]=(s[f+1]-c)/d}toSVGPath(){const e=[`M${l(this,Qt)[4]} ${l(this,Qt)[5]}`];for(let s=6,i=l(this,Qt).length;s<i;s+=6){if(isNaN(l(this,Qt)[s])){e.push(`L${l(this,Qt)[s+4]} ${l(this,Qt)[s+5]}`);continue}e.push(`C${l(this,Qt)[s]} ${l(this,Qt)[s+1]} ${l(this,Qt)[s+2]} ${l(this,Qt)[s+3]} ${l(this,Qt)[s+4]} ${l(this,Qt)[s+5]}`)}return e.push("Z"),e.join(" ")}serialize([e,s,i,n],r){const a=i-e,h=n-s;let c,u;switch(r){case 0:c=U._rescale(l(this,Qt),e,n,a,-h),u=U._rescale(l(this,ks),e,n,a,-h);break;case 90:c=U._rescaleAndSwap(l(this,Qt),e,s,a,h),u=U._rescaleAndSwap(l(this,ks),e,s,a,h);break;case 180:c=U._rescale(l(this,Qt),i,s,-a,h),u=U._rescale(l(this,ks),i,s,-a,h);break;case 270:c=U._rescaleAndSwap(l(this,Qt),i,n,-a,-h),u=U._rescaleAndSwap(l(this,ks),i,n,-a,-h);break}return{outline:Array.from(c),points:[Array.from(u)]}}get box(){return l(this,Wa)}newOutliner(e,s,i,n,r,a=0){return new Ad(e,s,i,n,r,a)}getNewOutline(e,s){const[i,n,r,a]=l(this,Wa),[h,c,u,d]=l(this,ph),f=r*u,g=a*d,p=i*u+h,m=n*d+c,y=this.newOutliner({x:l(this,ks)[0]*f+p,y:l(this,ks)[1]*g+m},l(this,ph),l(this,Mc),e,l(this,Pc),s??l(this,On));for(let b=2;b<l(this,ks).length;b+=2)y.add({x:l(this,ks)[b]*f+p,y:l(this,ks)[b+1]*g+m});return y.getOutlines()}}ph=new WeakMap,Wa=new WeakMap,On=new WeakMap,Pc=new WeakMap,ks=new WeakMap,Mc=new WeakMap,Qt=new WeakMap,Xd=new WeakSet,Xy=function(e){const s=l(this,Qt);let i=s[4],n=s[5],r=i,a=n,h=i,c=n,u=i,d=n;const f=e?Math.max:Math.min;for(let p=6,m=s.length;p<m;p+=6){if(isNaN(s[p]))r=Math.min(r,s[p+4]),a=Math.min(a,s[p+5]),h=Math.max(h,s[p+4]),c=Math.max(c,s[p+5]),d<s[p+5]?(u=s[p+4],d=s[p+5]):d===s[p+5]&&(u=f(u,s[p+4]));else{const y=q.bezierBoundingBox(i,n,...s.slice(p,p+6));r=Math.min(r,y[0]),a=Math.min(a,y[1]),h=Math.max(h,y[2]),c=Math.max(c,y[3]),d<y[3]?(u=y[2],d=y[3]):d===y[3]&&(u=f(u,y[2]))}i=s[p+4],n=s[p+5]}const g=l(this,Wa);g[0]=r-l(this,On),g[1]=a-l(this,On),g[2]=h-r+2*l(this,On),g[3]=c-a+2*l(this,On),this.lastPoint=[u,d]};class ip{constructor(t,e=0,s=0,i=!0){_(this,qe);_(this,Oc);_(this,Dc);_(this,yr,[]);_(this,pi,[]);let n=1/0,r=-1/0,a=1/0,h=-1/0;const c=10**-4;for(const{x:y,y:b,width:x,height:S}of t){const C=Math.floor((y-e)/c)*c,k=Math.ceil((y+x+e)/c)*c,O=Math.floor((b-e)/c)*c,P=Math.ceil((b+S+e)/c)*c,D=[C,O,P,!0],R=[k,O,P,!1];l(this,yr).push(D,R),n=Math.min(n,C),r=Math.max(r,k),a=Math.min(a,O),h=Math.max(h,P)}const u=r-n+2*s,d=h-a+2*s,f=n-s,g=a-s,p=l(this,yr).at(i?-1:-2),m=[p[0],p[2]];for(const y of l(this,yr)){const[b,x,S]=y;y[0]=(b-f)/u,y[1]=(x-g)/d,y[2]=(S-g)/d}v(this,Oc,new Float32Array([f,g,u,d])),v(this,Dc,m)}getOutlines(){l(this,yr).sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of l(this,yr))e[3]?(t.push(...w(this,qe,sm).call(this,e)),w(this,qe,Yy).call(this,e)):(w(this,qe,$y).call(this,e),t.push(...w(this,qe,sm).call(this,e)));return w(this,qe,Uy).call(this,t)}}Oc=new WeakMap,Dc=new WeakMap,yr=new WeakMap,pi=new WeakMap,qe=new WeakSet,Uy=function(t){const e=[],s=new Set;for(const r of t){const[a,h,c]=r;e.push([a,h,r],[a,c,r])}e.sort((r,a)=>r[1]-a[1]||r[0]-a[0]);for(let r=0,a=e.length;r<a;r+=2){const h=e[r][2],c=e[r+1][2];h.push(c),c.push(h),s.add(h),s.add(c)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[a,h,c,u,d]=r;s.delete(r);let f=a,g=h;for(n=[a,c],i.push(n);;){let p;if(s.has(u))p=u;else if(s.has(d))p=d;else break;s.delete(p),[a,h,c,u,d]=p,f!==a&&(n.push(f,g,a,g===h?h:c),f=a),g=g===h?c:h}n.push(f,g)}return new KC(i,l(this,Oc),l(this,Dc))},yf=function(t){const e=l(this,pi);let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1},Yy=function([,t,e]){const s=w(this,qe,yf).call(this,t);l(this,pi).splice(s,0,[t,e])},$y=function([,t,e]){const s=w(this,qe,yf).call(this,t);for(let i=s;i<l(this,pi).length;i++){const[n,r]=l(this,pi)[i];if(n!==t)break;if(n===t&&r===e){l(this,pi).splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=l(this,pi)[i];if(n!==t)break;if(n===t&&r===e){l(this,pi).splice(i,1);return}}},sm=function(t){const[e,s,i]=t,n=[[e,s,i]],r=w(this,qe,yf).call(this,i);for(let a=0;a<r;a++){const[h,c]=l(this,pi)[a];for(let u=0,d=n.length;u<d;u++){const[,f,g]=n[u];if(!(c<=f||g<=h)){if(f>=h){if(g>c)n[u][1]=c;else{if(d===1)return[];n.splice(u,1),u--,d--}continue}n[u][2]=h,g>c&&n.push([e,c,g])}}}return n};class KC extends U{constructor(e,s,i){super();_(this,Rc);_(this,mh);v(this,mh,e),v(this,Rc,s),this.lastPoint=i}toSVGPath(){const e=[];for(const s of l(this,mh)){let[i,n]=s;e.push(`M${i} ${n}`);for(let r=2;r<s.length;r+=2){const a=s[r],h=s[r+1];a===i?(e.push(`V${h}`),n=h):h===n&&(e.push(`H${a}`),i=a)}e.push("Z")}return e.join(" ")}serialize([e,s,i,n],r){const a=[],h=i-e,c=n-s;for(const u of l(this,mh)){const d=new Array(u.length);for(let f=0;f<u.length;f+=2)d[f]=e+u[f]*h,d[f+1]=n-u[f+1]*c;a.push(d)}return a}get box(){return l(this,Rc)}get classNamesForOutlining(){return["highlightOutline"]}}Rc=new WeakMap,mh=new WeakMap;class np extends Ad{newFreeDrawOutline(t,e,s,i,n,r){return new JC(t,e,s,i,n,r)}}class JC extends _b{newOutliner(t,e,s,i,n,r=0){return new np(t,e,s,i,n,r)}}const us=class us{constructor({editor:t=null,uiManager:e=null}){_(this,Et);_(this,mi,null);_(this,Ga,null);_(this,vh);_(this,fe,null);_(this,Fc,!1);_(this,bh,!1);_(this,Lc,null);_(this,Ic);_(this,_r,null);_(this,vi,null);_(this,yh);var s;t?(v(this,bh,!1),v(this,yh,gt.HIGHLIGHT_COLOR),v(this,Lc,t)):(v(this,bh,!0),v(this,yh,gt.HIGHLIGHT_DEFAULT_COLOR)),v(this,vi,(t==null?void 0:t._uiManager)||e),v(this,Ic,l(this,vi)._eventBus),v(this,vh,(t==null?void 0:t.color)||((s=l(this,vi))==null?void 0:s.highlightColors.values().next().value)||"#FFFF98"),l(us,jc)||v(us,jc,Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"}))}static get _keyboardManager(){return ct(this,"_keyboardManager",new dl([[["Escape","mac+Escape"],us.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],us.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],us.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],us.prototype._moveToPrevious],[["Home","mac+Home"],us.prototype._moveToBeginning],[["End","mac+End"],us.prototype._moveToEnd]]))}renderButton(){const t=v(this,mi,document.createElement("button"));t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=l(this,vi)._signal;t.addEventListener("click",w(this,Et,oo).bind(this),{signal:e}),t.addEventListener("keydown",w(this,Et,rm).bind(this),{signal:e});const s=v(this,Ga,document.createElement("span"));return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=l(this,vh),t.append(s),t}renderMainDropdown(){const t=v(this,fe,w(this,Et,im).call(this));return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}_colorSelectFromKeyboard(t){if(t.target===l(this,mi)){w(this,Et,oo).call(this,t);return}const e=t.target.getAttribute("data-color");e&&w(this,Et,nm).call(this,e,t)}_moveToNext(t){var e,s;if(!l(this,Et,Or)){w(this,Et,oo).call(this,t);return}if(t.target===l(this,mi)){(e=l(this,fe).firstChild)==null||e.focus();return}(s=t.target.nextSibling)==null||s.focus()}_moveToPrevious(t){var e,s;if(t.target===((e=l(this,fe))==null?void 0:e.firstChild)||t.target===l(this,mi)){l(this,Et,Or)&&this._hideDropdownFromKeyboard();return}l(this,Et,Or)||w(this,Et,oo).call(this,t),(s=t.target.previousSibling)==null||s.focus()}_moveToBeginning(t){var e;if(!l(this,Et,Or)){w(this,Et,oo).call(this,t);return}(e=l(this,fe).firstChild)==null||e.focus()}_moveToEnd(t){var e;if(!l(this,Et,Or)){w(this,Et,oo).call(this,t);return}(e=l(this,fe).lastChild)==null||e.focus()}hideDropdown(){var t,e;(t=l(this,fe))==null||t.classList.add("hidden"),(e=l(this,_r))==null||e.abort(),v(this,_r,null)}_hideDropdownFromKeyboard(){var t;if(!l(this,bh)){if(!l(this,Et,Or)){(t=l(this,Lc))==null||t.unselect();return}this.hideDropdown(),l(this,mi).focus({preventScroll:!0,focusVisible:l(this,Fc)})}}updateColor(t){if(l(this,Ga)&&(l(this,Ga).style.backgroundColor=t),!l(this,fe))return;const e=l(this,vi).highlightColors.values();for(const s of l(this,fe).children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){var t,e;(t=l(this,mi))==null||t.remove(),v(this,mi,null),v(this,Ga,null),(e=l(this,fe))==null||e.remove(),v(this,fe,null)}};mi=new WeakMap,Ga=new WeakMap,vh=new WeakMap,fe=new WeakMap,Fc=new WeakMap,bh=new WeakMap,Lc=new WeakMap,Ic=new WeakMap,_r=new WeakMap,vi=new WeakMap,yh=new WeakMap,jc=new WeakMap,Et=new WeakSet,im=function(){const t=document.createElement("div"),e=l(this,vi)._signal;t.addEventListener("contextmenu",ri,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of l(this,vi).highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",l(us,jc)[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===l(this,vh)),n.addEventListener("click",w(this,Et,nm).bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",w(this,Et,rm).bind(this),{signal:e}),t},nm=function(t,e){e.stopPropagation(),l(this,Ic).dispatch("switchannotationeditorparams",{source:this,type:l(this,yh),value:t})},rm=function(t){us._keyboardManager.exec(this,t)},oo=function(t){if(l(this,Et,Or)){this.hideDropdown();return}if(v(this,Fc,t.detail===0),l(this,_r)||(v(this,_r,new AbortController),window.addEventListener("pointerdown",w(this,Et,qy).bind(this),{signal:l(this,vi).combinedSignal(l(this,_r))})),l(this,fe)){l(this,fe).classList.remove("hidden");return}const e=v(this,fe,w(this,Et,im).call(this));l(this,mi).append(e)},qy=function(t){var e;(e=l(this,fe))!=null&&e.contains(t.target)||this.hideDropdown()},Or=function(){return l(this,fe)&&!l(this,fe).classList.contains("hidden")},_(us,jc,null);let Td=us;const yt=class yt extends Vt{constructor(e){super({...e,name:"highlightEditor"});_(this,at);_(this,_h,null);_(this,Nc,0);_(this,Dn);_(this,Xa,null);_(this,wh,null);_(this,ds,null);_(this,Bc,null);_(this,Hc,0);_(this,Ua,null);_(this,Ws,null);_(this,Ps,null);_(this,xe,!1);_(this,xh,null);_(this,Rn);_(this,Ie,null);_(this,Sh,"");_(this,Gs);_(this,zc,"");this.color=e.color||yt._defaultColor,v(this,Gs,e.thickness||yt._defaultThickness),v(this,Rn,e.opacity||yt._defaultOpacity),v(this,Dn,e.boxes||null),v(this,zc,e.methodOfCreation||""),v(this,Sh,e.text||""),this._isDraggable=!1,e.highlightId>-1?(v(this,xe,!0),w(this,at,_f).call(this,e),w(this,at,ho).call(this)):l(this,Dn)&&(v(this,_h,e.anchorNode),v(this,Nc,e.anchorOffset),v(this,Bc,e.focusNode),v(this,Hc,e.focusOffset),w(this,at,am).call(this),w(this,at,ho).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const e=yt.prototype;return ct(this,"_keyboardManager",new dl([[["ArrowLeft","mac+ArrowLeft"],e._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],e._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],e._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],e._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:l(this,xe)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:l(this,Gs),methodOfCreation:l(this,zc)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(e){return{numberOfColors:e.get("color").size}}static initialize(e,s){var i;Vt.initialize(e,s),yt._defaultColor||(yt._defaultColor=((i=s.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(e,s){switch(e){case gt.HIGHLIGHT_DEFAULT_COLOR:yt._defaultColor=s;break;case gt.HIGHLIGHT_THICKNESS:yt._defaultThickness=s;break}}translateInPage(e,s){}get toolbarPosition(){return l(this,xh)}updateParams(e,s){switch(e){case gt.HIGHLIGHT_COLOR:w(this,at,Ky).call(this,s);break;case gt.HIGHLIGHT_THICKNESS:w(this,at,Jy).call(this,s);break}}static get defaultPropertiesToUpdate(){return[[gt.HIGHLIGHT_DEFAULT_COLOR,yt._defaultColor],[gt.HIGHLIGHT_THICKNESS,yt._defaultThickness]]}get propertiesToUpdate(){return[[gt.HIGHLIGHT_COLOR,this.color||yt._defaultColor],[gt.HIGHLIGHT_THICKNESS,l(this,Gs)||yt._defaultThickness],[gt.HIGHLIGHT_FREE,l(this,xe)]]}async addEditToolbar(){const e=await super.addEditToolbar();return e?(this._uiManager.highlightColors&&(v(this,wh,new Td({editor:this})),e.addColorPicker(l(this,wh))),e):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(w(this,at,su).call(this))}getBaseTranslation(){return[0,0]}getRect(e,s){return super.getRect(e,s,w(this,at,su).call(this))}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),e&&this.div.focus()}remove(){w(this,at,om).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(w(this,at,ho).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?w(this,at,om).call(this):e&&(w(this,at,ho).call(this,e),s=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(e),this.show(this._isVisible),s&&this.select()}rotate(e){var n,r,a;const{drawLayer:s}=this.parent;let i;l(this,xe)?(e=(e-this.rotation+360)%360,i=w(n=yt,Xs,Vh).call(n,l(this,Ws).box,e)):i=w(r=yt,Xs,Vh).call(r,[this.x,this.y,this.width,this.height],e),s.updateProperties(l(this,Ps),{bbox:i,root:{"data-main-rotation":e}}),s.updateProperties(l(this,Ie),{bbox:w(a=yt,Xs,Vh).call(a,l(this,ds).box,e),root:{"data-main-rotation":e}})}render(){if(this.div)return this.div;const e=super.render();l(this,Sh)&&(e.setAttribute("aria-label",l(this,Sh)),e.setAttribute("role","mark")),l(this,xe)?e.classList.add("free"):this.div.addEventListener("keydown",w(this,at,Zy).bind(this),{signal:this._uiManager._signal});const s=v(this,Ua,document.createElement("div"));e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal",s.style.clipPath=l(this,Xa);const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),md(this,l(this,Ua),["pointerover","pointerleave"]),this.enableEditing(),e}pointerover(){var e;this.isSelected||(e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{hovered:!0}})}pointerleave(){var e;this.isSelected||(e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{hovered:!1}})}_moveCaret(e){switch(this.parent.unselect(this),e){case 0:case 2:w(this,at,wf).call(this,!0);break;case 1:case 3:w(this,at,wf).call(this,!1);break}}select(){var e;super.select(),l(this,Ie)&&((e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{hovered:!1,selected:!0}}))}unselect(){var e;super.unselect(),l(this,Ie)&&((e=this.parent)==null||e.drawLayer.updateProperties(l(this,Ie),{rootClass:{selected:!1}}),l(this,xe)||w(this,at,wf).call(this,!1))}get _mustFixPosition(){return!l(this,xe)}show(e=this._isVisible){super.show(e),this.parent&&(this.parent.drawLayer.updateProperties(l(this,Ps),{rootClass:{hidden:!e}}),this.parent.drawLayer.updateProperties(l(this,Ie),{rootClass:{hidden:!e}}))}static startHighlighting(e,s,{target:i,x:n,y:r}){const{x:a,y:h,width:c,height:u}=i.getBoundingClientRect(),d=new AbortController,f=e.combinedSignal(d),g=p=>{d.abort(),w(this,Xs,i_).call(this,e,p)};window.addEventListener("blur",g,{signal:f}),window.addEventListener("pointerup",g,{signal:f}),window.addEventListener("pointerdown",bs,{capture:!0,passive:!1,signal:f}),window.addEventListener("contextmenu",ri,{signal:f}),i.addEventListener("pointermove",w(this,Xs,s_).bind(this,e),{signal:f}),this._freeHighlight=new np({x:n,y:r},[a,h,c,u],e.scale,this._defaultThickness/2,s,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static async deserialize(e,s,i){var m,y,b,x;let n=null;if(e instanceof bb){const{data:{quadPoints:S,rect:C,rotation:k,id:O,color:P,opacity:D,popupRef:R},parent:{page:{pageNumber:z}}}=e;n=e={annotationType:ot.HIGHLIGHT,color:Array.from(P),opacity:D,quadPoints:S,boxes:null,pageIndex:z-1,rect:C.slice(0),rotation:k,id:O,deleted:!1,popupRef:R}}else if(e instanceof ep){const{data:{inkLists:S,rect:C,rotation:k,id:O,color:P,borderStyle:{rawWidth:D},popupRef:R},parent:{page:{pageNumber:z}}}=e;n=e={annotationType:ot.HIGHLIGHT,color:Array.from(P),thickness:D,inkLists:S,boxes:null,pageIndex:z-1,rect:C.slice(0),rotation:k,id:O,deleted:!1,popupRef:R}}const{color:r,quadPoints:a,inkLists:h,opacity:c}=e,u=await super.deserialize(e,s,i);u.color=q.makeHexColor(...r),v(u,Rn,c||1),h&&v(u,Gs,e.thickness),u.annotationElementId=e.id||null,u._initialData=n;const[d,f]=u.pageDimensions,[g,p]=u.pageTranslation;if(a){const S=v(u,Dn,[]);for(let C=0;C<a.length;C+=8)S.push({x:(a[C]-g)/d,y:1-(a[C+1]-p)/f,width:(a[C+2]-a[C])/d,height:(a[C+1]-a[C+5])/f});w(m=u,at,am).call(m),w(y=u,at,ho).call(y),u.rotate(u.rotation)}else if(h){v(u,xe,!0);const S=h[0],C={x:S[0]-g,y:f-(S[1]-p)},k=new np(C,[0,0,d,f],1,l(u,Gs)/2,!0,.001);for(let D=0,R=S.length;D<R;D+=2)C.x=S[D]-g,C.y=f-(S[D+1]-p),k.add(C);const{id:O,clipPathId:P}=s.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:u.color,"fill-opacity":u._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:k.toSVGPath()}},!0,!0);w(b=u,at,_f).call(b,{highlightOutlines:k.getOutlines(),highlightId:O,clipPathId:P}),w(x=u,at,ho).call(x)}return u}serialize(e=!1){if(this.isEmpty()||e)return null;if(this.deleted)return this.serializeDeleted();const s=this.getRect(0,0),i=Vt._colorManager.convert(this.color),n={annotationType:ot.HIGHLIGHT,color:i,opacity:l(this,Rn),thickness:l(this,Gs),quadPoints:w(this,at,t_).call(this),outlines:w(this,at,e_).call(this,s),pageIndex:this.pageIndex,rect:s,rotation:w(this,at,su).call(this),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!w(this,at,n_).call(this,n)?null:(n.id=this.annotationElementId,n)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}};_h=new WeakMap,Nc=new WeakMap,Dn=new WeakMap,Xa=new WeakMap,wh=new WeakMap,ds=new WeakMap,Bc=new WeakMap,Hc=new WeakMap,Ua=new WeakMap,Ws=new WeakMap,Ps=new WeakMap,xe=new WeakMap,xh=new WeakMap,Rn=new WeakMap,Ie=new WeakMap,Sh=new WeakMap,Gs=new WeakMap,zc=new WeakMap,at=new WeakSet,am=function(){const e=new ip(l(this,Dn),.001);v(this,Ws,e.getOutlines()),[this.x,this.y,this.width,this.height]=l(this,Ws).box;const s=new ip(l(this,Dn),.0025,.001,this._uiManager.direction==="ltr");v(this,ds,s.getOutlines());const{lastPoint:i}=l(this,ds);v(this,xh,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height])},_f=function({highlightOutlines:e,highlightId:s,clipPathId:i}){var d,f;if(v(this,Ws,e),v(this,ds,e.getNewOutline(l(this,Gs)/2+1.5,.0025)),s>=0)v(this,Ps,s),v(this,Xa,i),this.parent.drawLayer.finalizeDraw(s,{bbox:e.box,path:{d:e.toSVGPath()}}),v(this,Ie,this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:l(this,ds).box,path:{d:l(this,ds).toSVGPath()}},!0));else if(this.parent){const g=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(l(this,Ps),{bbox:w(d=yt,Xs,Vh).call(d,l(this,Ws).box,(g-this.rotation+360)%360),path:{d:e.toSVGPath()}}),this.parent.drawLayer.updateProperties(l(this,Ie),{bbox:w(f=yt,Xs,Vh).call(f,l(this,ds).box,g),path:{d:l(this,ds).toSVGPath()}})}const[r,a,h,c]=e.box;switch(this.rotation){case 0:this.x=r,this.y=a,this.width=h,this.height=c;break;case 90:{const[g,p]=this.parentDimensions;this.x=a,this.y=1-r,this.width=h*p/g,this.height=c*g/p;break}case 180:this.x=1-r,this.y=1-a,this.width=h,this.height=c;break;case 270:{const[g,p]=this.parentDimensions;this.x=1-a,this.y=r,this.width=h*p/g,this.height=c*g/p;break}}const{lastPoint:u}=l(this,ds);v(this,xh,[(u[0]-r)/h,(u[1]-a)/c])},Ky=function(e){const s=(r,a)=>{var h,c;this.color=r,v(this,Rn,a),(h=this.parent)==null||h.drawLayer.updateProperties(l(this,Ps),{root:{fill:r,"fill-opacity":a}}),(c=l(this,wh))==null||c.updateColor(r)},i=this.color,n=l(this,Rn);this.addCommands({cmd:s.bind(this,e,yt._defaultOpacity),undo:s.bind(this,i,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:gt.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(e)},!0)},Jy=function(e){const s=l(this,Gs),i=n=>{v(this,Gs,n),w(this,at,Qy).call(this,n)};this.addCommands({cmd:i.bind(this,e),undo:i.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:gt.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:e},!0)},Qy=function(e){if(!l(this,xe))return;w(this,at,_f).call(this,{highlightOutlines:l(this,Ws).getNewOutline(e/2)}),this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)},om=function(){l(this,Ps)===null||!this.parent||(this.parent.drawLayer.remove(l(this,Ps)),v(this,Ps,null),this.parent.drawLayer.remove(l(this,Ie)),v(this,Ie,null))},ho=function(e=this.parent){l(this,Ps)===null&&({id:es(this,Ps)._,clipPathId:es(this,Xa)._}=e.drawLayer.draw({bbox:l(this,Ws).box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":l(this,Rn)},rootClass:{highlight:!0,free:l(this,xe)},path:{d:l(this,Ws).toSVGPath()}},!1,!0),v(this,Ie,e.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:l(this,xe)},bbox:l(this,ds).box,path:{d:l(this,ds).toSVGPath()}},l(this,xe))),l(this,Ua)&&(l(this,Ua).style.clipPath=l(this,Xa)))},Xs=new WeakSet,Vh=function([e,s,i,n],r){switch(r){case 90:return[1-s-n,e,n,i];case 180:return[1-e-i,1-s-n,i,n];case 270:return[s,1-e-i,n,i]}return[e,s,i,n]},Zy=function(e){yt._keyboardManager.exec(this,e)},wf=function(e){if(!l(this,_h))return;const s=window.getSelection();e?s.setPosition(l(this,_h),l(this,Nc)):s.setPosition(l(this,Bc),l(this,Hc))},su=function(){return l(this,xe)?this.rotation:0},t_=function(){if(l(this,xe))return null;const[e,s]=this.pageDimensions,[i,n]=this.pageTranslation,r=l(this,Dn),a=new Float32Array(r.length*8);let h=0;for(const{x:c,y:u,width:d,height:f}of r){const g=c*e+i,p=(1-u)*s+n;a[h]=a[h+4]=g,a[h+1]=a[h+3]=p,a[h+2]=a[h+6]=g+d*e,a[h+5]=a[h+7]=p-f*s,h+=8}return a},e_=function(e){return l(this,Ws).serialize(e,w(this,at,su).call(this))},s_=function(e,s){this._freeHighlight.add(s)&&e.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})},i_=function(e,s){this._freeHighlight.isEmpty()?e.drawLayer.remove(this._freeHighlightId):e.createAndAddNewEditor(s,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},n_=function(e){const{color:s}=this._initialData;return e.color.some((i,n)=>i!==s[n])},_(yt,Xs),Q(yt,"_defaultColor",null),Q(yt,"_defaultOpacity",1),Q(yt,"_defaultThickness",12),Q(yt,"_type","highlight"),Q(yt,"_editorType",ot.HIGHLIGHT),Q(yt,"_freeHighlightId",-1),Q(yt,"_freeHighlight",null),Q(yt,"_freeHighlightClipId","");let Ed=yt;class QC{constructor(){_(this,Ya,Object.create(null))}updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){l(this,Ya)[t]=e}toSVGProperties(){const t=l(this,Ya);return v(this,Ya,Object.create(null)),{root:t}}reset(){v(this,Ya,Object.create(null))}updateAll(t=this){this.updateProperties(t)}clone(){kt("Not implemented")}}Ya=new WeakMap;const Y=class Y extends Vt{constructor(e){super(e);_(this,mt);_(this,Ms,null);_(this,Ch);Q(this,"_drawId",null);v(this,Ch,e.mustBeCommitted||!1),e.drawOutlines&&(w(this,mt,hm).call(this,e),w(this,mt,iu).call(this))}static _mergeSVGProperties(e,s){const i=new Set(Object.keys(e));for(const[n,r]of Object.entries(s))i.has(n)?Object.assign(e[n],r):e[n]=r;return e}static getDefaultDrawingOptions(e){kt("Not implemented")}static get typesMap(){kt("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(e,s){const i=this.typesMap.get(e);i&&this._defaultDrawingOptions.updateProperty(i,s),this._currentParent&&(l(Y,ve).updateProperty(i,s),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(e,s){const i=this.constructor.typesMap.get(e);i&&this._updateProperty(e,i,s)}static get defaultPropertiesToUpdate(){const e=[],s=this._defaultDrawingOptions;for(const[i,n]of this.typesMap)e.push([i,s[n]]);return e}get propertiesToUpdate(){const e=[],{_drawingOptions:s}=this;for(const[i,n]of this.constructor.typesMap)e.push([i,s[n]]);return e}_updateProperty(e,s,i){const n=this._drawingOptions,r=n[s],a=h=>{var u;n.updateProperty(s,h);const c=l(this,Ms).updateProperty(s,h);c&&w(this,mt,nu).call(this,c),(u=this.parent)==null||u.drawLayer.updateProperties(this._drawId,n.toSVGProperties())};this.addCommands({cmd:a.bind(this,i),undo:a.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:e,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties(l(this,Ms).getPathResizingSVGProperties(w(this,mt,xf).call(this)),{bbox:w(this,mt,Wh).call(this)}))}_onResized(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties(l(this,Ms).getPathResizedSVGProperties(w(this,mt,xf).call(this)),{bbox:w(this,mt,Wh).call(this)}))}_onTranslating(e,s){var i;(i=this.parent)==null||i.drawLayer.updateProperties(this._drawId,{bbox:w(this,mt,Wh).call(this,e,s)})}_onTranslated(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties(l(this,Ms).getPathTranslatedSVGProperties(w(this,mt,xf).call(this),this.parentDimensions),{bbox:w(this,mt,Wh).call(this)}))}_onStartDragging(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){var e;(e=this.parent)==null||e.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(e){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,l(this,Ch)&&(v(this,Ch,!1),this.commit(),this.parent.setSelected(this),e&&this.isOnScreen&&this.div.focus())}remove(){w(this,mt,cm).call(this),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(w(this,mt,iu).call(this),w(this,mt,nu).call(this,l(this,Ms).box),this.isAttachedToDOM||this.parent.add(this)))}setParent(e){var i;let s=!1;this.parent&&!e?(this._uiManager.removeShouldRescale(this),w(this,mt,cm).call(this)):e&&(this._uiManager.addShouldRescale(this),w(this,mt,iu).call(this,e),s=!this.parent&&((i=this.div)==null?void 0:i.classList.contains("selectedEditor"))),super.setParent(e),s&&this.select()}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,Y._mergeSVGProperties({bbox:w(this,mt,Wh).call(this)},l(this,Ms).updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&w(this,mt,nu).call(this,l(this,Ms).updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const e=super.render();e.classList.add("draw");const s=document.createElement("div");e.append(s),s.setAttribute("aria-hidden","true"),s.className="internal";const[i,n]=this.parentDimensions;return this.setDims(this.width*i,this.height*n),this._uiManager.addShouldRescale(this),this.disableEditing(),e}static createDrawerInstance(e,s,i,n,r){kt("Not implemented")}static startDrawing(e,s,i,n){var y;const{target:r,offsetX:a,offsetY:h,pointerId:c,pointerType:u}=n;if(l(Y,xr)&&l(Y,xr)!==u)return;const{viewport:{rotation:d}}=e,{width:f,height:g}=r.getBoundingClientRect(),p=v(Y,$a,new AbortController),m=e.combinedSignal(p);if(l(Y,wr)||v(Y,wr,c),l(Y,xr)??v(Y,xr,u),window.addEventListener("pointerup",b=>{var x;l(Y,wr)===b.pointerId?this._endDraw(b):(x=l(Y,Sr))==null||x.delete(b.pointerId)},{signal:m}),window.addEventListener("pointercancel",b=>{var x;l(Y,wr)===b.pointerId?this._currentParent.endDrawingSession():(x=l(Y,Sr))==null||x.delete(b.pointerId)},{signal:m}),window.addEventListener("pointerdown",b=>{l(Y,xr)===b.pointerType&&((l(Y,Sr)||v(Y,Sr,new Set)).add(b.pointerId),l(Y,ve).isCancellable()&&(l(Y,ve).removeLastElement(),l(Y,ve).isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",ri,{signal:m}),r.addEventListener("pointermove",this._drawMove.bind(this),{signal:m}),r.addEventListener("touchmove",b=>{b.timeStamp===l(Y,Ka)&&bs(b)},{signal:m}),e.toggleDrawing(),(y=s._editorUndoBar)==null||y.hide(),l(Y,ve)){e.drawLayer.updateProperties(this._currentDrawId,l(Y,ve).startNew(a,h,f,g,d));return}s.updateUIForDefaultProperties(this),v(Y,ve,this.createDrawerInstance(a,h,f,g,d)),v(Y,qa,this.getDefaultDrawingOptions()),this._currentParent=e,{id:this._currentDrawId}=e.drawLayer.draw(this._mergeSVGProperties(l(Y,qa).toSVGProperties(),l(Y,ve).defaultSVGProperties),!0,!1)}static _drawMove(e){var r;if(v(Y,Ka,-1),!l(Y,ve))return;const{offsetX:s,offsetY:i,pointerId:n}=e;if(l(Y,wr)===n){if(((r=l(Y,Sr))==null?void 0:r.size)>=1){this._endDraw(e);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,l(Y,ve).add(s,i)),v(Y,Ka,e.timeStamp),bs(e)}}static _cleanup(e){e&&(this._currentDrawId=-1,this._currentParent=null,v(Y,ve,null),v(Y,qa,null),v(Y,xr,null),v(Y,Ka,NaN)),l(Y,$a)&&(l(Y,$a).abort(),v(Y,$a,null),v(Y,wr,NaN),v(Y,Sr,null))}static _endDraw(e){const s=this._currentParent;if(s){if(s.toggleDrawing(!0),this._cleanup(!1),e&&s.drawLayer.updateProperties(this._currentDrawId,l(Y,ve).end(e.offsetX,e.offsetY)),this.supportMultipleDrawings){const i=l(Y,ve),n=this._currentDrawId,r=i.getLastElement();s.addCommands({cmd:()=>{s.drawLayer.updateProperties(n,i.setLastElement(r))},undo:()=>{s.drawLayer.updateProperties(n,i.removeLastElement())},mustExec:!1,type:gt.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(e){const s=this._currentParent;if(!s)return null;if(s.toggleDrawing(!0),s.cleanUndoStack(gt.DRAW_STEP),!l(Y,ve).isEmpty()){const{pageDimensions:[i,n],scale:r}=s,a=s.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:l(Y,ve).getOutlines(i*r,n*r,r,this._INNER_MARGIN),drawingOptions:l(Y,qa),mustBeCommitted:!e});return this._cleanup(!0),a}return s.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(e){}static deserializeDraw(e,s,i,n,r,a){kt("Not implemented")}static async deserialize(e,s,i){var d,f;const{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:h}}=s.viewport,c=this.deserializeDraw(a,h,n,r,this._INNER_MARGIN,e),u=await super.deserialize(e,s,i);return u.createDrawingOptions(e),w(d=u,mt,hm).call(d,{drawOutlines:c}),w(f=u,mt,iu).call(f),u.onScaleChanging(),u.rotate(),u}serializeDraw(e){const[s,i]=this.pageTranslation,[n,r]=this.pageDimensions;return l(this,Ms).serialize([s,i,n,r],e)}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}};Ms=new WeakMap,Ch=new WeakMap,ve=new WeakMap,$a=new WeakMap,qa=new WeakMap,wr=new WeakMap,xr=new WeakMap,Sr=new WeakMap,Ka=new WeakMap,mt=new WeakSet,hm=function({drawOutlines:e,drawId:s,drawingOptions:i}){v(this,Ms,e),this._drawingOptions||(this._drawingOptions=i),s>=0?(this._drawId=s,this.parent.drawLayer.finalizeDraw(s,e.defaultProperties)):this._drawId=w(this,mt,lm).call(this,e,this.parent),w(this,mt,nu).call(this,e.box)},lm=function(e,s){const{id:i}=s.drawLayer.draw(Y._mergeSVGProperties(this._drawingOptions.toSVGProperties(),e.defaultSVGProperties),!1,!1);return i},cm=function(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())},iu=function(e=this.parent){if(!(this._drawId!==null&&this.parent===e)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,e.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=w(this,mt,lm).call(this,l(this,Ms),e)}},r_=function([e,s,i,n]){const{parentDimensions:[r,a],rotation:h}=this;switch(h){case 90:return[s,1-e,i*(a/r),n*(r/a)];case 180:return[1-e,1-s,i,n];case 270:return[1-s,e,i*(a/r),n*(r/a)];default:return[e,s,i,n]}},xf=function(){const{x:e,y:s,width:i,height:n,parentDimensions:[r,a],rotation:h}=this;switch(h){case 90:return[1-s,e,i*(r/a),n*(a/r)];case 180:return[1-e,1-s,i,n];case 270:return[s,1-e,i*(r/a),n*(a/r)];default:return[e,s,i,n]}},nu=function(e){if([this.x,this.y,this.width,this.height]=w(this,mt,r_).call(this,e),this.div){this.fixAndSetPosition();const[s,i]=this.parentDimensions;this.setDims(this.width*s,this.height*i)}this._onResized()},Wh=function(){const{x:e,y:s,width:i,height:n,rotation:r,parentRotation:a,parentDimensions:[h,c]}=this;switch((r*4+a)/90){case 1:return[1-s-n,e,n,i];case 2:return[1-e-i,1-s-n,i,n];case 3:return[s,1-e-i,n,i];case 4:return[e,s-i*(h/c),n*(c/h),i*(h/c)];case 5:return[1-s,e,i*(h/c),n*(c/h)];case 6:return[1-e-n*(c/h),1-s,n*(c/h),i*(h/c)];case 7:return[s-i*(h/c),1-e-n*(c/h),i*(h/c),n*(c/h)];case 8:return[e-i,s-n,i,n];case 9:return[1-s,e-i,n,i];case 10:return[1-e,1-s,i,n];case 11:return[s-n,1-e,n,i];case 12:return[e-n*(c/h),s,n*(c/h),i*(h/c)];case 13:return[1-s-i*(h/c),e-n*(c/h),i*(h/c),n*(c/h)];case 14:return[1-e,1-s-i*(h/c),n*(c/h),i*(h/c)];case 15:return[s,1-e,i*(h/c),n*(c/h)];default:return[e,s,i,n]}},Q(Y,"_currentDrawId",-1),Q(Y,"_currentParent",null),_(Y,ve,null),_(Y,$a,null),_(Y,qa,null),_(Y,wr,NaN),_(Y,xr,null),_(Y,Sr,null),_(Y,Ka,NaN),Q(Y,"_INNER_MARGIN",3);let rp=Y;class ZC{constructor(t,e,s,i,n,r){_(this,Th);_(this,Hi,new Float64Array(6));_(this,be);_(this,ye);_(this,Ja);_(this,Ah);_(this,Ke);_(this,Se,"");_(this,Us,0);_(this,Qa,new kd);_(this,Za);_(this,to);v(this,Za,s),v(this,to,i),v(this,Ja,n),v(this,Ah,r),[t,e]=w(this,Th,Sf).call(this,t,e);const a=v(this,be,[NaN,NaN,NaN,NaN,t,e]);v(this,Ke,[t,e]),v(this,ye,[{line:a,points:l(this,Ke)}]),l(this,Hi).set(a,0)}updateProperty(t,e){t==="stroke-width"&&v(this,Ah,e)}isEmpty(){return!l(this,ye)||l(this,ye).length===0}isCancellable(){return l(this,Ke).length<=10}add(t,e){[t,e]=w(this,Th,Sf).call(this,t,e);const[s,i,n,r]=l(this,Hi).subarray(2,6),a=t-n,h=e-r;return Math.hypot(l(this,Za)*a,l(this,to)*h)<=2?null:(l(this,Ke).push(t,e),isNaN(s)?(l(this,Hi).set([n,r,t,e],2),l(this,be).push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(l(this,Hi)[0])&&l(this,be).splice(6,6),l(this,Hi).set([s,i,n,r,t,e],0),l(this,be).push(...U.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(l(this,Ke).length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){v(this,Za,s),v(this,to,i),v(this,Ja,n),[t,e]=w(this,Th,Sf).call(this,t,e);const r=v(this,be,[NaN,NaN,NaN,NaN,t,e]);v(this,Ke,[t,e]);const a=l(this,ye).at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),l(this,ye).push({line:r,points:l(this,Ke)}),l(this,Hi).set(r,0),v(this,Us,0),this.toSVGPath(),null}getLastElement(){return l(this,ye).at(-1)}setLastElement(t){return l(this,ye)?(l(this,ye).push(t),v(this,be,t.line),v(this,Ke,t.points),v(this,Us,0),{path:{d:this.toSVGPath()}}):l(this,Qa).setLastElement(t)}removeLastElement(){if(!l(this,ye))return l(this,Qa).removeLastElement();l(this,ye).pop(),v(this,Se,"");for(let t=0,e=l(this,ye).length;t<e;t++){const{line:s,points:i}=l(this,ye)[t];v(this,be,s),v(this,Ke,i),v(this,Us,0),this.toSVGPath()}return{path:{d:l(this,Se)}}}toSVGPath(){const t=U.svgRound(l(this,be)[4]),e=U.svgRound(l(this,be)[5]);if(l(this,Ke).length===2)return v(this,Se,`${l(this,Se)} M ${t} ${e} Z`),l(this,Se);if(l(this,Ke).length<=6){const i=l(this,Se).lastIndexOf("M");v(this,Se,`${l(this,Se).slice(0,i)} M ${t} ${e}`),v(this,Us,6)}if(l(this,Ke).length===4){const i=U.svgRound(l(this,be)[10]),n=U.svgRound(l(this,be)[11]);return v(this,Se,`${l(this,Se)} L ${i} ${n}`),v(this,Us,12),l(this,Se)}const s=[];l(this,Us)===0&&(s.push(`M ${t} ${e}`),v(this,Us,6));for(let i=l(this,Us),n=l(this,be).length;i<n;i+=6){const[r,a,h,c,u,d]=l(this,be).slice(i,i+6).map(U.svgRound);s.push(`C${r} ${a} ${h} ${c} ${u} ${d}`)}return v(this,Se,l(this,Se)+s.join(" ")),v(this,Us,l(this,be).length),l(this,Se)}getOutlines(t,e,s,i){const n=l(this,ye).at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),l(this,Qa).build(l(this,ye),t,e,s,l(this,Ja),l(this,Ah),i),v(this,Hi,null),v(this,be,null),v(this,ye,null),v(this,Se,null),l(this,Qa)}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}Hi=new WeakMap,be=new WeakMap,ye=new WeakMap,Ja=new WeakMap,Ah=new WeakMap,Ke=new WeakMap,Se=new WeakMap,Us=new WeakMap,Qa=new WeakMap,Za=new WeakMap,to=new WeakMap,Th=new WeakSet,Sf=function(t,e){return U._normalizePoint(t,e,l(this,Za),l(this,to),l(this,Ja))};const mp=class mp extends U{constructor(){super(...arguments);_(this,Ce);_(this,Je);_(this,Vc,0);_(this,Wc);_(this,Os);_(this,zi);_(this,Vi);_(this,Eh);_(this,kh);_(this,Ph)}build(e,s,i,n,r,a,h){v(this,zi,s),v(this,Vi,i),v(this,Eh,n),v(this,kh,r),v(this,Ph,a),v(this,Wc,h??0),v(this,Os,e),w(this,Ce,o_).call(this)}setLastElement(e){return l(this,Os).push(e),{path:{d:this.toSVGPath()}}}removeLastElement(){return l(this,Os).pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const e=[];for(const{line:s}of l(this,Os)){if(e.push(`M${U.svgRound(s[4])} ${U.svgRound(s[5])}`),s.length===6){e.push("Z");continue}if(s.length===12){e.push(`L${U.svgRound(s[10])} ${U.svgRound(s[11])}`);continue}for(let i=6,n=s.length;i<n;i+=6){const[r,a,h,c,u,d]=s.subarray(i,i+6).map(U.svgRound);e.push(`C${r} ${a} ${h} ${c} ${u} ${d}`)}}return e.join("")}serialize([e,s,i,n],r){const a=[],h=[],[c,u,d,f]=w(this,Ce,a_).call(this);let g,p,m,y,b,x,S,C,k;switch(l(this,kh)){case 0:k=U._rescale,g=e,p=s+n,m=i,y=-n,b=e+c*i,x=s+(1-u-f)*n,S=e+(c+d)*i,C=s+(1-u)*n;break;case 90:k=U._rescaleAndSwap,g=e,p=s,m=i,y=n,b=e+u*i,x=s+c*n,S=e+(u+f)*i,C=s+(c+d)*n;break;case 180:k=U._rescale,g=e+i,p=s,m=-i,y=n,b=e+(1-c-d)*i,x=s+u*n,S=e+(1-c)*i,C=s+(u+f)*n;break;case 270:k=U._rescaleAndSwap,g=e+i,p=s+n,m=-i,y=-n,b=e+(1-u-f)*i,x=s+(1-c-d)*n,S=e+(1-u)*i,C=s+(1-c)*n;break}for(const{line:O,points:P}of l(this,Os))a.push(k(O,g,p,m,y,r?new Array(O.length):null)),h.push(k(P,g,p,m,y,r?new Array(P.length):null));return{lines:a,points:h,rect:[b,x,S,C]}}static deserialize(e,s,i,n,r,{paths:{lines:a,points:h},rotation:c,thickness:u}){const d=[];let f,g,p,m,y;switch(c){case 0:y=U._rescale,f=-e/i,g=s/n+1,p=1/i,m=-1/n;break;case 90:y=U._rescaleAndSwap,f=-s/n,g=-e/i,p=1/n,m=1/i;break;case 180:y=U._rescale,f=e/i+1,g=-s/n,p=-1/i,m=1/n;break;case 270:y=U._rescaleAndSwap,f=s/n+1,g=e/i+1,p=-1/n,m=-1/i;break}if(!a){a=[];for(const x of h){const S=x.length;if(S===2){a.push(new Float32Array([NaN,NaN,NaN,NaN,x[0],x[1]]));continue}if(S===4){a.push(new Float32Array([NaN,NaN,NaN,NaN,x[0],x[1],NaN,NaN,NaN,NaN,x[2],x[3]]));continue}const C=new Float32Array(3*(S-2));a.push(C);let[k,O,P,D]=x.subarray(0,4);C.set([NaN,NaN,NaN,NaN,k,O],0);for(let R=4;R<S;R+=2){const z=x[R],B=x[R+1];C.set(U.createBezierPoints(k,O,P,D,z,B),(R-2)*3),[k,O,P,D]=[P,D,z,B]}}}for(let x=0,S=a.length;x<S;x++)d.push({line:y(a[x].map(C=>C??NaN),f,g,p,m),points:y(h[x].map(C=>C??NaN),f,g,p,m)});const b=new mp;return b.build(d,i,n,1,c,u,r),b}get box(){return l(this,Je)}updateProperty(e,s){return e==="stroke-width"?w(this,Ce,h_).call(this,s):null}updateParentDimensions([e,s],i){const[n,r]=w(this,Ce,Bn).call(this);v(this,zi,e),v(this,Vi,s),v(this,Eh,i);const[a,h]=w(this,Ce,Bn).call(this),c=a-n,u=h-r,d=l(this,Je);return d[0]-=c,d[1]-=u,d[2]+=2*c,d[3]+=2*u,d}updateRotation(e){return v(this,Vc,e),{path:{transform:this.rotationTransform}}}get viewBox(){return l(this,Je).map(U.svgRound).join(" ")}get defaultProperties(){const[e,s]=l(this,Je);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`}}}get rotationTransform(){const[,,e,s]=l(this,Je);let i=0,n=0,r=0,a=0,h=0,c=0;switch(l(this,Vc)){case 90:n=s/e,r=-e/s,h=e;break;case 180:i=-1,a=-1,h=e,c=s;break;case 270:n=-s/e,r=e/s,c=s;break;default:return""}return`matrix(${i} ${n} ${r} ${a} ${U.svgRound(h)} ${U.svgRound(c)})`}getPathResizingSVGProperties([e,s,i,n]){const[r,a]=w(this,Ce,Bn).call(this),[h,c,u,d]=l(this,Je);if(Math.abs(u-r)<=U.PRECISION||Math.abs(d-a)<=U.PRECISION){const y=e+i/2-(h+u/2),b=s+n/2-(c+d/2);return{path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`,transform:`${this.rotationTransform} translate(${y} ${b})`}}}const f=(i-2*r)/(u-2*r),g=(n-2*a)/(d-2*a),p=u/i,m=d/n;return{path:{"transform-origin":`${U.svgRound(h)} ${U.svgRound(c)}`,transform:`${this.rotationTransform} scale(${p} ${m}) translate(${U.svgRound(r)} ${U.svgRound(a)}) scale(${f} ${g}) translate(${U.svgRound(-r)} ${U.svgRound(-a)})`}}}getPathResizedSVGProperties([e,s,i,n]){const[r,a]=w(this,Ce,Bn).call(this),h=l(this,Je),[c,u,d,f]=h;if(h[0]=e,h[1]=s,h[2]=i,h[3]=n,Math.abs(d-r)<=U.PRECISION||Math.abs(f-a)<=U.PRECISION){const b=e+i/2-(c+d/2),x=s+n/2-(u+f/2);for(const{line:S,points:C}of l(this,Os))U._translate(S,b,x,S),U._translate(C,b,x,C);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const g=(i-2*r)/(d-2*r),p=(n-2*a)/(f-2*a),m=-g*(c+r)+e+r,y=-p*(u+a)+s+a;if(g!==1||p!==1||m!==0||y!==0)for(const{line:b,points:x}of l(this,Os))U._rescale(b,m,y,g,p,b),U._rescale(x,m,y,g,p,x);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([e,s],i){const[n,r]=i,a=l(this,Je),h=e-a[0],c=s-a[1];if(l(this,zi)===n&&l(this,Vi)===r)for(const{line:u,points:d}of l(this,Os))U._translate(u,h,c,u),U._translate(d,h,c,d);else{const u=l(this,zi)/n,d=l(this,Vi)/r;v(this,zi,n),v(this,Vi,r);for(const{line:f,points:g}of l(this,Os))U._rescale(f,h,c,u,d,f),U._rescale(g,h,c,u,d,g);a[2]*=u,a[3]*=d}return a[0]=e,a[1]=s,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${U.svgRound(e)} ${U.svgRound(s)}`}}}get defaultSVGProperties(){const e=l(this,Je);return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${U.svgRound(e[0])} ${U.svgRound(e[1])}`,transform:this.rotationTransform||null},bbox:e}}};Je=new WeakMap,Vc=new WeakMap,Wc=new WeakMap,Os=new WeakMap,zi=new WeakMap,Vi=new WeakMap,Eh=new WeakMap,kh=new WeakMap,Ph=new WeakMap,Ce=new WeakSet,Bn=function(e=l(this,Ph)){const s=l(this,Wc)+e/2*l(this,Eh);return l(this,kh)%180===0?[s/l(this,zi),s/l(this,Vi)]:[s/l(this,Vi),s/l(this,zi)]},a_=function(){const[e,s,i,n]=l(this,Je),[r,a]=w(this,Ce,Bn).call(this,0);return[e+r,s+a,i-2*r,n-2*a]},o_=function(){const e=v(this,Je,new Float32Array([1/0,1/0,-1/0,-1/0]));for(const{line:n}of l(this,Os)){if(n.length<=12){for(let h=4,c=n.length;h<c;h+=6){const[u,d]=n.subarray(h,h+2);e[0]=Math.min(e[0],u),e[1]=Math.min(e[1],d),e[2]=Math.max(e[2],u),e[3]=Math.max(e[3],d)}continue}let r=n[4],a=n[5];for(let h=6,c=n.length;h<c;h+=6){const[u,d,f,g,p,m]=n.subarray(h,h+6);q.bezierBoundingBox(r,a,u,d,f,g,p,m,e),r=p,a=m}}const[s,i]=w(this,Ce,Bn).call(this);e[0]=Math.min(1,Math.max(0,e[0]-s)),e[1]=Math.min(1,Math.max(0,e[1]-i)),e[2]=Math.min(1,Math.max(0,e[2]+s)),e[3]=Math.min(1,Math.max(0,e[3]+i)),e[2]-=e[0],e[3]-=e[1]},h_=function(e){const[s,i]=w(this,Ce,Bn).call(this);v(this,Ph,e);const[n,r]=w(this,Ce,Bn).call(this),[a,h]=[n-s,r-i],c=l(this,Je);return c[0]-=a,c[1]-=h,c[2]+=2*a,c[3]+=2*h,c};let kd=mp;const vp=class vp extends QC{constructor(e){super();_(this,Mh);v(this,Mh,e),super.updateProperties({fill:"none",stroke:Vt._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(e,s){e==="stroke-width"&&(s??(s=this["stroke-width"]),s*=l(this,Mh).realScale),super.updateSVGProperty(e,s)}clone(){const e=new vp(l(this,Mh));return e.updateAll(this),e}};Mh=new WeakMap;let ap=vp;const Oh=class Oh extends rp{constructor(e){super({...e,name:"inkEditor"});_(this,Ud);this._willKeepAspectRatio=!0}static initialize(e,s){Vt.initialize(e,s),this._defaultDrawingOptions=new ap(s.viewParameters)}static getDefaultDrawingOptions(e){const s=this._defaultDrawingOptions.clone();return s.updateProperties(e),s}static get supportMultipleDrawings(){return!0}static get typesMap(){return ct(this,"typesMap",new Map([[gt.INK_THICKNESS,"stroke-width"],[gt.INK_COLOR,"stroke"],[gt.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(e,s,i,n,r){return new ZC(e,s,i,n,r,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(e,s,i,n,r,a){return kd.deserialize(e,s,i,n,r,a)}static async deserialize(e,s,i){let n=null;if(e instanceof ep){const{data:{inkLists:a,rect:h,rotation:c,id:u,color:d,opacity:f,borderStyle:{rawWidth:g},popupRef:p},parent:{page:{pageNumber:m}}}=e;n=e={annotationType:ot.INK,color:Array.from(d),thickness:g,opacity:f,paths:{points:a},boxes:null,pageIndex:m-1,rect:h.slice(0),rotation:c,id:u,deleted:!1,popupRef:p}}const r=await super.deserialize(e,s,i);return r.annotationElementId=e.id||null,r._initialData=n,r}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:e,_drawingOptions:s,parent:i}=this;s.updateSVGProperty("stroke-width"),i.drawLayer.updateProperties(e,s.toSVGProperties())}static onScaleChangingWhenDrawing(){const e=this._currentParent;e&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),e.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:e,thickness:s,opacity:i}){this._drawingOptions=Oh.getDefaultDrawingOptions({stroke:q.makeHexColor(...e),"stroke-width":s,"stroke-opacity":i})}serialize(e=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:s,points:i,rect:n}=this.serializeDraw(e),{_drawingOptions:{stroke:r,"stroke-opacity":a,"stroke-width":h}}=this,c={annotationType:ot.INK,color:Vt._colorManager.convert(r),opacity:a,thickness:h,paths:{lines:s,points:i},pageIndex:this.pageIndex,rect:n,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return e?c:this.annotationElementId&&!w(this,Ud,l_).call(this,c)?null:(c.id=this.annotationElementId,c)}renderAnnotationElement(e){const{points:s,rect:i}=this.serializeDraw(!1);return e.updateEdited({rect:i,thickness:this._drawingOptions["stroke-width"],points:s}),null}};Ud=new WeakSet,l_=function(e){const{color:s,thickness:i,opacity:n,pageIndex:r}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||e.color.some((a,h)=>a!==s[h])||e.thickness!==i||e.opacity!==n||e.pageIndex!==r},Q(Oh,"_type","ink"),Q(Oh,"_editorType",ot.INK),Q(Oh,"_defaultDrawingOptions",null);let op=Oh;const Gc=class Gc extends Vt{constructor(e){super({...e,name:"stampEditor"});_(this,vt);_(this,Gt,null);_(this,Ae,null);_(this,Cr,null);_(this,Fn,null);_(this,Ar,null);_(this,Dh,"");_(this,Wi,null);_(this,Gi,null);_(this,Ds,!1);_(this,Rh,!1);v(this,Fn,e.bitmapUrl),v(this,Ar,e.bitmapFile)}static initialize(e,s){Vt.initialize(e,s)}static get supportedTypes(){return ct(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(s=>`image/${s}`))}static get supportedTypesStr(){return ct(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(e){return this.supportedTypes.includes(e)}static paste(e,s){s.pasteEditor(ot.STAMP,{bitmapFile:e.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var e;return{type:"stamp",hasAltText:!!((e=this.altTextData)!=null&&e.altText)}}static computeTelemetryFinalData(e){const s=e.get("hasAltText");return{hasAltText:s.get(!0)??0,hasNoAltText:s.get(!1)??0}}async mlGuessAltText(e=null,s=!0){if(this.hasAltTextData())return null;const{mlManager:i}=this._uiManager;if(!i)throw new Error("No ML.");if(!await i.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:n,width:r,height:a}=e||this.copyCanvas(null,null,!0).imageData,h=await i.guess({name:"altText",request:{data:n,width:r,height:a,channels:n.length/(r*a)}});if(!h)throw new Error("No response from the AI service.");if(h.error)throw new Error("Error from the AI service.");if(h.cancel)return null;if(!h.output)throw new Error("No valid response from the AI service.");const c=h.output;return await this.setGuessedAltText(c),s&&!this.hasAltTextData()&&(this.altTextData={alt:c,decorative:!1}),c}remove(){var e;l(this,Ae)&&(v(this,Gt,null),this._uiManager.imageManager.deleteId(l(this,Ae)),(e=l(this,Wi))==null||e.remove(),v(this,Wi,null),l(this,Gi)&&(clearTimeout(l(this,Gi)),v(this,Gi,null))),super.remove()}rebuild(){if(!this.parent){l(this,Ae)&&w(this,vt,Cf).call(this);return}super.rebuild(),this.div!==null&&(l(this,Ae)&&l(this,Wi)===null&&w(this,vt,Cf).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(e){this._isDraggable=!0,e&&this.div.focus()}isEmpty(){return!(l(this,Cr)||l(this,Gt)||l(this,Fn)||l(this,Ar)||l(this,Ae))}get isResizable(){return!0}render(){if(this.div)return this.div;let e,s;if(this.width&&(e=this.x,s=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),l(this,Gt)?w(this,vt,um).call(this):w(this,vt,Cf).call(this),this.width&&!this.annotationElementId){const[i,n]=this.parentDimensions;this.setAt(e*i,s*n,this.width*i,this.height*n)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;l(this,Gi)!==null&&clearTimeout(l(this,Gi)),v(this,Gi,setTimeout(()=>{v(this,Gi,null),w(this,vt,dm).call(this)},200))}copyCanvas(e,s,i=!1){var g;e||(e=224);const{width:n,height:r}=l(this,Gt),a=new Bg;let h=l(this,Gt),c=n,u=r,d=null;if(s){if(n>s||r>s){const D=Math.min(s/n,s/r);c=Math.floor(n*D),u=Math.floor(r*D)}d=document.createElement("canvas");const p=d.width=Math.ceil(c*a.sx),m=d.height=Math.ceil(u*a.sy);l(this,Ds)||(h=w(this,vt,Af).call(this,p,m));const y=d.getContext("2d");y.filter=this._uiManager.hcmFilter;let b="white",x="#cfcfd8";this._uiManager.hcmFilter!=="none"?x="black":(g=window.matchMedia)!=null&&g.call(window,"(prefers-color-scheme: dark)").matches&&(b="#8f8f9d",x="#42414d");const S=15,C=S*a.sx,k=S*a.sy,O=new OffscreenCanvas(C*2,k*2),P=O.getContext("2d");P.fillStyle=b,P.fillRect(0,0,C*2,k*2),P.fillStyle=x,P.fillRect(0,0,C,k),P.fillRect(C,k,C,k),y.fillStyle=y.createPattern(O,"repeat"),y.fillRect(0,0,p,m),y.drawImage(h,0,0,h.width,h.height,0,0,p,m)}let f=null;if(i){let p,m;if(a.symmetric&&h.width<e&&h.height<e)p=h.width,m=h.height;else if(h=l(this,Gt),n>e||r>e){const x=Math.min(e/n,e/r);p=Math.floor(n*x),m=Math.floor(r*x),l(this,Ds)||(h=w(this,vt,Af).call(this,p,m))}const b=new OffscreenCanvas(p,m).getContext("2d",{willReadFrequently:!0});b.drawImage(h,0,0,h.width,h.height,0,0,p,m),f={width:p,height:m,data:b.getImageData(0,0,p,m).data}}return{canvas:d,width:c,height:u,imageData:f}}getImageForAltText(){return l(this,Wi)}static async deserialize(e,s,i){var m;let n=null;if(e instanceof yb){const{data:{rect:y,rotation:b,id:x,structParent:S,popupRef:C},container:k,parent:{page:{pageNumber:O}}}=e,P=k.querySelector("canvas"),D=i.imageManager.getFromCanvas(k.id,P);P.remove();const R=((m=await s._structTree.getAriaAttributes(`${Fg}${x}`))==null?void 0:m.get("aria-label"))||"";n=e={annotationType:ot.STAMP,bitmapId:D.id,bitmap:D.bitmap,pageIndex:O-1,rect:y.slice(0),rotation:b,id:x,deleted:!1,accessibilityData:{decorative:!1,altText:R},isSvg:!1,structParent:S,popupRef:C}}const r=await super.deserialize(e,s,i),{rect:a,bitmap:h,bitmapUrl:c,bitmapId:u,isSvg:d,accessibilityData:f}=e;u&&i.imageManager.isValidId(u)?(v(r,Ae,u),h&&v(r,Gt,h)):v(r,Fn,c),v(r,Ds,d);const[g,p]=r.pageDimensions;return r.width=(a[2]-a[0])/g,r.height=(a[3]-a[1])/p,r.annotationElementId=e.id||null,f&&(r.altTextData=f),r._initialData=n,v(r,Rh,!!n),r}serialize(e=!1,s=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const i={annotationType:ot.STAMP,bitmapId:l(this,Ae),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:l(this,Ds),structTreeParentId:this._structTreeParentId};if(e)return i.bitmapUrl=w(this,vt,Tf).call(this,!0),i.accessibilityData=this.serializeAltText(!0),i;const{decorative:n,altText:r}=this.serializeAltText(!1);if(!n&&r&&(i.accessibilityData={type:"Figure",alt:r}),this.annotationElementId){const h=w(this,vt,c_).call(this,i);if(h.isSame)return null;h.isSameAltText?delete i.accessibilityData:i.accessibilityData.structParent=this._initialData.structParent??-1}if(i.id=this.annotationElementId,s===null)return i;s.stamps||(s.stamps=new Map);const a=l(this,Ds)?(i.rect[2]-i.rect[0])*(i.rect[3]-i.rect[1]):null;if(!s.stamps.has(l(this,Ae)))s.stamps.set(l(this,Ae),{area:a,serialized:i}),i.bitmap=w(this,vt,Tf).call(this,!1);else if(l(this,Ds)){const h=s.stamps.get(l(this,Ae));a>h.area&&(h.area=a,h.serialized.bitmap.close(),h.serialized.bitmap=w(this,vt,Tf).call(this,!1))}return i}renderAnnotationElement(e){return e.updateEdited({rect:this.getRect(0,0)}),null}};Gt=new WeakMap,Ae=new WeakMap,Cr=new WeakMap,Fn=new WeakMap,Ar=new WeakMap,Dh=new WeakMap,Wi=new WeakMap,Gi=new WeakMap,Ds=new WeakMap,Rh=new WeakMap,vt=new WeakSet,ru=function(e,s=!1){if(!e){this.remove();return}v(this,Gt,e.bitmap),s||(v(this,Ae,e.id),v(this,Ds,e.isSvg)),e.file&&v(this,Dh,e.file.name),w(this,vt,um).call(this)},au=function(){if(v(this,Cr,null),this._uiManager.enableWaiting(!1),!!l(this,Wi)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&l(this,Gt)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&l(this,Gt)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},Cf=function(){if(l(this,Ae)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(l(this,Ae)).then(i=>w(this,vt,ru).call(this,i,!0)).finally(()=>w(this,vt,au).call(this));return}if(l(this,Fn)){const i=l(this,Fn);v(this,Fn,null),this._uiManager.enableWaiting(!0),v(this,Cr,this._uiManager.imageManager.getFromUrl(i).then(n=>w(this,vt,ru).call(this,n)).finally(()=>w(this,vt,au).call(this)));return}if(l(this,Ar)){const i=l(this,Ar);v(this,Ar,null),this._uiManager.enableWaiting(!0),v(this,Cr,this._uiManager.imageManager.getFromFile(i).then(n=>w(this,vt,ru).call(this,n)).finally(()=>w(this,vt,au).call(this)));return}const e=document.createElement("input");e.type="file",e.accept=Gc.supportedTypesStr;const s=this._uiManager._signal;v(this,Cr,new Promise(i=>{e.addEventListener("change",async()=>{if(!e.files||e.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const n=await this._uiManager.imageManager.getFromFile(e.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),w(this,vt,ru).call(this,n)}i()},{signal:s}),e.addEventListener("cancel",()=>{this.remove(),i()},{signal:s})}).finally(()=>w(this,vt,au).call(this))),e.click()},um=function(){var d;const{div:e}=this;let{width:s,height:i}=l(this,Gt);const[n,r]=this.pageDimensions,a=.75;if(this.width)s=this.width*n,i=this.height*r;else if(s>a*n||i>a*r){const f=Math.min(a*n/s,a*r/i);s*=f,i*=f}const[h,c]=this.parentDimensions;this.setDims(s*h/n,i*c/r),this._uiManager.enableWaiting(!1);const u=v(this,Wi,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),this.width=s/n,this.height=i/r,(d=this._initialOptions)!=null&&d.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(e.hidden=!1),w(this,vt,dm).call(this),l(this,Rh)||(this.parent.addUndoableEditor(this),v(this,Rh,!0)),this._reportTelemetry({action:"inserted_image"}),l(this,Dh)&&u.setAttribute("aria-label",l(this,Dh))},Af=function(e,s){const{width:i,height:n}=l(this,Gt);let r=i,a=n,h=l(this,Gt);for(;r>2*e||a>2*s;){const c=r,u=a;r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2)),a>2*s&&(a=a>=16384?Math.floor(a/2)-1:Math.ceil(a/2));const d=new OffscreenCanvas(r,a);d.getContext("2d").drawImage(h,0,0,c,u,0,0,r,a),h=d.transferToImageBitmap()}return h},dm=function(){const[e,s]=this.parentDimensions,{width:i,height:n}=this,r=new Bg,a=Math.ceil(i*e*r.sx),h=Math.ceil(n*s*r.sy),c=l(this,Wi);if(!c||c.width===a&&c.height===h)return;c.width=a,c.height=h;const u=l(this,Ds)?l(this,Gt):w(this,vt,Af).call(this,a,h),d=c.getContext("2d");d.filter=this._uiManager.hcmFilter,d.drawImage(u,0,0,u.width,u.height,0,0,a,h)},Tf=function(e){if(e){if(l(this,Ds)){const n=this._uiManager.imageManager.getSvgUrl(l(this,Ae));if(n)return n}const s=document.createElement("canvas");return{width:s.width,height:s.height}=l(this,Gt),s.getContext("2d").drawImage(l(this,Gt),0,0),s.toDataURL()}if(l(this,Ds)){const[s,i]=this.pageDimensions,n=Math.round(this.width*s*Kn.PDF_TO_CSS_UNITS),r=Math.round(this.height*i*Kn.PDF_TO_CSS_UNITS),a=new OffscreenCanvas(n,r);return a.getContext("2d").drawImage(l(this,Gt),0,0,l(this,Gt).width,l(this,Gt).height,0,0,n,r),a.transferToImageBitmap()}return structuredClone(l(this,Gt))},c_=function(e){var a;const{pageIndex:s,accessibilityData:{altText:i}}=this._initialData,n=e.pageIndex===s,r=(((a=e.accessibilityData)==null?void 0:a.alt)||"")===i;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&n&&r,isSameAltText:r}},Q(Gc,"_type","stamp"),Q(Gc,"_editorType",ot.STAMP);let hp=Gc;const yi=class yi{constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:a,textLayer:h,viewport:c,l10n:u}){_(this,Nt);_(this,eo);_(this,Fh,!1);_(this,Xi,null);_(this,Tr,null);_(this,Ln,null);_(this,Ys,new Map);_(this,Er,!1);_(this,Lh,!1);_(this,so,!1);_(this,bi,null);_(this,In,null);_(this,je,null);_(this,jn,null);_(this,$);const d=[...l(yi,kr).values()];if(!yi._initialized){yi._initialized=!0;for(const f of d)f.initialize(u,t)}t.registerEditorTypes(d),v(this,$,t),this.pageIndex=e,this.div=s,v(this,eo,n),v(this,Xi,r),this.viewport=c,v(this,je,h),this.drawLayer=a,this._structTree=i,l(this,$).addLayer(this)}get isEmpty(){return l(this,Ys).size===0}get isInvisible(){return this.isEmpty&&l(this,$).getMode()===ot.NONE}updateToolbar(t){l(this,$).updateToolbar(t)}updateMode(t=l(this,$).getMode()){switch(w(this,Nt,Ef).call(this),t){case ot.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case ot.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case ot.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of l(yi,kr).values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){var e;return t===((e=l(this,je))==null?void 0:e.div)}setEditingState(t){l(this,$).setEditingState(t)}addCommands(t){l(this,$).addCommands(t)}cleanUndoStack(t){l(this,$).cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){var e;(e=l(this,Xi))==null||e.div.classList.toggle("disabled",!t)}async enable(){v(this,so,!0),this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of l(this,Ys).values())s.enableEditing(),s.show(!0),s.annotationElementId&&(l(this,$).removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!l(this,Xi)){v(this,so,!1);return}const e=l(this,Xi).getEditableAnnotations();for(const s of e){if(s.hide(),l(this,$).isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}v(this,so,!1)}disable(){var i;v(this,Lh,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const n of l(this,Ys).values())if(n.disableEditing(),!!n.annotationElementId){if(n.serialize()!==null){t.set(n.annotationElementId,n);continue}else e.set(n.annotationElementId,n);(i=this.getEditableAnnotation(n.annotationElementId))==null||i.show(),n.remove()}if(l(this,Xi)){const n=l(this,Xi).getEditableAnnotations();for(const r of n){const{id:a}=r.data;if(l(this,$).isDeletedAnnotationElement(a))continue;let h=e.get(a);if(h){h.resetAnnotationElement(r),h.show(!1),r.show();continue}h=t.get(a),h&&(l(this,$).addChangedExistingAnnotation(h),h.renderAnnotationElement(r)&&h.show(!1)),r.show()}}w(this,Nt,Ef).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const n of l(yi,kr).values())s.remove(`${n._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),v(this,Lh,!1)}getEditableAnnotation(t){var e;return((e=l(this,Xi))==null?void 0:e.getEditableAnnotation(t))||null}setActiveEditor(t){l(this,$).getActive()!==t&&l(this,$).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=l(this,je))!=null&&t.div&&!l(this,jn)){v(this,jn,new AbortController);const e=l(this,$).combinedSignal(l(this,jn));l(this,je).div.addEventListener("pointerdown",w(this,Nt,u_).bind(this),{signal:e}),l(this,je).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=l(this,je))!=null&&t.div&&l(this,jn)&&(l(this,jn).abort(),v(this,jn,null),l(this,je).div.classList.remove("highlighting"))}enableClick(){if(l(this,Tr))return;v(this,Tr,new AbortController);const t=l(this,$).combinedSignal(l(this,Tr));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){var t;(t=l(this,Tr))==null||t.abort(),v(this,Tr,null)}attach(t){l(this,Ys).set(t.id,t);const{annotationElementId:e}=t;e&&l(this,$).isDeletedAnnotationElement(e)&&l(this,$).removeDeletedAnnotationElement(t)}detach(t){var e;l(this,Ys).delete(t.id),(e=l(this,eo))==null||e.removePointerInTextLayer(t.contentDiv),!l(this,Lh)&&t.annotationElementId&&l(this,$).addDeletedAnnotationElement(t)}remove(t){this.detach(t),l(this,$).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){var e;t.parent!==this&&(t.parent&&t.annotationElementId&&(l(this,$).addDeletedAnnotationElement(t.annotationElementId),Vt.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(e=t.parent)==null||e.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),l(this,$).addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!l(this,so)),l(this,$).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var s;if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!l(this,Ln)&&(t._focusEventsAllowed=!1,v(this,Ln,setTimeout(()=>{v(this,Ln,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:l(this,$)._signal}),e.focus())},0))),t._structTreeParentId=(s=l(this,eo))==null?void 0:s.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||(t.parent=this),t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return l(this,$).getId()}combinedSignal(t){return l(this,$).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=l(this,Nt,Yi))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,e){l(this,$).updateToolbar(t),l(this,$).updateMode(t);const{offsetX:s,offsetY:i}=w(this,Nt,gm).call(this),n=this.getNextId(),r=w(this,Nt,fm).call(this,{parent:this,id:n,x:s,y:i,uiManager:l(this,$),isCentered:!0,...e});r&&this.add(r)}async deserialize(t){var e;return await((e=l(yi,kr).get(t.annotationType??t.annotationEditorType))==null?void 0:e.deserialize(t,this,l(this,$)))||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=w(this,Nt,fm).call(this,{parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:l(this,$),isCentered:e,...s});return n&&this.add(n),n}addNewEditor(){this.createAndAddNewEditor(w(this,Nt,gm).call(this),!0)}setSelected(t){l(this,$).setSelected(t)}toggleSelected(t){l(this,$).toggleSelected(t)}unselect(t){l(this,$).unselect(t)}pointerup(t){var s;const{isMac:e}=Ue.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&l(this,Er)&&(v(this,Er,!1),!((s=l(this,Nt,Yi))!=null&&s.isDrawer&&l(this,Nt,Yi).supportMultipleDrawings))){if(!l(this,Fh)){v(this,Fh,!0);return}if(l(this,$).getMode()===ot.STAMP){l(this,$).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){var i;if(l(this,$).getMode()===ot.HIGHLIGHT&&this.enableTextSelection(),l(this,Er)){v(this,Er,!1);return}const{isMac:e}=Ue.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(v(this,Er,!0),(i=l(this,Nt,Yi))!=null&&i.isDrawer){this.startDrawingSession(t);return}const s=l(this,$).getActive();v(this,Fh,!s||s.isEmpty())}startDrawingSession(t){if(this.div.focus(),l(this,bi)){l(this,Nt,Yi).startDrawing(this,l(this,$),!1,t);return}l(this,$).setCurrentDrawingSession(this),v(this,bi,new AbortController);const e=l(this,$).combinedSignal(l(this,bi));this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(v(this,In,null),this.commitOrRemove())},{signal:e}),l(this,Nt,Yi).startDrawing(this,l(this,$),!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&v(this,In,e);return}l(this,In)&&setTimeout(()=>{var e;(e=l(this,In))==null||e.focus(),v(this,In,null)},0)}endDrawingSession(t=!1){return l(this,bi)?(l(this,$).setCurrentDrawingSession(null),l(this,bi).abort(),v(this,bi,null),v(this,In,null),l(this,Nt,Yi).endDrawing(t)):null}findNewParent(t,e,s){const i=l(this,$).findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return l(this,bi)?(this.endDrawingSession(),!0):!1}onScaleChanging(){l(this,bi)&&l(this,Nt,Yi).onScaleChangingWhenDrawing(this)}destroy(){var t,e;this.commitOrRemove(),((t=l(this,$).getActive())==null?void 0:t.parent)===this&&(l(this,$).commitOrRemove(),l(this,$).setActiveEditor(null)),l(this,Ln)&&(clearTimeout(l(this,Ln)),v(this,Ln,null));for(const s of l(this,Ys).values())(e=l(this,eo))==null||e.removePointerInTextLayer(s.contentDiv),s.setParent(null),s.isAttachedToDOM=!1,s.div.remove();this.div=null,l(this,Ys).clear(),l(this,$).removeLayer(this)}render({viewport:t}){this.viewport=t,Yr(this.div,t);for(const e of l(this,$).getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){l(this,$).commitOrRemove(),w(this,Nt,Ef).call(this);const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,Yr(this.div,{rotation:s}),e!==s)for(const i of l(this,Ys).values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return l(this,$).viewParameters.realScale}};eo=new WeakMap,Fh=new WeakMap,Xi=new WeakMap,Tr=new WeakMap,Ln=new WeakMap,Ys=new WeakMap,Er=new WeakMap,Lh=new WeakMap,so=new WeakMap,bi=new WeakMap,In=new WeakMap,je=new WeakMap,jn=new WeakMap,$=new WeakMap,kr=new WeakMap,Nt=new WeakSet,u_=function(t){l(this,$).unselectAll();const{target:e}=t;if(e===l(this,je).div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&l(this,je).div.contains(e)){const{isMac:s}=Ue.platform;if(t.button!==0||t.ctrlKey&&s)return;l(this,$).showAllEditors("highlight",!0,!0),l(this,je).div.classList.add("free"),this.toggleDrawing(),Ed.startHighlighting(this,l(this,$).direction==="ltr",{target:l(this,je).div,x:t.x,y:t.y}),l(this,je).div.addEventListener("pointerup",()=>{l(this,je).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:l(this,$)._signal}),t.preventDefault()}},Yi=function(){return l(yi,kr).get(l(this,$).getMode())},fm=function(t){const e=l(this,Nt,Yi);return e?new e.prototype.constructor(t):null},gm=function(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),a=Math.min(window.innerWidth,t+s),h=Math.min(window.innerHeight,e+i),c=(n+a)/2-t,u=(r+h)/2-e,[d,f]=this.viewport.rotation%180===0?[c,u]:[u,c];return{offsetX:d,offsetY:f}},Ef=function(){for(const t of l(this,Ys).values())t.isEmpty()&&t.remove()},Q(yi,"_initialized",!1),_(yi,kr,new Map([sp,op,hp,Ed].map(t=>[t._editorType,t])));let lp=yi;const Ne=class Ne{constructor({pageIndex:t}){_(this,Ui);_(this,_i,null);_(this,Xc,0);_(this,Qe,new Map);_(this,io,new Map);this.pageIndex=t}setParent(t){if(!l(this,_i)){v(this,_i,t);return}if(l(this,_i)!==t){if(l(this,Qe).size>0)for(const e of l(this,Qe).values())e.remove(),t.append(e);v(this,_i,t)}}static get _svgFactory(){return ct(this,"_svgFactory",new Zg)}draw(t,e=!1,s=!1){const i=es(this,Xc)._++,n=w(this,Ui,pm).call(this),r=Ne._svgFactory.createElement("defs");n.append(r);const a=Ne._svgFactory.createElement("path");r.append(a);const h=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",h),a.setAttribute("vector-effect","non-scaling-stroke"),e&&l(this,io).set(i,a);const c=s?w(this,Ui,f_).call(this,r,h):null,u=Ne._svgFactory.createElement("use");return n.append(u),u.setAttribute("href",`#${h}`),this.updateProperties(n,t),l(this,Qe).set(i,n),{id:i,clipPathId:`url(#${c})`}}drawOutline(t,e){const s=es(this,Xc)._++,i=w(this,Ui,pm).call(this),n=Ne._svgFactory.createElement("defs");i.append(n);const r=Ne._svgFactory.createElement("path");n.append(r);const a=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",a),r.setAttribute("vector-effect","non-scaling-stroke");let h;if(e){const d=Ne._svgFactory.createElement("mask");n.append(d),h=`mask_p${this.pageIndex}_${s}`,d.setAttribute("id",h),d.setAttribute("maskUnits","objectBoundingBox");const f=Ne._svgFactory.createElement("rect");d.append(f),f.setAttribute("width","1"),f.setAttribute("height","1"),f.setAttribute("fill","white");const g=Ne._svgFactory.createElement("use");d.append(g),g.setAttribute("href",`#${a}`),g.setAttribute("stroke","none"),g.setAttribute("fill","black"),g.setAttribute("fill-rule","nonzero"),g.classList.add("mask")}const c=Ne._svgFactory.createElement("use");i.append(c),c.setAttribute("href",`#${a}`),h&&c.setAttribute("mask",`url(#${h})`);const u=c.cloneNode();return i.append(u),c.classList.add("mainOutline"),u.classList.add("secondaryOutline"),this.updateProperties(i,t),l(this,Qe).set(s,i),s}finalizeDraw(t,e){l(this,io).delete(t),this.updateProperties(t,e)}updateProperties(t,e){var h;if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,a=typeof t=="number"?l(this,Qe).get(t):t;if(a){if(s&&w(this,Ui,mm).call(this,a,s),i&&w(h=Ne,Yd,d_).call(h,a,i),n){const{classList:c}=a;for(const[u,d]of Object.entries(n))c.toggle(u,d)}if(r){const u=a.firstChild.firstChild;w(this,Ui,mm).call(this,u,r)}}}updateParent(t,e){if(e===this)return;const s=l(this,Qe).get(t);s&&(l(e,_i).append(s),l(this,Qe).delete(t),l(e,Qe).set(t,s))}remove(t){l(this,io).delete(t),l(this,_i)!==null&&(l(this,Qe).get(t).remove(),l(this,Qe).delete(t))}destroy(){v(this,_i,null);for(const t of l(this,Qe).values())t.remove();l(this,Qe).clear(),l(this,io).clear()}};_i=new WeakMap,Xc=new WeakMap,Qe=new WeakMap,io=new WeakMap,Yd=new WeakSet,d_=function(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`},Ui=new WeakSet,pm=function(){const t=Ne._svgFactory.create(1,1,!0);return l(this,_i).append(t),t.setAttribute("aria-hidden",!0),t},f_=function(t,e){const s=Ne._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=Ne._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i},mm=function(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)},_(Ne,Yd);let cp=Ne;globalThis.pdfjsTestingUtils={HighlightOutliner:ip},tt.AbortException,tt.AnnotationEditorLayer,tt.AnnotationEditorParamsType,tt.AnnotationEditorType,tt.AnnotationEditorUIManager,tt.AnnotationLayer,tt.AnnotationMode,tt.ColorPicker,tt.DOMSVGFactory,tt.DrawLayer,tt.FeatureTest;var tA=tt.GlobalWorkerOptions;tt.ImageKind,tt.InvalidPDFException,tt.MissingPDFException,tt.OPS,tt.OutputScale,tt.PDFDataRangeTransport,tt.PDFDateString,tt.PDFWorker,tt.PasswordResponses,tt.PermissionFlag,tt.PixelsPerInch,tt.RenderingCancelledException,tt.TextLayer,tt.TouchManager,tt.UnexpectedResponseException,tt.Util,tt.VerbosityLevel,tt.XfaLayer,tt.build,tt.createValidAbsoluteUrl,tt.fetchData;var eA=tt.getDocument;tt.getFilenameFromUrl,tt.getPdfFilenameFromUrl,tt.getXfaPageViewport,tt.isDataScheme,tt.isPdfFile,tt.noContextMenu,tt.normalizeUnicode,tt.setLayerDimensions,tt.shadow,tt.stopEvent,tt.version;const sA={"pdfjs-dist":"4.10.38"};function iA(o){return new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>t(s.result)),s.addEventListener("error",e),s.readAsDataURL(o)})}const nA=sA["pdfjs-dist"].replace("^","");tA.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${nA}/pdf.worker.min.mjs`;async function rA(o){const t="data:application/pdf;base64,",e=await iA(o);if(typeof e=="string")return window.atob(e.slice(t.length))}function aA(o,t){return eA({data:o,password:t}).promise}const hs=new Map;function oA(o){const t=new pg(o);return hs.set(o,t),t}function hA(o,t){const e=Date.now();return{PDFId:`${o.name}-${e}`,name:o.name.replace(/.pdf/,""),updateDate:e,PDFBase64:t}}function lA(o,t){const e=o.getViewport({scale:t}),s=document.createElement("canvas"),i=s.getContext("2d"),n=Jx()/window.devicePixelRatio;s.width=Math.floor(e.width*n),s.height=Math.floor(e.height*n);const r={canvasContext:i,viewport:e,transform:[n,0,0,n,0,0]},a=o.render(r);return{canvas:s,renderTask:a}}async function cA({src:o},t,e){if(!o||!e)return null;const{objects:s,options:i}=await Bx(o),n=s.filter(a=>a!==null),r=Zw.groupSVGElements(n,i);return n.forEach(a=>{a.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function uA(o,t){if(!hs.get(o))return;const s=1/3,i=bA(t,s);xb(o,i,s)}async function dA(o,t){const e=await Zx(t),s=Date.now(),n={PDFId:`${t.name}${s}`,name:t.name.replace(/.png|.jpg|.jpeg/,""),updateDate:s,PDFBase64:e};return wb(o,{url:e}),{...n,pages:1}}async function wb(o,{url:t,scale:e=.5}){if(!hs.get(o))return;const i=await Me.fromURL(t);i.scale(e),xb(o,i,e)}function xb(o,t,e){const s=hs.get(o);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function fA(o,t){if(!t)return;const{oCoords:e}=o;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:a,scaleX:h}=t;t.top=i-n*a/2,t.left=s-r*h/2,t.setCoords()}function gA(o,t,e){!e||!o||(e.scale(1/t),fA(o,e))}function pA(o,t){if(!o)return;const e=o._cornerSize||6;o.borderScaleFactor=1/t,o.cornerSize=e*(1/t),o.touchCornerSize=e*4*(1/t),o.setCoords()}function mA(o){const t=hs.get(o);t&&(t.discardActiveObject(),t.renderAll())}function vA(o){const t=hs.get(o);t&&(t.clear(),hs.delete(o))}function bA(o,t){return new Me(o,{scaleX:t,scaleY:t})}function up(o,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:a}=o,h=t.x*r*i,c=t.y*a*n;o.set({left:e-h,top:s-c})}function Sb(o,t,e){var n;const s=o.type,i={"application/pdf":yA,"image/png":Ab,"image/jpeg":Ab};return((n=i[s])==null?void 0:n.call(i,o,t,e))??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function yA(o,t,e){const s=await rA(o);if(!s)return;const i=hA(o,s);try{const n=await Cb({page:1,PDFBase64:s,scale:.8,password:t},e);return{...i,pages:n}}catch(n){return Promise.reject(n)}}async function Cb({page:o,PDFBase64:t,scale:e,password:s},i){try{const n=await aA(t,s),r=await n.getPage(o),{renderTask:a,canvas:h}=lA(r,e);return a.promise.then(()=>(i&&uA(i,h),n.numPages))}catch(n){return Promise.reject(n)}}async function Ab(o,t,e){if(e)return await dA(e,o)}async function _A(o,t){const e=hs.get(o);if(!e)return;const s=e==null?void 0:e.getActiveObject();if(!s)return;const i=await s.clone(w_);i instanceof Ls?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),up(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function wA(o){const t=hs.get(o);if(!t)return;const e=t.getActiveObject();e&&(e instanceof Ls?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function Tb(o){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:a}=o||{},h=Z.useRef(null),c=Z.useRef(null),u=Z.useRef(1),d=Z.useRef({...__});function f(){if(!t||hs.has(t))return;const F=oA(t);return F.on("selection:created",L=>{if(r==null||r(L),L.selected.length<=1)return;const N=F.getActiveObject();N&&(c.current=N,e!=null&&e.value&&c.current.set(e.value),c.current._cornerSize=c.current.cornerSize,k(u.current))}),F.on("selection:cleared",L=>{a==null||a(L),P(F)}),s&&F.on("mouse:down",s),i&&F.on("mouse:move",i),n&&F.on("mouse:up",n),F}function g(F,L){return Sb(F,L,t)}function p(F){return Cb(F,t)}function m({url:F,scale:L=.5}){return wb(t,{url:F,scale:L})}async function y(F,L,N){const K=hs.get(t);if(!K)return;const I=await Me.fromURL(F,{},{...v_,...L});up(I,N),K.add(I),x(K,I),K.setActiveObject(I)}function b(F,L,N){const K=hs.get(t);if(!K)return;const I=new Pe(F,{...b_,...L});up(I,N),K.add(I),x(K,I),K.setActiveObject(I)}function x(F,L){L.on("selected",N=>S({canvas:F,target:N.target})),L.on("modified",N=>S({canvas:F,target:N.target})),L.on("scaling",()=>P(F)),L.on("moving",()=>P(F)),L.on("rotating",()=>P(F)),L._cornerSize=L._cornerSize??L.cornerSize}async function S({canvas:F,target:L,stroke:N=d.current.stroke,uuid:K=Date.now()}){var it;if(F.getActiveObjects().length>1||((it=h.current)==null?void 0:it.stroke)===`${N}-${K}`)return;const V=await cA(d.current,K,N);P(F),h.current=V,c.current=L,C(F,L,K),k(u.current,!0),V&&F.add(V)}function C(F,L,N){h.current&&(h.current.on("selected",()=>{F.remove(L),P(F)}),h.current.on("mouseover",()=>{S({canvas:F,target:L,stroke:d.current.hoverStroke,uuid:N})}),h.current.on("mouseout",()=>{S({canvas:F,target:L,stroke:d.current.stroke,uuid:N})}))}function k(F,L=!1){const N=hs.get(t);u.current=F,N&&(pA(c.current,F),gA(c.current,F,h.current),!L&&N.renderAll())}function O(F){if(!F)return;d.current={...d.current,...F};const L=hs.get(t);!h||!c.current||!L||S({target:c.current,canvas:L})}function P(F){c.current=null,h.current&&(F.remove(h.current),h.current=null)}function D(){mA(t)}function R(){vA(t)}function z(){return _A(t,x)}function B(){wA(t)}return{createCanvas:f,loadFile:g,specifyPage:p,renderImage:m,addFabric:y,addTextFabric:b,clearActive:D,deleteCanvas:R,scaleFabric:k,setCloseSvgOptions:O,copyActiveFabric:z,deleteActiveFabric:B}}function xA(o){let t=0;const e=Qx(()=>{t!==window.innerWidth&&(t=window.innerWidth,o())});Z.useEffect(()=>(window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)),[])}const SA=Z.forwardRef(CA);function CA({file:o,page:t=1,canvasId:e="PDF-canvas",fileZoom:s=1,fileScale:i=1,canvasScale:n=1,canvasClass:r="",isDrop:a=!1,password:h,dropTextOptions:c,dropImageOptions:u,closeSvgOptions:d,selectionOptions:f,manualReload:g,onLoaded:p,onReload:m,onPointerDown:y,onPointerMove:b,onPointerUp:x,onSelectionCreated:S,onSelectionCleared:C},k){const O=Z.useRef(null),P=`${e}-${t-1}`,D=Z.useMemo(()=>s*n,[s,n]),R=Z.useMemo(()=>({...y_,...f}),[f]),{createCanvas:z,specifyPage:B,addFabric:F,addTextFabric:L,renderImage:N,clearActive:K,deleteCanvas:I,scaleFabric:V,setCloseSvgOptions:it,copyActiveFabric:Ot,deleteActiveFabric:Bt}=Tb({id:P,selectionOptions:R,pointerDown:y,pointerMove:b,pointerUp:x,selectionCreated:S,selectionCleared:C});xA(Ze);async function Xt(){window.requestAnimationFrame(async()=>{if(z(),o.PDFBase64.startsWith("data:image")||o.canvas){const{canvas:st}=o,nt=st?7:3,Zt=st!=null&&st.length?st[t-1]:o.PDFBase64;N({url:Zt,scale:i/nt});return}await B({page:t,PDFBase64:o.PDFBase64,scale:i,password:h}),p==null||p()})}function Ft(st){if(st.preventDefault(),st.stopPropagation(),!a||!st.dataTransfer)return;const{dataTransfer:nt,nativeEvent:Zt}=st,{offsetX:$s,offsetY:Te}=Zt,$d=nt.getData("text/plain"),Uc=nt.getData("text/uri-list"),qd=nt.getData("custom/offset"),Pr=qd?JSON.parse(qd):null,no={top:Te,left:$s},Mr={x:(Pr==null?void 0:Pr.offsetX)??0,y:(Pr==null?void 0:Pr.offsetY)??0};Uc?_t(Uc,no,Mr):$d&&ae($d,no,Mr)}function _t(st,nt,Zt){F(st,{...u,...nt},Zt)}function ae(st,nt,Zt){L(st,{...c,...nt},Zt)}function Ze(){g||Xt(),m==null||m()}return Z.useImperativeHandle(k,()=>({reload:Xt,addImage:_t,addText:ae,clearActive:K,deleteCanvas:I,copyActiveFabric:Ot,deleteActiveFabric:Bt,canvasRef:O})),Z.useEffect(()=>{Ze()},[i,t,o,h]),Z.useEffect(()=>{V(D)},[D]),Z.useEffect(()=>{it(d)},[d]),Z.useEffect(()=>()=>I(),[]),ym.jsx("div",{style:{transform:`scale(${D})`},onDragOver:st=>st.preventDefault(),onDragEnter:st=>st.preventDefault(),onDrop:Ft,children:ym.jsx("canvas",{id:P,ref:O,className:r})})}dt.default=SA,dt.loadFile=Sb,dt.useFabric=Tb,Object.defineProperties(dt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
533
|
+
`}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let i=0;i<e.length;i+=4){const n=e[i],r=e[i+1],a=e[i+2],l=Math.max(n,r,a),h=(n+r+a)/3,c=2*Math.abs(l-h)/255*s;e[i]+=l!==n?(l-n)*c:0,e[i+1]+=l!==r?(l-r)*c:0,e[i+2]+=l!==a?(l-a)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}S(Xn,"type","Vibrance"),S(Xn,"defaults",{vibrance:0}),S(Xn,"uniformLocations",["uVibrance"]),I.setClass(Xn);let vh=null;function bf(){const o=document.createElement("div");o.style.width="1in",document.body.append(o);const t=o.offsetWidth;return o.remove(),t}function yf(){const o=vh??bf();return vh=o,o/72}function _f(o,t=500){if(typeof o!="function")throw new TypeError("The first argument is not a function.");let e=null;return function(...s){e&&clearTimeout(e),e=setTimeout(()=>{e=null,o.apply(this,s)},t)}}function wf(o){return new Promise((t,e)=>{const s=window.URL.createObjectURL(o),i=new Image;i.src=s,i.addEventListener("load",async()=>{window.URL.revokeObjectURL(s),t(await xf(i))}),i.addEventListener("error",n=>{window.URL.revokeObjectURL(s),e(n)})})}function xf(o){return new Promise(t=>{const e=document.createElement("canvas"),s=e.getContext("2d"),{naturalWidth:i,naturalHeight:n}=o;e.width=i,e.height=n,s?.drawImage(o,0,0,i,n),t(e.toDataURL("image/jpeg",.8))})}var Pi={};Pi.d=(o,t)=>{for(var e in t)Pi.o(t,e)&&!Pi.o(o,e)&&Object.defineProperty(o,e,{enumerable:!0,get:t[e]})},Pi.o=(o,t)=>Object.prototype.hasOwnProperty.call(o,t);var X=globalThis.pdfjsLib={};Pi.d(X,{AbortException:()=>cs,AnnotationEditorLayer:()=>ss,AnnotationEditorParamsType:()=>st,AnnotationEditorType:()=>J,AnnotationEditorUIManager:()=>us,AnnotationLayer:()=>vp,AnnotationMode:()=>ls,ColorPicker:()=>ye,DOMSVGFactory:()=>za,DrawLayer:()=>te,FeatureTest:()=>Qt,GlobalWorkerOptions:()=>Ni,ImageKind:()=>Un,InvalidPDFException:()=>wa,MissingPDFException:()=>Oi,OPS:()=>Me,OutputScale:()=>Pa,PDFDataRangeTransport:()=>Zh,PDFDateString:()=>Sh,PDFWorker:()=>ii,PasswordResponses:()=>Tf,PermissionFlag:()=>Af,PixelsPerInch:()=>ti,RenderingCancelledException:()=>Ta,TextLayer:()=>Zt,TouchManager:()=>er,UnexpectedResponseException:()=>Kn,Util:()=>z,VerbosityLevel:()=>Yn,XfaLayer:()=>ic,build:()=>Jg,createValidAbsoluteUrl:()=>Mf,fetchData:()=>Qn,getDocument:()=>Vg,getFilenameFromUrl:()=>Bf,getPdfFilenameFromUrl:()=>Hf,getXfaPageViewport:()=>zf,isDataScheme:()=>Zn,isPdfFile:()=>Ea,noContextMenu:()=>Oe,normalizeUnicode:()=>If,setLayerDimensions:()=>Ms,shadow:()=>tt,stopEvent:()=>ge,version:()=>Kg});const Gt=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),bh=[1,0,0,1,0,0],ba=[.001,0,0,.001,0,0],Sf=1e7,ya=1.35,fe={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},ls={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Cf="pdfjs_internal_editor_",J={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},st={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35,DRAW_STEP:41},Af={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Wt={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Un={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Lt={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,WIDGET:20},Mi={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Yn={ERRORS:0,WARNINGS:1,INFOS:5},Me={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},Tf={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let $n=Yn.WARNINGS;function Ef(o){Number.isInteger(o)&&($n=o)}function kf(){return $n}function qn(o){$n>=Yn.INFOS&&console.log(`Info: ${o}`)}function Q(o){$n>=Yn.WARNINGS&&console.log(`Warning: ${o}`)}function ut(o){throw new Error(o)}function Mt(o,t){o||ut(t)}function Pf(o){switch(o?.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function Mf(o,t=null,e=null){if(!o)return null;try{if(e&&typeof o=="string"&&(e.addDefaultProtocol&&o.startsWith("www.")&&o.match(/\./g)?.length>=2&&(o=`http://${o}`),e.tryConvertEncoding))try{o=Lf(o)}catch{}const s=t?new URL(o,t):new URL(o);if(Pf(s))return s}catch{}return null}function tt(o,t,e,s=!1){return Object.defineProperty(o,t,{value:e,enumerable:!s,configurable:!0,writable:!1}),e}const hs=function(){function t(e,s){this.message=e,this.name=s}return t.prototype=new Error,t.constructor=t,t}();class yh extends hs{constructor(t,e){super(t,"PasswordException"),this.code=e}}class _a extends hs{constructor(t,e){super(t,"UnknownErrorException"),this.details=e}}class wa extends hs{constructor(t){super(t,"InvalidPDFException")}}class Oi extends hs{constructor(t){super(t,"MissingPDFException")}}class Kn extends hs{constructor(t,e){super(t,"UnexpectedResponseException"),this.status=e}}class Of extends hs{constructor(t){super(t,"FormatError")}}class cs extends hs{constructor(t){super(t,"AbortException")}}function _h(o){(typeof o!="object"||o?.length===void 0)&&ut("Invalid argument for bytesToString");const t=o.length,e=8192;if(t<e)return String.fromCharCode.apply(null,o);const s=[];for(let i=0;i<t;i+=e){const n=Math.min(i+e,t),r=o.subarray(i,n);s.push(String.fromCharCode.apply(null,r))}return s.join("")}function Jn(o){typeof o!="string"&&ut("Invalid argument for stringToBytes");const t=o.length,e=new Uint8Array(t);for(let s=0;s<t;++s)e[s]=o.charCodeAt(s)&255;return e}function Df(o){return String.fromCharCode(o>>24&255,o>>16&255,o>>8&255,o&255)}function xa(o){const t=Object.create(null);for(const[e,s]of o)t[e]=s;return t}function Rf(){const o=new Uint8Array(4);return o[0]=1,new Uint32Array(o.buffer,0,1)[0]===1}function Ff(){try{return new Function(""),!0}catch{return!1}}class Qt{static get isLittleEndian(){return tt(this,"isLittleEndian",Rf())}static get isEvalSupported(){return tt(this,"isEvalSupported",Ff())}static get isOffscreenCanvasSupported(){return tt(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return tt(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get platform(){return typeof navigator<"u"&&typeof navigator?.platform=="string"?tt(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof navigator?.userAgent=="string"&&navigator.userAgent.includes("Firefox")}):tt(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){return tt(this,"isCSSRoundSupported",globalThis.CSS?.supports?.("width: round(1.5px, 1px)"))}}const Sa=Array.from(Array(256).keys(),o=>o.toString(16).padStart(2,"0"));class z{static makeHexColor(t,e,s){return`#${Sa[t]}${Sa[e]}${Sa[s]}`}static scaleMinMax(t,e){let s;t[0]?(t[0]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[0],e[2]*=t[0],t[3]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[3],e[3]*=t[3]):(s=e[0],e[0]=e[1],e[1]=s,s=e[2],e[2]=e[3],e[3]=s,t[1]<0&&(s=e[1],e[1]=e[3],e[3]=s),e[1]*=t[1],e[3]*=t[1],t[2]<0&&(s=e[0],e[0]=e[2],e[2]=s),e[0]*=t[2],e[2]*=t[2]),e[0]+=t[4],e[1]+=t[5],e[2]+=t[4],e[3]+=t[5]}static transform(t,e){return[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],t[0]*e[4]+t[2]*e[5]+t[4],t[1]*e[4]+t[3]*e[5]+t[5]]}static applyTransform(t,e){const s=t[0]*e[0]+t[1]*e[2]+e[4],i=t[0]*e[1]+t[1]*e[3]+e[5];return[s,i]}static applyInverseTransform(t,e){const s=e[0]*e[3]-e[1]*e[2],i=(t[0]*e[3]-t[1]*e[2]+e[2]*e[5]-e[4]*e[3])/s,n=(-t[0]*e[1]+t[1]*e[0]+e[4]*e[1]-e[5]*e[0])/s;return[i,n]}static getAxialAlignedBoundingBox(t,e){const s=this.applyTransform(t,e),i=this.applyTransform(t.slice(2,4),e),n=this.applyTransform([t[0],t[3]],e),r=this.applyTransform([t[2],t[1]],e);return[Math.min(s[0],i[0],n[0],r[0]),Math.min(s[1],i[1],n[1],r[1]),Math.max(s[0],i[0],n[0],r[0]),Math.max(s[1],i[1],n[1],r[1])]}static inverseTransform(t){const e=t[0]*t[3]-t[1]*t[2];return[t[3]/e,-t[1]/e,-t[2]/e,t[0]/e,(t[2]*t[5]-t[4]*t[3])/e,(t[4]*t[1]-t[5]*t[0])/e]}static singularValueDecompose2dScale(t){const e=[t[0],t[2],t[1],t[3]],s=t[0]*e[0]+t[1]*e[2],i=t[0]*e[1]+t[1]*e[3],n=t[2]*e[0]+t[3]*e[2],r=t[2]*e[1]+t[3]*e[3],a=(s+r)/2,l=Math.sqrt((s+r)**2-4*(s*r-n*i))/2,h=a+l||1,c=a-l||1;return[Math.sqrt(h),Math.sqrt(c)]}static normalizeRect(t){const e=t.slice(0);return t[0]>t[2]&&(e[0]=t[2],e[2]=t[0]),t[1]>t[3]&&(e[1]=t[3],e[3]=t[1]),e}static intersect(t,e){const s=Math.max(Math.min(t[0],t[2]),Math.min(e[0],e[2])),i=Math.min(Math.max(t[0],t[2]),Math.max(e[0],e[2]));if(s>i)return null;const n=Math.max(Math.min(t[1],t[3]),Math.min(e[1],e[3])),r=Math.min(Math.max(t[1],t[3]),Math.max(e[1],e[3]));return n>r?null:[s,n,i,r]}static#t(t,e,s,i,n,r,a,l,h,c){if(h<=0||h>=1)return;const u=1-h,d=h*h,f=d*h,g=u*(u*(u*t+3*h*e)+3*d*s)+f*i,p=u*(u*(u*n+3*h*r)+3*d*a)+f*l;c[0]=Math.min(c[0],g),c[1]=Math.min(c[1],p),c[2]=Math.max(c[2],g),c[3]=Math.max(c[3],p)}static#e(t,e,s,i,n,r,a,l,h,c,u,d){if(Math.abs(h)<1e-12){Math.abs(c)>=1e-12&&this.#t(t,e,s,i,n,r,a,l,-u/c,d);return}const f=c**2-4*u*h;if(f<0)return;const g=Math.sqrt(f),p=2*h;this.#t(t,e,s,i,n,r,a,l,(-c+g)/p,d),this.#t(t,e,s,i,n,r,a,l,(-c-g)/p,d)}static bezierBoundingBox(t,e,s,i,n,r,a,l,h){return h?(h[0]=Math.min(h[0],t,a),h[1]=Math.min(h[1],e,l),h[2]=Math.max(h[2],t,a),h[3]=Math.max(h[3],e,l)):h=[Math.min(t,a),Math.min(e,l),Math.max(t,a),Math.max(e,l)],this.#e(t,s,n,a,e,i,r,l,3*(-t+3*(s-n)+a),6*(t-2*s+n),3*(s-t),h),this.#e(t,s,n,a,e,i,r,l,3*(-e+3*(i-r)+l),6*(e-2*i+r),3*(i-e),h),h}}function Lf(o){return decodeURIComponent(escape(o))}let Ca=null,wh=null;function If(o){return Ca||(Ca=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,wh=new Map([["ſt","ſt"]])),o.replaceAll(Ca,(t,e,s)=>e?e.normalize("NFKC"):wh.get(s))}function jf(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const o=new Uint8Array(32);return crypto.getRandomValues(o),_h(o)}const Aa="pdfjs_internal_id_";function Nf(o){return Uint8Array.prototype.toBase64?o.toBase64():btoa(_h(o))}typeof Promise.try!="function"&&(Promise.try=function(o,...t){return new Promise(e=>{e(o(...t))})});const es="http://www.w3.org/2000/svg";class ti{static CSS=96;static PDF=72;static PDF_TO_CSS_UNITS=this.CSS/this.PDF}async function Qn(o,t="text"){if(Ri(o,document.baseURI)){const e=await fetch(o);if(!e.ok)throw new Error(e.statusText);switch(t){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"json":return e.json()}return e.text()}return new Promise((e,s)=>{const i=new XMLHttpRequest;i.open("GET",o,!0),i.responseType=t,i.onreadystatechange=()=>{if(i.readyState===XMLHttpRequest.DONE){if(i.status===200||i.status===0){switch(t){case"arraybuffer":case"blob":case"json":e(i.response);return}e(i.responseText);return}s(new Error(i.statusText))}},i.send(null)})}class Di{constructor({viewBox:t,userUnit:e,scale:s,rotation:i,offsetX:n=0,offsetY:r=0,dontFlip:a=!1}){this.viewBox=t,this.userUnit=e,this.scale=s,this.rotation=i,this.offsetX=n,this.offsetY=r,s*=e;const l=(t[2]+t[0])/2,h=(t[3]+t[1])/2;let c,u,d,f;switch(i%=360,i<0&&(i+=360),i){case 180:c=-1,u=0,d=0,f=1;break;case 90:c=0,u=1,d=1,f=0;break;case 270:c=0,u=-1,d=-1,f=0;break;case 0:c=1,u=0,d=0,f=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(d=-d,f=-f);let g,p,v,m;c===0?(g=Math.abs(h-t[1])*s+n,p=Math.abs(l-t[0])*s+r,v=(t[3]-t[1])*s,m=(t[2]-t[0])*s):(g=Math.abs(l-t[0])*s+n,p=Math.abs(h-t[1])*s+r,v=(t[2]-t[0])*s,m=(t[3]-t[1])*s),this.transform=[c*s,u*s,d*s,f*s,g-c*s*l-d*s*h,p-u*s*l-f*s*h],this.width=v,this.height=m}get rawDims(){const{userUnit:t,viewBox:e}=this,s=e.map(i=>i*t);return tt(this,"rawDims",{pageWidth:s[2]-s[0],pageHeight:s[3]-s[1],pageX:s[0],pageY:s[1]})}clone({scale:t=this.scale,rotation:e=this.rotation,offsetX:s=this.offsetX,offsetY:i=this.offsetY,dontFlip:n=!1}={}){return new Di({viewBox:this.viewBox.slice(),userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}convertToViewportPoint(t,e){return z.applyTransform([t,e],this.transform)}convertToViewportRectangle(t){const e=z.applyTransform([t[0],t[1]],this.transform),s=z.applyTransform([t[2],t[3]],this.transform);return[e[0],e[1],s[0],s[1]]}convertToPdfPoint(t,e){return z.applyInverseTransform([t,e],this.transform)}}class Ta extends hs{constructor(t,e=0){super(t,"RenderingCancelledException"),this.extraDelay=e}}function Zn(o){const t=o.length;let e=0;for(;e<t&&o[e].trim()==="";)e++;return o.substring(e,e+5).toLowerCase()==="data:"}function Ea(o){return typeof o=="string"&&/\.pdf$/i.test(o)}function Bf(o){return[o]=o.split(/[#?]/,1),o.substring(o.lastIndexOf("/")+1)}function Hf(o,t="document.pdf"){if(typeof o!="string")return t;if(Zn(o))return Q('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),t;const e=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/,s=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,i=e.exec(o);let n=s.exec(i[1])||s.exec(i[2])||s.exec(i[3]);if(n&&(n=n[0],n.includes("%")))try{n=s.exec(decodeURIComponent(n))[0]}catch{}return n||t}class xh{started=Object.create(null);times=[];time(t){t in this.started&&Q(`Timer is already running for ${t}`),this.started[t]=Date.now()}timeEnd(t){t in this.started||Q(`Timer has not been started for ${t}`),this.times.push({name:t,start:this.started[t],end:Date.now()}),delete this.started[t]}toString(){const t=[];let e=0;for(const{name:s}of this.times)e=Math.max(s.length,e);for(const{name:s,start:i,end:n}of this.times)t.push(`${s.padEnd(e)} ${n-i}ms
|
|
534
|
+
`);return t.join("")}}function Ri(o,t){try{const{protocol:e}=t?new URL(o,t):new URL(o);return e==="http:"||e==="https:"}catch{return!1}}function Oe(o){o.preventDefault()}function ge(o){o.preventDefault(),o.stopPropagation()}class Sh{static#t;static toDateObject(t){if(!t||typeof t!="string")return null;this.#t||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");const e=this.#t.exec(t);if(!e)return null;const s=parseInt(e[1],10);let i=parseInt(e[2],10);i=i>=1&&i<=12?i-1:0;let n=parseInt(e[3],10);n=n>=1&&n<=31?n:1;let r=parseInt(e[4],10);r=r>=0&&r<=23?r:0;let a=parseInt(e[5],10);a=a>=0&&a<=59?a:0;let l=parseInt(e[6],10);l=l>=0&&l<=59?l:0;const h=e[7]||"Z";let c=parseInt(e[8],10);c=c>=0&&c<=23?c:0;let u=parseInt(e[9],10)||0;return u=u>=0&&u<=59?u:0,h==="-"?(r+=c,a+=u):h==="+"&&(r-=c,a-=u),new Date(Date.UTC(s,i,n,r,a,l))}}function zf(o,{scale:t=1,rotation:e=0}){const{width:s,height:i}=o.attributes.style,n=[0,0,parseInt(s),parseInt(i)];return new Di({viewBox:n,userUnit:1,scale:t,rotation:e})}function ka(o){if(o.startsWith("#")){const t=parseInt(o.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return o.startsWith("rgb(")?o.slice(4,-1).split(",").map(t=>parseInt(t)):o.startsWith("rgba(")?o.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(Q(`Not a valid color format: "${o}"`),[0,0,0])}function Vf(o){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const e of o.keys()){t.style.color=e;const s=window.getComputedStyle(t).color;o.set(e,ka(s))}t.remove()}function mt(o){const{a:t,b:e,c:s,d:i,e:n,f:r}=o.getTransform();return[t,e,s,i,n,r]}function ze(o){const{a:t,b:e,c:s,d:i,e:n,f:r}=o.getTransform().invertSelf();return[t,e,s,i,n,r]}function Ms(o,t,e=!1,s=!0){if(t instanceof Di){const{pageWidth:i,pageHeight:n}=t.rawDims,{style:r}=o,a=Qt.isCSSRoundSupported,l=`var(--scale-factor) * ${i}px`,h=`var(--scale-factor) * ${n}px`,c=a?`round(down, ${l}, var(--scale-round-x, 1px))`:`calc(${l})`,u=a?`round(down, ${h}, var(--scale-round-y, 1px))`:`calc(${h})`;!e||t.rotation%180===0?(r.width=c,r.height=u):(r.width=u,r.height=c)}s&&o.setAttribute("data-main-rotation",t.rotation)}class Pa{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}class Fi{#t=null;#e=null;#s;#i=null;#r=null;static#n=null;constructor(t){this.#s=t,Fi.#n||=Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"})}render(){const t=this.#t=document.createElement("div");t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const e=this.#s._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:e}),t.addEventListener("pointerdown",Fi.#l,{signal:e});const s=this.#i=document.createElement("div");s.className="buttons",t.append(s);const i=this.#s.toolbarPosition;if(i){const{style:n}=t,r=this.#s._uiManager.direction==="ltr"?1-i[0]:i[0];n.insetInlineEnd=`${100*r}%`,n.top=`calc(${100*i[1]}% + var(--editor-toolbar-vert-offset))`}return this.#d(),t}get div(){return this.#t}static#l(t){t.stopPropagation()}#o(t){this.#s._focusEventsAllowed=!1,ge(t)}#c(t){this.#s._focusEventsAllowed=!0,ge(t)}#h(t){const e=this.#s._uiManager._signal;t.addEventListener("focusin",this.#o.bind(this),{capture:!0,signal:e}),t.addEventListener("focusout",this.#c.bind(this),{capture:!0,signal:e}),t.addEventListener("contextmenu",Oe,{signal:e})}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden"),this.#r?.shown()}#d(){const{editorType:t,_uiManager:e}=this.#s,s=document.createElement("button");s.className="delete",s.tabIndex=0,s.setAttribute("data-l10n-id",Fi.#n[t]),this.#h(s),s.addEventListener("click",i=>{e.delete()},{signal:e._signal}),this.#i.append(s)}get#u(){const t=document.createElement("div");return t.className="divider",t}async addAltText(t){const e=await t.render();this.#h(e),this.#i.prepend(e,this.#u),this.#r=t}addColorPicker(t){this.#e=t;const e=t.renderButton();this.#h(e),this.#i.prepend(e,this.#u)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class Gf{#t=null;#e=null;#s;constructor(t){this.#s=t}#i(){const t=this.#e=document.createElement("div");t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",Oe,{signal:this.#s._signal});const e=this.#t=document.createElement("div");return e.className="buttons",t.append(e),this.#n(),t}#r(t,e){let s=0,i=0;for(const n of t){const r=n.y+n.height;if(r<s)continue;const a=n.x+(e?n.width:0);if(r>s){i=a,s=r;continue}e?a>i&&(i=a):a<i&&(i=a)}return[e?1-i:i,s]}show(t,e,s){const[i,n]=this.#r(e,s),{style:r}=this.#e||=this.#i();t.append(this.#e),r.insetInlineEnd=`${100*i}%`,r.top=`calc(${100*n}% + var(--editor-toolbar-vert-offset))`}hide(){this.#e.remove()}#n(){const t=document.createElement("button");t.className="highlightButton",t.tabIndex=0,t.setAttribute("data-l10n-id","pdfjs-highlight-floating-button1");const e=document.createElement("span");t.append(e),e.className="visuallyHidden",e.setAttribute("data-l10n-id","pdfjs-highlight-floating-button-label");const s=this.#s._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("click",()=>{this.#s.highlightSelection("floating_button")},{signal:s}),this.#t.append(t)}}function tr(o,t,e){for(const s of e)t.addEventListener(s,o[s].bind(o))}class Wf{#t=0;get id(){return`${Cf}${this.#t++}`}}class Ma{#t=jf();#e=0;#s=null;static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1" style="fill:red;"/></svg>',s=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),i=new Image;i.src=t;const n=i.decode().then(()=>(s.drawImage(i,0,0,1,1,0,0,1,3),new Uint32Array(s.getImageData(0,0,1,1).data.buffer)[0]===0));return tt(this,"_isSVGFittingCanvas",n)}async#i(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s===null)return null;if(s?.bitmap)return s.refCounter+=1,s;try{s||={bitmap:null,id:`image_${this.#t}_${this.#e++}`,refCounter:0,isSvg:!1};let i;if(typeof e=="string"?(s.url=e,i=await Qn(e,"blob")):e instanceof File?i=s.file=e:e instanceof Blob&&(i=e),i.type==="image/svg+xml"){const n=Ma._isSVGFittingCanvas,r=new FileReader,a=new Image,l=new Promise((h,c)=>{a.onload=()=>{s.bitmap=a,s.isSvg=!0,h()},r.onload=async()=>{const u=s.svgUrl=r.result;a.src=await n?`${u}#svgView(preserveAspectRatio(none))`:u},a.onerror=r.onerror=c});r.readAsDataURL(i),await l}else s.bitmap=await createImageBitmap(i);s.refCounter=1}catch(i){Q(i),s=null}return this.#s.set(t,s),s&&this.#s.set(s.id,s),s}async getFromFile(t){const{lastModified:e,name:s,size:i,type:n}=t;return this.#i(`${e}_${s}_${i}_${n}`,t)}async getFromUrl(t){return this.#i(t,t)}async getFromBlob(t,e){const s=await e;return this.#i(t,s)}async getFromId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e)return null;if(e.bitmap)return e.refCounter+=1,e;if(e.file)return this.getFromFile(e.file);if(e.blobPromise){const{blobPromise:s}=e;return delete e.blobPromise,this.getFromBlob(e.id,s)}return this.getFromUrl(e.url)}getFromCanvas(t,e){this.#s||=new Map;let s=this.#s.get(t);if(s?.bitmap)return s.refCounter+=1,s;const i=new OffscreenCanvas(e.width,e.height);return i.getContext("2d").drawImage(e,0,0),s={bitmap:i.transferToImageBitmap(),id:`image_${this.#t}_${this.#e++}`,refCounter:1,isSvg:!1},this.#s.set(t,s),this.#s.set(s.id,s),s}getSvgUrl(t){const e=this.#s.get(t);return e?.isSvg?e.svgUrl:null}deleteId(t){this.#s||=new Map;const e=this.#s.get(t);if(!e||(e.refCounter-=1,e.refCounter!==0))return;const{bitmap:s}=e;if(!e.url&&!e.file){const i=new OffscreenCanvas(s.width,s.height);i.getContext("bitmaprenderer").transferFromImageBitmap(s),e.blobPromise=i.convertToBlob()}s.close?.(),e.bitmap=null}isValidId(t){return t.startsWith(`image_${this.#t}_`)}}class Xf{#t=[];#e=!1;#s;#i=-1;constructor(t=128){this.#s=t}add({cmd:t,undo:e,post:s,mustExec:i,type:n=NaN,overwriteIfSameType:r=!1,keepUndo:a=!1}){if(i&&t(),this.#e)return;const l={cmd:t,undo:e,post:s,type:n};if(this.#i===-1){this.#t.length>0&&(this.#t.length=0),this.#i=0,this.#t.push(l);return}if(r&&this.#t[this.#i].type===n){a&&(l.undo=this.#t[this.#i].undo),this.#t[this.#i]=l;return}const h=this.#i+1;h===this.#s?this.#t.splice(0,1):(this.#i=h,h<this.#t.length&&this.#t.splice(h)),this.#t.push(l)}undo(){if(this.#i===-1)return;this.#e=!0;const{undo:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1,this.#i-=1}redo(){if(this.#i<this.#t.length-1){this.#i+=1,this.#e=!0;const{cmd:t,post:e}=this.#t[this.#i];t(),e?.(),this.#e=!1}}hasSomethingToUndo(){return this.#i!==-1}hasSomethingToRedo(){return this.#i<this.#t.length-1}cleanType(t){if(this.#i!==-1){for(let e=this.#i;e>=0;e--)if(this.#t[e].type!==t){this.#t.splice(e+1,this.#i-e),this.#i=e;return}this.#t.length=0,this.#i=-1}}destroy(){this.#t=null}}class Li{constructor(t){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:e}=Qt.platform;for(const[s,i,n={}]of t)for(const r of s){const a=r.startsWith("mac+");e&&a?(this.callbacks.set(r.slice(4),{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1))):!e&&!a&&(this.callbacks.set(r,{callback:i,options:n}),this.allKeys.add(r.split("+").at(-1)))}}#t(t){t.altKey&&this.buffer.push("alt"),t.ctrlKey&&this.buffer.push("ctrl"),t.metaKey&&this.buffer.push("meta"),t.shiftKey&&this.buffer.push("shift"),this.buffer.push(t.key);const e=this.buffer.join("+");return this.buffer.length=0,e}exec(t,e){if(!this.allKeys.has(e.key))return;const s=this.callbacks.get(this.#t(e));if(!s)return;const{callback:i,options:{bubbles:n=!1,args:r=[],checker:a=null}}=s;a&&!a(t,e)||(i.bind(t,...r,e)(),n||ge(e))}}class Oa{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){const t=new Map([["CanvasText",null],["Canvas",null]]);return Vf(t),tt(this,"_colors",t)}convert(t){const e=ka(t);if(!window.matchMedia("(forced-colors: active)").matches)return e;for(const[s,i]of this._colors)if(i.every((n,r)=>n===e[r]))return Oa._colorsMapping.get(s);return e}getHexCode(t){const e=this._colors.get(t);return e?z.makeHexColor(...e):t}}class us{#t=new AbortController;#e=null;#s=new Map;#i=new Map;#r=null;#n=null;#l=null;#o=new Xf;#c=null;#h=null;#d=0;#u=new Set;#f=null;#a=null;#g=new Set;_editorUndoBar=null;#m=!1;#p=!1;#v=!1;#_=null;#b=null;#w=null;#S=null;#A=!1;#E=null;#P=new Wf;#x=!1;#k=!1;#T=null;#O=null;#F=null;#I=null;#C=J.NONE;#y=new Set;#R=null;#z=null;#V=null;#G={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#j=[0,0];#L=null;#N=null;#W=null;#D=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){const t=us.prototype,e=r=>r.#N.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&r.hasSomethingToControl(),s=(r,{target:a})=>{if(a instanceof HTMLInputElement){const{type:l}=a;return l!=="text"&&l!=="number"}return!0},i=this.TRANSLATE_SMALL,n=this.TRANSLATE_BIG;return tt(this,"_keyboardManager",new Li([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:s}],[["ctrl+z","mac+meta+z"],t.undo,{checker:s}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:s}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:s}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(r,{target:a})=>!(a instanceof HTMLButtonElement)&&r.#N.contains(a)&&!r.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(r,{target:a})=>!(a instanceof HTMLButtonElement)&&r.#N.contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-n,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[n,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-n],checker:e}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,n],checker:e}]]))}constructor(t,e,s,i,n,r,a,l,h,c,u,d,f){const g=this._signal=this.#t.signal;this.#N=t,this.#W=e,this.#r=s,this._eventBus=i,i._on("editingaction",this.onEditingAction.bind(this),{signal:g}),i._on("pagechanging",this.onPageChanging.bind(this),{signal:g}),i._on("scalechanging",this.onScaleChanging.bind(this),{signal:g}),i._on("rotationchanging",this.onRotationChanging.bind(this),{signal:g}),i._on("setpreference",this.onSetPreference.bind(this),{signal:g}),i._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:g}),this.#et(),this.#rt(),this.#$(),this.#n=n.annotationStorage,this.#_=n.filterFactory,this.#z=r,this.#S=a||null,this.#m=l,this.#p=h,this.#v=c,this.#I=u||null,this.viewParameters={realScale:ti.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=d||null,this._supportsPinchToZoom=f!==!1}destroy(){this.#D?.resolve(),this.#D=null,this.#t?.abort(),this.#t=null,this._signal=null;for(const t of this.#i.values())t.destroy();this.#i.clear(),this.#s.clear(),this.#g.clear(),this.#e=null,this.#y.clear(),this.#o.destroy(),this.#r?.destroy(),this.#E?.hide(),this.#E=null,this.#b&&(clearTimeout(this.#b),this.#b=null),this.#L&&(clearTimeout(this.#L),this.#L=null),this._editorUndoBar?.destroy()}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return this.#I}get useNewAltTextFlow(){return this.#p}get useNewAltTextWhenAddingImage(){return this.#v}get hcmFilter(){return tt(this,"hcmFilter",this.#z?this.#_.addHCMFilter(this.#z.foreground,this.#z.background):"none")}get direction(){return tt(this,"direction",getComputedStyle(this.#N).direction)}get highlightColors(){return tt(this,"highlightColors",this.#S?new Map(this.#S.split(",").map(t=>t.split("=").map(e=>e.trim()))):null)}get highlightColorNames(){return tt(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setCurrentDrawingSession(t){t?(this.unselectAll(),this.disableUserSelect(!0)):this.disableUserSelect(!1),this.#h=t}setMainHighlightColorPicker(t){this.#F=t}editAltText(t,e=!1){this.#r?.editAltText(this,t,e)}switchToMode(t,e){this._eventBus.on("annotationeditormodechanged",e,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,e){this._eventBus.dispatch("setpreference",{source:this,name:t,value:e})}onSetPreference({name:t,value:e}){switch(t){case"enableNewAltTextWhenAddingImage":this.#v=e;break}}onPageChanging({pageNumber:t}){this.#d=t-1}focusMainContainer(){this.#N.focus()}findParent(t,e){for(const s of this.#i.values()){const{x:i,y:n,width:r,height:a}=s.div.getBoundingClientRect();if(t>=i&&t<=i+r&&e>=n&&e<=n+a)return s}return null}disableUserSelect(t=!1){this.#W.classList.toggle("noUserSelect",t)}addShouldRescale(t){this.#g.add(t)}removeShouldRescale(t){this.#g.delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*ti.PDF_TO_CSS_UNITS;for(const e of this.#g)e.onScaleChanging();this.#h?.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}#B({anchorNode:t}){return t.nodeType===Node.TEXT_NODE?t.parentElement:t}#Y(t){const{currentLayer:e}=this;if(e.hasTextLayer(t))return e;for(const s of this.#i.values())if(s.hasTextLayer(t))return s;return null}highlightSelection(t=""){const e=document.getSelection();if(!e||e.isCollapsed)return;const{anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r}=e,a=e.toString(),h=this.#B(e).closest(".textLayer"),c=this.getSelectionBoxes(h);if(!c)return;e.empty();const u=this.#Y(h),d=this.#C===J.NONE,f=()=>{u?.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:c,anchorNode:s,anchorOffset:i,focusNode:n,focusOffset:r,text:a}),d&&this.showAllEditors("highlight",!0,!0)};if(d){this.switchToMode(J.HIGHLIGHT,f);return}f()}#Z(){const t=document.getSelection();if(!t||t.isCollapsed)return;const s=this.#B(t).closest(".textLayer"),i=this.getSelectionBoxes(s);i&&(this.#E||=new Gf(this),this.#E.show(s,i,this.direction==="ltr"))}addToAnnotationStorage(t){!t.isEmpty()&&this.#n&&!this.#n.has(t.id)&&this.#n.setValue(t.id,t)}#tt(){const t=document.getSelection();if(!t||t.isCollapsed){this.#R&&(this.#E?.hide(),this.#R=null,this.#M({hasSelectedText:!1}));return}const{anchorNode:e}=t;if(e===this.#R)return;const i=this.#B(t).closest(".textLayer");if(!i){this.#R&&(this.#E?.hide(),this.#R=null,this.#M({hasSelectedText:!1}));return}if(this.#E?.hide(),this.#R=e,this.#M({hasSelectedText:!0}),!(this.#C!==J.HIGHLIGHT&&this.#C!==J.NONE)&&(this.#C===J.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),this.#A=this.isShiftKeyDown,!this.isShiftKeyDown)){const n=this.#C===J.HIGHLIGHT?this.#Y(i):null;n?.toggleDrawing();const r=new AbortController,a=this.combinedSignal(r),l=h=>{h.type==="pointerup"&&h.button!==0||(r.abort(),n?.toggleDrawing(!0),h.type==="pointerup"&&this.#U("main_toolbar"))};window.addEventListener("pointerup",l,{signal:a}),window.addEventListener("blur",l,{signal:a})}}#U(t=""){this.#C===J.HIGHLIGHT?this.highlightSelection(t):this.#m&&this.#Z()}#et(){document.addEventListener("selectionchange",this.#tt.bind(this),{signal:this._signal})}#st(){if(this.#w)return;this.#w=new AbortController;const t=this.combinedSignal(this.#w);window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})}#it(){this.#w?.abort(),this.#w=null}blur(){if(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const e of this.#y)if(e.div.contains(t)){this.#O=[e,t],e._focusEventsAllowed=!1;break}}focus(){if(!this.#O)return;const[t,e]=this.#O;this.#O=null,e.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),e.focus()}#$(){if(this.#T)return;this.#T=new AbortController;const t=this.combinedSignal(this.#T);window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})}#nt(){this.#T?.abort(),this.#T=null}#q(){if(this.#c)return;this.#c=new AbortController;const t=this.combinedSignal(this.#c);document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})}#K(){this.#c?.abort(),this.#c=null}#rt(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})}addEditListeners(){this.#$(),this.#q()}removeEditListeners(){this.#nt(),this.#K()}dragOver(t){for(const{type:e}of t.dataTransfer.items)for(const s of this.#a)if(s.isHandlingMimeForPasting(e)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const e of t.dataTransfer.items)for(const s of this.#a)if(s.isHandlingMimeForPasting(e.type)){s.paste(e,this.currentLayer),t.preventDefault();return}}copy(t){if(t.preventDefault(),this.#e?.commitOrRemove(),!this.hasSelection)return;const e=[];for(const s of this.#y){const i=s.serialize(!0);i&&e.push(i)}e.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(e))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:e}=t;for(const n of e.items)for(const r of this.#a)if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer);return}let s=e.getData("application/pdfjs");if(!s)return;try{s=JSON.parse(s)}catch(n){Q(`paste: "${n.message}".`);return}if(!Array.isArray(s))return;this.unselectAll();const i=this.currentLayer;try{const n=[];for(const l of s){const h=await i.deserialize(l);if(!h)return;n.push(h)}const r=()=>{for(const l of n)this.#J(l);this.#Q(n)},a=()=>{for(const l of n)l.remove()};this.addCommands({cmd:r,undo:a,mustExec:!0})}catch(n){Q(`paste: "${n.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),this.#C!==J.NONE&&!this.isEditorHandlingKeyboard&&us._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,this.#A&&(this.#A=!1,this.#U("main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}#M(t){Object.entries(t).some(([s,i])=>this.#G[s]!==i)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#G,t)}),this.#C===J.HIGHLIGHT&&t.hasSelectedEditor===!1&&this.#H([[st.HIGHLIGHT_FREE,!0]]))}#H(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})}setEditingState(t){t?(this.#st(),this.#q(),this.#M({isEditing:this.#C!==J.NONE,isEmpty:this.#X(),hasSomethingToUndo:this.#o.hasSomethingToUndo(),hasSomethingToRedo:this.#o.hasSomethingToRedo(),hasSelectedEditor:!1})):(this.#it(),this.#K(),this.#M({isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!this.#a){this.#a=t;for(const e of this.#a)this.#H(e.defaultPropertiesToUpdate)}}getId(){return this.#P.id}get currentLayer(){return this.#i.get(this.#d)}getLayer(t){return this.#i.get(t)}get currentPageIndex(){return this.#d}addLayer(t){this.#i.set(t.pageIndex,t),this.#x?t.enable():t.disable()}removeLayer(t){this.#i.delete(t.pageIndex)}async updateMode(t,e=null,s=!1){if(this.#C!==t&&!(this.#D&&(await this.#D.promise,!this.#D))){if(this.#D=Promise.withResolvers(),this.#C=t,t===J.NONE){this.setEditingState(!1),this.#ot(),this._editorUndoBar?.hide(),this.#D.resolve();return}this.setEditingState(!0),await this.#at(),this.unselectAll();for(const i of this.#i.values())i.updateMode(t);if(!e){s&&this.addNewEditorFromKeyboard(),this.#D.resolve();return}for(const i of this.#s.values())i.annotationElementId===e?(this.setSelected(i),i.enterInEditMode()):i.unselect();this.#D.resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==this.#C&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,e){if(this.#a){switch(t){case st.CREATE:this.currentLayer.addNewEditor();return;case st.HIGHLIGHT_DEFAULT_COLOR:this.#F?.updateColor(e);break;case st.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#V||=new Map).set(t,e),this.showAllEditors("highlight",e);break}for(const s of this.#y)s.updateParams(t,e);for(const s of this.#a)s.updateDefaultParams(t,e)}}showAllEditors(t,e,s=!1){for(const n of this.#s.values())n.editorType===t&&n.show(e);(this.#V?.get(st.HIGHLIGHT_SHOW_ALL)??!0)!==e&&this.#H([[st.HIGHLIGHT_SHOW_ALL,e]])}enableWaiting(t=!1){if(this.#k!==t){this.#k=t;for(const e of this.#i.values())t?e.disableClick():e.enableClick(),e.div.classList.toggle("waiting",t)}}async#at(){if(!this.#x){this.#x=!0;const t=[];for(const e of this.#i.values())t.push(e.enable());await Promise.all(t);for(const e of this.#s.values())e.enable()}}#ot(){if(this.unselectAll(),this.#x){this.#x=!1;for(const t of this.#i.values())t.disable();for(const t of this.#s.values())t.disable()}}getEditors(t){const e=[];for(const s of this.#s.values())s.pageIndex===t&&e.push(s);return e}getEditor(t){return this.#s.get(t)}addEditor(t){this.#s.set(t.id,t)}removeEditor(t){t.div.contains(document.activeElement)&&(this.#b&&clearTimeout(this.#b),this.#b=setTimeout(()=>{this.focusMainContainer(),this.#b=null},0)),this.#s.delete(t.id),this.unselect(t),(!t.annotationElementId||!this.#u.has(t.annotationElementId))&&this.#n?.remove(t.id)}addDeletedAnnotationElement(t){this.#u.add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return this.#u.has(t)}removeDeletedAnnotationElement(t){this.#u.delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}#J(t){const e=this.#i.get(t.pageIndex);e?e.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))}setActiveEditor(t){this.#e!==t&&(this.#e=t,t&&this.#H(t.propertiesToUpdate))}get#lt(){let t=null;for(t of this.#y);return t}updateUI(t){this.#lt===t&&this.#H(t.propertiesToUpdate)}updateUIForDefaultProperties(t){this.#H(t.defaultPropertiesToUpdate)}toggleSelected(t){if(this.#y.has(t)){this.#y.delete(t),t.unselect(),this.#M({hasSelectedEditor:this.hasSelection});return}this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#M({hasSelectedEditor:!0})}setSelected(t){this.#h?.commitOrRemove();for(const e of this.#y)e!==t&&e.unselect();this.#y.clear(),this.#y.add(t),t.select(),this.#H(t.propertiesToUpdate),this.#M({hasSelectedEditor:!0})}isSelected(t){return this.#y.has(t)}get firstSelectedEditor(){return this.#y.values().next().value}unselect(t){t.unselect(),this.#y.delete(t),this.#M({hasSelectedEditor:this.hasSelection})}get hasSelection(){return this.#y.size!==0}get isEnterHandled(){return this.#y.size===1&&this.firstSelectedEditor.isEnterHandled}undo(){this.#o.undo(),this.#M({hasSomethingToUndo:this.#o.hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:this.#X()}),this._editorUndoBar?.hide()}redo(){this.#o.redo(),this.#M({hasSomethingToUndo:!0,hasSomethingToRedo:this.#o.hasSomethingToRedo(),isEmpty:this.#X()})}addCommands(t){this.#o.add(t),this.#M({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#X()})}cleanUndoStack(t){this.#o.cleanType(t)}#X(){if(this.#s.size===0)return!0;if(this.#s.size===1)for(const t of this.#s.values())return t.isEmpty();return!1}delete(){this.commitOrRemove();const t=this.currentLayer?.endDrawingSession(!0);if(!this.hasSelection&&!t)return;const e=t?[t]:[...this.#y],s=()=>{this._editorUndoBar?.show(i,e.length===1?e[0].editorType:e.length);for(const n of e)n.remove()},i=()=>{for(const n of e)this.#J(n)};this.addCommands({cmd:s,undo:i,mustExec:!0})}commitOrRemove(){this.#e?.commitOrRemove()}hasSomethingToControl(){return this.#e||this.hasSelection}#Q(t){for(const e of this.#y)e.unselect();this.#y.clear();for(const e of t)e.isEmpty()||(this.#y.add(e),e.select());this.#M({hasSelectedEditor:this.hasSelection})}selectAll(){for(const t of this.#y)t.commit();this.#Q(this.#s.values())}unselectAll(){if(!(this.#e&&(this.#e.commitOrRemove(),this.#C!==J.NONE))&&!this.#h?.commitOrRemove()&&this.hasSelection){for(const t of this.#y)t.unselect();this.#y.clear(),this.#M({hasSelectedEditor:!1})}}translateSelectedEditors(t,e,s=!1){if(s||this.commitOrRemove(),!this.hasSelection)return;this.#j[0]+=t,this.#j[1]+=e;const[i,n]=this.#j,r=[...this.#y],a=1e3;this.#L&&clearTimeout(this.#L),this.#L=setTimeout(()=>{this.#L=null,this.#j[0]=this.#j[1]=0,this.addCommands({cmd:()=>{for(const l of r)this.#s.has(l.id)&&l.translateInPage(i,n)},undo:()=>{for(const l of r)this.#s.has(l.id)&&l.translateInPage(-i,-n)},mustExec:!1})},a);for(const l of r)l.translateInPage(t,e)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#f=new Map;for(const t of this.#y)this.#f.set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#f)return!1;this.disableUserSelect(!1);const t=this.#f;this.#f=null;let e=!1;for(const[{x:i,y:n,pageIndex:r},a]of t)a.newX=i,a.newY=n,a.newPageIndex=r,e||=i!==a.savedX||n!==a.savedY||r!==a.savedPageIndex;if(!e)return!1;const s=(i,n,r,a)=>{if(this.#s.has(i.id)){const l=this.#i.get(a);l?i._setParentAndPosition(l,n,r):(i.pageIndex=a,i.x=n,i.y=r)}};return this.addCommands({cmd:()=>{for(const[i,{newX:n,newY:r,newPageIndex:a}]of t)s(i,n,r,a)},undo:()=>{for(const[i,{savedX:n,savedY:r,savedPageIndex:a}]of t)s(i,n,r,a)},mustExec:!0}),!0}dragSelectedEditors(t,e){if(this.#f)for(const s of this.#f.keys())s.drag(t,e)}rebuild(t){if(t.parent===null){const e=this.getLayer(t.pageIndex);e?(e.changeParent(t),e.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#y.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return this.#e===t}getActive(){return this.#e}getMode(){return this.#C}get imageManager(){return tt(this,"imageManager",new Ma)}getSelectionBoxes(t){if(!t)return null;const e=document.getSelection();for(let h=0,c=e.rangeCount;h<c;h++)if(!t.contains(e.getRangeAt(h).commonAncestorContainer))return null;const{x:s,y:i,width:n,height:r}=t.getBoundingClientRect();let a;switch(t.getAttribute("data-main-rotation")){case"90":a=(h,c,u,d)=>({x:(c-i)/r,y:1-(h+u-s)/n,width:d/r,height:u/n});break;case"180":a=(h,c,u,d)=>({x:1-(h+u-s)/n,y:1-(c+d-i)/r,width:u/n,height:d/r});break;case"270":a=(h,c,u,d)=>({x:1-(c+d-i)/r,y:(h-s)/n,width:d/r,height:u/n});break;default:a=(h,c,u,d)=>({x:(h-s)/n,y:(c-i)/r,width:u/n,height:d/r});break}const l=[];for(let h=0,c=e.rangeCount;h<c;h++){const u=e.getRangeAt(h);if(!u.collapsed)for(const{x:d,y:f,width:g,height:p}of u.getClientRects())g===0||p===0||l.push(a(d,f,g,p))}return l.length===0?null:l}addChangedExistingAnnotation({annotationElementId:t,id:e}){(this.#l||=new Map).set(t,e)}removeChangedExistingAnnotation({annotationElementId:t}){this.#l?.delete(t)}renderAnnotationElement(t){const e=this.#l?.get(t.data.id);if(!e)return;const s=this.#n.getRawValue(e);s&&(this.#C===J.NONE&&!s.hasBeenModified||s.renderAnnotationElement(t))}}class Ve{#t=null;#e=!1;#s=null;#i=null;#r=null;#n=null;#l=!1;#o=null;#c=null;#h=null;#d=null;#u=!1;static#f=null;static _l10n=null;constructor(t){this.#c=t,this.#u=t._uiManager.useNewAltTextFlow,Ve.#f||=Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"})}static initialize(t){Ve._l10n??=t}async render(){const t=this.#s=document.createElement("button");t.className="altText",t.tabIndex="0";const e=this.#i=document.createElement("span");t.append(e),this.#u?(t.classList.add("new"),t.setAttribute("data-l10n-id",Ve.#f.missing),e.setAttribute("data-l10n-id",Ve.#f["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const s=this.#c._uiManager._signal;t.addEventListener("contextmenu",Oe,{signal:s}),t.addEventListener("pointerdown",n=>n.stopPropagation(),{signal:s});const i=n=>{n.preventDefault(),this.#c._uiManager.editAltText(this.#c),this.#u&&this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:this.#a}})};return t.addEventListener("click",i,{capture:!0,signal:s}),t.addEventListener("keydown",n=>{n.target===t&&n.key==="Enter"&&(this.#l=!0,i(n))},{signal:s}),await this.#g(),t}get#a(){return this.#t&&"added"||this.#t===null&&this.guessedText&&"review"||"missing"}finish(){this.#s&&(this.#s.focus({focusVisible:this.#l}),this.#l=!1)}isEmpty(){return this.#u?this.#t===null:!this.#t&&!this.#e}hasData(){return this.#u?this.#t!==null||!!this.#h:this.isEmpty()}get guessedText(){return this.#h}async setGuessedText(t){this.#t===null&&(this.#h=t,this.#d=await Ve._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t}),this.#g())}toggleAltTextBadge(t=!1){if(!this.#u||this.#t){this.#o?.remove(),this.#o=null;return}if(!this.#o){const e=this.#o=document.createElement("div");e.className="noAltTextBadge",this.#c.div.append(e)}this.#o.classList.toggle("hidden",!t)}serialize(t){let e=this.#t;return!t&&this.#h===e&&(e=this.#d),{altText:e,decorative:this.#e,guessedText:this.#h,textWithDisclaimer:this.#d}}get data(){return{altText:this.#t,decorative:this.#e}}set data({altText:t,decorative:e,guessedText:s,textWithDisclaimer:i,cancel:n=!1}){s&&(this.#h=s,this.#d=i),!(this.#t===t&&this.#e===e)&&(n||(this.#t=t,this.#e=e),this.#g())}toggle(t=!1){this.#s&&(!t&&this.#n&&(clearTimeout(this.#n),this.#n=null),this.#s.disabled=!t)}shown(){this.#c._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:this.#a}})}destroy(){this.#s?.remove(),this.#s=null,this.#i=null,this.#r=null,this.#o?.remove(),this.#o=null}async#g(){const t=this.#s;if(!t)return;if(this.#u){if(t.classList.toggle("done",!!this.#t),t.setAttribute("data-l10n-id",Ve.#f[this.#a]),this.#i?.setAttribute("data-l10n-id",Ve.#f[`${this.#a}-label`]),!this.#t){this.#r?.remove();return}}else{if(!this.#t&&!this.#e){t.classList.remove("done"),this.#r?.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let e=this.#r;if(!e){this.#r=e=document.createElement("span"),e.className="tooltip",e.setAttribute("role","tooltip"),e.id=`alt-text-tooltip-${this.#c.id}`;const i=100,n=this.#c._uiManager._signal;n.addEventListener("abort",()=>{clearTimeout(this.#n),this.#n=null},{once:!0}),t.addEventListener("mouseenter",()=>{this.#n=setTimeout(()=>{this.#n=null,this.#r.classList.add("show"),this.#c._reportTelemetry({action:"alt_text_tooltip"})},i)},{signal:n}),t.addEventListener("mouseleave",()=>{this.#n&&(clearTimeout(this.#n),this.#n=null),this.#r?.classList.remove("show")},{signal:n})}this.#e?e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(e.removeAttribute("data-l10n-id"),e.textContent=this.#t),e.parentNode||t.append(e),this.#c.getImageForAltText()?.setAttribute("aria-describedby",e.id)}}class er{#t;#e=!1;#s=null;#i;#r;#n;#l;#o;#c=null;#h;#d=null;constructor({container:t,isPinchingDisabled:e=null,isPinchingStopped:s=null,onPinchStart:i=null,onPinching:n=null,onPinchEnd:r=null,signal:a}){this.#t=t,this.#s=s,this.#i=e,this.#r=i,this.#n=n,this.#l=r,this.#h=new AbortController,this.#o=AbortSignal.any([a,this.#h.signal]),t.addEventListener("touchstart",this.#u.bind(this),{passive:!1,signal:this.#o})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return tt(this,"MIN_TOUCH_DISTANCE_TO_PINCH",35/(window.devicePixelRatio||1))}#u(t){if(this.#i?.()||t.touches.length<2)return;if(!this.#d){this.#d=new AbortController;const i=AbortSignal.any([this.#o,this.#d.signal]),n=this.#t,r={signal:i,passive:!1};n.addEventListener("touchmove",this.#f.bind(this),r),n.addEventListener("touchend",this.#a.bind(this),r),n.addEventListener("touchcancel",this.#a.bind(this),r),this.#r?.()}if(ge(t),t.touches.length!==2||this.#s?.()){this.#c=null;return}let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]),this.#c={touch0X:e.screenX,touch0Y:e.screenY,touch1X:s.screenX,touch1Y:s.screenY}}#f(t){if(!this.#c||t.touches.length!==2)return;let[e,s]=t.touches;e.identifier>s.identifier&&([e,s]=[s,e]);const{screenX:i,screenY:n}=e,{screenX:r,screenY:a}=s,l=this.#c,{touch0X:h,touch0Y:c,touch1X:u,touch1Y:d}=l,f=u-h,g=d-c,p=r-i,v=a-n,m=Math.hypot(p,v)||1,b=Math.hypot(f,g)||1;if(!this.#e&&Math.abs(b-m)<=er.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(l.touch0X=i,l.touch0Y=n,l.touch1X=r,l.touch1Y=a,t.preventDefault(),!this.#e){this.#e=!0;return}const _=[(i+r)/2,(n+a)/2];this.#n?.(_,b,m)}#a(t){this.#d.abort(),this.#d=null,this.#l?.(),this.#c&&(t.preventDefault(),this.#c=null,this.#e=!1)}destroy(){this.#h?.abort(),this.#h=null}}class G{#t=null;#e=null;#s=null;#i=!1;#r=null;#n="";#l=!1;#o=null;#c=null;#h=null;#d=null;#u="";#f=!1;#a=null;#g=!1;#m=!1;#p=!1;#v=null;#_=0;#b=0;#w=null;#S=null;_editToolbar=null;_initialOptions=Object.create(null);_initialData=null;_isVisible=!0;_uiManager=null;_focusEventsAllowed=!0;static _l10n=null;static _l10nResizer=null;#A=!1;#E=G._zIndex++;static _borderLineWidth=-1;static _colorManager=new Oa;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){const t=G.prototype._resizeWithKeyboard,e=us.TRANSLATE_SMALL,s=us.TRANSLATE_BIG;return tt(this,"_resizerKeyboardManager",new Li([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-e,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-s,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[e,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[s,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-e]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-s]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,e]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,s]}],[["Escape","mac+Escape"],G.prototype._stopResizingWithKeyboard]]))}constructor(t){this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:e,rawDims:{pageWidth:s,pageHeight:i,pageX:n,pageY:r}}=this.parent.viewport;this.rotation=e,this.pageRotation=(360+e-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[s,i],this.pageTranslation=[n,r];const[a,l]=this.parentDimensions;this.x=t.x/a,this.y=t.y/l,this.isAttachedToDOM=!1,this.deleted=!1}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get isDrawer(){return!1}static get _defaultLineColor(){return tt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const e=new Uf({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});e.annotationElementId=t.annotationElementId,e.deleted=!0,e._uiManager.addToAnnotationStorage(e)}static initialize(t,e){if(G._l10n??=t,G._l10nResizer||=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"}),G._borderLineWidth!==-1)return;const s=getComputedStyle(document.documentElement);G._borderLineWidth=parseFloat(s.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,e){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,e){ut("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#A}set _isDraggable(t){this.#A=t,this.div?.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,e]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*e/(t*2),this.y+=this.width*t/(e*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*e/(t*2),this.y-=this.width*t/(e*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#E}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):this.#B(),this.parent=t}focusin(t){this._focusEventsAllowed&&(this.#f?this.#f=!1:this.parent.setSelected(this))}focusout(t){!this._focusEventsAllowed||!this.isAttachedToDOM||t.relatedTarget?.closest(`#${this.id}`)||(t.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,e,s,i){const[n,r]=this.parentDimensions;[s,i]=this.screenToPageTranslation(s,i),this.x=(t+s)/n,this.y=(e+i)/r,this.fixAndSetPosition()}#P([t,e],s,i){[s,i]=this.screenToPageTranslation(s,i),this.x+=s/t,this.y+=i/e,this._onTranslating(this.x,this.y),this.fixAndSetPosition()}translate(t,e){this.#P(this.parentDimensions,t,e)}translateInPage(t,e){this.#a||=[this.x,this.y,this.width,this.height],this.#P(this.pageDimensions,t,e),this.div.scrollIntoView({block:"nearest"})}drag(t,e){this.#a||=[this.x,this.y,this.width,this.height];const{div:s,parentDimensions:[i,n]}=this;if(this.x+=t/i,this.y+=e/n,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:u,y:d}=this.div.getBoundingClientRect();this.parent.findNewParent(this,u,d)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:r,y:a}=this;const[l,h]=this.getBaseTranslation();r+=l,a+=h;const{style:c}=s;c.left=`${(100*r).toFixed(2)}%`,c.top=`${(100*a).toFixed(2)}%`,this._onTranslating(r,a),s.scrollIntoView({block:"nearest"})}_onTranslating(t,e){}_onTranslated(t,e){}get _hasBeenMoved(){return!!this.#a&&(this.#a[0]!==this.x||this.#a[1]!==this.y)}get _hasBeenResized(){return!!this.#a&&(this.#a[2]!==this.width||this.#a[3]!==this.height)}getBaseTranslation(){const[t,e]=this.parentDimensions,{_borderLineWidth:s}=G,i=s/t,n=s/e;switch(this.rotation){case 90:return[-i,n];case 180:return[i,n];case 270:return[i,-n];default:return[-i,-n]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const{div:{style:e},pageDimensions:[s,i]}=this;let{x:n,y:r,width:a,height:l}=this;if(a*=s,l*=i,n*=s,r*=i,this._mustFixPosition)switch(t){case 0:n=Math.max(0,Math.min(s-a,n)),r=Math.max(0,Math.min(i-l,r));break;case 90:n=Math.max(0,Math.min(s-l,n)),r=Math.min(i,Math.max(a,r));break;case 180:n=Math.min(s,Math.max(a,n)),r=Math.min(i,Math.max(l,r));break;case 270:n=Math.min(s,Math.max(l,n)),r=Math.max(0,Math.min(i-a,r));break}this.x=n/=s,this.y=r/=i;const[h,c]=this.getBaseTranslation();n+=h,r+=c,e.left=`${(100*n).toFixed(2)}%`,e.top=`${(100*r).toFixed(2)}%`,this.moveInDOM()}static#x(t,e,s){switch(s){case 90:return[e,-t];case 180:return[-t,-e];case 270:return[-e,t];default:return[t,e]}}screenToPageTranslation(t,e){return G.#x(t,e,this.parentRotation)}pageTranslationToScreen(t,e){return G.#x(t,e,360-this.parentRotation)}#k(t){switch(t){case 90:{const[e,s]=this.pageDimensions;return[0,-e/s,s/e,0]}case 180:return[-1,0,0,-1];case 270:{const[e,s]=this.pageDimensions;return[0,e/s,-s/e,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[e,s]}=this;return[e*t,s*t]}setDims(t,e){const[s,i]=this.parentDimensions,{style:n}=this.div;n.width=`${(100*t/s).toFixed(2)}%`,this.#l||(n.height=`${(100*e/i).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:e,width:s}=t,i=s.endsWith("%"),n=!this.#l&&e.endsWith("%");if(i&&n)return;const[r,a]=this.parentDimensions;i||(t.width=`${(100*parseFloat(s)/r).toFixed(2)}%`),!this.#l&&!n&&(t.height=`${(100*parseFloat(e)/a).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#T(){if(this.#o)return;this.#o=document.createElement("div"),this.#o.classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],e=this._uiManager._signal;for(const s of t){const i=document.createElement("div");this.#o.append(i),i.classList.add("resizer",s),i.setAttribute("data-resizer-name",s),i.addEventListener("pointerdown",this.#O.bind(this,s),{signal:e}),i.addEventListener("contextmenu",Oe,{signal:e}),i.tabIndex=-1}this.div.prepend(this.#o)}#O(t,e){e.preventDefault();const{isMac:s}=Qt.platform;if(e.button!==0||e.ctrlKey&&s)return;this.#s?.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,this.#c=[e.screenX,e.screenY];const n=new AbortController,r=this._uiManager.combinedSignal(n);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",this.#C.bind(this,t),{passive:!0,capture:!0,signal:r}),window.addEventListener("touchmove",ge,{passive:!1,signal:r}),window.addEventListener("contextmenu",Oe,{signal:r}),this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const a=this.parent.div.style.cursor,l=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(e.target).cursor;const h=()=>{n.abort(),this.parent.togglePointerEvents(!0),this.#s?.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=l,this.#I()};window.addEventListener("pointerup",h,{signal:r}),window.addEventListener("blur",h,{signal:r})}#F(t,e,s,i){this.width=s,this.height=i,this.x=t,this.y=e;const[n,r]=this.parentDimensions;this.setDims(n*s,r*i),this.fixAndSetPosition(),this._onResized()}_onResized(){}#I(){if(!this.#h)return;const{savedX:t,savedY:e,savedWidth:s,savedHeight:i}=this.#h;this.#h=null;const n=this.x,r=this.y,a=this.width,l=this.height;n===t&&r===e&&a===s&&l===i||this.addCommands({cmd:this.#F.bind(this,n,r,a,l),undo:this.#F.bind(this,t,e,s,i),mustExec:!0})}static _round(t){return Math.round(t*1e4)/1e4}#C(t,e){const[s,i]=this.parentDimensions,n=this.x,r=this.y,a=this.width,l=this.height,h=G.MIN_SIZE/s,c=G.MIN_SIZE/i,u=this.#k(this.rotation),d=(M,L)=>[u[0]*M+u[2]*L,u[1]*M+u[3]*L],f=this.#k(360-this.rotation),g=(M,L)=>[f[0]*M+f[2]*L,f[1]*M+f[3]*L];let p,v,m=!1,b=!1;switch(t){case"topLeft":m=!0,p=(M,L)=>[0,0],v=(M,L)=>[M,L];break;case"topMiddle":p=(M,L)=>[M/2,0],v=(M,L)=>[M/2,L];break;case"topRight":m=!0,p=(M,L)=>[M,0],v=(M,L)=>[0,L];break;case"middleRight":b=!0,p=(M,L)=>[M,L/2],v=(M,L)=>[0,L/2];break;case"bottomRight":m=!0,p=(M,L)=>[M,L],v=(M,L)=>[0,0];break;case"bottomMiddle":p=(M,L)=>[M/2,L],v=(M,L)=>[M/2,0];break;case"bottomLeft":m=!0,p=(M,L)=>[0,L],v=(M,L)=>[M,0];break;case"middleLeft":b=!0,p=(M,L)=>[0,L/2],v=(M,L)=>[M,L/2];break}const _=p(a,l),w=v(a,l);let C=d(...w);const T=G._round(n+C[0]),E=G._round(r+C[1]);let k=1,O=1,H,N;if(e.fromKeyboard)({deltaX:H,deltaY:N}=e);else{const{screenX:M,screenY:L}=e,[Y,ft]=this.#c;[H,N]=this.screenToPageTranslation(M-Y,L-ft),this.#c[0]=M,this.#c[1]=L}if([H,N]=g(H/s,N/i),m){const M=Math.hypot(a,l);k=O=Math.max(Math.min(Math.hypot(w[0]-_[0]-H,w[1]-_[1]-N)/M,1/a,1/l),h/a,c/l)}else b?k=Math.max(h,Math.min(1,Math.abs(w[0]-_[0]-H)))/a:O=Math.max(c,Math.min(1,Math.abs(w[1]-_[1]-N)))/l;const P=G._round(a*k),R=G._round(l*O);C=d(...v(P,R));const F=T-C[0],V=E-C[1];this.#a||=[this.x,this.y,this.width,this.height],this.width=P,this.height=R,this.x=F,this.y=V,this.setDims(s*P,i*R),this.fixAndSetPosition(),this._onResizing()}_onResizing(){}altTextFinish(){this.#s?.finish()}async addEditToolbar(){return this._editToolbar||this.#m?this._editToolbar:(this._editToolbar=new Fi(this),this.div.append(this._editToolbar.render()),this.#s&&await this._editToolbar.addAltText(this.#s),this._editToolbar)}removeEditToolbar(){this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,this.#s?.destroy())}addContainer(t){const e=this._editToolbar?.div;e?e.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){this.#s||(Ve.initialize(G._l10n),this.#s=new Ve(this),this.#t&&(this.#s.data=this.#t,this.#t=null),await this.addEditToolbar())}get altTextData(){return this.#s?.data}set altTextData(t){this.#s&&(this.#s.data=t)}get guessedAltText(){return this.#s?.guessedText}async setGuessedAltText(t){await this.#s?.setGuessedText(t)}serializeAltText(t){return this.#s?.serialize(t)}hasAltText(){return!!this.#s&&!this.#s.isEmpty()}hasAltTextData(){return this.#s?.hasData()??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=this.#i?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),this.#j();const[t,e]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*e/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/e).toFixed(2)}%`);const[s,i]=this.getInitialTranslation();return this.translate(s,i),tr(this,this.div,["pointerdown"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(this.#S||=new er({container:this.div,isPinchingDisabled:()=>!this.isSelected,onPinchStart:this.#y.bind(this),onPinching:this.#R.bind(this),onPinchEnd:this.#z.bind(this),signal:this._uiManager._signal})),this._uiManager._editorUndoBar?.hide(),this.div}#y(){this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height},this.#s?.toggle(!1),this.parent.togglePointerEvents(!1)}#R(t,e,s){let n=.7*(s/e)+1-.7;if(n===1)return;const r=this.#k(this.rotation),a=(T,E)=>[r[0]*T+r[2]*E,r[1]*T+r[3]*E],[l,h]=this.parentDimensions,c=this.x,u=this.y,d=this.width,f=this.height,g=G.MIN_SIZE/l,p=G.MIN_SIZE/h;n=Math.max(Math.min(n,1/d,1/f),g/d,p/f);const v=G._round(d*n),m=G._round(f*n);if(v===d&&m===f)return;this.#a||=[c,u,d,f];const b=a(d/2,f/2),_=G._round(c+b[0]),w=G._round(u+b[1]),C=a(v/2,m/2);this.x=_-C[0],this.y=w-C[1],this.width=v,this.height=m,this.setDims(l*v,h*m),this.fixAndSetPosition(),this._onResizing()}#z(){this.#s?.toggle(!0),this.parent.togglePointerEvents(!0),this.#I()}pointerdown(t){const{isMac:e}=Qt.platform;if(t.button!==0||t.ctrlKey&&e){t.preventDefault();return}if(this.#f=!0,this._isDraggable){this.#G(t);return}this.#V(t)}get isSelected(){return this._uiManager.isSelected(this)}#V(t){const{isMac:e}=Qt.platform;t.ctrlKey&&!e||t.shiftKey||t.metaKey&&e?this.parent.toggleSelected(this):this.parent.setSelected(this)}#G(t){const{isSelected:e}=this;this._uiManager.setUpDragSession();let s=!1;const i=new AbortController,n=this._uiManager.combinedSignal(i),r={capture:!0,passive:!1,signal:n},a=h=>{i.abort(),this.#r=null,this.#f=!1,this._uiManager.endDragSession()||this.#V(h),s&&this._onStopDragging()};e&&(this.#_=t.clientX,this.#b=t.clientY,this.#r=t.pointerId,this.#n=t.pointerType,window.addEventListener("pointermove",h=>{s||(s=!0,this._onStartDragging());const{clientX:c,clientY:u,pointerId:d}=h;if(d!==this.#r){ge(h);return}const[f,g]=this.screenToPageTranslation(c-this.#_,u-this.#b);this.#_=c,this.#b=u,this._uiManager.dragSelectedEditors(f,g)},r),window.addEventListener("touchmove",ge,r),window.addEventListener("pointerdown",h=>{h.pointerType===this.#n&&(this.#S||h.isPrimary)&&a(h),ge(h)},r));const l=h=>{if(!this.#r||this.#r===h.pointerId){a(h);return}ge(h)};window.addEventListener("pointerup",l,{signal:n}),window.addEventListener("blur",l,{signal:n})}_onStartDragging(){}_onStopDragging(){}moveInDOM(){this.#v&&clearTimeout(this.#v),this.#v=setTimeout(()=>{this.#v=null,this.parent?.moveEditorInDOM(this)},0)}_setParentAndPosition(t,e,s){t.changeParent(this),this.x=e,this.y=s,this.fixAndSetPosition(),this._onTranslated()}getRect(t,e,s=this.rotation){const i=this.parentScale,[n,r]=this.pageDimensions,[a,l]=this.pageTranslation,h=t/i,c=e/i,u=this.x*n,d=this.y*r,f=this.width*n,g=this.height*r;switch(s){case 0:return[u+h+a,r-d-c-g+l,u+h+f+a,r-d-c+l];case 90:return[u+c+a,r-d+h+l,u+c+g+a,r-d+h+f+l];case 180:return[u-h-f+a,r-d+c+l,u-h+a,r-d+c+g+l];case 270:return[u-c-g+a,r-d-h-f+l,u-c+a,r-d-h+l];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,e){const[s,i,n,r]=t,a=n-s,l=r-i;switch(this.rotation){case 0:return[s,e-r,a,l];case 90:return[s,e-i,l,a];case 180:return[n,e-i,a,l];case 270:return[n,e-r,l,a];default:throw new Error("Invalid rotation")}}onceAdded(t){}isEmpty(){return!1}enableEditMode(){this.#m=!0}disableEditMode(){this.#m=!1}isInEditMode(){return this.#m}shouldGetKeyboardEvents(){return this.#p}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}get isOnScreen(){const{top:t,left:e,bottom:s,right:i}=this.getClientDimensions(),{innerHeight:n,innerWidth:r}=window;return e<r&&i>0&&t<n&&s>0}#j(){if(this.#d||!this.div)return;this.#d=new AbortController;const t=this._uiManager.combinedSignal(this.#d);this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})}rebuild(){this.#j()}rotate(t){}resize(){}serializeDeleted(){return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:this._initialData?.popupRef||""}}serialize(t=!1,e=null){ut("An editor must be serializable")}static async deserialize(t,e,s){const i=new this.prototype.constructor({parent:e,id:e.getNextId(),uiManager:s});i.rotation=t.rotation,i.#t=t.accessibilityData;const[n,r]=i.pageDimensions,[a,l,h,c]=i.getRectInCurrentCoords(t.rect,r);return i.x=a/n,i.y=l/r,i.width=h/n,i.height=c/r,i}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){if(this.#d?.abort(),this.#d=null,this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.#v&&(clearTimeout(this.#v),this.#v=null),this.#B(),this.removeEditToolbar(),this.#w){for(const t of this.#w.values())clearTimeout(t);this.#w=null}this.parent=null,this.#S?.destroy(),this.#S=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(this.#T(),this.#o.classList.remove("hidden"),tr(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),this.#h={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};const e=this.#o.children;if(!this.#e){this.#e=Array.from(e);const r=this.#L.bind(this),a=this.#N.bind(this),l=this._uiManager._signal;for(const h of this.#e){const c=h.getAttribute("data-resizer-name");h.setAttribute("role","spinbutton"),h.addEventListener("keydown",r,{signal:l}),h.addEventListener("blur",a,{signal:l}),h.addEventListener("focus",this.#W.bind(this,c),{signal:l}),h.setAttribute("data-l10n-id",G._l10nResizer[c])}}const s=this.#e[0];let i=0;for(const r of e){if(r===s)break;i++}const n=(360-this.rotation+this.parentRotation)%360/90*(this.#e.length/4);if(n!==i){if(n<i)for(let a=0;a<i-n;a++)this.#o.append(this.#o.firstChild);else if(n>i)for(let a=0;a<n-i;a++)this.#o.firstChild.before(this.#o.lastChild);let r=0;for(const a of e){const h=this.#e[r++].getAttribute("data-resizer-name");a.setAttribute("data-l10n-id",G._l10nResizer[h])}}this.#D(0),this.#p=!0,this.#o.firstChild.focus({focusVisible:!0}),t.preventDefault(),t.stopImmediatePropagation()}#L(t){G._resizerKeyboardManager.exec(this,t)}#N(t){this.#p&&t.relatedTarget?.parentNode!==this.#o&&this.#B()}#W(t){this.#u=this.#p?t:""}#D(t){if(this.#e)for(const e of this.#e)e.tabIndex=t}_resizeWithKeyboard(t,e){this.#p&&this.#C(this.#u,{deltaX:t,deltaY:e,fromKeyboard:!0})}#B(){this.#p=!1,this.#D(-1),this.#I()}_stopResizingWithKeyboard(){this.#B(),this.div.focus()}select(){if(this.makeResizable(),this.div?.classList.add("selectedEditor"),!this._editToolbar){this.addEditToolbar().then(()=>{this.div?.classList.contains("selectedEditor")&&this._editToolbar?.show()});return}this._editToolbar?.show(),this.#s?.toggleAltTextBadge(!1)}unselect(){this.#o?.classList.add("hidden"),this.div?.classList.remove("selectedEditor"),this.div?.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),this._editToolbar?.hide(),this.#s?.toggleAltTextBadge(!0)}updateParams(t,e){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#g}set isEditing(t){this.#g=t,this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,e){this.#l=!0;const s=t/e,{style:i}=this.div;i.aspectRatio=s,i.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,e=!1){if(e){this.#w||=new Map;const{action:s}=t;let i=this.#w.get(s);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(t),this.#w.delete(s),this.#w.size===0&&(this.#w=null)},G._telemetryTimeout),this.#w.set(s,i);return}t.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}renderAnnotationElement(t){let e=t.container.querySelector(".annotationContent");if(!e)e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),t.container.prepend(e);else if(e.nodeName==="CANVAS"){const s=e;e=document.createElement("div"),e.classList.add("annotationContent",this.editorType),s.before(e)}return e}resetAnnotationElement(t){const{firstChild:e}=t.container;e?.nodeName==="DIV"&&e.classList.contains("annotationContent")&&e.remove()}}class Uf extends G{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const Ch=3285377520,be=4294901760,Ge=65535;class Ah{constructor(t){this.h1=t?t&4294967295:Ch,this.h2=t?t&4294967295:Ch}update(t){let e,s;if(typeof t=="string"){e=new Uint8Array(t.length*2),s=0;for(let p=0,v=t.length;p<v;p++){const m=t.charCodeAt(p);m<=255?e[s++]=m:(e[s++]=m>>>8,e[s++]=m&255)}}else if(ArrayBuffer.isView(t))e=t.slice(),s=e.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const i=s>>2,n=s-i*4,r=new Uint32Array(e.buffer,0,i);let a=0,l=0,h=this.h1,c=this.h2;const u=3432918353,d=461845907,f=u&Ge,g=d&Ge;for(let p=0;p<i;p++)p&1?(a=r[p],a=a*u&be|a*f&Ge,a=a<<15|a>>>17,a=a*d&be|a*g&Ge,h^=a,h=h<<13|h>>>19,h=h*5+3864292196):(l=r[p],l=l*u&be|l*f&Ge,l=l<<15|l>>>17,l=l*d&be|l*g&Ge,c^=l,c=c<<13|c>>>19,c=c*5+3864292196);switch(a=0,n){case 3:a^=e[i*4+2]<<16;case 2:a^=e[i*4+1]<<8;case 1:a^=e[i*4],a=a*u&be|a*f&Ge,a=a<<15|a>>>17,a=a*d&be|a*g&Ge,i&1?h^=a:c^=a}this.h1=h,this.h2=c}hexdigest(){let t=this.h1,e=this.h2;return t^=e>>>1,t=t*3981806797&be|t*36045&Ge,e=e*4283543511&be|((e<<16|t>>>16)*2950163797&be)>>>16,t^=e>>>1,t=t*444984403&be|t*60499&Ge,e=e*3301882366&be|((e<<16|t>>>16)*3120437893&be)>>>16,t^=e>>>1,(t>>>0).toString(16).padStart(8,"0")+(e>>>0).toString(16).padStart(8,"0")}}const Da=Object.freeze({map:null,hash:"",transfer:void 0});class Ra{#t=!1;#e=null;#s=new Map;constructor(){this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,e){const s=this.#s.get(t);return s===void 0?e:Object.assign(e,s)}getRawValue(t){return this.#s.get(t)}remove(t){if(this.#s.delete(t),this.#s.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const e of this.#s.values())if(e instanceof G)return;this.onAnnotationEditor(null)}}setValue(t,e){const s=this.#s.get(t);let i=!1;if(s!==void 0)for(const[n,r]of Object.entries(e))s[n]!==r&&(i=!0,s[n]=r);else i=!0,this.#s.set(t,e);i&&this.#i(),e instanceof G&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(e.constructor._type)}has(t){return this.#s.has(t)}getAll(){return this.#s.size>0?xa(this.#s):null}setAll(t){for(const[e,s]of Object.entries(t))this.setValue(e,s)}get size(){return this.#s.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Th(this)}get serializable(){if(this.#s.size===0)return Da;const t=new Map,e=new Ah,s=[],i=Object.create(null);let n=!1;for(const[r,a]of this.#s){const l=a instanceof G?a.serialize(!1,i):a;l&&(t.set(r,l),e.update(`${r}:${JSON.stringify(l)}`),n||=!!l.bitmap)}if(n)for(const r of t.values())r.bitmap&&s.push(r.bitmap);return t.size>0?{map:t,hash:e.hexdigest(),transfer:s}:Da}get editorStats(){let t=null;const e=new Map;for(const s of this.#s.values()){if(!(s instanceof G))continue;const i=s.telemetryFinalData;if(!i)continue;const{type:n}=i;e.has(n)||e.set(n,Object.getPrototypeOf(s).constructor),t||=Object.create(null);const r=t[n]||=new Map;for(const[a,l]of Object.entries(i)){if(a==="type")continue;let h=r.get(a);h||(h=new Map,r.set(a,h));const c=h.get(l)??0;h.set(l,c+1)}}for(const[s,i]of e)t[s]=i.computeTelemetryFinalData(t[s]);return t}resetModifiedIds(){this.#e=null}get modifiedIds(){if(this.#e)return this.#e;const t=[];for(const e of this.#s.values())!(e instanceof G)||!e.annotationElementId||!e.serialize()||t.push(e.annotationElementId);return this.#e={ids:new Set(t),hash:t.join(",")}}}class Th extends Ra{#t;constructor(t){super();const{map:e,hash:s,transfer:i}=t.serializable,n=structuredClone(e,i?{transfer:i}:null);this.#t={map:n,hash:s,transfer:i}}get print(){ut("Should not call PrintAnnotationStorage.print")}get serializable(){return this.#t}get modifiedIds(){return tt(this,"modifiedIds",{ids:new Set,hash:""})}}class Yf{#t=new Set;constructor({ownerDocument:t=globalThis.document,styleElement:e=null}){this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const e=this.styleElement.sheet;e.insertRule(t,e.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),this.#t.clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:e}){if(!(!t||this.#t.has(t.loadedName))){if(Mt(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:s,src:i,style:n}=t,r=new FontFace(s,i,n);this.addNativeFontFace(r);try{await r.load(),this.#t.add(s),e?.(t)}catch{Q(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(r)}return}ut("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const s=t.createNativeFontFace();if(s){this.addNativeFontFace(s);try{await s.loaded}catch(i){throw Q(`Failed to load font '${s.family}': '${i}'.`),t.disableFontFace=!0,i}}return}const e=t.createFontFaceRule();if(e){if(this.insertRule(e),this.isSyncFontLoadingSupported)return;await new Promise(s=>{const i=this._queueLoadingCallback(s);this._prepareFontLoadEvent(t,i)})}}get isFontLoadingAPISupported(){const t=!!this._document?.fonts;return tt(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(Gt||typeof navigator<"u"&&typeof navigator?.userAgent=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),tt(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function e(){for(Mt(!i.done,"completeRequest() cannot be called twice."),i.done=!0;s.length>0&&s[0].done;){const n=s.shift();setTimeout(n.callback,0)}}const{loadingRequests:s}=this,i={done:!1,complete:e,callback:t};return s.push(i),i}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return tt(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,e){function s(w,C){return w.charCodeAt(C)<<24|w.charCodeAt(C+1)<<16|w.charCodeAt(C+2)<<8|w.charCodeAt(C+3)&255}function i(w,C,T,E){const k=w.substring(0,C),O=w.substring(C+T);return k+E+O}let n,r;const a=this._document.createElement("canvas");a.width=1,a.height=1;const l=a.getContext("2d");let h=0;function c(w,C){if(++h>30){Q("Load test font never loaded."),C();return}if(l.font="30px "+w,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){C();return}setTimeout(c.bind(null,w,C))}const u=`lt${Date.now()}${this.loadTestFontId++}`;let d=this._loadTestFont;d=i(d,976,u.length,u);const g=16,p=1482184792;let v=s(d,g);for(n=0,r=u.length-3;n<r;n+=4)v=v-p+s(u,n)|0;n<u.length&&(v=v-p+s(u+"XXX",n)|0),d=i(d,g,4,Df(v));const m=`url(data:font/opentype;base64,${btoa(d)});`,b=`@font-face {font-family:"${u}";src:${m}}`;this.insertRule(b);const _=this._document.createElement("div");_.style.visibility="hidden",_.style.width=_.style.height="10px",_.style.position="absolute",_.style.top=_.style.left="0px";for(const w of[t.loadedName,u]){const C=this._document.createElement("span");C.textContent="Hi",C.style.fontFamily=w,_.append(C)}this._document.body.append(_),c(u,()=>{_.remove(),e.complete()})}}class $f{constructor(t,{disableFontFace:e=!1,fontExtraProperties:s=!1,inspectFont:i=null}){this.compiledGlyphs=Object.create(null);for(const n in t)this[n]=t[n];this.disableFontFace=e===!0,this.fontExtraProperties=s===!0,this._inspectFont=i}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const e={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(e.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,e)}return this._inspectFont?.(this),t}createFontFaceRule(){if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${Nf(this.data)});`;let e;if(!this.cssFontInfo)e=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let s=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(s+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),e=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${s}src:${t}}`}return this._inspectFont?.(this,t),e}getPathGenerator(t,e){if(this.compiledGlyphs[e]!==void 0)return this.compiledGlyphs[e];const s=this.loadedName+"_path_"+e;let i;try{i=t.get(s)}catch(r){Q(`getPathGenerator - ignoring character: "${r}".`)}const n=new Path2D(i||"");return this.fontExtraProperties||t.delete(s),this.compiledGlyphs[e]=n}}const sr={DATA:1,ERROR:2},Ot={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function Eh(){}function re(o){if(o instanceof cs||o instanceof wa||o instanceof Oi||o instanceof yh||o instanceof Kn||o instanceof _a)return o;switch(o instanceof Error||typeof o=="object"&&o!==null||ut('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),o.name){case"AbortException":return new cs(o.message);case"InvalidPDFException":return new wa(o.message);case"MissingPDFException":return new Oi(o.message);case"PasswordException":return new yh(o.message,o.code);case"UnexpectedResponseException":return new Kn(o.message,o.status);case"UnknownErrorException":return new _a(o.message,o.details)}return new _a(o.message,o.toString())}class Ii{#t=new AbortController;constructor(t,e,s){this.sourceName=t,this.targetName=e,this.comObj=s,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),s.addEventListener("message",this.#e.bind(this),{signal:this.#t.signal})}#e({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){this.#i(t);return}if(t.callback){const s=t.callbackId,i=this.callbackCapabilities[s];if(!i)throw new Error(`Cannot resolve callback ${s}`);if(delete this.callbackCapabilities[s],t.callback===sr.DATA)i.resolve(t.data);else if(t.callback===sr.ERROR)i.reject(re(t.reason));else throw new Error("Unexpected callback case");return}const e=this.actionHandler[t.action];if(!e)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const s=this.sourceName,i=t.sourceName,n=this.comObj;Promise.try(e,t.data).then(function(r){n.postMessage({sourceName:s,targetName:i,callback:sr.DATA,callbackId:t.callbackId,data:r})},function(r){n.postMessage({sourceName:s,targetName:i,callback:sr.ERROR,callbackId:t.callbackId,reason:re(r)})});return}if(t.streamId){this.#s(t);return}e(t.data)}on(t,e){const s=this.actionHandler;if(s[t])throw new Error(`There is already an actionName called "${t}"`);s[t]=e}send(t,e,s){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:e},s)}sendWithPromise(t,e,s){const i=this.callbackId++,n=Promise.withResolvers();this.callbackCapabilities[i]=n;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:i,data:e},s)}catch(r){n.reject(r)}return n.promise}sendWithStream(t,e,s,i){const n=this.streamId++,r=this.sourceName,a=this.targetName,l=this.comObj;return new ReadableStream({start:h=>{const c=Promise.withResolvers();return this.streamControllers[n]={controller:h,startCall:c,pullCall:null,cancelCall:null,isClosed:!1},l.postMessage({sourceName:r,targetName:a,action:t,streamId:n,data:e,desiredSize:h.desiredSize},i),c.promise},pull:h=>{const c=Promise.withResolvers();return this.streamControllers[n].pullCall=c,l.postMessage({sourceName:r,targetName:a,stream:Ot.PULL,streamId:n,desiredSize:h.desiredSize}),c.promise},cancel:h=>{Mt(h instanceof Error,"cancel must have a valid reason");const c=Promise.withResolvers();return this.streamControllers[n].cancelCall=c,this.streamControllers[n].isClosed=!0,l.postMessage({sourceName:r,targetName:a,stream:Ot.CANCEL,streamId:n,reason:re(h)}),c.promise}},s)}#s(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this,a=this.actionHandler[t.action],l={enqueue(h,c=1,u){if(this.isCancelled)return;const d=this.desiredSize;this.desiredSize-=c,d>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),n.postMessage({sourceName:s,targetName:i,stream:Ot.ENQUEUE,streamId:e,chunk:h},u)},close(){this.isCancelled||(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ot.CLOSE,streamId:e}),delete r.streamSinks[e])},error(h){Mt(h instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,n.postMessage({sourceName:s,targetName:i,stream:Ot.ERROR,streamId:e,reason:re(h)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};l.sinkCapability.resolve(),l.ready=l.sinkCapability.promise,this.streamSinks[e]=l,Promise.try(a,t.data,l).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ot.START_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Ot.START_COMPLETE,streamId:e,reason:re(h)})})}#i(t){const e=t.streamId,s=this.sourceName,i=t.sourceName,n=this.comObj,r=this.streamControllers[e],a=this.streamSinks[e];switch(t.stream){case Ot.START_COMPLETE:t.success?r.startCall.resolve():r.startCall.reject(re(t.reason));break;case Ot.PULL_COMPLETE:t.success?r.pullCall.resolve():r.pullCall.reject(re(t.reason));break;case Ot.PULL:if(!a){n.postMessage({sourceName:s,targetName:i,stream:Ot.PULL_COMPLETE,streamId:e,success:!0});break}a.desiredSize<=0&&t.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=t.desiredSize,Promise.try(a.onPull||Eh).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ot.PULL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Ot.PULL_COMPLETE,streamId:e,reason:re(h)})});break;case Ot.ENQUEUE:if(Mt(r,"enqueue should have stream controller"),r.isClosed)break;r.controller.enqueue(t.chunk);break;case Ot.CLOSE:if(Mt(r,"close should have stream controller"),r.isClosed)break;r.isClosed=!0,r.controller.close(),this.#r(r,e);break;case Ot.ERROR:Mt(r,"error should have stream controller"),r.controller.error(re(t.reason)),this.#r(r,e);break;case Ot.CANCEL_COMPLETE:t.success?r.cancelCall.resolve():r.cancelCall.reject(re(t.reason)),this.#r(r,e);break;case Ot.CANCEL:if(!a)break;const l=re(t.reason);Promise.try(a.onCancel||Eh,l).then(function(){n.postMessage({sourceName:s,targetName:i,stream:Ot.CANCEL_COMPLETE,streamId:e,success:!0})},function(h){n.postMessage({sourceName:s,targetName:i,stream:Ot.CANCEL_COMPLETE,streamId:e,reason:re(h)})}),a.sinkCapability.reject(l),a.isCancelled=!0,delete this.streamSinks[e];break;default:throw new Error("Unexpected stream case")}}async#r(t,e){await Promise.allSettled([t.startCall?.promise,t.pullCall?.promise,t.cancelCall?.promise]),delete this.streamControllers[e]}destroy(){this.#t?.abort(),this.#t=null}}class kh{#t=!1;constructor({enableHWA:t=!1}){this.#t=t}create(t,e){if(t<=0||e<=0)throw new Error("Invalid canvas size");const s=this._createCanvas(t,e);return{canvas:s,context:s.getContext("2d",{willReadFrequently:!this.#t})}}reset(t,e,s){if(!t.canvas)throw new Error("Canvas is not specified");if(e<=0||s<=0)throw new Error("Invalid canvas size");t.canvas.width=e,t.canvas.height=s}destroy(t){if(!t.canvas)throw new Error("Canvas is not specified");t.canvas.width=0,t.canvas.height=0,t.canvas=null,t.context=null}_createCanvas(t,e){ut("Abstract method `_createCanvas` called.")}}class qf extends kh{constructor({ownerDocument:t=globalThis.document,enableHWA:e=!1}){super({enableHWA:e}),this._document=t}_createCanvas(t,e){const s=this._document.createElement("canvas");return s.width=t,s.height=e,s}}class Ph{constructor({baseUrl:t=null,isCompressed:e=!0}){this.baseUrl=t,this.isCompressed=e}async fetch({name:t}){if(!this.baseUrl)throw new Error("Ensure that the `cMapUrl` and `cMapPacked` API parameters are provided.");if(!t)throw new Error("CMap name must be specified.");const e=this.baseUrl+t+(this.isCompressed?".bcmap":"");return this._fetch(e).then(s=>({cMapData:s,isCompressed:this.isCompressed})).catch(s=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${e}`)})}async _fetch(t){ut("Abstract method `_fetch` called.")}}class Mh extends Ph{async _fetch(t){const e=await Qn(t,this.isCompressed?"arraybuffer":"text");return e instanceof ArrayBuffer?new Uint8Array(e):Jn(e)}}class Oh{addFilter(t){return"none"}addHCMFilter(t,e){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,e,s,i,n){return"none"}destroy(t=!1){}}class Kf extends Oh{#t;#e;#s;#i;#r;#n;#l=0;constructor({docId:t,ownerDocument:e=globalThis.document}){super(),this.#i=t,this.#r=e}get#o(){return this.#e||=new Map}get#c(){return this.#n||=new Map}get#h(){if(!this.#s){const t=this.#r.createElement("div"),{style:e}=t;e.visibility="hidden",e.contain="strict",e.width=e.height=0,e.position="absolute",e.top=e.left=0,e.zIndex=-1;const s=this.#r.createElementNS(es,"svg");s.setAttribute("width",0),s.setAttribute("height",0),this.#s=this.#r.createElementNS(es,"defs"),t.append(s),s.append(this.#s),this.#r.body.append(t)}return this.#s}#d(t){if(t.length===1){const l=t[0],h=new Array(256);for(let u=0;u<256;u++)h[u]=l[u]/255;const c=h.join(",");return[c,c,c]}const[e,s,i]=t,n=new Array(256),r=new Array(256),a=new Array(256);for(let l=0;l<256;l++)n[l]=e[l]/255,r[l]=s[l]/255,a[l]=i[l]/255;return[n.join(","),r.join(","),a.join(",")]}#u(t){if(this.#t===void 0){this.#t="";const e=this.#r.URL;e!==this.#r.baseURI&&(Zn(e)?Q('#createUrl: ignore "data:"-URL for performance reasons.'):this.#t=e.split("#",1)[0])}return`url(${this.#t}#${t})`}addFilter(t){if(!t)return"none";let e=this.#o.get(t);if(e)return e;const[s,i,n]=this.#d(t),r=t.length===1?s:`${s}${i}${n}`;if(e=this.#o.get(r),e)return this.#o.set(t,e),e;const a=`g_${this.#i}_transfer_map_${this.#l++}`,l=this.#u(a);this.#o.set(t,l),this.#o.set(r,l);const h=this.#g(a);return this.#p(s,i,n,h),l}addHCMFilter(t,e){const s=`${t}-${e}`,i="base";let n=this.#c.get(i);if(n?.key===s||(n?(n.filter?.remove(),n.key=s,n.url="none",n.filter=null):(n={key:s,url:"none",filter:null},this.#c.set(i,n)),!t||!e))return n.url;const r=this.#_(t);t=z.makeHexColor(...r);const a=this.#_(e);if(e=z.makeHexColor(...a),this.#h.style.color="",t==="#000000"&&e==="#ffffff"||t===e)return n.url;const l=new Array(256);for(let f=0;f<=255;f++){const g=f/255;l[f]=g<=.03928?g/12.92:((g+.055)/1.055)**2.4}const h=l.join(","),c=`g_${this.#i}_hcm_filter`,u=n.filter=this.#g(c);this.#p(h,h,h,u),this.#a(u);const d=(f,g)=>{const p=r[f]/255,v=a[f]/255,m=new Array(g+1);for(let b=0;b<=g;b++)m[b]=p+b/g*(v-p);return m.join(",")};return this.#p(d(0,5),d(1,5),d(2,5),u),n.url=this.#u(c),n.url}addAlphaFilter(t){let e=this.#o.get(t);if(e)return e;const[s]=this.#d([t]),i=`alpha_${s}`;if(e=this.#o.get(i),e)return this.#o.set(t,e),e;const n=`g_${this.#i}_alpha_map_${this.#l++}`,r=this.#u(n);this.#o.set(t,r),this.#o.set(i,r);const a=this.#g(n);return this.#v(s,a),r}addLuminosityFilter(t){let e=this.#o.get(t||"luminosity");if(e)return e;let s,i;if(t?([s]=this.#d([t]),i=`luminosity_${s}`):i="luminosity",e=this.#o.get(i),e)return this.#o.set(t,e),e;const n=`g_${this.#i}_luminosity_map_${this.#l++}`,r=this.#u(n);this.#o.set(t,r),this.#o.set(i,r);const a=this.#g(n);return this.#f(a),t&&this.#v(s,a),r}addHighlightHCMFilter(t,e,s,i,n){const r=`${e}-${s}-${i}-${n}`;let a=this.#c.get(t);if(a?.key===r||(a?(a.filter?.remove(),a.key=r,a.url="none",a.filter=null):(a={key:r,url:"none",filter:null},this.#c.set(t,a)),!e||!s))return a.url;const[l,h]=[e,s].map(this.#_.bind(this));let c=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),u=Math.round(.2126*h[0]+.7152*h[1]+.0722*h[2]),[d,f]=[i,n].map(this.#_.bind(this));u<c&&([c,u,d,f]=[u,c,f,d]),this.#h.style.color="";const g=(m,b,_)=>{const w=new Array(256),C=(u-c)/_,T=m/255,E=(b-m)/(255*_);let k=0;for(let O=0;O<=_;O++){const H=Math.round(c+O*C),N=T+O*E;for(let P=k;P<=H;P++)w[P]=N;k=H+1}for(let O=k;O<256;O++)w[O]=w[k-1];return w.join(",")},p=`g_${this.#i}_hcm_${t}_filter`,v=a.filter=this.#g(p);return this.#a(v),this.#p(g(d[0],f[0],5),g(d[1],f[1],5),g(d[2],f[2],5),v),a.url=this.#u(p),a.url}destroy(t=!1){t&&this.#n?.size||(this.#s?.parentNode.parentNode.remove(),this.#s=null,this.#e?.clear(),this.#e=null,this.#n?.clear(),this.#n=null,this.#l=0)}#f(t){const e=this.#r.createElementNS(es,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),t.append(e)}#a(t){const e=this.#r.createElementNS(es,"feColorMatrix");e.setAttribute("type","matrix"),e.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),t.append(e)}#g(t){const e=this.#r.createElementNS(es,"filter");return e.setAttribute("color-interpolation-filters","sRGB"),e.setAttribute("id",t),this.#h.append(e),e}#m(t,e,s){const i=this.#r.createElementNS(es,e);i.setAttribute("type","discrete"),i.setAttribute("tableValues",s),t.append(i)}#p(t,e,s,i){const n=this.#r.createElementNS(es,"feComponentTransfer");i.append(n),this.#m(n,"feFuncR",t),this.#m(n,"feFuncG",e),this.#m(n,"feFuncB",s)}#v(t,e){const s=this.#r.createElementNS(es,"feComponentTransfer");e.append(s),this.#m(s,"feFuncA",t)}#_(t){return this.#h.style.color=t,ka(getComputedStyle(this.#h).getPropertyValue("color"))}}class Dh{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const e=`${this.baseUrl}${t}`;return this._fetch(e).catch(s=>{throw new Error(`Unable to load font data at: ${e}`)})}async _fetch(t){ut("Abstract method `_fetch` called.")}}class Rh extends Dh{async _fetch(t){const e=await Qn(t,"arraybuffer");return new Uint8Array(e)}}Gt&&Q("Please use the `legacy` build in Node.js environments.");async function Fh(o){const e=await process.getBuiltinModule("fs").promises.readFile(o);return new Uint8Array(e)}class Jf extends Oh{}class Qf extends kh{_createCanvas(t,e){return process.getBuiltinModule("module").createRequire(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:jt&&jt.tagName.toUpperCase()==="SCRIPT"&&jt.src||new URL("pdf-canvas.umd.js",document.baseURI).href)("@napi-rs/canvas").createCanvas(t,e)}}class Zf extends Ph{async _fetch(t){return Fh(t)}}class tg extends Dh{async _fetch(t){return Fh(t)}}const Xt={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Fa(o,t){if(!t)return;const e=t[2]-t[0],s=t[3]-t[1],i=new Path2D;i.rect(t[0],t[1],e,s),o.clip(i)}class La{getPattern(){ut("Abstract method `getPattern` called.")}}class eg extends La{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let e;this._type==="axial"?e=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(e=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const s of this._colorStops)e.addColorStop(s[0],s[1]);return e}getPattern(t,e,s,i){let n;if(i===Xt.STROKE||i===Xt.FILL){const r=e.current.getClippedPathBoundingBox(i,mt(t))||[0,0,0,0],a=Math.ceil(r[2]-r[0])||1,l=Math.ceil(r[3]-r[1])||1,h=e.cachedCanvases.getCanvas("pattern",a,l),c=h.context;c.clearRect(0,0,c.canvas.width,c.canvas.height),c.beginPath(),c.rect(0,0,c.canvas.width,c.canvas.height),c.translate(-r[0],-r[1]),s=z.transform(s,[1,0,0,1,r[0],r[1]]),c.transform(...e.baseTransform),this.matrix&&c.transform(...this.matrix),Fa(c,this._bbox),c.fillStyle=this._createGradient(c),c.fill(),n=t.createPattern(h.canvas,"no-repeat");const u=new DOMMatrix(s);n.setTransform(u)}else Fa(t,this._bbox),n=this._createGradient(t);return n}}function Ia(o,t,e,s,i,n,r,a){const l=t.coords,h=t.colors,c=o.data,u=o.width*4;let d;l[e+1]>l[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d),l[s+1]>l[i+1]&&(d=s,s=i,i=d,d=r,r=a,a=d),l[e+1]>l[s+1]&&(d=e,e=s,s=d,d=n,n=r,r=d);const f=(l[e]+t.offsetX)*t.scaleX,g=(l[e+1]+t.offsetY)*t.scaleY,p=(l[s]+t.offsetX)*t.scaleX,v=(l[s+1]+t.offsetY)*t.scaleY,m=(l[i]+t.offsetX)*t.scaleX,b=(l[i+1]+t.offsetY)*t.scaleY;if(g>=b)return;const _=h[n],w=h[n+1],C=h[n+2],T=h[r],E=h[r+1],k=h[r+2],O=h[a],H=h[a+1],N=h[a+2],P=Math.round(g),R=Math.round(b);let F,V,M,L,Y,ft,bt,_t;for(let gt=P;gt<=R;gt++){if(gt<v){const $=gt<g?0:(g-gt)/(g-v);F=f-(f-p)*$,V=_-(_-T)*$,M=w-(w-E)*$,L=C-(C-k)*$}else{let $;gt>b?$=1:v===b?$=0:$=(v-gt)/(v-b),F=p-(p-m)*$,V=T-(T-O)*$,M=E-(E-H)*$,L=k-(k-N)*$}let rt;gt<g?rt=0:gt>b?rt=1:rt=(g-gt)/(g-b),Y=f-(f-m)*rt,ft=_-(_-O)*rt,bt=w-(w-H)*rt,_t=C-(C-N)*rt;const Dt=Math.round(Math.min(F,Y)),ee=Math.round(Math.max(F,Y));let K=u*gt+Dt*4;for(let $=Dt;$<=ee;$++)rt=(F-$)/(F-Y),rt<0?rt=0:rt>1&&(rt=1),c[K++]=V-(V-ft)*rt|0,c[K++]=M-(M-bt)*rt|0,c[K++]=L-(L-_t)*rt|0,c[K++]=255}}function sg(o,t,e){const s=t.coords,i=t.colors;let n,r;switch(t.type){case"lattice":const a=t.verticesPerRow,l=Math.floor(s.length/a)-1,h=a-1;for(n=0;n<l;n++){let c=n*a;for(let u=0;u<h;u++,c++)Ia(o,e,s[c],s[c+1],s[c+a],i[c],i[c+1],i[c+a]),Ia(o,e,s[c+a+1],s[c+1],s[c+a],i[c+a+1],i[c+1],i[c+a])}break;case"triangles":for(n=0,r=s.length;n<r;n+=3)Ia(o,e,s[n],s[n+1],s[n+2],i[n],i[n+1],i[n+2]);break;default:throw new Error("illegal figure")}}class ig extends La{constructor(t){super(),this._coords=t[2],this._colors=t[3],this._figures=t[4],this._bounds=t[5],this._bbox=t[7],this._background=t[8],this.matrix=null}_createMeshCanvas(t,e,s){const a=Math.floor(this._bounds[0]),l=Math.floor(this._bounds[1]),h=Math.ceil(this._bounds[2])-a,c=Math.ceil(this._bounds[3])-l,u=Math.min(Math.ceil(Math.abs(h*t[0]*1.1)),3e3),d=Math.min(Math.ceil(Math.abs(c*t[1]*1.1)),3e3),f=h/u,g=c/d,p={coords:this._coords,colors:this._colors,offsetX:-a,offsetY:-l,scaleX:1/f,scaleY:1/g},v=u+2*2,m=d+2*2,b=s.getCanvas("mesh",v,m),_=b.context,w=_.createImageData(u,d);if(e){const T=w.data;for(let E=0,k=T.length;E<k;E+=4)T[E]=e[0],T[E+1]=e[1],T[E+2]=e[2],T[E+3]=255}for(const T of this._figures)sg(w,T,p);return _.putImageData(w,2,2),{canvas:b.canvas,offsetX:a-2*f,offsetY:l-2*g,scaleX:f,scaleY:g}}getPattern(t,e,s,i){Fa(t,this._bbox);let n;if(i===Xt.SHADING)n=z.singularValueDecompose2dScale(mt(t));else if(n=z.singularValueDecompose2dScale(e.baseTransform),this.matrix){const a=z.singularValueDecompose2dScale(this.matrix);n=[n[0]*a[0],n[1]*a[1]]}const r=this._createMeshCanvas(n,i===Xt.SHADING?null:this._background,e.cachedCanvases);return i!==Xt.SHADING&&(t.setTransform(...e.baseTransform),this.matrix&&t.transform(...this.matrix)),t.translate(r.offsetX,r.offsetY),t.scale(r.scaleX,r.scaleY),t.createPattern(r.canvas,"no-repeat")}}class ng extends La{getPattern(){return"hotpink"}}function rg(o){switch(o[0]){case"RadialAxial":return new eg(o);case"Mesh":return new ig(o);case"Dummy":return new ng}throw new Error(`Unknown IR type: ${o[0]}`)}const Lh={COLORED:1,UNCOLORED:2};class ja{static MAX_PATTERN_SIZE=3e3;constructor(t,e,s,i,n){this.operatorList=t[2],this.matrix=t[3],this.bbox=t[4],this.xstep=t[5],this.ystep=t[6],this.paintType=t[7],this.tilingType=t[8],this.color=e,this.ctx=s,this.canvasGraphicsFactory=i,this.baseTransform=n}createPatternCanvas(t){const{bbox:e,operatorList:s,paintType:i,tilingType:n,color:r,canvasGraphicsFactory:a}=this;let{xstep:l,ystep:h}=this;l=Math.abs(l),h=Math.abs(h),qn("TilingType: "+n);const c=e[0],u=e[1],d=e[2],f=e[3],g=d-c,p=f-u,v=z.singularValueDecompose2dScale(this.matrix),m=z.singularValueDecompose2dScale(this.baseTransform),b=v[0]*m[0],_=v[1]*m[1];let w=g,C=p,T=!1,E=!1;const k=Math.ceil(l*b),O=Math.ceil(h*_),H=Math.ceil(g*b),N=Math.ceil(p*_);k>=H?w=l:T=!0,O>=N?C=h:E=!0;const P=this.getSizeAndScale(w,this.ctx.canvas.width,b),R=this.getSizeAndScale(C,this.ctx.canvas.height,_),F=t.cachedCanvases.getCanvas("pattern",P.size,R.size),V=F.context,M=a.createCanvasGraphics(V);if(M.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(M,i,r),V.translate(-P.scale*c,-R.scale*u),M.transform(P.scale,0,0,R.scale,0,0),V.save(),this.clipBbox(M,c,u,d,f),M.baseTransform=mt(M.ctx),M.executeOperatorList(s),M.endDrawing(),V.restore(),T||E){const L=F.canvas;T&&(w=l),E&&(C=h);const Y=this.getSizeAndScale(w,this.ctx.canvas.width,b),ft=this.getSizeAndScale(C,this.ctx.canvas.height,_),bt=Y.size,_t=ft.size,gt=t.cachedCanvases.getCanvas("pattern-workaround",bt,_t),rt=gt.context,Dt=T?Math.floor(g/l):0,ee=E?Math.floor(p/h):0;for(let K=0;K<=Dt;K++)for(let $=0;$<=ee;$++)rt.drawImage(L,bt*K,_t*$,bt,_t,0,0,bt,_t);return{canvas:gt.canvas,scaleX:Y.scale,scaleY:ft.scale,offsetX:c,offsetY:u}}return{canvas:F.canvas,scaleX:P.scale,scaleY:R.scale,offsetX:c,offsetY:u}}getSizeAndScale(t,e,s){const i=Math.max(ja.MAX_PATTERN_SIZE,e);let n=Math.ceil(t*s);return n>=i?n=i:s=n/t,{scale:s,size:n}}clipBbox(t,e,s,i,n){const r=i-e,a=n-s;t.ctx.rect(e,s,r,a),t.current.updateRectMinMax(mt(t.ctx),[e,s,i,n]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,e,s){const i=t.ctx,n=t.current;switch(e){case Lh.COLORED:const r=this.ctx;i.fillStyle=r.fillStyle,i.strokeStyle=r.strokeStyle,n.fillColor=r.fillStyle,n.strokeColor=r.strokeStyle;break;case Lh.UNCOLORED:const a=z.makeHexColor(s[0],s[1],s[2]);i.fillStyle=a,i.strokeStyle=a,n.fillColor=a,n.strokeColor=a;break;default:throw new Of(`Unsupported paint type: ${e}`)}}getPattern(t,e,s,i){let n=s;i!==Xt.SHADING&&(n=z.transform(n,e.baseTransform),this.matrix&&(n=z.transform(n,this.matrix)));const r=this.createPatternCanvas(e);let a=new DOMMatrix(n);a=a.translate(r.offsetX,r.offsetY),a=a.scale(1/r.scaleX,1/r.scaleY);const l=t.createPattern(r.canvas,"repeat");return l.setTransform(a),l}}function ag({src:o,srcPos:t=0,dest:e,width:s,height:i,nonBlackColor:n=4294967295,inverseDecode:r=!1}){const a=Qt.isLittleEndian?4278190080:255,[l,h]=r?[n,a]:[a,n],c=s>>3,u=s&7,d=o.length;e=new Uint32Array(e.buffer);let f=0;for(let g=0;g<i;g++){for(const v=t+c;t<v;t++){const m=t<d?o[t]:255;e[f++]=m&128?h:l,e[f++]=m&64?h:l,e[f++]=m&32?h:l,e[f++]=m&16?h:l,e[f++]=m&8?h:l,e[f++]=m&4?h:l,e[f++]=m&2?h:l,e[f++]=m&1?h:l}if(u===0)continue;const p=t<d?o[t++]:255;for(let v=0;v<u;v++)e[f++]=p&1<<7-v?h:l}return{srcPos:t,destPos:f}}const Ih=16,jh=100,og=15,Nh=10,Bh=1e3,ae=16;function lg(o,t){if(o._removeMirroring)throw new Error("Context is already forwarding operations.");o.__originalSave=o.save,o.__originalRestore=o.restore,o.__originalRotate=o.rotate,o.__originalScale=o.scale,o.__originalTranslate=o.translate,o.__originalTransform=o.transform,o.__originalSetTransform=o.setTransform,o.__originalResetTransform=o.resetTransform,o.__originalClip=o.clip,o.__originalMoveTo=o.moveTo,o.__originalLineTo=o.lineTo,o.__originalBezierCurveTo=o.bezierCurveTo,o.__originalRect=o.rect,o.__originalClosePath=o.closePath,o.__originalBeginPath=o.beginPath,o._removeMirroring=()=>{o.save=o.__originalSave,o.restore=o.__originalRestore,o.rotate=o.__originalRotate,o.scale=o.__originalScale,o.translate=o.__originalTranslate,o.transform=o.__originalTransform,o.setTransform=o.__originalSetTransform,o.resetTransform=o.__originalResetTransform,o.clip=o.__originalClip,o.moveTo=o.__originalMoveTo,o.lineTo=o.__originalLineTo,o.bezierCurveTo=o.__originalBezierCurveTo,o.rect=o.__originalRect,o.closePath=o.__originalClosePath,o.beginPath=o.__originalBeginPath,delete o._removeMirroring},o.save=function(){t.save(),this.__originalSave()},o.restore=function(){t.restore(),this.__originalRestore()},o.translate=function(s,i){t.translate(s,i),this.__originalTranslate(s,i)},o.scale=function(s,i){t.scale(s,i),this.__originalScale(s,i)},o.transform=function(s,i,n,r,a,l){t.transform(s,i,n,r,a,l),this.__originalTransform(s,i,n,r,a,l)},o.setTransform=function(s,i,n,r,a,l){t.setTransform(s,i,n,r,a,l),this.__originalSetTransform(s,i,n,r,a,l)},o.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},o.rotate=function(s){t.rotate(s),this.__originalRotate(s)},o.clip=function(s){t.clip(s),this.__originalClip(s)},o.moveTo=function(e,s){t.moveTo(e,s),this.__originalMoveTo(e,s)},o.lineTo=function(e,s){t.lineTo(e,s),this.__originalLineTo(e,s)},o.bezierCurveTo=function(e,s,i,n,r,a){t.bezierCurveTo(e,s,i,n,r,a),this.__originalBezierCurveTo(e,s,i,n,r,a)},o.rect=function(e,s,i,n){t.rect(e,s,i,n),this.__originalRect(e,s,i,n)},o.closePath=function(){t.closePath(),this.__originalClosePath()},o.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class hg{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,e,s){let i;return this.cache[t]!==void 0?(i=this.cache[t],this.canvasFactory.reset(i,e,s)):(i=this.canvasFactory.create(e,s),this.cache[t]=i),i}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const e=this.cache[t];this.canvasFactory.destroy(e),delete this.cache[t]}}}function ir(o,t,e,s,i,n,r,a,l,h){const[c,u,d,f,g,p]=mt(o);if(u===0&&d===0){const b=r*c+g,_=Math.round(b),w=a*f+p,C=Math.round(w),T=(r+l)*c+g,E=Math.abs(Math.round(T)-_)||1,k=(a+h)*f+p,O=Math.abs(Math.round(k)-C)||1;return o.setTransform(Math.sign(c),0,0,Math.sign(f),_,C),o.drawImage(t,e,s,i,n,0,0,E,O),o.setTransform(c,u,d,f,g,p),[E,O]}if(c===0&&f===0){const b=a*d+g,_=Math.round(b),w=r*u+p,C=Math.round(w),T=(a+h)*d+g,E=Math.abs(Math.round(T)-_)||1,k=(r+l)*u+p,O=Math.abs(Math.round(k)-C)||1;return o.setTransform(0,Math.sign(u),Math.sign(d),0,_,C),o.drawImage(t,e,s,i,n,0,0,O,E),o.setTransform(c,u,d,f,g,p),[O,E]}o.drawImage(t,e,s,i,n,r,a,l,h);const v=Math.hypot(c,u),m=Math.hypot(d,f);return[v*l,m*h]}function cg(o){const{width:t,height:e}=o;if(t>Bh||e>Bh)return null;const s=1e3,i=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),n=t+1;let r=new Uint8Array(n*(e+1)),a,l,h;const c=t+7&-8;let u=new Uint8Array(c*e),d=0;for(const m of o.data){let b=128;for(;b>0;)u[d++]=m&b?0:255,b>>=1}let f=0;for(d=0,u[d]!==0&&(r[0]=1,++f),l=1;l<t;l++)u[d]!==u[d+1]&&(r[l]=u[d]?2:1,++f),d++;for(u[d]!==0&&(r[l]=2,++f),a=1;a<e;a++){d=a*c,h=a*n,u[d-c]!==u[d]&&(r[h]=u[d]?1:8,++f);let m=(u[d]?4:0)+(u[d-c]?8:0);for(l=1;l<t;l++)m=(m>>2)+(u[d+1]?4:0)+(u[d-c+1]?8:0),i[m]&&(r[h+l]=i[m],++f),d++;if(u[d-c]!==u[d]&&(r[h+l]=u[d]?2:4,++f),f>s)return null}for(d=c*(e-1),h=a*n,u[d]!==0&&(r[h]=8,++f),l=1;l<t;l++)u[d]!==u[d+1]&&(r[h+l]=u[d]?4:8,++f),d++;if(u[d]!==0&&(r[h+l]=4,++f),f>s)return null;const g=new Int32Array([0,n,-1,0,-n,0,0,0,1]),p=new Path2D;for(a=0;f&&a<=e;a++){let m=a*n;const b=m+t;for(;m<b&&!r[m];)m++;if(m===b)continue;p.moveTo(m%n,a);const _=m;let w=r[m];do{const C=g[w];do m+=C;while(!r[m]);const T=r[m];T!==5&&T!==10?(w=T,r[m]=0):(w=T&51*w>>4,r[m]&=w>>2|w<<2),p.lineTo(m%n,m/n|0),r[m]||--f}while(_!==m);--a}return u=null,r=null,function(m){m.save(),m.scale(1/t,-1/e),m.translate(0,-e),m.fill(p),m.beginPath(),m.restore()}}class Hh{constructor(t,e){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=bh,this.textMatrixScale=1,this.fontMatrix=ba,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Wt.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.patternStroke=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,e])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,e){this.x=t,this.y=e}updatePathMinMax(t,e,s){[e,s]=z.applyTransform([e,s],t),this.minX=Math.min(this.minX,e),this.minY=Math.min(this.minY,s),this.maxX=Math.max(this.maxX,e),this.maxY=Math.max(this.maxY,s)}updateRectMinMax(t,e){const s=z.applyTransform(e,t),i=z.applyTransform(e.slice(2),t),n=z.applyTransform([e[0],e[3]],t),r=z.applyTransform([e[2],e[1]],t);this.minX=Math.min(this.minX,s[0],i[0],n[0],r[0]),this.minY=Math.min(this.minY,s[1],i[1],n[1],r[1]),this.maxX=Math.max(this.maxX,s[0],i[0],n[0],r[0]),this.maxY=Math.max(this.maxY,s[1],i[1],n[1],r[1])}updateScalingPathMinMax(t,e){z.scaleMinMax(t,e),this.minX=Math.min(this.minX,e[0]),this.minY=Math.min(this.minY,e[1]),this.maxX=Math.max(this.maxX,e[2]),this.maxY=Math.max(this.maxY,e[3])}updateCurvePathMinMax(t,e,s,i,n,r,a,l,h,c){const u=z.bezierBoundingBox(e,s,i,n,r,a,l,h,c);c||this.updateRectMinMax(t,u)}getPathBoundingBox(t=Xt.FILL,e=null){const s=[this.minX,this.minY,this.maxX,this.maxY];if(t===Xt.STROKE){e||ut("Stroke bounding box must include transform.");const i=z.singularValueDecompose2dScale(e),n=i[0]*this.lineWidth/2,r=i[1]*this.lineWidth/2;s[0]-=n,s[1]-=r,s[2]+=n,s[3]+=r}return s}updateClipFromPath(){const t=z.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=Xt.FILL,e=null){return z.intersect(this.clipBox,this.getPathBoundingBox(t,e))}}function zh(o,t){if(t instanceof ImageData){o.putImageData(t,0,0);return}const e=t.height,s=t.width,i=e%ae,n=(e-i)/ae,r=i===0?n:n+1,a=o.createImageData(s,ae);let l=0,h;const c=t.data,u=a.data;let d,f,g,p;if(t.kind===Un.GRAYSCALE_1BPP){const v=c.byteLength,m=new Uint32Array(u.buffer,0,u.byteLength>>2),b=m.length,_=s+7>>3,w=4294967295,C=Qt.isLittleEndian?4278190080:255;for(d=0;d<r;d++){for(g=d<n?ae:i,h=0,f=0;f<g;f++){const T=v-l;let E=0;const k=T>_?s:T*8-7,O=k&-8;let H=0,N=0;for(;E<O;E+=8)N=c[l++],m[h++]=N&128?w:C,m[h++]=N&64?w:C,m[h++]=N&32?w:C,m[h++]=N&16?w:C,m[h++]=N&8?w:C,m[h++]=N&4?w:C,m[h++]=N&2?w:C,m[h++]=N&1?w:C;for(;E<k;E++)H===0&&(N=c[l++],H=128),m[h++]=N&H?w:C,H>>=1}for(;h<b;)m[h++]=0;o.putImageData(a,0,d*ae)}}else if(t.kind===Un.RGBA_32BPP){for(f=0,p=s*ae*4,d=0;d<n;d++)u.set(c.subarray(l,l+p)),l+=p,o.putImageData(a,0,f),f+=ae;d<r&&(p=s*i*4,u.set(c.subarray(l,l+p)),o.putImageData(a,0,f))}else if(t.kind===Un.RGB_24BPP)for(g=ae,p=s*g,d=0;d<r;d++){for(d>=n&&(g=i,p=s*g),h=0,f=p;f--;)u[h++]=c[l++],u[h++]=c[l++],u[h++]=c[l++],u[h++]=255;o.putImageData(a,0,d*ae)}else throw new Error(`bad image kind: ${t.kind}`)}function Vh(o,t){if(t.bitmap){o.drawImage(t.bitmap,0,0);return}const e=t.height,s=t.width,i=e%ae,n=(e-i)/ae,r=i===0?n:n+1,a=o.createImageData(s,ae);let l=0;const h=t.data,c=a.data;for(let u=0;u<r;u++){const d=u<n?ae:i;({srcPos:l}=ag({src:h,srcPos:l,dest:c,width:s,height:d,nonBlackColor:0})),o.putImageData(a,0,u*ae)}}function ji(o,t){const e=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(const s of e)o[s]!==void 0&&(t[s]=o[s]);o.setLineDash!==void 0&&(t.setLineDash(o.getLineDash()),t.lineDashOffset=o.lineDashOffset)}function nr(o){if(o.strokeStyle=o.fillStyle="#000000",o.fillRule="nonzero",o.globalAlpha=1,o.lineWidth=1,o.lineCap="butt",o.lineJoin="miter",o.miterLimit=10,o.globalCompositeOperation="source-over",o.font="10px sans-serif",o.setLineDash!==void 0&&(o.setLineDash([]),o.lineDashOffset=0),!Gt){const{filter:t}=o;t!=="none"&&t!==""&&(o.filter="none")}}function Gh(o,t){if(t)return!0;const e=z.singularValueDecompose2dScale(o);e[0]=Math.fround(e[0]),e[1]=Math.fround(e[1]);const s=Math.fround((globalThis.devicePixelRatio||1)*ti.PDF_TO_CSS_UNITS);return e[0]<=s&&e[1]<=s}const ug=["butt","round","square"],dg=["miter","round","bevel"],fg={},Wh={};class ei{constructor(t,e,s,i,n,{optionalContentConfig:r,markedContentStack:a=null},l,h){this.ctx=t,this.current=new Hh(this.ctx.canvas.width,this.ctx.canvas.height),this.stateStack=[],this.pendingClip=null,this.pendingEOFill=!1,this.res=null,this.xobjs=null,this.commonObjs=e,this.objs=s,this.canvasFactory=i,this.filterFactory=n,this.groupStack=[],this.processingType3=null,this.baseTransform=null,this.baseTransformStack=[],this.groupLevel=0,this.smaskStack=[],this.smaskCounter=0,this.tempSMask=null,this.suspendedCtx=null,this.contentVisible=!0,this.markedContentStack=a||[],this.optionalContentConfig=r,this.cachedCanvases=new hg(this.canvasFactory),this.cachedPatterns=new Map,this.annotationCanvasMap=l,this.viewportScale=1,this.outputScaleX=1,this.outputScaleY=1,this.pageColors=h,this._cachedScaleForStroking=[-1,0],this._cachedGetSinglePixelWidth=null,this._cachedBitmapsMap=new Map}getObject(t,e=null){return typeof t=="string"?t.startsWith("g_")?this.commonObjs.get(t):this.objs.get(t):e}beginDrawing({transform:t,viewport:e,transparency:s=!1,background:i=null}){const n=this.ctx.canvas.width,r=this.ctx.canvas.height,a=this.ctx.fillStyle;if(this.ctx.fillStyle=i||"#ffffff",this.ctx.fillRect(0,0,n,r),this.ctx.fillStyle=a,s){const l=this.cachedCanvases.getCanvas("transparent",n,r);this.compositeCtx=this.ctx,this.transparentCanvas=l.canvas,this.ctx=l.context,this.ctx.save(),this.ctx.transform(...mt(this.compositeCtx))}this.ctx.save(),nr(this.ctx),t&&(this.ctx.transform(...t),this.outputScaleX=t[0],this.outputScaleY=t[0]),this.ctx.transform(...e.transform),this.viewportScale=e.scale,this.baseTransform=mt(this.ctx)}executeOperatorList(t,e,s,i){const n=t.argsArray,r=t.fnArray;let a=e||0;const l=n.length;if(l===a)return a;const h=l-a>Nh&&typeof s=="function",c=h?Date.now()+og:0;let u=0;const d=this.commonObjs,f=this.objs;let g;for(;;){if(i!==void 0&&a===i.nextBreakPoint)return i.breakIt(a,s),a;if(g=r[a],g!==Me.dependency)this[g].apply(this,n[a]);else for(const p of n[a]){const v=p.startsWith("g_")?d:f;if(!v.has(p))return v.get(p,s),a}if(a++,a===l)return a;if(h&&++u>Nh){if(Date.now()>c)return s(),a;u=0}}}#t(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)}endDrawing(){this.#t(),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const e of t.values())typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement&&(e.width=e.height=0);t.clear()}this._cachedBitmapsMap.clear(),this.#e()}#e(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const e=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=e}}}_scaleImage(t,e){const s=t.width??t.displayWidth,i=t.height??t.displayHeight;let n=Math.max(Math.hypot(e[0],e[1]),1),r=Math.max(Math.hypot(e[2],e[3]),1),a=s,l=i,h="prescale1",c,u;for(;n>2&&a>1||r>2&&l>1;){let d=a,f=l;n>2&&a>1&&(d=a>=16384?Math.floor(a/2)-1||1:Math.ceil(a/2),n/=a/d),r>2&&l>1&&(f=l>=16384?Math.floor(l/2)-1||1:Math.ceil(l)/2,r/=l/f),c=this.cachedCanvases.getCanvas(h,d,f),u=c.context,u.clearRect(0,0,d,f),u.drawImage(t,0,0,a,l,0,0,d,f),t=c.canvas,a=d,l=f,h=h==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:a,paintHeight:l}}_createMaskCanvas(t){const e=this.ctx,{width:s,height:i}=t,n=this.current.fillColor,r=this.current.patternFill,a=mt(e);let l,h,c,u;if((t.bitmap||t.data)&&t.count>1){const k=t.bitmap||t.data.buffer;h=JSON.stringify(r?a:[a.slice(0,4),n]),l=this._cachedBitmapsMap.get(k),l||(l=new Map,this._cachedBitmapsMap.set(k,l));const O=l.get(h);if(O&&!r){const H=Math.round(Math.min(a[0],a[2])+a[4]),N=Math.round(Math.min(a[1],a[3])+a[5]);return{canvas:O,offsetX:H,offsetY:N}}c=O}c||(u=this.cachedCanvases.getCanvas("maskCanvas",s,i),Vh(u.context,t));let d=z.transform(a,[1/s,0,0,-1/i,0,0]);d=z.transform(d,[1,0,0,1,0,-i]);const[f,g,p,v]=z.getAxialAlignedBoundingBox([0,0,s,i],d),m=Math.round(p-f)||1,b=Math.round(v-g)||1,_=this.cachedCanvases.getCanvas("fillCanvas",m,b),w=_.context,C=f,T=g;w.translate(-C,-T),w.transform(...d),c||(c=this._scaleImage(u.canvas,ze(w)),c=c.img,l&&r&&l.set(h,c)),w.imageSmoothingEnabled=Gh(mt(w),t.interpolate),ir(w,c,0,0,c.width,c.height,0,0,s,i),w.globalCompositeOperation="source-in";const E=z.transform(ze(w),[1,0,0,1,-C,-T]);return w.fillStyle=r?n.getPattern(e,this,E,Xt.FILL):n,w.fillRect(0,0,s,i),l&&!r&&(this.cachedCanvases.delete("fillCanvas"),l.set(h,_.canvas)),{canvas:_.canvas,offsetX:Math.round(C),offsetY:Math.round(T)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=ug[t]}setLineJoin(t){this.ctx.lineJoin=dg[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,e){const s=this.ctx;s.setLineDash!==void 0&&(s.setLineDash(t),s.lineDashOffset=e)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[e,s]of t)switch(e){case"LW":this.setLineWidth(s);break;case"LC":this.setLineCap(s);break;case"LJ":this.setLineJoin(s);break;case"ML":this.setMiterLimit(s);break;case"D":this.setDash(s[0],s[1]);break;case"RI":this.setRenderingIntent(s);break;case"FL":this.setFlatness(s);break;case"Font":this.setFont(s[0],s[1]);break;case"CA":this.current.strokeAlpha=s;break;case"ca":this.current.fillAlpha=s,this.ctx.globalAlpha=s;break;case"BM":this.ctx.globalCompositeOperation=s;break;case"SMask":this.current.activeSMask=s?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(s);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,e=this.ctx.canvas.height,s="smaskGroupAt"+this.groupLevel,i=this.cachedCanvases.getCanvas(s,t,e);this.suspendedCtx=this.ctx,this.ctx=i.context;const n=this.ctx;n.setTransform(...mt(this.suspendedCtx)),ji(this.suspendedCtx,n),lg(n,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),ji(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const e=this.current.activeSMask,s=this.suspendedCtx;this.composeSMask(s,e,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,e,s,i){const n=i[0],r=i[1],a=i[2]-n,l=i[3]-r;a===0||l===0||(this.genericComposeSMask(e.context,s,a,l,e.subtype,e.backdrop,e.transferMap,n,r,e.offsetX,e.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(s.canvas,0,0),t.restore())}genericComposeSMask(t,e,s,i,n,r,a,l,h,c,u){let d=t.canvas,f=l-c,g=h-u;if(r){const v=z.makeHexColor(...r);if(f<0||g<0||f+s>d.width||g+i>d.height){const m=this.cachedCanvases.getCanvas("maskExtension",s,i),b=m.context;b.drawImage(d,-f,-g),b.globalCompositeOperation="destination-atop",b.fillStyle=v,b.fillRect(0,0,s,i),b.globalCompositeOperation="source-over",d=m.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const m=new Path2D;m.rect(f,g,s,i),t.clip(m),t.globalCompositeOperation="destination-atop",t.fillStyle=v,t.fillRect(f,g,s,i),t.restore()}}e.save(),e.globalAlpha=1,e.setTransform(1,0,0,1,0,0),n==="Alpha"&&a?e.filter=this.filterFactory.addAlphaFilter(a):n==="Luminosity"&&(e.filter=this.filterFactory.addLuminosityFilter(a));const p=new Path2D;p.rect(l,h,s,i),e.clip(p),e.globalCompositeOperation="destination-in",e.drawImage(d,f,g,s,i,l,h,s,i),e.restore()}save(){this.inSMaskMode?(ji(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),ji(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,e,s,i,n,r){this.ctx.transform(t,e,s,i,n,r),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,e,s){const i=this.ctx,n=this.current;let r=n.x,a=n.y,l,h;const c=mt(i),u=c[0]===0&&c[3]===0||c[1]===0&&c[2]===0,d=u?s.slice(0):null;for(let f=0,g=0,p=t.length;f<p;f++)switch(t[f]|0){case Me.rectangle:r=e[g++],a=e[g++];const v=e[g++],m=e[g++],b=r+v,_=a+m;i.moveTo(r,a),v===0||m===0?i.lineTo(b,_):(i.lineTo(b,a),i.lineTo(b,_),i.lineTo(r,_)),u||n.updateRectMinMax(c,[r,a,b,_]),i.closePath();break;case Me.moveTo:r=e[g++],a=e[g++],i.moveTo(r,a),u||n.updatePathMinMax(c,r,a);break;case Me.lineTo:r=e[g++],a=e[g++],i.lineTo(r,a),u||n.updatePathMinMax(c,r,a);break;case Me.curveTo:l=r,h=a,r=e[g+4],a=e[g+5],i.bezierCurveTo(e[g],e[g+1],e[g+2],e[g+3],r,a),n.updateCurvePathMinMax(c,l,h,e[g],e[g+1],e[g+2],e[g+3],r,a,d),g+=6;break;case Me.curveTo2:l=r,h=a,i.bezierCurveTo(r,a,e[g],e[g+1],e[g+2],e[g+3]),n.updateCurvePathMinMax(c,l,h,r,a,e[g],e[g+1],e[g+2],e[g+3],d),r=e[g+2],a=e[g+3],g+=4;break;case Me.curveTo3:l=r,h=a,r=e[g+2],a=e[g+3],i.bezierCurveTo(e[g],e[g+1],r,a,r,a),n.updateCurvePathMinMax(c,l,h,e[g],e[g+1],r,a,r,a,d),g+=4;break;case Me.closePath:i.closePath();break}u&&n.updateScalingPathMinMax(c,d),n.setCurrentPoint(r,a)}closePath(){this.ctx.closePath()}stroke(t=!0){const e=this.ctx,s=this.current.strokeColor;e.globalAlpha=this.current.strokeAlpha,this.contentVisible&&(typeof s=="object"&&s?.getPattern?(e.save(),e.strokeStyle=s.getPattern(e,this,ze(e),Xt.STROKE),this.rescaleAndStroke(!1),e.restore()):this.rescaleAndStroke(!0)),t&&this.consumePath(this.current.getClippedPathBoundingBox()),e.globalAlpha=this.current.fillAlpha}closeStroke(){this.closePath(),this.stroke()}fill(t=!0){const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;let n=!1;i&&(e.save(),e.fillStyle=s.getPattern(e,this,ze(e),Xt.FILL),n=!0);const r=this.current.getClippedPathBoundingBox();this.contentVisible&&r!==null&&(this.pendingEOFill?(e.fill("evenodd"),this.pendingEOFill=!1):e.fill()),n&&e.restore(),t&&this.consumePath(r)}eoFill(){this.pendingEOFill=!0,this.fill()}fillStroke(){this.fill(!1),this.stroke(!1),this.consumePath()}eoFillStroke(){this.pendingEOFill=!0,this.fillStroke()}closeFillStroke(){this.closePath(),this.fillStroke()}closeEOFillStroke(){this.pendingEOFill=!0,this.closePath(),this.fillStroke()}endPath(){this.consumePath()}clip(){this.pendingClip=fg}eoClip(){this.pendingClip=Wh}beginText(){this.current.textMatrix=bh,this.current.textMatrixScale=1,this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}endText(){const t=this.pendingTextPaths,e=this.ctx;if(t===void 0){e.beginPath();return}const s=new Path2D,i=e.getTransform().invertSelf();for(const{transform:n,x:r,y:a,fontSize:l,path:h}of t)s.addPath(h,new DOMMatrix(n).preMultiplySelf(i).translate(r,a).scale(l,-l));e.clip(s),e.beginPath(),delete this.pendingTextPaths}setCharSpacing(t){this.current.charSpacing=t}setWordSpacing(t){this.current.wordSpacing=t}setHScale(t){this.current.textHScale=t/100}setLeading(t){this.current.leading=-t}setFont(t,e){const s=this.commonObjs.get(t),i=this.current;if(!s)throw new Error(`Can't find font for ${t}`);if(i.fontMatrix=s.fontMatrix||ba,(i.fontMatrix[0]===0||i.fontMatrix[3]===0)&&Q("Invalid font matrix for font "+t),e<0?(e=-e,i.fontDirection=-1):i.fontDirection=1,this.current.font=s,this.current.fontSize=e,s.isType3Font)return;const n=s.loadedName||"sans-serif",r=s.systemFontInfo?.css||`"${n}", ${s.fallbackName}`;let a="normal";s.black?a="900":s.bold&&(a="bold");const l=s.italic?"italic":"normal";let h=e;e<Ih?h=Ih:e>jh&&(h=jh),this.current.fontSizeScale=e/h,this.ctx.font=`${l} ${a} ${h}px ${r}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,e){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=e}setLeadingMoveText(t,e){this.setLeading(-e),this.moveText(t,e)}setTextMatrix(t,e,s,i,n,r){this.current.textMatrix=[t,e,s,i,n,r],this.current.textMatrixScale=Math.hypot(t,e),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}#s(t,e,s){const i=new Path2D;return i.addPath(t,new DOMMatrix(s).invertSelf().multiplySelf(e)),i}paintChar(t,e,s,i,n){const r=this.ctx,a=this.current,l=a.font,h=a.textRenderingMode,c=a.fontSize/a.fontSizeScale,u=h&Wt.FILL_STROKE_MASK,d=!!(h&Wt.ADD_TO_PATH_FLAG),f=a.patternFill&&!l.missingFile,g=a.patternStroke&&!l.missingFile;let p;if((l.disableFontFace||d||f||g)&&(p=l.getPathGenerator(this.commonObjs,t)),l.disableFontFace||f||g){if(r.save(),r.translate(e,s),r.scale(c,-c),u===Wt.FILL||u===Wt.FILL_STROKE)if(i){const v=r.getTransform();r.setTransform(...i),r.fill(this.#s(p,v,i))}else r.fill(p);if(u===Wt.STROKE||u===Wt.FILL_STROKE)if(n){const v=r.getTransform();r.setTransform(...n),r.stroke(this.#s(p,v,n))}else r.lineWidth/=c,r.stroke(p);r.restore()}else(u===Wt.FILL||u===Wt.FILL_STROKE)&&r.fillText(t,e,s),(u===Wt.STROKE||u===Wt.FILL_STROKE)&&r.strokeText(t,e,s);d&&(this.pendingTextPaths||=[]).push({transform:mt(r),x:e,y:s,fontSize:c,path:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const e=t.getImageData(0,0,10,10).data;let s=!1;for(let i=3;i<e.length;i+=4)if(e[i]>0&&e[i]<255){s=!0;break}return tt(this,"isFontSubpixelAAEnabled",s)}showText(t){const e=this.current,s=e.font;if(s.isType3Font)return this.showType3Text(t);const i=e.fontSize;if(i===0)return;const n=this.ctx,r=e.fontSizeScale,a=e.charSpacing,l=e.wordSpacing,h=e.fontDirection,c=e.textHScale*h,u=t.length,d=s.vertical,f=d?1:-1,g=s.defaultVMetrics,p=i*e.fontMatrix[0],v=e.textRenderingMode===Wt.FILL&&!s.disableFontFace&&!e.patternFill;n.save(),n.transform(...e.textMatrix),n.translate(e.x,e.y+e.textRise),h>0?n.scale(c,-1):n.scale(c,1);let m,b;if(e.patternFill){n.save();const E=e.fillColor.getPattern(n,this,ze(n),Xt.FILL);m=mt(n),n.restore(),n.fillStyle=E}if(e.patternStroke){n.save();const E=e.strokeColor.getPattern(n,this,ze(n),Xt.STROKE);b=mt(n),n.restore(),n.strokeStyle=E}let _=e.lineWidth;const w=e.textMatrixScale;if(w===0||_===0){const E=e.textRenderingMode&Wt.FILL_STROKE_MASK;(E===Wt.STROKE||E===Wt.FILL_STROKE)&&(_=this.getSinglePixelWidth())}else _/=w;if(r!==1&&(n.scale(r,r),_/=r),n.lineWidth=_,s.isInvalidPDFjsFont){const E=[];let k=0;for(const O of t)E.push(O.unicode),k+=O.width;n.fillText(E.join(""),0,0),e.x+=k*p*c,n.restore(),this.compose();return}let C=0,T;for(T=0;T<u;++T){const E=t[T];if(typeof E=="number"){C+=f*E*i/1e3;continue}let k=!1;const O=(E.isSpace?l:0)+a,H=E.fontChar,N=E.accent;let P,R,F=E.width;if(d){const M=E.vmetric||g,L=-(E.vmetric?M[1]:F*.5)*p,Y=M[2]*p;F=M?-M[0]:F,P=L/r,R=(C+Y)/r}else P=C/r,R=0;if(s.remeasure&&F>0){const M=n.measureText(H).width*1e3/i*r;if(F<M&&this.isFontSubpixelAAEnabled){const L=F/M;k=!0,n.save(),n.scale(L,1),P/=L}else F!==M&&(P+=(F-M)/2e3*i/r)}if(this.contentVisible&&(E.isInFont||s.missingFile)){if(v&&!N)n.fillText(H,P,R);else if(this.paintChar(H,P,R,m,b),N){const M=P+i*N.offset.x/r,L=R-i*N.offset.y/r;this.paintChar(N.fontChar,M,L,m,b)}}const V=d?F*p-O*h:F*p+O*h;C+=V,k&&n.restore()}d?e.y-=C:e.x+=C*c,n.restore(),this.compose()}showType3Text(t){const e=this.ctx,s=this.current,i=s.font,n=s.fontSize,r=s.fontDirection,a=i.vertical?1:-1,l=s.charSpacing,h=s.wordSpacing,c=s.textHScale*r,u=s.fontMatrix||ba,d=t.length,f=s.textRenderingMode===Wt.INVISIBLE;let g,p,v,m;if(!(f||n===0)){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,e.save(),e.transform(...s.textMatrix),e.translate(s.x,s.y),e.scale(c,r),g=0;g<d;++g){if(p=t[g],typeof p=="number"){m=a*p*n/1e3,this.ctx.translate(m,0),s.x+=m*c;continue}const b=(p.isSpace?h:0)+l,_=i.charProcOperatorList[p.operatorListId];if(!_){Q(`Type3 character "${p.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=p,this.save(),e.scale(n,n),e.transform(...u),this.executeOperatorList(_),this.restore()),v=z.applyTransform([p.width,0],u)[0]*n+b,e.translate(v,0),s.x+=v*c}e.restore(),this.processingType3=null}}setCharWidth(t,e){}setCharWidthAndBounds(t,e,s,i,n,r){this.ctx.rect(s,i,n-s,r-i),this.ctx.clip(),this.endPath()}getColorN_Pattern(t){let e;if(t[0]==="TilingPattern"){const s=t[1],i=this.baseTransform||mt(this.ctx),n={createCanvasGraphics:r=>new ei(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};e=new ja(t,s,this.ctx,n,i)}else e=this._getPattern(t[1],t[2]);return e}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments),this.current.patternStroke=!0}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,e,s){this.ctx.strokeStyle=this.current.strokeColor=z.makeHexColor(t,e,s),this.current.patternStroke=!1}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent",this.current.patternStroke=!1}setFillRGBColor(t,e,s){this.ctx.fillStyle=this.current.fillColor=z.makeHexColor(t,e,s),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,e=null){let s;return this.cachedPatterns.has(t)?s=this.cachedPatterns.get(t):(s=rg(this.getObject(t)),this.cachedPatterns.set(t,s)),e&&(s.matrix=e),s}shadingFill(t){if(!this.contentVisible)return;const e=this.ctx;this.save();const s=this._getPattern(t);e.fillStyle=s.getPattern(e,this,ze(e),Xt.SHADING);const i=ze(e);if(i){const{width:n,height:r}=e.canvas,[a,l,h,c]=z.getAxialAlignedBoundingBox([0,0,n,r],i);this.ctx.fillRect(a,l,h-a,c-l)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){ut("Should not call beginInlineImage")}beginImageData(){ut("Should not call beginImageData")}paintFormXObjectBegin(t,e){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=mt(this.ctx),e)){const s=e[2]-e[0],i=e[3]-e[1];this.ctx.rect(e[0],e[1],s,i),this.current.updateRectMinMax(mt(this.ctx),e),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const e=this.ctx;t.isolated||qn("TODO: Support non-isolated groups."),t.knockout&&Q("Knockout groups not supported.");const s=mt(e);if(t.matrix&&e.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let i=z.getAxialAlignedBoundingBox(t.bbox,mt(e));const n=[0,0,e.canvas.width,e.canvas.height];i=z.intersect(i,n)||[0,0,0,0];const r=Math.floor(i[0]),a=Math.floor(i[1]),l=Math.max(Math.ceil(i[2])-r,1),h=Math.max(Math.ceil(i[3])-a,1);this.current.startNewPathAndClipBox([0,0,l,h]);let c="groupAt"+this.groupLevel;t.smask&&(c+="_smask_"+this.smaskCounter++%2);const u=this.cachedCanvases.getCanvas(c,l,h),d=u.context;d.translate(-r,-a),d.transform(...s),t.smask?this.smaskStack.push({canvas:u.canvas,context:d,offsetX:r,offsetY:a,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(e.setTransform(1,0,0,1,0,0),e.translate(r,a),e.save()),ji(e,d),this.ctx=d,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(e),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const e=this.ctx,s=this.groupStack.pop();if(this.ctx=s,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const i=mt(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...i);const n=z.getAxialAlignedBoundingBox([0,0,e.canvas.width,e.canvas.height],i);this.ctx.drawImage(e.canvas,0,0),this.ctx.restore(),this.compose(n)}}beginAnnotation(t,e,s,i,n){if(this.#t(),nr(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),e){const r=e[2]-e[0],a=e[3]-e[1];if(n&&this.annotationCanvasMap){s=s.slice(),s[4]-=e[0],s[5]-=e[1],e=e.slice(),e[0]=e[1]=0,e[2]=r,e[3]=a;const[l,h]=z.singularValueDecompose2dScale(mt(this.ctx)),{viewportScale:c}=this,u=Math.ceil(r*this.outputScaleX*c),d=Math.ceil(a*this.outputScaleY*c);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(l,0,0,-h,0,a*h),nr(this.ctx)}else nr(this.ctx),this.endPath(),this.ctx.rect(e[0],e[1],r,a),this.ctx.clip(),this.ctx.beginPath()}this.current=new Hh(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...s),this.transform(...i)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),this.#e(),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const e=t.count;t=this.getObject(t.data,t),t.count=e;const s=this.ctx,i=this.processingType3;if(i&&(i.compiled===void 0&&(i.compiled=cg(t)),i.compiled)){i.compiled(s);return}const n=this._createMaskCanvas(t),r=n.canvas;s.save(),s.setTransform(1,0,0,1,0,0),s.drawImage(r,n.offsetX,n.offsetY),s.restore(),this.compose()}paintImageMaskXObjectRepeat(t,e,s=0,i=0,n,r){if(!this.contentVisible)return;t=this.getObject(t.data,t);const a=this.ctx;a.save();const l=mt(a);a.transform(e,s,i,n,0,0);const h=this._createMaskCanvas(t);a.setTransform(1,0,0,1,h.offsetX-l[4],h.offsetY-l[5]);for(let c=0,u=r.length;c<u;c+=2){const d=z.transform(l,[e,s,i,n,r[c],r[c+1]]),[f,g]=z.applyTransform([0,0],d);a.drawImage(h.canvas,f,g)}a.restore(),this.compose()}paintImageMaskXObjectGroup(t){if(!this.contentVisible)return;const e=this.ctx,s=this.current.fillColor,i=this.current.patternFill;for(const n of t){const{data:r,width:a,height:l,transform:h}=n,c=this.cachedCanvases.getCanvas("maskCanvas",a,l),u=c.context;u.save();const d=this.getObject(r,n);Vh(u,d),u.globalCompositeOperation="source-in",u.fillStyle=i?s.getPattern(u,this,ze(e),Xt.FILL):s,u.fillRect(0,0,a,l),u.restore(),e.save(),e.transform(...h),e.scale(1,-1),ir(e,c.canvas,0,0,a,l,0,-1,1,1),e.restore()}this.compose()}paintImageXObject(t){if(!this.contentVisible)return;const e=this.getObject(t);if(!e){Q("Dependent image isn't ready yet");return}this.paintInlineImageXObject(e)}paintImageXObjectRepeat(t,e,s,i){if(!this.contentVisible)return;const n=this.getObject(t);if(!n){Q("Dependent image isn't ready yet");return}const r=n.width,a=n.height,l=[];for(let h=0,c=i.length;h<c;h+=2)l.push({transform:[e,0,0,s,i[h],i[h+1]],x:0,y:0,w:r,h:a});this.paintInlineImageXObjectGroup(n,l)}applyTransferMapsToCanvas(t){return this.current.transferMaps!=="none"&&(t.filter=this.current.transferMaps,t.drawImage(t.canvas,0,0),t.filter="none"),t.canvas}applyTransferMapsToBitmap(t){if(this.current.transferMaps==="none")return t.bitmap;const{bitmap:e,width:s,height:i}=t,n=this.cachedCanvases.getCanvas("inlineImage",s,i),r=n.context;return r.filter=this.current.transferMaps,r.drawImage(e,0,0),r.filter="none",n.canvas}paintInlineImageXObject(t){if(!this.contentVisible)return;const e=t.width,s=t.height,i=this.ctx;if(this.save(),!Gt){const{filter:a}=i;a!=="none"&&a!==""&&(i.filter="none")}i.scale(1/e,-1/s);let n;if(t.bitmap)n=this.applyTransferMapsToBitmap(t);else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)n=t;else{const l=this.cachedCanvases.getCanvas("inlineImage",e,s).context;zh(l,t),n=this.applyTransferMapsToCanvas(l)}const r=this._scaleImage(n,ze(i));i.imageSmoothingEnabled=Gh(mt(i),t.interpolate),ir(i,r.img,0,0,r.paintWidth,r.paintHeight,0,-s,e,s),this.compose(),this.restore()}paintInlineImageXObjectGroup(t,e){if(!this.contentVisible)return;const s=this.ctx;let i;if(t.bitmap)i=t.bitmap;else{const n=t.width,r=t.height,l=this.cachedCanvases.getCanvas("inlineImage",n,r).context;zh(l,t),i=this.applyTransferMapsToCanvas(l)}for(const n of e)s.save(),s.transform(...n.transform),s.scale(1,-1),ir(s,i,n.x,n.y,n.w,n.h,0,-1,1,1),s.restore();this.compose()}paintSolidColorImageMask(){this.contentVisible&&(this.ctx.fillRect(0,0,1,1),this.compose())}markPoint(t){}markPointProps(t,e){}beginMarkedContent(t){this.markedContentStack.push({visible:!0})}beginMarkedContentProps(t,e){t==="OC"?this.markedContentStack.push({visible:this.optionalContentConfig.isVisible(e)}):this.markedContentStack.push({visible:!0}),this.contentVisible=this.isContentVisible()}endMarkedContent(){this.markedContentStack.pop(),this.contentVisible=this.isContentVisible()}beginCompat(){}endCompat(){}consumePath(t){const e=this.current.isEmptyClip();this.pendingClip&&this.current.updateClipFromPath(),this.pendingClip||this.compose(t);const s=this.ctx;this.pendingClip&&(e||(this.pendingClip===Wh?s.clip("evenodd"):s.clip()),this.pendingClip=null),this.current.startNewPathAndClipBox(this.current.clipBox),s.beginPath()}getSinglePixelWidth(){if(!this._cachedGetSinglePixelWidth){const t=mt(this.ctx);if(t[1]===0&&t[2]===0)this._cachedGetSinglePixelWidth=1/Math.min(Math.abs(t[0]),Math.abs(t[3]));else{const e=Math.abs(t[0]*t[3]-t[2]*t[1]),s=Math.hypot(t[0],t[2]),i=Math.hypot(t[1],t[3]);this._cachedGetSinglePixelWidth=Math.max(s,i)/e}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){const{lineWidth:t}=this.current,{a:e,b:s,c:i,d:n}=this.ctx.getTransform();let r,a;if(s===0&&i===0){const l=Math.abs(e),h=Math.abs(n);if(l===h)if(t===0)r=a=1/l;else{const c=l*t;r=a=c<1?1/c:1}else if(t===0)r=1/l,a=1/h;else{const c=l*t,u=h*t;r=c<1?1/c:1,a=u<1?1/u:1}}else{const l=Math.abs(e*n-s*i),h=Math.hypot(e,s),c=Math.hypot(i,n);if(t===0)r=c/l,a=h/l;else{const u=t*l;r=c>u?c/u:1,a=h>u?h/u:1}}this._cachedScaleForStroking[0]=r,this._cachedScaleForStroking[1]=a}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:e}=this,{lineWidth:s}=this.current,[i,n]=this.getScaleForStroking();if(e.lineWidth=s||1,i===1&&n===1){e.stroke();return}const r=e.getLineDash();if(t&&e.save(),e.scale(i,n),r.length>0){const a=Math.max(i,n);e.setLineDash(r.map(l=>l/a)),e.lineDashOffset/=a}e.stroke(),t&&e.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}}for(const o in Me)ei.prototype[o]!==void 0&&(ei.prototype[Me[o]]=ei.prototype[o]);class Ni{static#t=null;static#e="";static get workerPort(){return this.#t}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");this.#t=t}static get workerSrc(){return this.#e}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");this.#e=t}}class gg{#t;#e;constructor({parsedData:t,rawData:e}){this.#t=t,this.#e=e}getRaw(){return this.#e}get(t){return this.#t.get(t)??null}getAll(){return xa(this.#t)}has(t){return this.#t.has(t)}}const si=Symbol("INTERNAL");class pg{#t=!1;#e=!1;#s=!1;#i=!0;constructor(t,{name:e,intent:s,usage:i,rbGroups:n}){this.#t=!!(t&fe.DISPLAY),this.#e=!!(t&fe.PRINT),this.name=e,this.intent=s,this.usage=i,this.rbGroups=n}get visible(){if(this.#s)return this.#i;if(!this.#i)return!1;const{print:t,view:e}=this.usage;return this.#t?e?.viewState!=="OFF":this.#e?t?.printState!=="OFF":!0}_setVisible(t,e,s=!1){t!==si&&ut("Internal method `_setVisible` called."),this.#s=s,this.#i=e}}class mg{#t=null;#e=new Map;#s=null;#i=null;constructor(t,e=fe.DISPLAY){if(this.renderingIntent=e,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,this.#i=t.order;for(const s of t.groups)this.#e.set(s.id,new pg(e,s));if(t.baseState==="OFF")for(const s of this.#e.values())s._setVisible(si,!1);for(const s of t.on)this.#e.get(s)._setVisible(si,!0);for(const s of t.off)this.#e.get(s)._setVisible(si,!1);this.#s=this.getHash()}}#r(t){const e=t.length;if(e<2)return!0;const s=t[0];for(let i=1;i<e;i++){const n=t[i];let r;if(Array.isArray(n))r=this.#r(n);else if(this.#e.has(n))r=this.#e.get(n).visible;else return Q(`Optional content group not found: ${n}`),!0;switch(s){case"And":if(!r)return!1;break;case"Or":if(r)return!0;break;case"Not":return!r;default:return!0}}return s==="And"}isVisible(t){if(this.#e.size===0)return!0;if(!t)return qn("Optional content group not defined."),!0;if(t.type==="OCG")return this.#e.has(t.id)?this.#e.get(t.id).visible:(Q(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return this.#r(t.expression);if(!t.policy||t.policy==="AnyOn"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(!this.#e.get(e).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const e of t.ids){if(!this.#e.has(e))return Q(`Optional content group not found: ${e}`),!0;if(this.#e.get(e).visible)return!1}return!0}return Q(`Unknown optional content policy ${t.policy}.`),!0}return Q(`Unknown group type ${t.type}.`),!0}setVisibility(t,e=!0,s=!0){const i=this.#e.get(t);if(!i){Q(`Optional content group not found: ${t}`);return}if(s&&e&&i.rbGroups.length)for(const n of i.rbGroups)for(const r of n)r!==t&&this.#e.get(r)?._setVisible(si,!1,!0);i._setVisible(si,!!e,!0),this.#t=null}setOCGState({state:t,preserveRB:e}){let s;for(const i of t){switch(i){case"ON":case"OFF":case"Toggle":s=i;continue}const n=this.#e.get(i);if(n)switch(s){case"ON":this.setVisibility(i,!0,e);break;case"OFF":this.setVisibility(i,!1,e);break;case"Toggle":this.setVisibility(i,!n.visible,e);break}}this.#t=null}get hasInitialVisibility(){return this.#s===null||this.getHash()===this.#s}getOrder(){return this.#e.size?this.#i?this.#i.slice():[...this.#e.keys()]:null}getGroups(){return this.#e.size>0?xa(this.#e):null}getGroup(t){return this.#e.get(t)||null}getHash(){if(this.#t!==null)return this.#t;const t=new Ah;for(const[e,s]of this.#e)t.update(`${e}:${s.visible}`);return this.#t=t.hexdigest()}}class vg{constructor(t,{disableRange:e=!1,disableStream:s=!1}){Mt(t,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');const{length:i,initialData:n,progressiveDone:r,contentDispositionFilename:a}=t;if(this._queuedChunks=[],this._progressiveDone=r,this._contentDispositionFilename=a,n?.length>0){const l=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;this._queuedChunks.push(l)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!s,this._isRangeSupported=!e,this._contentLength=i,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((l,h)=>{this._onReceiveData({begin:l,chunk:h})}),t.addProgressListener((l,h)=>{this._onProgress({loaded:l,total:h})}),t.addProgressiveReadListener(l=>{this._onReceiveData({chunk:l})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:e}){const s=e instanceof Uint8Array&&e.byteLength===e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(s):this._queuedChunks.push(s);else{const i=this._rangeReaders.some(function(n){return n._begin!==t?!1:(n._enqueue(s),!0)});Mt(i,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}_onProgress(t){t.total===void 0?this._rangeReaders[0]?.onProgress?.({loaded:t.loaded}):this._fullRequestReader?.onProgress?.({loaded:t.loaded,total:t.total})}_onProgressiveDone(){this._fullRequestReader?.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const e=this._rangeReaders.indexOf(t);e>=0&&this._rangeReaders.splice(e,1)}getFullReader(){Mt(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new bg(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new yg(this,t,e);return this._pdfDataRangeTransport.requestDataRange(t,e),this._rangeReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeReaders.slice(0))e.cancel(t);this._pdfDataRangeTransport.abort()}}class bg{constructor(t,e,s=!1,i=null){this._stream=t,this._done=s||!1,this._filename=Ea(i)?i:null,this._queuedChunks=e||[],this._loaded=0;for(const n of this._queuedChunks)this._loaded+=n.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class yg{constructor(t,e,s){this._stream=t,this._begin=e,this._end=s,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function _g(o){let t=!0,e=s("filename\\*","i").exec(o);if(e){e=e[1];let c=a(e);return c=unescape(c),c=l(c),c=h(c),n(c)}if(e=r(o),e){const c=h(e);return n(c)}if(e=s("filename","i").exec(o),e){e=e[1];let c=a(e);return c=h(c),n(c)}function s(c,u){return new RegExp("(?:^|;)\\s*"+c+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',u)}function i(c,u){if(c){if(!/^[\x00-\xFF]+$/.test(u))return u;try{const d=new TextDecoder(c,{fatal:!0}),f=Jn(u);u=d.decode(f),t=!1}catch{}}return u}function n(c){return t&&/[\x80-\xff]/.test(c)&&(c=i("utf-8",c),t&&(c=i("iso-8859-1",c))),c}function r(c){const u=[];let d;const f=s("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(d=f.exec(c))!==null;){let[,p,v,m]=d;if(p=parseInt(p,10),p in u){if(p===0)break;continue}u[p]=[v,m]}const g=[];for(let p=0;p<u.length&&p in u;++p){let[v,m]=u[p];m=a(m),v&&(m=unescape(m),p===0&&(m=l(m))),g.push(m)}return g.join("")}function a(c){if(c.startsWith('"')){const u=c.slice(1).split('\\"');for(let d=0;d<u.length;++d){const f=u[d].indexOf('"');f!==-1&&(u[d]=u[d].slice(0,f),u.length=d+1),u[d]=u[d].replaceAll(/\\(.)/g,"$1")}c=u.join('"')}return c}function l(c){const u=c.indexOf("'");if(u===-1)return c;const d=c.slice(0,u),g=c.slice(u+1).replace(/^[^']*'/,"");return i(d,g)}function h(c){return!c.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(c)?c:c.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,function(u,d,f,g){if(f==="q"||f==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-fA-F]{2})/g,function(p,v){return String.fromCharCode(parseInt(v,16))}),i(d,g);try{g=atob(g)}catch{}return i(d,g)})}return""}function Xh(o,t){const e=new Headers;if(!o||!t||typeof t!="object")return e;for(const s in t){const i=t[s];i!==void 0&&e.append(s,i)}return e}function rr(o){try{return new URL(o).origin}catch{}return null}function Uh({responseHeaders:o,isHttp:t,rangeChunkSize:e,disableRange:s}){const i={allowRangeRequests:!1,suggestedLength:void 0},n=parseInt(o.get("Content-Length"),10);return!Number.isInteger(n)||(i.suggestedLength=n,n<=2*e)||s||!t||o.get("Accept-Ranges")!=="bytes"||(o.get("Content-Encoding")||"identity")!=="identity"||(i.allowRangeRequests=!0),i}function Yh(o){const t=o.get("Content-Disposition");if(t){let e=_g(t);if(e.includes("%"))try{e=decodeURIComponent(e)}catch{}if(Ea(e))return e}return null}function ar(o,t){return o===404||o===0&&t.startsWith("file:")?new Oi('Missing PDF "'+t+'".'):new Kn(`Unexpected server response (${o}) while retrieving PDF "${t}".`,o)}function $h(o){return o===200||o===206}function qh(o,t,e){return{method:"GET",headers:o,signal:e.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"}}function Kh(o){return o instanceof Uint8Array?o.buffer:o instanceof ArrayBuffer?o:(Q(`getArrayBuffer - unexpected data format: ${o}`),new Uint8Array(o).buffer)}class Jh{_responseOrigin=null;constructor(t){this.source=t,this.isHttp=/^https?:/i.test(t.url),this.headers=Xh(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return Mt(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new wg(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new xg(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class wg{constructor(t){this._stream=t,this._reader=null,this._loaded=0,this._filename=null;const e=t.source;this._withCredentials=e.withCredentials||!1,this._contentLength=e.length,this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._abortController=new AbortController,this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange;const s=new Headers(t.headers),i=e.url;fetch(i,qh(s,this._withCredentials,this._abortController)).then(n=>{if(t._responseOrigin=rr(n.url),!$h(n.status))throw ar(n.status,i);this._reader=n.body.getReader(),this._headersCapability.resolve();const r=n.headers,{allowRangeRequests:a,suggestedLength:l}=Uh({responseHeaders:r,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=a,this._contentLength=l||this._contentLength,this._filename=Yh(r),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new cs("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:Kh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}class xg{constructor(t,e,s){this._stream=t,this._reader=null,this._loaded=0;const i=t.source;this._withCredentials=i.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!i.disableStream,this._abortController=new AbortController;const n=new Headers(t.headers);n.append("Range",`bytes=${e}-${s-1}`);const r=i.url;fetch(r,qh(n,this._withCredentials,this._abortController)).then(a=>{const l=rr(a.url);if(l!==t._responseOrigin)throw new Error(`Expected range response-origin "${l}" to match "${t._responseOrigin}".`);if(!$h(a.status))throw ar(a.status,r);this._readCapability.resolve(),this._reader=a.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._readCapability.promise;const{value:t,done:e}=await this._reader.read();return e?{value:t,done:e}:(this._loaded+=t.byteLength,this.onProgress?.({loaded:this._loaded}),{value:Kh(t),done:!1})}cancel(t){this._reader?.cancel(t),this._abortController.abort()}}const Na=200,Ba=206;function Sg(o){const t=o.response;return typeof t!="string"?t:Jn(t).buffer}class Cg{_responseOrigin=null;constructor({url:t,httpHeaders:e,withCredentials:s}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Xh(this.isHttp,e),this.withCredentials=s||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}request(t){const e=new XMLHttpRequest,s=this.currXhrId++,i=this.pendingRequests[s]={xhr:e};e.open("GET",this.url),e.withCredentials=this.withCredentials;for(const[n,r]of this.headers)e.setRequestHeader(n,r);return this.isHttp&&"begin"in t&&"end"in t?(e.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),i.expectedStatus=Ba):i.expectedStatus=Na,e.responseType="arraybuffer",Mt(t.onError,"Expected `onError` callback to be provided."),e.onerror=()=>{t.onError(e.status)},e.onreadystatechange=this.onStateChange.bind(this,s),e.onprogress=this.onProgress.bind(this,s),i.onHeadersReceived=t.onHeadersReceived,i.onDone=t.onDone,i.onError=t.onError,i.onProgress=t.onProgress,e.send(null),s}onProgress(t,e){const s=this.pendingRequests[t];s&&s.onProgress?.(e)}onStateChange(t,e){const s=this.pendingRequests[t];if(!s)return;const i=s.xhr;if(i.readyState>=2&&s.onHeadersReceived&&(s.onHeadersReceived(),delete s.onHeadersReceived),i.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],i.status===0&&this.isHttp){s.onError(i.status);return}const n=i.status||Na;if(!(n===Na&&s.expectedStatus===Ba)&&n!==s.expectedStatus){s.onError(i.status);return}const a=Sg(i);if(n===Ba){const l=i.getResponseHeader("Content-Range"),h=/bytes (\d+)-(\d+)\/(\d+)/.exec(l);h?s.onDone({begin:parseInt(h[1],10),chunk:a}):(Q('Missing or invalid "Content-Range" header.'),s.onError(0))}else a?s.onDone({begin:0,chunk:a}):s.onError(i.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const e=this.pendingRequests[t].xhr;delete this.pendingRequests[t],e.abort()}}class Ag{constructor(t){this._source=t,this._manager=new Cg(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const e=this._rangeRequestReaders.indexOf(t);e>=0&&this._rangeRequestReaders.splice(e,1)}getFullReader(){return Mt(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new Tg(this._manager,this._source),this._fullRequestReader}getRangeReader(t,e){const s=new Eg(this._manager,t,e);return s.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Tg{constructor(t,e){this._manager=t,this._url=e.url,this._fullRequestId=t.request({onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._headersCapability=Promise.withResolvers(),this._disableRange=e.disableRange||!1,this._contentLength=e.length,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,e=this._manager.getRequestXhr(t);this._manager._responseOrigin=rr(e.responseURL);const s=e.getAllResponseHeaders(),i=new Headers(s?s.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(a=>{const[l,...h]=a.split(": ");return[l,h.join(": ")]}):[]),{allowRangeRequests:n,suggestedLength:r}=Uh({responseHeaders:i,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});n&&(this._isRangeSupported=!0),this._contentLength=r||this._contentLength,this._filename=Yh(i),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=ar(t,this._url),this._headersCapability.reject(this._storedError);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){this.onProgress?.({loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(await this._headersCapability.promise,this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class Eg{constructor(t,e,s){this._manager=t,this._url=t.url,this._requestId=t.request({begin:e,end:s,onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)}),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_onHeadersReceived(){const t=rr(this._manager.getRequestXhr(this._requestId)?.responseURL);t!==this._manager._responseOrigin&&(this._storedError=new Error(`Expected range response-origin "${t}" to match "${this._manager._responseOrigin}".`),this._onError(0))}_close(){this.onClosed?.(this)}_onDone(t){const e=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:e,done:!1}):this._queuedChunk=e,this._done=!0;for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError??=ar(t,this._url);for(const e of this._requests)e.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){this.isStreamingSupported||this.onProgress?.({loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const e=this._queuedChunk;return this._queuedChunk=null,{value:e,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const e of this._requests)e.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const kg=/^[a-z][a-z0-9\-+.]+:/i;function Pg(o){if(kg.test(o))return new URL(o);const t=process.getBuiltinModule("url");return new URL(t.pathToFileURL(o))}class Mg{constructor(t){this.source=t,this.url=Pg(t.url),Mt(this.url.protocol==="file:","PDFNodeStream only supports file:// URLs."),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return Mt(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=new Og(this),this._fullRequestReader}getRangeReader(t,e){if(e<=this._progressiveDataLength)return null;const s=new Dg(this,t,e);return this._rangeRequestReaders.push(s),s}cancelAllRequests(t){this._fullRequestReader?.cancel(t);for(const e of this._rangeRequestReaders.slice(0))e.cancel(t)}}class Og{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const e=t.source;this._contentLength=e.length,this._loaded=0,this._filename=null,this._disableRange=e.disableRange||!1,this._rangeChunkSize=e.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!e.disableStream,this._isRangeSupported=!e.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers();const s=process.getBuiltinModule("fs");s.promises.lstat(this._url).then(i=>{this._contentLength=i.size,this._setReadableStream(s.createReadStream(this._url)),this._headersCapability.resolve()},i=>{i.code==="ENOENT"&&(i=new Oi(`Missing PDF "${this._url}".`)),this._storedError=i,this._headersCapability.reject(i)})}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new cs("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class Dg{constructor(t,e,s){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const i=t.source;this._isStreamingSupported=!i.disableStream;const n=process.getBuiltinModule("fs");this._setReadableStream(n.createReadStream(this._url,{start:e,end:s-1}))}get isStreamingSupported(){return this._isStreamingSupported}async read(){if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",e=>{this._error(e)}),this._storedError&&this._readableStream.destroy(this._storedError)}}const Rg=1e5,oe=30,Fg=.8;class Zt{#t=Promise.withResolvers();#e=null;#s=!1;#i=!!globalThis.FontInspector?.enabled;#r=null;#n=null;#l=0;#o=0;#c=null;#h=null;#d=0;#u=0;#f=Object.create(null);#a=[];#g=null;#m=[];#p=new WeakMap;#v=null;static#_=new Map;static#b=new Map;static#w=new WeakMap;static#S=null;static#A=new Set;constructor({textContentSource:t,container:e,viewport:s}){if(t instanceof ReadableStream)this.#g=t;else if(typeof t=="object")this.#g=new ReadableStream({start(l){l.enqueue(t),l.close()}});else throw new Error('No "textContentSource" parameter specified.');this.#e=this.#h=e,this.#u=s.scale*(globalThis.devicePixelRatio||1),this.#d=s.rotation,this.#n={div:null,properties:null,ctx:null};const{pageWidth:i,pageHeight:n,pageX:r,pageY:a}=s.rawDims;this.#v=[1,0,0,-1,-r,a+n],this.#o=i,this.#l=n,Zt.#O(),Ms(e,s),this.#t.promise.finally(()=>{Zt.#A.delete(this),this.#n=null,this.#f=null}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:e}=Qt.platform;return tt(this,"fontFamilyMap",new Map([["sans-serif",`${t&&e?"Calibri, ":""}sans-serif`],["monospace",`${t&&e?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{this.#c.read().then(({value:e,done:s})=>{if(s){this.#t.resolve();return}this.#r??=e.lang,Object.assign(this.#f,e.styles),this.#E(e.items),t()},this.#t.reject)};return this.#c=this.#g.getReader(),Zt.#A.add(this),t(),this.#t.promise}update({viewport:t,onBefore:e=null}){const s=t.scale*(globalThis.devicePixelRatio||1),i=t.rotation;if(i!==this.#d&&(e?.(),this.#d=i,Ms(this.#h,{rotation:i})),s!==this.#u){e?.(),this.#u=s;const n={div:null,properties:null,ctx:Zt.#k(this.#r)};for(const r of this.#m)n.properties=this.#p.get(r),n.div=r,this.#x(n)}}cancel(){const t=new cs("TextLayer task cancelled.");this.#c?.cancel(t).catch(()=>{}),this.#c=null,this.#t.reject(t)}get textDivs(){return this.#m}get textContentItemsStr(){return this.#a}#E(t){if(this.#s)return;this.#n.ctx??=Zt.#k(this.#r);const e=this.#m,s=this.#a;for(const i of t){if(e.length>Rg){Q("Ignoring additional textDivs for performance reasons."),this.#s=!0;return}if(i.str===void 0){if(i.type==="beginMarkedContentProps"||i.type==="beginMarkedContent"){const n=this.#e;this.#e=document.createElement("span"),this.#e.classList.add("markedContent"),i.id!==null&&this.#e.setAttribute("id",`${i.id}`),n.append(this.#e)}else i.type==="endMarkedContent"&&(this.#e=this.#e.parentNode);continue}s.push(i.str),this.#P(i)}}#P(t){const e=document.createElement("span"),s={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};this.#m.push(e);const i=z.transform(this.#v,t.transform);let n=Math.atan2(i[1],i[0]);const r=this.#f[t.fontName];r.vertical&&(n+=Math.PI/2);let a=this.#i&&r.fontSubstitution||r.fontFamily;a=Zt.fontFamilyMap.get(a)||a;const l=Math.hypot(i[2],i[3]),h=l*Zt.#F(a,this.#r);let c,u;n===0?(c=i[4],u=i[5]-h):(c=i[4]+h*Math.sin(n),u=i[5]-h*Math.cos(n));const d="calc(var(--scale-factor)*",f=e.style;this.#e===this.#h?(f.left=`${(100*c/this.#o).toFixed(2)}%`,f.top=`${(100*u/this.#l).toFixed(2)}%`):(f.left=`${d}${c.toFixed(2)}px)`,f.top=`${d}${u.toFixed(2)}px)`),f.fontSize=`${d}${(Zt.#S*l).toFixed(2)}px)`,f.fontFamily=a,s.fontSize=l,e.setAttribute("role","presentation"),e.textContent=t.str,e.dir=t.dir,this.#i&&(e.dataset.fontName=r.fontSubstitutionLoadedName||t.fontName),n!==0&&(s.angle=n*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const p=Math.abs(t.transform[0]),v=Math.abs(t.transform[3]);p!==v&&Math.max(p,v)/Math.min(p,v)>1.5&&(g=!0)}if(g&&(s.canvasWidth=r.vertical?t.height:t.width),this.#p.set(e,s),this.#n.div=e,this.#n.properties=s,this.#x(this.#n),s.hasText&&this.#e.append(e),s.hasEOL){const p=document.createElement("br");p.setAttribute("role","presentation"),this.#e.append(p)}}#x(t){const{div:e,properties:s,ctx:i}=t,{style:n}=e;let r="";if(Zt.#S>1&&(r=`scale(${1/Zt.#S})`),s.canvasWidth!==0&&s.hasText){const{fontFamily:a}=n,{canvasWidth:l,fontSize:h}=s;Zt.#T(i,h*this.#u,a);const{width:c}=i.measureText(e.textContent);c>0&&(r=`scaleX(${l*this.#u/c}) ${r}`)}s.angle!==0&&(r=`rotate(${s.angle}deg) ${r}`),r.length>0&&(n.transform=r)}static cleanup(){if(!(this.#A.size>0)){this.#_.clear();for(const{canvas:t}of this.#b.values())t.remove();this.#b.clear()}}static#k(t=null){let e=this.#b.get(t||="");if(!e){const s=document.createElement("canvas");s.className="hiddenCanvasElement",s.lang=t,document.body.append(s),e=s.getContext("2d",{alpha:!1,willReadFrequently:!0}),this.#b.set(t,e),this.#w.set(e,{size:0,family:""})}return e}static#T(t,e,s){const i=this.#w.get(t);e===i.size&&s===i.family||(t.font=`${e}px ${s}`,i.size=e,i.family=s)}static#O(){if(this.#S!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),this.#S=t.getBoundingClientRect().height,t.remove()}static#F(t,e){const s=this.#_.get(t);if(s)return s;const i=this.#k(e);i.canvas.width=i.canvas.height=oe,this.#T(i,oe,t);const n=i.measureText("");let r=n.fontBoundingBoxAscent,a=Math.abs(n.fontBoundingBoxDescent);if(r){const c=r/(r+a);return this.#_.set(t,c),i.canvas.width=i.canvas.height=0,c}i.strokeStyle="red",i.clearRect(0,0,oe,oe),i.strokeText("g",0,0);let l=i.getImageData(0,0,oe,oe).data;a=0;for(let c=l.length-1-3;c>=0;c-=4)if(l[c]>0){a=Math.ceil(c/4/oe);break}i.clearRect(0,0,oe,oe),i.strokeText("A",0,oe),l=i.getImageData(0,0,oe,oe).data,r=0;for(let c=0,u=l.length;c<u;c+=4)if(l[c]>0){r=oe-Math.floor(c/4/oe);break}i.canvas.width=i.canvas.height=0;const h=r?r/(r+a):Fg;return this.#_.set(t,h),h}}class Bi{static textContent(t){const e=[],s={items:e,styles:Object.create(null)};function i(n){if(!n)return;let r=null;const a=n.name;if(a==="#text")r=n.value;else if(Bi.shouldBuildText(a))n?.attributes?.textContent?r=n.attributes.textContent:n.value&&(r=n.value);else return;if(r!==null&&e.push({str:r}),!!n.children)for(const l of n.children)i(l)}return i(t),s}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const Lg=65536,Ig=100,jg=5e3,Ng=Gt?Qf:qf,Bg=Gt?Zf:Mh,Hg=Gt?Jf:Kf,zg=Gt?tg:Rh;function Vg(o={}){typeof o=="string"||o instanceof URL?o={url:o}:(o instanceof ArrayBuffer||ArrayBuffer.isView(o))&&(o={data:o});const t=new Ha,{docId:e}=t,s=o.url?Gg(o.url):null,i=o.data?Wg(o.data):null,n=o.httpHeaders||null,r=o.withCredentials===!0,a=o.password??null,l=o.range instanceof Zh?o.range:null,h=Number.isInteger(o.rangeChunkSize)&&o.rangeChunkSize>0?o.rangeChunkSize:Lg;let c=o.worker instanceof ii?o.worker:null;const u=o.verbosity,d=typeof o.docBaseUrl=="string"&&!Zn(o.docBaseUrl)?o.docBaseUrl:null,f=typeof o.cMapUrl=="string"?o.cMapUrl:null,g=o.cMapPacked!==!1,p=o.CMapReaderFactory||Bg,v=typeof o.standardFontDataUrl=="string"?o.standardFontDataUrl:null,m=o.StandardFontDataFactory||zg,b=o.stopAtErrors!==!0,_=Number.isInteger(o.maxImageSize)&&o.maxImageSize>-1?o.maxImageSize:-1,w=o.isEvalSupported!==!1,C=typeof o.isOffscreenCanvasSupported=="boolean"?o.isOffscreenCanvasSupported:!Gt,T=typeof o.isImageDecoderSupported=="boolean"?o.isImageDecoderSupported:!Gt&&(Qt.platform.isFirefox||!globalThis.chrome),E=Number.isInteger(o.canvasMaxAreaInBytes)?o.canvasMaxAreaInBytes:-1,k=typeof o.disableFontFace=="boolean"?o.disableFontFace:Gt,O=o.fontExtraProperties===!0,H=o.enableXfa===!0,N=o.ownerDocument||globalThis.document,P=o.disableRange===!0,R=o.disableStream===!0,F=o.disableAutoFetch===!0,V=o.pdfBug===!0,M=o.CanvasFactory||Ng,L=o.FilterFactory||Hg,Y=o.enableHWA===!0,ft=l?l.length:o.length??NaN,bt=typeof o.useSystemFonts=="boolean"?o.useSystemFonts:!Gt&&!k,_t=typeof o.useWorkerFetch=="boolean"?o.useWorkerFetch:p===Mh&&m===Rh&&f&&v&&Ri(f,document.baseURI)&&Ri(v,document.baseURI),gt=null;Ef(u);const rt={canvasFactory:new M({ownerDocument:N,enableHWA:Y}),filterFactory:new L({docId:e,ownerDocument:N}),cMapReaderFactory:_t?null:new p({baseUrl:f,isCompressed:g}),standardFontDataFactory:_t?null:new m({baseUrl:v})};if(!c){const K={verbosity:u,port:Ni.workerPort};c=K.port?ii.fromPort(K):new ii(K),t._worker=c}const Dt={docId:e,apiVersion:"4.10.38",data:i,password:a,disableAutoFetch:F,rangeChunkSize:h,length:ft,docBaseUrl:d,enableXfa:H,evaluatorOptions:{maxImageSize:_,disableFontFace:k,ignoreErrors:b,isEvalSupported:w,isOffscreenCanvasSupported:C,isImageDecoderSupported:T,canvasMaxAreaInBytes:E,fontExtraProperties:O,useSystemFonts:bt,cMapUrl:_t?f:null,standardFontDataUrl:_t?v:null}},ee={disableFontFace:k,fontExtraProperties:O,ownerDocument:N,pdfBug:V,styleElement:gt,loadingParams:{disableAutoFetch:F,enableXfa:H}};return c.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const K=c.messageHandler.sendWithPromise("GetDocRequest",Dt,i?[i.buffer]:null);let $;if(l)$=new vg(l,{disableRange:P,disableStream:R});else if(!i){if(!s)throw new Error("getDocument - no `url` parameter provided.");let Tt;if(Gt)if(Ri(s)){if(typeof fetch>"u"||typeof Response>"u"||!("body"in Response.prototype))throw new Error("getDocument - the Fetch API was disabled in Node.js, see `--no-experimental-fetch`.");Tt=Jh}else Tt=Mg;else Tt=Ri(s)?Jh:Ag;$=new Tt({url:s,length:ft,httpHeaders:n,withCredentials:r,rangeChunkSize:h,disableRange:P,disableStream:R})}return K.then(Tt=>{if(t.destroyed)throw new Error("Loading aborted");if(c.destroyed)throw new Error("Worker was destroyed");const _e=new Ii(e,Tt,c.port),Nt=new $g(_e,t,$,ee,rt);t._transport=Nt,_e.send("Ready",null)})}).catch(t._capability.reject),t}function Gg(o){if(o instanceof URL)return o.href;try{return new URL(o,window.location).href}catch{if(Gt&&typeof o=="string")return o}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function Wg(o){if(Gt&&typeof Buffer<"u"&&o instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(o instanceof Uint8Array&&o.byteLength===o.buffer.byteLength)return o;if(typeof o=="string")return Jn(o);if(o instanceof ArrayBuffer||ArrayBuffer.isView(o)||typeof o=="object"&&!isNaN(o?.length))return new Uint8Array(o);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function Qh(o){return typeof o=="object"&&Number.isInteger(o?.num)&&o.num>=0&&Number.isInteger(o?.gen)&&o.gen>=0}class Ha{static#t=0;constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Ha.#t++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){this.destroyed=!0;try{this._worker?.port&&(this._worker._pendingDestroy=!0),await this._transport?.destroy()}catch(t){throw this._worker?.port&&delete this._worker._pendingDestroy,t}this._transport=null,this._worker?.destroy(),this._worker=null}}class Zh{constructor(t,e,s=!1,i=null){this.length=t,this.initialData=e,this.progressiveDone=s,this.contentDispositionFilename=i,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,e){for(const s of this._rangeListeners)s(t,e)}onDataProgress(t,e){this._readyCapability.promise.then(()=>{for(const s of this._progressListeners)s(t,e)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const e of this._progressiveReadListeners)e(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,e){ut("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class Xg{constructor(t,e){this._pdfInfo=t,this._transport=e}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return tt(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(e)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class Ug{#t=null;#e=!1;constructor(t,e,s,i=!1){this._pageIndex=t,this._pageInfo=e,this._transport=s,this._stats=i?new xh:null,this._pdfBug=i,this.commonObjs=s.commonObjs,this.objs=new tc,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:e=this.rotate,offsetX:s=0,offsetY:i=0,dontFlip:n=!1}={}){return new Di({viewBox:this.view,userUnit:this.userUnit,scale:t,rotation:e,offsetX:s,offsetY:i,dontFlip:n})}getAnnotations({intent:t="display"}={}){const{renderingIntent:e}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,e)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return tt(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:t,viewport:e,intent:s="display",annotationMode:i=ls.ENABLE,transform:n=null,background:r=null,optionalContentConfigPromise:a=null,annotationCanvasMap:l=null,pageColors:h=null,printAnnotationStorage:c=null,isEditing:u=!1}){this._stats?.time("Overall");const d=this._transport.getRenderingIntent(s,i,c,u),{renderingIntent:f,cacheKey:g}=d;this.#e=!1,this.#i(),a||=this._transport.getOptionalContentConfig(f);let p=this._intentStates.get(g);p||(p=Object.create(null),this._intentStates.set(g,p)),p.streamReaderCancelTimeout&&(clearTimeout(p.streamReaderCancelTimeout),p.streamReaderCancelTimeout=null);const v=!!(f&fe.PRINT);p.displayReadyCapability||(p.displayReadyCapability=Promise.withResolvers(),p.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(d));const m=w=>{p.renderTasks.delete(b),(this._maybeCleanupAfterRender||v)&&(this.#e=!0),this.#s(!v),w?(b.capability.reject(w),this._abortOperatorList({intentState:p,reason:w instanceof Error?w:new Error(w)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),globalThis.Stats?.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new ni({callback:m,params:{canvasContext:t,viewport:e,transform:n,background:r},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:p.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!v,pdfBug:this._pdfBug,pageColors:h});(p.renderTasks||=new Set).add(b);const _=b.task;return Promise.all([p.displayReadyCapability.promise,a]).then(([w,C])=>{if(this.destroyed){m();return}if(this._stats?.time("Rendering"),!(C.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:w,optionalContentConfig:C}),b.operatorListChanged()}).catch(m),_}getOperatorList({intent:t="display",annotationMode:e=ls.ENABLE,printAnnotationStorage:s=null,isEditing:i=!1}={}){function n(){a.operatorList.lastChunk&&(a.opListReadCapability.resolve(a.operatorList),a.renderTasks.delete(l))}const r=this._transport.getRenderingIntent(t,e,s,i,!0);let a=this._intentStates.get(r.cacheKey);a||(a=Object.create(null),this._intentStates.set(r.cacheKey,a));let l;return a.opListReadCapability||(l=Object.create(null),l.operatorListChanged=n,a.opListReadCapability=Promise.withResolvers(),(a.renderTasks||=new Set).add(l),a.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(r)),a.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:e=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:e===!0},{highWaterMark:100,size(i){return i.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(s=>Bi.textContent(s));const e=this.streamTextContent(t);return new Promise(function(s,i){function n(){r.read().then(function({value:l,done:h}){if(h){s(a);return}a.lang??=l.lang,Object.assign(a.styles,l.styles),a.items.push(...l.items),n()},i)}const r=e.getReader(),a={items:[],styles:Object.create(null),lang:null};n()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const e of this._intentStates.values())if(this._abortOperatorList({intentState:e,reason:new Error("Page was destroyed."),force:!0}),!e.opListReadCapability)for(const s of e.renderTasks)t.push(s.completed),s.cancel();return this.objs.clear(),this.#e=!1,this.#i(),Promise.all(t)}cleanup(t=!1){this.#e=!0;const e=this.#s(!1);return t&&e&&(this._stats&&=new xh),e}#s(t=!1){if(this.#i(),!this.#e||this.destroyed)return!1;if(t)return this.#t=setTimeout(()=>{this.#t=null,this.#s(!1)},jg),!1;for(const{renderTasks:e,operatorList:s}of this._intentStates.values())if(e.size>0||!s.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),this.#e=!1,!0}#i(){this.#t&&(clearTimeout(this.#t),this.#t=null)}_startRenderPage(t,e){const s=this._intentStates.get(e);s&&(this._stats?.timeEnd("Page Request"),s.displayReadyCapability?.resolve(t))}_renderPageChunk(t,e){for(let s=0,i=t.length;s<i;s++)e.operatorList.fnArray.push(t.fnArray[s]),e.operatorList.argsArray.push(t.argsArray[s]);e.operatorList.lastChunk=t.lastChunk,e.operatorList.separateAnnots=t.separateAnnots;for(const s of e.renderTasks)s.operatorListChanged();t.lastChunk&&this.#s(!0)}_pumpOperatorList({renderingIntent:t,cacheKey:e,annotationStorageSerializable:s,modifiedIds:i}){const{map:n,transfer:r}=s,l=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:t,cacheKey:e,annotationStorage:n,modifiedIds:i},r).getReader(),h=this._intentStates.get(e);h.streamReader=l;const c=()=>{l.read().then(({value:u,done:d})=>{if(d){h.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(u,h),c())},u=>{if(h.streamReader=null,!this._transport.destroyed){if(h.operatorList){h.operatorList.lastChunk=!0;for(const d of h.renderTasks)d.operatorListChanged();this.#s(!0)}if(h.displayReadyCapability)h.displayReadyCapability.reject(u);else if(h.opListReadCapability)h.opListReadCapability.reject(u);else throw u}})};c()}_abortOperatorList({intentState:t,reason:e,force:s=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!s){if(t.renderTasks.size>0)return;if(e instanceof Ta){let i=Ig;e.extraDelay>0&&e.extraDelay<1e3&&(i+=e.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:e,force:!0})},i);return}}if(t.streamReader.cancel(new cs(e.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[i,n]of this._intentStates)if(n===t){this._intentStates.delete(i);break}this.cleanup()}}}get stats(){return this._stats}}class Yg{#t=new Map;#e=Promise.resolve();postMessage(t,e){const s={data:structuredClone(t,e?{transfer:e}:null)};this.#e.then(()=>{for(const[i]of this.#t)i.call(this,s)})}addEventListener(t,e,s=null){let i=null;if(s?.signal instanceof AbortSignal){const{signal:n}=s;if(n.aborted){Q("LoopbackPort - cannot use an `aborted` signal.");return}const r=()=>this.removeEventListener(t,e);i=()=>n.removeEventListener("abort",r),n.addEventListener("abort",r)}this.#t.set(e,i)}removeEventListener(t,e){this.#t.get(e)?.(),this.#t.delete(e)}terminate(){for(const[,t]of this.#t)t?.();this.#t.clear()}}const vt=class vt{constructor({name:t=null,port:e=null,verbosity:s=kf()}={}){hi(this,ri);if(this.name=t,this.destroyed=!1,this.verbosity=s,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,e){if(De(vt,Ls)?.has(e))throw new Error("Cannot use more than one PDFWorker per port.");(De(vt,Ls)||Wi(vt,Ls,new WeakMap)).set(e,this),this._initializeFromPort(e);return}this._initialize()}get promise(){return this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new Ii("main","worker",t),this._messageHandler.on("ready",function(){}),gr(this,ri,mr).call(this)}_initialize(){if(De(vt,Fs)||De(vt,ai,vr)){this._setupFakeWorker();return}let{workerSrc:t}=vt;try{vt._isSameOrigin(window.location.href,t)||(t=vt._createCDNWrapper(new URL(t,window.location).href));const e=new Worker(t,{type:"module"}),s=new Ii("main","worker",e),i=()=>{n.abort(),s.destroy(),e.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},n=new AbortController;e.addEventListener("error",()=>{this._webWorker||i()},{signal:n.signal}),s.on("test",a=>{if(n.abort(),this.destroyed||!a){i();return}this._messageHandler=s,this._port=e,this._webWorker=e,gr(this,ri,mr).call(this)}),s.on("ready",a=>{if(n.abort(),this.destroyed){i();return}try{r()}catch{this._setupFakeWorker()}});const r=()=>{const a=new Uint8Array;s.send("test",a,[a.buffer])};r();return}catch{qn("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){De(vt,Fs)||(Q("Setting up fake worker."),Wi(vt,Fs,!0)),vt._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const e=new Yg;this._port=e;const s=`fake${Dc(vt,hr)._++}`,i=new Ii(s+"_worker",s,e);t.setup(i,e),this._messageHandler=new Ii(s,s+"_worker",e),gr(this,ri,mr).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){this.destroyed=!0,this._webWorker?.terminate(),this._webWorker=null,De(vt,Ls)?.delete(this._port),this._port=null,this._messageHandler?.destroy(),this._messageHandler=null}static fromPort(t){if(!t?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");const e=De(this,Ls)?.get(t.port);if(e){if(e._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return e}return new vt(t)}static get workerSrc(){if(Ni.workerSrc)return Ni.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return tt(this,"_setupFakeWorkerGlobal",(async()=>De(this,ai,vr)?De(this,ai,vr):(await import(this.workerSrc)).WorkerMessageHandler)())}};hr=new WeakMap,Fs=new WeakMap,Ls=new WeakMap,ri=new WeakSet,mr=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},ai=new WeakSet,vr=function(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}},hi(vt,ai),hi(vt,hr,0),hi(vt,Fs,!1),hi(vt,Ls),Gt&&(Wi(vt,Fs,!0),Ni.workerSrc||="./pdf.worker.mjs"),vt._isSameOrigin=(t,e)=>{let s;try{if(s=new URL(t),!s.origin||s.origin==="null")return!1}catch{return!1}const i=new URL(e,s);return s.origin===i.origin},vt._createCDNWrapper=t=>{const e=`await import("${t}");`;return URL.createObjectURL(new Blob([e],{type:"text/javascript"}))};let ii=vt;class $g{#t=new Map;#e=new Map;#s=new Map;#i=new Map;#r=null;constructor(t,e,s,i,n){this.messageHandler=t,this.loadingTask=e,this.commonObjs=new tc,this.fontLoader=new Yf({ownerDocument:i.ownerDocument,styleElement:i.styleElement}),this.loadingParams=i.loadingParams,this._params=i,this.canvasFactory=n.canvasFactory,this.filterFactory=n.filterFactory,this.cMapReaderFactory=n.cMapReaderFactory,this.standardFontDataFactory=n.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=s,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#n(t,e=null){const s=this.#t.get(t);if(s)return s;const i=this.messageHandler.sendWithPromise(t,e);return this.#t.set(t,i),i}get annotationStorage(){return tt(this,"annotationStorage",new Ra)}getRenderingIntent(t,e=ls.ENABLE,s=null,i=!1,n=!1){let r=fe.DISPLAY,a=Da;switch(t){case"any":r=fe.ANY;break;case"display":break;case"print":r=fe.PRINT;break;default:Q(`getRenderingIntent - invalid intent: ${t}`)}const l=r&fe.PRINT&&s instanceof Th?s:this.annotationStorage;switch(e){case ls.DISABLE:r+=fe.ANNOTATIONS_DISABLE;break;case ls.ENABLE:break;case ls.ENABLE_FORMS:r+=fe.ANNOTATIONS_FORMS;break;case ls.ENABLE_STORAGE:r+=fe.ANNOTATIONS_STORAGE,a=l.serializable;break;default:Q(`getRenderingIntent - invalid annotationMode: ${e}`)}i&&(r+=fe.IS_EDITING),n&&(r+=fe.OPLIST);const{ids:h,hash:c}=l.modifiedIds,u=[r,a.hash,c];return{renderingIntent:r,cacheKey:u.join("_"),annotationStorageSerializable:a,modifiedIds:h}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#r?.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const s of this.#e.values())t.push(s._destroy());this.#e.clear(),this.#s.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const e=this.messageHandler.sendWithPromise("Terminate",null);return t.push(e),Promise.all(t).then(()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),Zt.cleanup(),this._networkStream?.cancelAllRequests(new cs("Worker was terminated.")),this.messageHandler?.destroy(),this.messageHandler=null,this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:e}=this;t.on("GetReader",(s,i)=>{Mt(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=n=>{this._lastProgress={loaded:n.loaded,total:n.total}},i.onPull=()=>{this._fullReader.read().then(function({value:n,done:r}){if(r){i.close();return}Mt(n instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(n),1,[n])}).catch(n=>{i.error(n)})},i.onCancel=n=>{this._fullReader.cancel(n),i.ready.catch(r=>{if(!this.destroyed)throw r})}}),t.on("ReaderHeadersReady",async s=>{await this._fullReader.headersReady;const{isStreamingSupported:i,isRangeSupported:n,contentLength:r}=this._fullReader;return(!i||!n)&&(this._lastProgress&&e.onProgress?.(this._lastProgress),this._fullReader.onProgress=a=>{e.onProgress?.({loaded:a.loaded,total:a.total})}),{isStreamingSupported:i,isRangeSupported:n,contentLength:r}}),t.on("GetRangeReader",(s,i)=>{Mt(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const n=this._networkStream.getRangeReader(s.begin,s.end);if(!n){i.close();return}i.onPull=()=>{n.read().then(function({value:r,done:a}){if(a){i.close();return}Mt(r instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{n.cancel(r),i.ready.catch(a=>{if(!this.destroyed)throw a})}}),t.on("GetDoc",({pdfInfo:s})=>{this._numPages=s.numPages,this._htmlForXfa=s.htmlForXfa,delete s.htmlForXfa,e._capability.resolve(new Xg(s,this))}),t.on("DocException",s=>{e._capability.reject(re(s))}),t.on("PasswordRequest",s=>{this.#r=Promise.withResolvers();try{if(!e.onPassword)throw re(s);const i=n=>{n instanceof Error?this.#r.reject(n):this.#r.resolve({password:n})};e.onPassword(i,s.code)}catch(i){this.#r.reject(i)}return this.#r.promise}),t.on("DataLoaded",s=>{e.onProgress?.({loaded:s.length,total:s.length}),this.downloadInfoCapability.resolve(s)}),t.on("StartRenderPage",s=>{if(this.destroyed)return;this.#e.get(s.pageIndex)._startRenderPage(s.transparency,s.cacheKey)}),t.on("commonobj",([s,i,n])=>{if(this.destroyed||this.commonObjs.has(s))return null;switch(i){case"Font":const{disableFontFace:r,fontExtraProperties:a,pdfBug:l}=this._params;if("error"in n){const d=n.error;Q(`Error during font loading: ${d}`),this.commonObjs.resolve(s,d);break}const h=l&&globalThis.FontInspector?.enabled?(d,f)=>globalThis.FontInspector.fontAdded(d,f):null,c=new $f(n,{disableFontFace:r,fontExtraProperties:a,inspectFont:h});this.fontLoader.bind(c).catch(()=>t.sendWithPromise("FontFallback",{id:s})).finally(()=>{!a&&c.data&&(c.data=null),this.commonObjs.resolve(s,c)});break;case"CopyLocalImage":const{imageRef:u}=n;Mt(u,"The imageRef must be defined.");for(const d of this.#e.values())for(const[,f]of d.objs)if(f?.ref===u)return f.dataLen?(this.commonObjs.resolve(s,structuredClone(f)),f.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(s,n);break;default:throw new Error(`Got unknown common object type ${i}`)}return null}),t.on("obj",([s,i,n,r])=>{if(this.destroyed)return;const a=this.#e.get(i);if(!a.objs.has(s)){if(a._intentStates.size===0){r?.bitmap?.close();return}switch(n){case"Image":a.objs.resolve(s,r),r?.dataLen>Sf&&(a._maybeCleanupAfterRender=!0);break;case"Pattern":a.objs.resolve(s,r);break;default:throw new Error(`Got unknown object type ${n}`)}}}),t.on("DocProgress",s=>{this.destroyed||e.onProgress?.({loaded:s.loaded,total:s.total})}),t.on("FetchBuiltInCMap",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(s)}),t.on("FetchStandardFontData",async s=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(s)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){this.annotationStorage.size<=0&&Q("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:e}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:this._fullReader?.filename??null},e).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const e=t-1,s=this.#s.get(e);if(s)return s;const i=this.messageHandler.sendWithPromise("GetPage",{pageIndex:e}).then(n=>{if(this.destroyed)throw new Error("Transport destroyed");n.refStr&&this.#i.set(n.refStr,t);const r=new Ug(e,n,this,this._params.pdfBug);return this.#e.set(e,r),r});return this.#s.set(e,i),i}getPageIndex(t){return Qh(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,e){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:e})}getFieldObjects(){return this.#n("GetFieldObjects")}hasJSActions(){return this.#n("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#n("GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return this.#n("GetOptionalContentConfig").then(e=>new mg(e,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",e=this.#t.get(t);if(e)return e;const s=this.messageHandler.sendWithPromise(t,null).then(i=>({info:i[0],metadata:i[1]?new gg(i[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null}));return this.#t.set(t,s),s}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const e of this.#e.values())if(!e.cleanup())throw new Error(`startCleanup: Page ${e.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),Zt.cleanup()}}cachedPageNumber(t){if(!Qh(t))return null;const e=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return this.#i.get(e)??null}}const Hi=Symbol("INITIAL_DATA");class tc{#t=Object.create(null);#e(t){return this.#t[t]||={...Promise.withResolvers(),data:Hi}}get(t,e=null){if(e){const i=this.#e(t);return i.promise.then(()=>e(i.data)),null}const s=this.#t[t];if(!s||s.data===Hi)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return s.data}has(t){const e=this.#t[t];return!!e&&e.data!==Hi}delete(t){const e=this.#t[t];return!e||e.data===Hi?!1:(delete this.#t[t],!0)}resolve(t,e=null){const s=this.#e(t);s.data=e,s.resolve()}clear(){for(const t in this.#t){const{data:e}=this.#t[t];e?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(const t in this.#t){const{data:e}=this.#t[t];e!==Hi&&(yield[t,e])}}}class qg{#t=null;constructor(t){this.#t=t,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(t=0){this.#t.cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=this.#t.operatorList;if(!t)return!1;const{annotationCanvasMap:e}=this.#t;return t.form||t.canvas&&e?.size>0}}class ni{#t=null;static#e=new WeakSet;constructor({callback:t,params:e,objs:s,commonObjs:i,annotationCanvasMap:n,operatorList:r,pageIndex:a,canvasFactory:l,filterFactory:h,useRequestAnimationFrame:c=!1,pdfBug:u=!1,pageColors:d=null}){this.callback=t,this.params=e,this.objs=s,this.commonObjs=i,this.annotationCanvasMap=n,this.operatorListIdx=null,this.operatorList=r,this._pageIndex=a,this.canvasFactory=l,this.filterFactory=h,this._pdfBug=u,this.pageColors=d,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=c===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new qg(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=e.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:e}){if(this.cancelled)return;if(this._canvas){if(ni.#e.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");ni.#e.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:s,viewport:i,transform:n,background:r}=this.params;this.gfx=new ei(s,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:e},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:n,viewport:i,transparency:t,background:r}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(t=null,e=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),this.#t&&(window.cancelAnimationFrame(this.#t),this.#t=null),ni.#e.delete(this._canvas),this.callback(t||new Ta(`Rendering cancelled, page ${this._pageIndex+1}`,e))}operatorListChanged(){if(!this.graphicsReady){this.graphicsReadyCallback||=this._continueBound;return}this.stepper?.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?this.#t=window.requestAnimationFrame(()=>{this.#t=null,this._nextBound().catch(this._cancelBound)}):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),ni.#e.delete(this._canvas),this.callback())))}}const Kg="4.10.38",Jg="f9bea397f";function ec(o){return Math.floor(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0")}function zi(o){return Math.max(0,Math.min(255,255*o))}class sc{static CMYK_G([t,e,s,i]){return["G",1-Math.min(1,.3*t+.59*s+.11*e+i)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=zi(t),[t,t,t]}static G_HTML([t]){const e=ec(t);return`#${e}${e}${e}`}static RGB_G([t,e,s]){return["G",.3*t+.59*e+.11*s]}static RGB_rgb(t){return t.map(zi)}static RGB_HTML(t){return`#${t.map(ec).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,e,s,i]){return["RGB",1-Math.min(1,t+i),1-Math.min(1,s+i),1-Math.min(1,e+i)]}static CMYK_rgb([t,e,s,i]){return[zi(1-Math.min(1,t+i)),zi(1-Math.min(1,s+i)),zi(1-Math.min(1,e+i))]}static CMYK_HTML(t){const e=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(e)}static RGB_CMYK([t,e,s]){const i=1-t,n=1-e,r=1-s,a=Math.min(i,n,r);return["CMYK",i,n,r,a]}}class Qg{create(t,e,s=!1){if(t<=0||e<=0)throw new Error("Invalid SVG dimensions");const i=this._createSVG("svg:svg");return i.setAttribute("version","1.1"),s||(i.setAttribute("width",`${t}px`),i.setAttribute("height",`${e}px`)),i.setAttribute("preserveAspectRatio","none"),i.setAttribute("viewBox",`0 0 ${t} ${e}`),i}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){ut("Abstract method `_createSVG` called.")}}class za extends Qg{_createSVG(t){return document.createElementNS(es,t)}}class ic{static setupStorage(t,e,s,i,n){const r=i.getValue(e,{value:null});switch(s.name){case"textarea":if(r.value!==null&&(t.textContent=r.value),n==="print")break;t.addEventListener("input",a=>{i.setValue(e,{value:a.target.value})});break;case"input":if(s.attributes.type==="radio"||s.attributes.type==="checkbox"){if(r.value===s.attributes.xfaOn?t.setAttribute("checked",!0):r.value===s.attributes.xfaOff&&t.removeAttribute("checked"),n==="print")break;t.addEventListener("change",a=>{i.setValue(e,{value:a.target.checked?a.target.getAttribute("xfaOn"):a.target.getAttribute("xfaOff")})})}else{if(r.value!==null&&t.setAttribute("value",r.value),n==="print")break;t.addEventListener("input",a=>{i.setValue(e,{value:a.target.value})})}break;case"select":if(r.value!==null){t.setAttribute("value",r.value);for(const a of s.children)a.attributes.value===r.value?a.attributes.selected=!0:a.attributes.hasOwnProperty("selected")&&delete a.attributes.selected}t.addEventListener("input",a=>{const l=a.target.options,h=l.selectedIndex===-1?"":l[l.selectedIndex].value;i.setValue(e,{value:h})});break}}static setAttributes({html:t,element:e,storage:s=null,intent:i,linkService:n}){const{attributes:r}=e,a=t instanceof HTMLAnchorElement;r.type==="radio"&&(r.name=`${r.name}-${i}`);for(const[l,h]of Object.entries(r))if(h!=null)switch(l){case"class":h.length&&t.setAttribute(l,h.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",h);break;case"style":Object.assign(t.style,h);break;case"textContent":t.textContent=h;break;default:(!a||l!=="href"&&l!=="newWindow")&&t.setAttribute(l,h)}a&&n.addLinkAttributes(t,r.href,r.newWindow),s&&r.dataId&&this.setupStorage(t,r.dataId,e,s)}static render(t){const e=t.annotationStorage,s=t.linkService,i=t.xfaHtml,n=t.intent||"display",r=document.createElement(i.name);i.attributes&&this.setAttributes({html:r,element:i,intent:n,linkService:s});const a=n!=="richText",l=t.div;if(l.append(r),t.viewport){const u=`matrix(${t.viewport.transform.join(",")})`;l.style.transform=u}a&&l.setAttribute("class","xfaLayer xfaFont");const h=[];if(i.children.length===0){if(i.value){const u=document.createTextNode(i.value);r.append(u),a&&Bi.shouldBuildText(i.name)&&h.push(u)}return{textDivs:h}}const c=[[i,-1,r]];for(;c.length>0;){const[u,d,f]=c.at(-1);if(d+1===u.children.length){c.pop();continue}const g=u.children[++c.at(-1)[1]];if(g===null)continue;const{name:p}=g;if(p==="#text"){const m=document.createTextNode(g.value);h.push(m),f.append(m);continue}const v=g?.attributes?.xmlns?document.createElementNS(g.attributes.xmlns,p):document.createElement(p);if(f.append(v),g.attributes&&this.setAttributes({html:v,element:g,storage:e,intent:n,linkService:s}),g.children?.length>0)c.push([g,-1,v]);else if(g.value){const m=document.createTextNode(g.value);a&&Bi.shouldBuildText(p)&&h.push(m),v.append(m)}}for(const u of l.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))u.setAttribute("readOnly",!0);return{textDivs:h}}static update(t){const e=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=e,t.div.hidden=!1}}const Vi=1e3,Zg=9,Os=new WeakSet;function ds(o){return{width:o[2]-o[0],height:o[3]-o[1]}}class tp{static create(t){switch(t.data.annotationType){case Lt.LINK:return new nc(t);case Lt.TEXT:return new ep(t);case Lt.WIDGET:switch(t.data.fieldType){case"Tx":return new sp(t);case"Btn":return t.data.radioButton?new rc(t):t.data.checkBox?new np(t):new rp(t);case"Ch":return new ap(t);case"Sig":return new ip(t)}return new Ds(t);case Lt.POPUP:return new Va(t);case Lt.FREETEXT:return new ac(t);case Lt.LINE:return new lp(t);case Lt.SQUARE:return new hp(t);case Lt.CIRCLE:return new cp(t);case Lt.POLYLINE:return new oc(t);case Lt.CARET:return new dp(t);case Lt.INK:return new Ga(t);case Lt.POLYGON:return new up(t);case Lt.HIGHLIGHT:return new lc(t);case Lt.UNDERLINE:return new fp(t);case Lt.SQUIGGLY:return new gp(t);case Lt.STRIKEOUT:return new pp(t);case Lt.STAMP:return new hc(t);case Lt.FILEATTACHMENT:return new mp(t);default:return new Ct(t)}}}class Ct{#t=null;#e=!1;#s=null;constructor(t,{isRenderable:e=!1,ignoreBorder:s=!1,createQuadrilaterals:i=!1}={}){this.isRenderable=e,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,e&&(this.container=this._createContainer(s)),i&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:e,richText:s}){return!!(t?.str||e?.str||s?.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return Ct._hasPopupData(this.data)}updateEdited(t){if(!this.container)return;this.#t||={rect:this.data.rect.slice(0)};const{rect:e}=t;e&&this.#i(e),this.#s?.popup.updateEdited(t)}resetEdited(){this.#t&&(this.#i(this.#t.rect),this.#s?.popup.resetEdited(),this.#t=null)}#i(t){const{container:{style:e},data:{rect:s,rotation:i},parent:{viewport:{rawDims:{pageWidth:n,pageHeight:r,pageX:a,pageY:l}}}}=this;s?.splice(0,4,...t);const{width:h,height:c}=ds(t);e.left=`${100*(t[0]-a)/n}%`,e.top=`${100*(r-t[3]+l)/r}%`,i===0?(e.width=`${100*h/n}%`,e.height=`${100*c/r}%`):this.setRotation(i)}_createContainer(t){const{data:e,parent:{page:s,viewport:i}}=this,n=document.createElement("section");n.setAttribute("data-annotation-id",e.id),this instanceof Ds||(n.tabIndex=Vi);const{style:r}=n;if(r.zIndex=this.parent.zIndex++,e.alternativeText&&(n.title=e.alternativeText),e.noRotate&&n.classList.add("norotate"),!e.rect||this instanceof Va){const{rotation:p}=e;return!e.hasOwnCanvas&&p!==0&&this.setRotation(p,n),n}const{width:a,height:l}=ds(e.rect);if(!t&&e.borderStyle.width>0){r.borderWidth=`${e.borderStyle.width}px`;const p=e.borderStyle.horizontalCornerRadius,v=e.borderStyle.verticalCornerRadius;if(p>0||v>0){const b=`calc(${p}px * var(--scale-factor)) / calc(${v}px * var(--scale-factor))`;r.borderRadius=b}else if(this instanceof rc){const b=`calc(${a}px * var(--scale-factor)) / calc(${l}px * var(--scale-factor))`;r.borderRadius=b}switch(e.borderStyle.style){case Mi.SOLID:r.borderStyle="solid";break;case Mi.DASHED:r.borderStyle="dashed";break;case Mi.BEVELED:Q("Unimplemented border style: beveled");break;case Mi.INSET:Q("Unimplemented border style: inset");break;case Mi.UNDERLINE:r.borderBottomStyle="solid";break}const m=e.borderColor||null;m?(this.#e=!0,r.borderColor=z.makeHexColor(m[0]|0,m[1]|0,m[2]|0)):r.borderWidth=0}const h=z.normalizeRect([e.rect[0],s.view[3]-e.rect[1]+s.view[1],e.rect[2],s.view[3]-e.rect[3]+s.view[1]]),{pageWidth:c,pageHeight:u,pageX:d,pageY:f}=i.rawDims;r.left=`${100*(h[0]-d)/c}%`,r.top=`${100*(h[1]-f)/u}%`;const{rotation:g}=e;return e.hasOwnCanvas||g===0?(r.width=`${100*a/c}%`,r.height=`${100*l/u}%`):this.setRotation(g,n),n}setRotation(t,e=this.container){if(!this.data.rect)return;const{pageWidth:s,pageHeight:i}=this.parent.viewport.rawDims,{width:n,height:r}=ds(this.data.rect);let a,l;t%180===0?(a=100*n/s,l=100*r/i):(a=100*r/s,l=100*n/i),e.style.width=`${a}%`,e.style.height=`${l}%`,e.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(e,s,i)=>{const n=i.detail[e],r=n[0],a=n.slice(1);i.target.style[s]=sc[`${r}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[s]:sc[`${r}_rgb`](a)})};return tt(this,"_commonActions",{display:e=>{const{display:s}=e.detail,i=s%2===1;this.container.style.visibility=i?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:i,noPrint:s===1||s===2})},print:e=>{this.annotationStorage.setValue(this.data.id,{noPrint:!e.detail.print})},hidden:e=>{const{hidden:s}=e.detail;this.container.style.visibility=s?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:s,noView:s})},focus:e=>{setTimeout(()=>e.target.focus({preventScroll:!1}),0)},userName:e=>{e.target.title=e.detail.userName},readonly:e=>{e.target.disabled=e.detail.readonly},required:e=>{this._setRequired(e.target,e.detail.required)},bgColor:e=>{t("bgColor","backgroundColor",e)},fillColor:e=>{t("fillColor","backgroundColor",e)},fgColor:e=>{t("fgColor","color",e)},textColor:e=>{t("textColor","color",e)},borderColor:e=>{t("borderColor","borderColor",e)},strokeColor:e=>{t("strokeColor","borderColor",e)},rotation:e=>{const s=e.detail.rotation;this.setRotation(s),this.annotationStorage.setValue(this.data.id,{rotation:s})}})}_dispatchEventFromSandbox(t,e){const s=this._commonActions;for(const i of Object.keys(e.detail))(t[i]||s[i])?.(e)}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const e=this.annotationStorage.getRawValue(this.data.id);if(!e)return;const s=this._commonActions;for(const[i,n]of Object.entries(e)){const r=s[i];if(r){const a={detail:{[i]:n},target:t};r(a),delete e[i]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[e,s,i,n]=this.data.rect.map(p=>Math.fround(p));if(t.length===8){const[p,v,m,b]=t.subarray(2,6);if(i===p&&n===v&&e===m&&s===b)return}const{style:r}=this.container;let a;if(this.#e){const{borderColor:p,borderWidth:v}=r;r.borderWidth=0,a=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${p}" stroke-width="${v}">`],this.container.classList.add("hasBorder")}const l=i-e,h=n-s,{svgFactory:c}=this,u=c.createElement("svg");u.classList.add("quadrilateralsContainer"),u.setAttribute("width",0),u.setAttribute("height",0);const d=c.createElement("defs");u.append(d);const f=c.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),d.append(f);for(let p=2,v=t.length;p<v;p+=8){const m=t[p],b=t[p+1],_=t[p+2],w=t[p+3],C=c.createElement("rect"),T=(_-e)/l,E=(n-b)/h,k=(m-_)/l,O=(b-w)/h;C.setAttribute("x",T),C.setAttribute("y",E),C.setAttribute("width",k),C.setAttribute("height",O),f.append(C),a?.push(`<rect vector-effect="non-scaling-stroke" x="${T}" y="${E}" width="${k}" height="${O}"/>`)}this.#e&&(a.push("</g></svg>')"),r.backgroundImage=a.join("")),this.container.append(u),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,e=this.#s=new Va({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]});this.parent.div.append(e.render())}render(){ut("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,e=null){const s=[];if(this._fieldObjects){const i=this._fieldObjects[t];if(i)for(const{page:n,id:r,exportValues:a}of i){if(n===-1||r===e)continue;const l=typeof a=="string"?a:null,h=document.querySelector(`[data-element-id="${r}"]`);if(h&&!Os.has(h)){Q(`_getElementsByName - element not allowed: ${r}`);continue}s.push({id:r,exportValue:l,domElement:h})}return s}for(const i of document.getElementsByName(t)){const{exportValue:n}=i,r=i.getAttribute("data-element-id");r!==e&&Os.has(i)&&s.push({id:r,exportValue:n,domElement:i})}return s}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const e of t)e.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:e}}=this;this.container.addEventListener("dblclick",()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:t,editId:e})})}}class nc extends Ct{constructor(t,e=null){super(t,{isRenderable:!0,ignoreBorder:!!e?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=t.data.isTooltipOnly}render(){const{data:t,linkService:e}=this,s=document.createElement("a");s.setAttribute("data-element-id",t.id);let i=!1;return t.url?(e.addLinkAttributes(s,t.url,t.newWindow),i=!0):t.action?(this._bindNamedAction(s,t.action),i=!0):t.attachment?(this.#e(s,t.attachment,t.attachmentDest),i=!0):t.setOCGState?(this.#s(s,t.setOCGState),i=!0):t.dest?(this._bindLink(s,t.dest),i=!0):(t.actions&&(t.actions.Action||t.actions["Mouse Up"]||t.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(s,t),i=!0),t.resetForm?(this._bindResetFormAction(s,t.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(s,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(s),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(t,e){t.href=this.linkService.getDestinationHash(e),t.onclick=()=>(e&&this.linkService.goToDestination(e),!1),(e||e==="")&&this.#t()}_bindNamedAction(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeNamedAction(e),!1),this.#t()}#e(t,e,s=null){t.href=this.linkService.getAnchorUrl(""),e.description&&(t.title=e.description),t.onclick=()=>(this.downloadManager?.openOrDownloadData(e.content,e.filename,s),!1),this.#t()}#s(t,e){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(e),!1),this.#t()}_bindJSAction(t,e){t.href=this.linkService.getAnchorUrl("");const s=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(e.actions)){const n=s.get(i);n&&(t[n]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e.id,name:i}}),!1))}t.onclick||(t.onclick=()=>!1),this.#t()}_bindResetFormAction(t,e){const s=t.onclick;if(s||(t.href=this.linkService.getAnchorUrl("")),this.#t(),!this._fieldObjects){Q('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),s||(t.onclick=()=>!1);return}t.onclick=()=>{s?.();const{fields:i,refs:n,include:r}=e,a=[];if(i.length!==0||n.length!==0){const c=new Set(n);for(const u of i){const d=this._fieldObjects[u]||[];for(const{id:f}of d)c.add(f)}for(const u of Object.values(this._fieldObjects))for(const d of u)c.has(d.id)===r&&a.push(d)}else for(const c of Object.values(this._fieldObjects))a.push(...c);const l=this.annotationStorage,h=[];for(const c of a){const{id:u}=c;switch(h.push(u),c.type){case"text":{const f=c.defaultValue||"";l.setValue(u,{value:f});break}case"checkbox":case"radiobutton":{const f=c.defaultValue===c.exportValues;l.setValue(u,{value:f});break}case"combobox":case"listbox":{const f=c.defaultValue||"";l.setValue(u,{value:f});break}default:continue}const d=document.querySelector(`[data-element-id="${u}"]`);if(d){if(!Os.has(d)){Q(`_bindResetFormAction - element not allowed: ${u}`);continue}}else continue;d.dispatchEvent(new Event("resetform"))}return this.enableScripting&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:h,name:"ResetForm"}}),!1}}}class ep extends Ct{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class Ds extends Ct{render(){return this.container}showElementAndHideCanvas(t){this.data.hasOwnCanvas&&(t.previousSibling?.nodeName==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return Qt.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,e,s,i,n){s.includes("mouse")?t.addEventListener(s,r=>{this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r),shift:r.shiftKey,modifier:this._getKeyModifier(r)}})}):t.addEventListener(s,r=>{if(s==="blur"){if(!e.focused||!r.relatedTarget)return;e.focused=!1}else if(s==="focus"){if(e.focused)return;e.focused=!0}n&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:i,value:n(r)}})})}_setEventListeners(t,e,s,i){for(const[n,r]of s)(r==="Action"||this.data.actions?.[r])&&((r==="Focus"||r==="Blur")&&(e||={focused:!1}),this._setEventListener(t,e,n,r,i),r==="Focus"&&!this.data.actions?.Blur?this._setEventListener(t,e,"blur","Blur",null):r==="Blur"&&!this.data.actions?.Focus&&this._setEventListener(t,e,"focus","Focus",null))}_setBackgroundColor(t){const e=this.data.backgroundColor||null;t.style.backgroundColor=e===null?"transparent":z.makeHexColor(e[0],e[1],e[2])}_setTextStyle(t){const e=["left","center","right"],{fontColor:s}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Zg,n=t.style;let r;const a=2,l=h=>Math.round(10*h)/10;if(this.data.multiLine){const h=Math.abs(this.data.rect[3]-this.data.rect[1]-a),c=Math.round(h/(ya*i))||1,u=h/c;r=Math.min(i,l(u/ya))}else{const h=Math.abs(this.data.rect[3]-this.data.rect[1]-a);r=Math.min(i,l(h/ya))}n.fontSize=`calc(${r}px * var(--scale-factor))`,n.color=z.makeHexColor(s[0],s[1],s[2]),this.data.textAlignment!==null&&(n.textAlign=e[this.data.textAlignment])}_setRequired(t,e){e?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",e)}}class sp extends Ds{constructor(t){const e=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:e})}setPropertyOnSiblings(t,e,s,i){const n=this.annotationStorage;for(const r of this._getElementsByName(t.name,t.id))r.domElement&&(r.domElement[e]=s),n.setValue(r.id,{[i]:s})}render(){const t=this.annotationStorage,e=this.data.id;this.container.classList.add("textWidgetAnnotation");let s=null;if(this.renderForms){const i=t.getValue(e,{value:this.data.fieldValue});let n=i.value||"";const r=t.getValue(e,{charLimit:this.data.maxLen}).charLimit;r&&n.length>r&&(n=n.slice(0,r));let a=i.formattedValue||this.data.textContent?.join(`
|
|
535
|
+
`)||null;a&&this.data.comb&&(a=a.replaceAll(/\s+/g,""));const l={userValue:n,formattedValue:a,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(s=document.createElement("textarea"),s.textContent=a??n,this.data.doNotScroll&&(s.style.overflowY="hidden")):(s=document.createElement("input"),s.type="text",s.setAttribute("value",a??n),this.data.doNotScroll&&(s.style.overflowX="hidden")),this.data.hasOwnCanvas&&(s.hidden=!0),Os.add(s),s.setAttribute("data-element-id",e),s.disabled=this.data.readOnly,s.name=this.data.fieldName,s.tabIndex=Vi,this._setRequired(s,this.data.required),r&&(s.maxLength=r),s.addEventListener("input",c=>{t.setValue(e,{value:c.target.value}),this.setPropertyOnSiblings(s,"value",c.target.value,"value"),l.formattedValue=null}),s.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue??"";s.value=l.userValue=u,l.formattedValue=null});let h=c=>{const{formattedValue:u}=l;u!=null&&(c.target.value=u),c.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){s.addEventListener("focus",u=>{if(l.focused)return;const{target:d}=u;l.userValue&&(d.value=l.userValue),l.lastCommittedValue=d.value,l.commitKey=1,this.data.actions?.Focus||(l.focused=!0)}),s.addEventListener("updatefromsandbox",u=>{this.showElementAndHideCanvas(u.target);const d={value(f){l.userValue=f.detail.value??"",t.setValue(e,{value:l.userValue.toString()}),f.target.value=l.userValue},formattedValue(f){const{formattedValue:g}=f.detail;l.formattedValue=g,g!=null&&f.target!==document.activeElement&&(f.target.value=g),t.setValue(e,{formattedValue:g})},selRange(f){f.target.setSelectionRange(...f.detail.selRange)},charLimit:f=>{const{charLimit:g}=f.detail,{target:p}=f;if(g===0){p.removeAttribute("maxLength");return}p.setAttribute("maxLength",g);let v=l.userValue;!v||v.length<=g||(v=v.slice(0,g),p.value=l.userValue=v,t.setValue(e,{value:v}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:v,willCommit:!0,commitKey:1,selStart:p.selectionStart,selEnd:p.selectionEnd}}))}};this._dispatchEventFromSandbox(d,u)}),s.addEventListener("keydown",u=>{l.commitKey=1;let d=-1;if(u.key==="Escape"?d=0:u.key==="Enter"&&!this.data.multiLine?d=2:u.key==="Tab"&&(l.commitKey=3),d===-1)return;const{value:f}=u.target;l.lastCommittedValue!==f&&(l.lastCommittedValue=f,l.userValue=f,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:f,willCommit:!0,commitKey:d,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}))});const c=h;h=null,s.addEventListener("blur",u=>{if(!l.focused||!u.relatedTarget)return;this.data.actions?.Blur||(l.focused=!1);const{value:d}=u.target;l.userValue=d,l.lastCommittedValue!==d&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:d,willCommit:!0,commitKey:l.commitKey,selStart:u.target.selectionStart,selEnd:u.target.selectionEnd}}),c(u)}),this.data.actions?.Keystroke&&s.addEventListener("beforeinput",u=>{l.lastCommittedValue=null;const{data:d,target:f}=u,{value:g,selectionStart:p,selectionEnd:v}=f;let m=p,b=v;switch(u.inputType){case"deleteWordBackward":{const _=g.substring(0,p).match(/\w*[^\w]*$/);_&&(m-=_[0].length);break}case"deleteWordForward":{const _=g.substring(p).match(/^[^\w]*\w*/);_&&(b+=_[0].length);break}case"deleteContentBackward":p===v&&(m-=1);break;case"deleteContentForward":p===v&&(b+=1);break}u.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:g,change:d||"",willCommit:!1,selStart:m,selEnd:b}})}),this._setEventListeners(s,l,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],u=>u.target.value)}if(h&&s.addEventListener("blur",h),this.data.comb){const u=(this.data.rect[2]-this.data.rect[0])/r;s.classList.add("comb"),s.style.letterSpacing=`calc(${u}px * var(--scale-factor) - 1ch)`}}else s=document.createElement("div"),s.textContent=this.data.fieldValue,s.style.verticalAlign="middle",s.style.display="table-cell",this.data.hasOwnCanvas&&(s.hidden=!0);return this._setTextStyle(s),this._setBackgroundColor(s),this._setDefaultPropertiesFromJS(s),this.container.append(s),this.container}}class ip extends Ds{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class np extends Ds{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.exportValue===e.fieldValue}).value;typeof i=="string"&&(i=i!=="Off",t.setValue(s,{value:i})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const n=document.createElement("input");return Os.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="checkbox",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.setAttribute("exportValue",e.exportValue),n.tabIndex=Vi,n.addEventListener("change",r=>{const{name:a,checked:l}=r.target;for(const h of this._getElementsByName(a,s)){const c=l&&h.exportValue===e.exportValue;h.domElement&&(h.domElement.checked=c),t.setValue(h.id,{value:c})}t.setValue(s,{value:l})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue||"Off";r.target.checked=a===e.exportValue}),this.enableScripting&&this.hasJSActions&&(n.addEventListener("updatefromsandbox",r=>{const a={value(l){l.target.checked=l.detail.value!=="Off",t.setValue(s,{value:l.target.checked})}};this._dispatchEventFromSandbox(a,r)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],r=>r.target.checked)),this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class rc extends Ds{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,e=this.data,s=e.id;let i=t.getValue(s,{value:e.fieldValue===e.buttonValue}).value;if(typeof i=="string"&&(i=i!==e.buttonValue,t.setValue(s,{value:i})),i)for(const r of this._getElementsByName(e.fieldName,s))t.setValue(r.id,{value:!1});const n=document.createElement("input");if(Os.add(n),n.setAttribute("data-element-id",s),n.disabled=e.readOnly,this._setRequired(n,this.data.required),n.type="radio",n.name=e.fieldName,i&&n.setAttribute("checked",!0),n.tabIndex=Vi,n.addEventListener("change",r=>{const{name:a,checked:l}=r.target;for(const h of this._getElementsByName(a,s))t.setValue(h.id,{value:!1});t.setValue(s,{value:l})}),n.addEventListener("resetform",r=>{const a=e.defaultFieldValue;r.target.checked=a!=null&&a===e.buttonValue}),this.enableScripting&&this.hasJSActions){const r=e.buttonValue;n.addEventListener("updatefromsandbox",a=>{const l={value:h=>{const c=r===h.detail.value;for(const u of this._getElementsByName(h.target.name)){const d=c&&u.id===s;u.domElement&&(u.domElement.checked=d),t.setValue(u.id,{value:d})}}};this._dispatchEventFromSandbox(l,a)}),this._setEventListeners(n,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],a=>a.target.checked)}return this._setBackgroundColor(n),this._setDefaultPropertiesFromJS(n),this.container.append(n),this.container}}class rp extends nc{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const e=t.lastChild;return this.enableScripting&&this.hasJSActions&&e&&(this._setDefaultPropertiesFromJS(e),e.addEventListener("updatefromsandbox",s=>{this._dispatchEventFromSandbox({},s)})),t}}class ap extends Ds{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,e=this.data.id,s=t.getValue(e,{value:this.data.fieldValue}),i=document.createElement("select");Os.add(i),i.setAttribute("data-element-id",e),i.disabled=this.data.readOnly,this._setRequired(i,this.data.required),i.name=this.data.fieldName,i.tabIndex=Vi;let n=this.data.combo&&this.data.options.length>0;this.data.combo||(i.size=this.data.options.length,this.data.multiSelect&&(i.multiple=!0)),i.addEventListener("resetform",c=>{const u=this.data.defaultFieldValue;for(const d of i.options)d.selected=d.value===u});for(const c of this.data.options){const u=document.createElement("option");u.textContent=c.displayValue,u.value=c.exportValue,s.value.includes(c.exportValue)&&(u.setAttribute("selected",!0),n=!1),i.append(u)}let r=null;if(n){const c=document.createElement("option");c.value=" ",c.setAttribute("hidden",!0),c.setAttribute("selected",!0),i.prepend(c),r=()=>{c.remove(),i.removeEventListener("input",r),r=null},i.addEventListener("input",r)}const a=c=>{const u=c?"value":"textContent",{options:d,multiple:f}=i;return f?Array.prototype.filter.call(d,g=>g.selected).map(g=>g[u]):d.selectedIndex===-1?null:d[d.selectedIndex][u]};let l=a(!1);const h=c=>{const u=c.target.options;return Array.prototype.map.call(u,d=>({displayValue:d.textContent,exportValue:d.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",c=>{const u={value(d){r?.();const f=d.detail.value,g=new Set(Array.isArray(f)?f:[f]);for(const p of i.options)p.selected=g.has(p.value);t.setValue(e,{value:a(!0)}),l=a(!1)},multipleSelection(d){i.multiple=!0},remove(d){const f=i.options,g=d.detail.remove;f[g].selected=!1,i.remove(g),f.length>0&&Array.prototype.findIndex.call(f,v=>v.selected)===-1&&(f[0].selected=!0),t.setValue(e,{value:a(!0),items:h(d)}),l=a(!1)},clear(d){for(;i.length!==0;)i.remove(0);t.setValue(e,{value:null,items:[]}),l=a(!1)},insert(d){const{index:f,displayValue:g,exportValue:p}=d.detail.insert,v=i.children[f],m=document.createElement("option");m.textContent=g,m.value=p,v?v.before(m):i.append(m),t.setValue(e,{value:a(!0),items:h(d)}),l=a(!1)},items(d){const{items:f}=d.detail;for(;i.length!==0;)i.remove(0);for(const g of f){const{displayValue:p,exportValue:v}=g,m=document.createElement("option");m.textContent=p,m.value=v,i.append(m)}i.options.length>0&&(i.options[0].selected=!0),t.setValue(e,{value:a(!0),items:h(d)}),l=a(!1)},indices(d){const f=new Set(d.detail.indices);for(const g of d.target.options)g.selected=f.has(g.index);t.setValue(e,{value:a(!0)}),l=a(!1)},editable(d){d.target.disabled=!d.detail.editable}};this._dispatchEventFromSandbox(u,c)}),i.addEventListener("input",c=>{const u=a(!0),d=a(!1);t.setValue(e,{value:u}),c.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:e,name:"Keystroke",value:l,change:d,changeEx:u,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(i,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],c=>c.target.value)):i.addEventListener("input",function(c){t.setValue(e,{value:a(!0)})}),this.data.combo&&this._setTextStyle(i),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class Va extends Ct{constructor(t){const{data:e,elements:s}=t;super(t,{isRenderable:Ct._hasPopupData(e)}),this.elements=s,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new op({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),e=[];for(const s of this.elements)s.popup=t,s.container.ariaHasPopup="dialog",e.push(s.data.id),s.addHighlightArea();return this.container.setAttribute("aria-controls",e.map(s=>`${Aa}${s}`).join(",")),this.container}}class op{#t=this.#E.bind(this);#e=this.#T.bind(this);#s=this.#k.bind(this);#i=this.#x.bind(this);#r=null;#n=null;#l=null;#o=null;#c=null;#h=null;#d=null;#u=!1;#f=null;#a=null;#g=null;#m=null;#p=null;#v=null;#_=!1;constructor({container:t,color:e,elements:s,titleObj:i,modificationDate:n,contentsObj:r,richText:a,parent:l,rect:h,parentRect:c,open:u}){this.#n=t,this.#p=i,this.#l=r,this.#m=a,this.#h=l,this.#r=e,this.#g=h,this.#d=c,this.#c=s,this.#o=Sh.toDateObject(n),this.trigger=s.flatMap(d=>d.getElementsToTriggerPopup());for(const d of this.trigger)d.addEventListener("click",this.#i),d.addEventListener("mouseenter",this.#s),d.addEventListener("mouseleave",this.#e),d.classList.add("popupTriggerArea");for(const d of s)d.container?.addEventListener("keydown",this.#t);this.#n.hidden=!0,u&&this.#x()}render(){if(this.#f)return;const t=this.#f=document.createElement("div");if(t.className="popup",this.#r){const n=t.style.outlineColor=z.makeHexColor(...this.#r);CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${n} 30%, white)`:t.style.backgroundColor=z.makeHexColor(...this.#r.map(a=>Math.floor(.7*(255-a)+a)))}const e=document.createElement("span");e.className="header";const s=document.createElement("h1");if(e.append(s),{dir:s.dir,str:s.textContent}=this.#p,t.append(e),this.#o){const n=document.createElement("span");n.classList.add("popupDate"),n.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),n.setAttribute("data-l10n-args",JSON.stringify({dateObj:this.#o.valueOf()})),e.append(n)}const i=this.#b;if(i)ic.render({xfaHtml:i,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const n=this._formatContents(this.#l);t.append(n)}this.#n.append(t)}get#b(){const t=this.#m,e=this.#l;return t?.str&&(!e?.str||e.str===t.str)&&this.#m.html||null}get#w(){return this.#b?.attributes?.style?.fontSize||0}get#S(){return this.#b?.attributes?.style?.color||null}#A(t){const e=[],s={str:t,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:e}]}},i={style:{color:this.#S,fontSize:this.#w?`calc(${this.#w}px * var(--scale-factor))`:""}};for(const n of t.split(`
|
|
536
|
+
`))e.push({name:"span",value:n,attributes:i});return s}_formatContents({str:t,dir:e}){const s=document.createElement("p");s.classList.add("popupContent"),s.dir=e;const i=t.split(/(?:\r\n?|\n)/);for(let n=0,r=i.length;n<r;++n){const a=i[n];s.append(document.createTextNode(a)),n<r-1&&s.append(document.createElement("br"))}return s}#E(t){t.altKey||t.shiftKey||t.ctrlKey||t.metaKey||(t.key==="Enter"||t.key==="Escape"&&this.#u)&&this.#x()}updateEdited({rect:t,popupContent:e}){this.#v||={contentsObj:this.#l,richText:this.#m},t&&(this.#a=null),e&&(this.#m=this.#A(e),this.#l=null),this.#f?.remove(),this.#f=null}resetEdited(){this.#v&&({contentsObj:this.#l,richText:this.#m}=this.#v,this.#v=null,this.#f?.remove(),this.#f=null,this.#a=null)}#P(){if(this.#a!==null)return;const{page:{view:t},viewport:{rawDims:{pageWidth:e,pageHeight:s,pageX:i,pageY:n}}}=this.#h;let r=!!this.#d,a=r?this.#d:this.#g;for(const g of this.#c)if(!a||z.intersect(g.data.rect,a)!==null){a=g.data.rect,r=!0;break}const l=z.normalizeRect([a[0],t[3]-a[1]+t[1],a[2],t[3]-a[3]+t[1]]),c=r?a[2]-a[0]+5:0,u=l[0]+c,d=l[1];this.#a=[100*(u-i)/e,100*(d-n)/s];const{style:f}=this.#n;f.left=`${this.#a[0]}%`,f.top=`${this.#a[1]}%`}#x(){this.#u=!this.#u,this.#u?(this.#k(),this.#n.addEventListener("click",this.#i),this.#n.addEventListener("keydown",this.#t)):(this.#T(),this.#n.removeEventListener("click",this.#i),this.#n.removeEventListener("keydown",this.#t))}#k(){this.#f||this.render(),this.isVisible?this.#u&&this.#n.classList.add("focused"):(this.#P(),this.#n.hidden=!1,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)+1e3)}#T(){this.#n.classList.remove("focused"),!(this.#u||!this.isVisible)&&(this.#n.hidden=!0,this.#n.style.zIndex=parseInt(this.#n.style.zIndex)-1e3)}forceHide(){this.#_=this.isVisible,this.#_&&(this.#n.hidden=!0)}maybeShow(){this.#_&&(this.#f||this.#k(),this.#_=!1,this.#n.hidden=!1)}get isVisible(){return this.#n.hidden===!1}}class ac extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.textContent=t.data.textContent,this.textPosition=t.data.textPosition,this.annotationEditorType=J.FREETEXT}render(){if(this.container.classList.add("freeTextAnnotation"),this.textContent){const t=document.createElement("div");t.classList.add("annotationTextContent"),t.setAttribute("role","comment");for(const e of this.textContent){const s=document.createElement("span");s.textContent=e,t.append(s)}this.container.append(t)}return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class lp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");const t=this.data,{width:e,height:s}=ds(t.rect),i=this.svgFactory.create(e,s,!0),n=this.#t=this.svgFactory.createElement("svg:line");return n.setAttribute("x1",t.rect[2]-t.lineCoordinates[0]),n.setAttribute("y1",t.rect[3]-t.lineCoordinates[1]),n.setAttribute("x2",t.rect[2]-t.lineCoordinates[2]),n.setAttribute("y2",t.rect[3]-t.lineCoordinates[3]),n.setAttribute("stroke-width",t.borderStyle.width||1),n.setAttribute("stroke","transparent"),n.setAttribute("fill","transparent"),i.append(n),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class hp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");const t=this.data,{width:e,height:s}=ds(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:rect");return r.setAttribute("x",n/2),r.setAttribute("y",n/2),r.setAttribute("width",e-n),r.setAttribute("height",s-n),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class cp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");const t=this.data,{width:e,height:s}=ds(t.rect),i=this.svgFactory.create(e,s,!0),n=t.borderStyle.width,r=this.#t=this.svgFactory.createElement("svg:ellipse");return r.setAttribute("cx",e/2),r.setAttribute("cy",s/2),r.setAttribute("rx",e/2-n/2),r.setAttribute("ry",s/2-n/2),r.setAttribute("stroke-width",n||1),r.setAttribute("stroke","transparent"),r.setAttribute("fill","transparent"),i.append(r),this.container.append(i),!t.popupRef&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class oc extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="polylineAnnotation",this.svgElementName="svg:polyline"}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,vertices:e,borderStyle:s,popupRef:i}}=this;if(!e)return this.container;const{width:n,height:r}=ds(t),a=this.svgFactory.create(n,r,!0);let l=[];for(let c=0,u=e.length;c<u;c+=2){const d=e[c]-t[0],f=t[3]-e[c+1];l.push(`${d},${f}`)}l=l.join(" ");const h=this.#t=this.svgFactory.createElement(this.svgElementName);return h.setAttribute("points",l),h.setAttribute("stroke-width",s.width||1),h.setAttribute("stroke","transparent"),h.setAttribute("fill","transparent"),a.append(h),this.container.append(a),!i&&this.hasPopupData&&this._createPopup(),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class up extends oc{constructor(t){super(t),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class dp extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0})}render(){return this.container.classList.add("caretAnnotation"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container}}class Ga extends Ct{#t=null;#e=[];constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?J.HIGHLIGHT:J.INK}#s(t,e){switch(t){case 90:return{transform:`rotate(90) translate(${-e[0]},${e[1]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};case 180:return{transform:`rotate(180) translate(${-e[2]},${e[1]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]};case 270:return{transform:`rotate(270) translate(${-e[2]},${e[3]}) scale(1,-1)`,width:e[3]-e[1],height:e[2]-e[0]};default:return{transform:`translate(${-e[0]},${e[3]}) scale(1,-1)`,width:e[2]-e[0],height:e[3]-e[1]}}}render(){this.container.classList.add(this.containerClassName);const{data:{rect:t,rotation:e,inkLists:s,borderStyle:i,popupRef:n}}=this,{transform:r,width:a,height:l}=this.#s(e,t),h=this.svgFactory.create(a,l,!0),c=this.#t=this.svgFactory.createElement("svg:g");h.append(c),c.setAttribute("stroke-width",i.width||1),c.setAttribute("stroke-linecap","round"),c.setAttribute("stroke-linejoin","round"),c.setAttribute("stroke-miterlimit",10),c.setAttribute("stroke","transparent"),c.setAttribute("fill","transparent"),c.setAttribute("transform",r);for(let u=0,d=s.length;u<d;u++){const f=this.svgFactory.createElement(this.svgElementName);this.#e.push(f),f.setAttribute("points",s[u].join(",")),c.append(f)}return!n&&this.hasPopupData&&this._createPopup(),this.container.append(h),this._editOnDoubleClick(),this.container}updateEdited(t){super.updateEdited(t);const{thickness:e,points:s,rect:i}=t,n=this.#t;if(e>=0&&n.setAttribute("stroke-width",e||1),s)for(let r=0,a=this.#e.length;r<a;r++)this.#e[r].setAttribute("points",s[r].join(","));if(i){const{transform:r,width:a,height:l}=this.#s(this.data.rotation,i);n.parentElement.setAttribute("viewBox",`0 0 ${a} ${l}`),n.setAttribute("transform",r)}}getElementsToTriggerPopup(){return this.#e}addHighlightArea(){this.container.classList.add("highlightArea")}}class lc extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=J.HIGHLIGHT}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("highlightAnnotation"),this._editOnDoubleClick(),this.container}}class fp extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("underlineAnnotation"),this.container}}class gp extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("squigglyAnnotation"),this.container}}class pp extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0})}render(){return!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.classList.add("strikeoutAnnotation"),this.container}}class hc extends Ct{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=J.STAMP}render(){return this.container.classList.add("stampAnnotation"),this.container.setAttribute("role","img"),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this._editOnDoubleClick(),this.container}}class mp extends Ct{#t=null;constructor(t){super(t,{isRenderable:!0});const{file:e}=this.data;this.filename=e.filename,this.content=e.content,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,...e})}render(){this.container.classList.add("fileAttachmentAnnotation");const{container:t,data:e}=this;let s;e.hasAppearance||e.fillAlpha===0?s=document.createElement("div"):(s=document.createElement("img"),s.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(e.name)?"paperclip":"pushpin"}.svg`,e.fillAlpha&&e.fillAlpha<1&&(s.style=`filter: opacity(${Math.round(e.fillAlpha*100)}%);`)),s.addEventListener("dblclick",this.#e.bind(this)),this.#t=s;const{isMac:i}=Qt.platform;return t.addEventListener("keydown",n=>{n.key==="Enter"&&(i?n.metaKey:n.ctrlKey)&&this.#e()}),!e.popupRef&&this.hasPopupData?this._createPopup():s.classList.add("popupTriggerArea"),t.append(s),t}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}#e(){this.downloadManager?.openOrDownloadData(this.content,this.filename)}}class vp{#t=null;#e=null;#s=new Map;#i=null;constructor({div:t,accessibilityManager:e,annotationCanvasMap:s,annotationEditorUIManager:i,page:n,viewport:r,structTreeLayer:a}){this.div=t,this.#t=e,this.#e=s,this.#i=a||null,this.page=n,this.viewport=r,this.zIndex=0,this._annotationEditorUIManager=i}hasEditableAnnotations(){return this.#s.size>0}async#r(t,e){const s=t.firstChild||t,i=s.id=`${Aa}${e}`,n=await this.#i?.getAriaAttributes(i);if(n)for(const[r,a]of n)s.setAttribute(r,a);this.div.append(t),this.#t?.moveElementInDOM(this.div,t,s,!1)}async render(t){const{annotations:e}=t,s=this.div;Ms(s,this.viewport);const i=new Map,n={data:null,layer:s,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new za,annotationStorage:t.annotationStorage||new Ra,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const r of e){if(r.noHTML)continue;const a=r.annotationType===Lt.POPUP;if(a){const c=i.get(r.id);if(!c)continue;n.elements=c}else{const{width:c,height:u}=ds(r.rect);if(c<=0||u<=0)continue}n.data=r;const l=tp.create(n);if(!l.isRenderable)continue;if(!a&&r.popupRef){const c=i.get(r.popupRef);c?c.push(l):i.set(r.popupRef,[l])}const h=l.render();r.hidden&&(h.style.visibility="hidden"),await this.#r(h,r.id),l._isEditable&&(this.#s.set(l.data.id,l),this._annotationEditorUIManager?.renderAnnotationElement(l))}this.#n()}update({viewport:t}){const e=this.div;this.viewport=t,Ms(e,{rotation:t.rotation}),this.#n(),e.hidden=!1}#n(){if(!this.#e)return;const t=this.div;for(const[e,s]of this.#e){const i=t.querySelector(`[data-annotation-id="${e}"]`);if(!i)continue;s.className="annotationContent";const{firstChild:n}=i;n?n.nodeName==="CANVAS"?n.replaceWith(s):n.classList.contains("annotationContent")?n.after(s):n.before(s):i.append(s)}this.#e.clear()}getEditableAnnotations(){return Array.from(this.#s.values())}getEditableAnnotation(t){return this.#s.get(t)}}const or=/\r\n?|\n/g;class It extends G{#t;#e="";#s=`${this.id}-editor`;#i=null;#r;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){const t=It.prototype,e=n=>n.isEmpty(),s=us.TRANSLATE_SMALL,i=us.TRANSLATE_BIG;return tt(this,"_keyboardManager",new Li([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],t.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],t.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],t._translateEmpty,{args:[-s,0],checker:e}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t._translateEmpty,{args:[-i,0],checker:e}],[["ArrowRight","mac+ArrowRight"],t._translateEmpty,{args:[s,0],checker:e}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t._translateEmpty,{args:[i,0],checker:e}],[["ArrowUp","mac+ArrowUp"],t._translateEmpty,{args:[0,-s],checker:e}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t._translateEmpty,{args:[0,-i],checker:e}],[["ArrowDown","mac+ArrowDown"],t._translateEmpty,{args:[0,s],checker:e}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t._translateEmpty,{args:[0,i],checker:e}]]))}static _type="freetext";static _editorType=J.FREETEXT;constructor(t){super({...t,name:"freeTextEditor"}),this.#t=t.color||It._defaultColor||G._defaultLineColor,this.#r=t.fontSize||It._defaultFontSize}static initialize(t,e){G.initialize(t,e);const s=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(s.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,e){switch(t){case st.FREETEXT_SIZE:It._defaultFontSize=e;break;case st.FREETEXT_COLOR:It._defaultColor=e;break}}updateParams(t,e){switch(t){case st.FREETEXT_SIZE:this.#n(e);break;case st.FREETEXT_COLOR:this.#l(e);break}}static get defaultPropertiesToUpdate(){return[[st.FREETEXT_SIZE,It._defaultFontSize],[st.FREETEXT_COLOR,It._defaultColor||G._defaultLineColor]]}get propertiesToUpdate(){return[[st.FREETEXT_SIZE,this.#r],[st.FREETEXT_COLOR,this.#t]]}#n(t){const e=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-this.#r)*this.parentScale),this.#r=i,this.#c()},s=this.#r;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})}#l(t){const e=i=>{this.#t=this.editorDiv.style.color=i},s=this.#t;this.addCommands({cmd:e.bind(this,t),undo:e.bind(this,s),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(t,e){this._uiManager.translateSelectedEditors(t,e,!0)}getInitialTranslation(){const t=this.parentScale;return[-It._internalPadding*t,-(It._internalPadding+this.#r)*t]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(J.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),this.#i=new AbortController;const t=this._uiManager.combinedSignal(this.#i);this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:t}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:t}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:t}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:t}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:t})}disableEditMode(){this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",this.#s),this._isDraggable=!0,this.#i?.abort(),this.#i=null,this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(t){this._focusEventsAllowed&&(super.focusin(t),t.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(t){this.width||(this.enableEditMode(),t&&this.editorDiv.focus(),this._initialOptions?.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}#o(){const t=[];this.editorDiv.normalize();let e=null;for(const s of this.editorDiv.childNodes)e?.nodeType===Node.TEXT_NODE&&s.nodeName==="BR"||(t.push(It.#h(s)),e=s);return t.join(`
|
|
537
|
+
`)}#c(){const[t,e]=this.parentDimensions;let s;if(this.isAttachedToDOM)s=this.div.getBoundingClientRect();else{const{currentLayer:i,div:n}=this,r=n.style.display,a=n.classList.contains("hidden");n.classList.remove("hidden"),n.style.display="hidden",i.div.append(this.div),s=n.getBoundingClientRect(),n.remove(),n.style.display=r,n.classList.toggle("hidden",a)}this.rotation%180===this.parentRotation%180?(this.width=s.width/t,this.height=s.height/e):(this.width=s.height/t,this.height=s.width/e),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const t=this.#e,e=this.#e=this.#o().trimEnd();if(t===e)return;const s=i=>{if(this.#e=i,!i){this.remove();return}this.#d(),this._uiManager.rebuild(this),this.#c()};this.addCommands({cmd:()=>{s(e)},undo:()=>{s(t)},mustExec:!1}),this.#c()}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(t){this.enterInEditMode()}keydown(t){t.target===this.div&&t.key==="Enter"&&(this.enterInEditMode(),t.preventDefault())}editorDivKeydown(t){It._keyboardManager.exec(this,t)}editorDivFocus(t){this.isEditing=!0}editorDivBlur(t){this.isEditing=!1}editorDivInput(t){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let t,e;this.width&&(t=this.x,e=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",this.#s),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:s}=this.editorDiv;if(s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),tr(this,this.div,["dblclick","keydown"]),this.width){const[i,n]=this.parentDimensions;if(this.annotationElementId){const{position:r}=this._initialData;let[a,l]=this.getInitialTranslation();[a,l]=this.pageTranslationToScreen(a,l);const[h,c]=this.pageDimensions,[u,d]=this.pageTranslation;let f,g;switch(this.rotation){case 0:f=t+(r[0]-u)/h,g=e+this.height-(r[1]-d)/c;break;case 90:f=t+(r[0]-u)/h,g=e-(r[1]-d)/c,[a,l]=[l,-a];break;case 180:f=t-this.width+(r[0]-u)/h,g=e-(r[1]-d)/c,[a,l]=[-a,-l];break;case 270:f=t+(r[0]-u-this.height*c)/h,g=e+(r[1]-d-this.width*h)/c,[a,l]=[-l,a];break}this.setAt(f*i,g*n,a,l)}else this.setAt(t*i,e*n,this.width*i,this.height*n);this.#d(),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}static#h(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(or,"")}editorDivPaste(t){const e=t.clipboardData||window.clipboardData,{types:s}=e;if(s.length===1&&s[0]==="text/plain")return;t.preventDefault();const i=It.#f(e.getData("text")||"").replaceAll(or,`
|
|
538
|
+
`);if(!i)return;const n=window.getSelection();if(!n.rangeCount)return;this.editorDiv.normalize(),n.deleteFromDocument();const r=n.getRangeAt(0);if(!i.includes(`
|
|
539
|
+
`)){r.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),n.collapseToStart();return}const{startContainer:a,startOffset:l}=r,h=[],c=[];if(a.nodeType===Node.TEXT_NODE){const f=a.parentElement;if(c.push(a.nodeValue.slice(l).replaceAll(or,"")),f!==this.editorDiv){let g=h;for(const p of this.editorDiv.childNodes){if(p===f){g=c;continue}g.push(It.#h(p))}}h.push(a.nodeValue.slice(0,l).replaceAll(or,""))}else if(a===this.editorDiv){let f=h,g=0;for(const p of this.editorDiv.childNodes)g++===l&&(f=c),f.push(It.#h(p))}this.#e=`${h.join(`
|
|
540
|
+
`)}${i}${c.join(`
|
|
541
|
+
`)}`,this.#d();const u=new Range;let d=h.reduce((f,g)=>f+g.length,0);for(const{firstChild:f}of this.editorDiv.childNodes)if(f.nodeType===Node.TEXT_NODE){const g=f.nodeValue.length;if(d<=g){u.setStart(f,d),u.setEnd(f,d);break}d-=g}n.removeAllRanges(),n.addRange(u)}#d(){if(this.editorDiv.replaceChildren(),!!this.#e)for(const t of this.#e.split(`
|
|
542
|
+
`)){const e=document.createElement("div");e.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(e)}}#u(){return this.#e.replaceAll(" "," ")}static#f(t){return t.replaceAll(" "," ")}get contentDiv(){return this.editorDiv}static async deserialize(t,e,s){let i=null;if(t instanceof ac){const{data:{defaultAppearanceData:{fontSize:r,fontColor:a},rect:l,rotation:h,id:c,popupRef:u},textContent:d,textPosition:f,parent:{page:{pageNumber:g}}}=t;if(!d||d.length===0)return null;i=t={annotationType:J.FREETEXT,color:Array.from(a),fontSize:r,value:d.join(`
|
|
543
|
+
`),position:f,pageIndex:g-1,rect:l.slice(0),rotation:h,id:c,deleted:!1,popupRef:u}}const n=await super.deserialize(t,e,s);return n.#r=t.fontSize,n.#t=z.makeHexColor(...t.color),n.#e=It.#f(t.value),n.annotationElementId=t.id||null,n._initialData=i,n}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const e=It._internalPadding*this.parentScale,s=this.getRect(e,e),i=G._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#t),n={annotationType:J.FREETEXT,color:i,fontSize:this.#r,value:this.#u(),pageIndex:this.pageIndex,rect:s,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?n:this.annotationElementId&&!this.#a(n)?null:(n.id=this.annotationElementId,n)}#a(t){const{value:e,fontSize:s,color:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||t.value!==e||t.fontSize!==s||t.color.some((r,a)=>r!==i[a])||t.pageIndex!==n}renderAnnotationElement(t){const e=super.renderAnnotationElement(t);if(this.deleted)return e;const{style:s}=e;s.fontSize=`calc(${this.#r}px * var(--scale-factor))`,s.color=this.#t,e.replaceChildren();for(const n of this.#e.split(`
|
|
544
|
+
`)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),e.append(r)}const i=It._internalPadding*this.parentScale;return t.updateEdited({rect:this.getRect(i,i),popupContent:this.#e}),e}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}}class B{static PRECISION=1e-4;toSVGPath(){ut("Abstract method `toSVGPath` must be implemented.")}get box(){ut("Abstract getter `box` must be implemented.")}serialize(t,e){ut("Abstract method `serialize` must be implemented.")}static _rescale(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,l=t.length;a<l;a+=2)r[a]=e+t[a]*i,r[a+1]=s+t[a+1]*n;return r}static _rescaleAndSwap(t,e,s,i,n,r){r||=new Float32Array(t.length);for(let a=0,l=t.length;a<l;a+=2)r[a]=e+t[a+1]*i,r[a+1]=s+t[a]*n;return r}static _translate(t,e,s,i){i||=new Float32Array(t.length);for(let n=0,r=t.length;n<r;n+=2)i[n]=e+t[n],i[n+1]=s+t[n+1];return i}static svgRound(t){return Math.round(t*1e4)}static _normalizePoint(t,e,s,i,n){switch(n){case 90:return[1-e/s,t/i];case 180:return[1-t/s,1-e/i];case 270:return[e/s,1-t/i];default:return[t/s,e/i]}}static _normalizePagePoint(t,e,s){switch(s){case 90:return[1-e,t];case 180:return[1-t,1-e];case 270:return[e,1-t];default:return[t,e]}}static createBezierPoints(t,e,s,i,n,r){return[(t+5*s)/6,(e+5*i)/6,(5*s+n)/6,(5*i+r)/6,(s+n)/2,(i+r)/2]}}class Rs{#t;#e=[];#s;#i;#r=[];#n=new Float32Array(18);#l;#o;#c;#h;#d;#u;#f=[];static#a=8;static#g=2;static#m=Rs.#a+Rs.#g;constructor({x:t,y:e},s,i,n,r,a=0){this.#t=s,this.#u=n*i,this.#i=r,this.#n.set([NaN,NaN,NaN,NaN,t,e],6),this.#s=a,this.#h=Rs.#a*i,this.#c=Rs.#m*i,this.#d=i,this.#f.push(t,e)}isEmpty(){return isNaN(this.#n[8])}#p(){const t=this.#n.subarray(4,6),e=this.#n.subarray(16,18),[s,i,n,r]=this.#t;return[(this.#l+(t[0]-e[0])/2-s)/n,(this.#o+(t[1]-e[1])/2-i)/r,(this.#l+(e[0]-t[0])/2-s)/n,(this.#o+(e[1]-t[1])/2-i)/r]}add({x:t,y:e}){this.#l=t,this.#o=e;const[s,i,n,r]=this.#t;let[a,l,h,c]=this.#n.subarray(8,12);const u=t-h,d=e-c,f=Math.hypot(u,d);if(f<this.#c)return!1;const g=f-this.#h,p=g/f,v=p*u,m=p*d;let b=a,_=l;a=h,l=c,h+=v,c+=m,this.#f?.push(t,e);const w=-m/g,C=v/g,T=w*this.#u,E=C*this.#u;return this.#n.set(this.#n.subarray(2,8),0),this.#n.set([h+T,c+E],4),this.#n.set(this.#n.subarray(14,18),12),this.#n.set([h-T,c-E],16),isNaN(this.#n[6])?(this.#r.length===0&&(this.#n.set([a+T,l+E],2),this.#r.push(NaN,NaN,NaN,NaN,(a+T-s)/n,(l+E-i)/r),this.#n.set([a-T,l-E],14),this.#e.push(NaN,NaN,NaN,NaN,(a-T-s)/n,(l-E-i)/r)),this.#n.set([b,_,a,l,h,c],6),!this.isEmpty()):(this.#n.set([b,_,a,l,h,c],6),Math.abs(Math.atan2(_-l,b-a)-Math.atan2(m,v))<Math.PI/2?([a,l,h,c]=this.#n.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((a+h)/2-s)/n,((l+c)/2-i)/r),[a,l,b,_]=this.#n.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((b+a)/2-s)/n,((_+l)/2-i)/r),!0):([b,_,a,l,h,c]=this.#n.subarray(0,6),this.#r.push(((b+5*a)/6-s)/n,((_+5*l)/6-i)/r,((5*a+h)/6-s)/n,((5*l+c)/6-i)/r,((a+h)/2-s)/n,((l+c)/2-i)/r),[h,c,a,l,b,_]=this.#n.subarray(12,18),this.#e.push(((b+5*a)/6-s)/n,((_+5*l)/6-i)/r,((5*a+h)/6-s)/n,((5*l+c)/6-i)/r,((a+h)/2-s)/n,((l+c)/2-i)/r),!0))}toSVGPath(){if(this.isEmpty())return"";const t=this.#r,e=this.#e;if(isNaN(this.#n[6])&&!this.isEmpty())return this.#v();const s=[];s.push(`M${t[4]} ${t[5]}`);for(let i=6;i<t.length;i+=6)isNaN(t[i])?s.push(`L${t[i+4]} ${t[i+5]}`):s.push(`C${t[i]} ${t[i+1]} ${t[i+2]} ${t[i+3]} ${t[i+4]} ${t[i+5]}`);this.#b(s);for(let i=e.length-6;i>=6;i-=6)isNaN(e[i])?s.push(`L${e[i+4]} ${e[i+5]}`):s.push(`C${e[i]} ${e[i+1]} ${e[i+2]} ${e[i+3]} ${e[i+4]} ${e[i+5]}`);return this.#_(s),s.join(" ")}#v(){const[t,e,s,i]=this.#t,[n,r,a,l]=this.#p();return`M${(this.#n[2]-t)/s} ${(this.#n[3]-e)/i} L${(this.#n[4]-t)/s} ${(this.#n[5]-e)/i} L${n} ${r} L${a} ${l} L${(this.#n[16]-t)/s} ${(this.#n[17]-e)/i} L${(this.#n[14]-t)/s} ${(this.#n[15]-e)/i} Z`}#_(t){const e=this.#e;t.push(`L${e[4]} ${e[5]} Z`)}#b(t){const[e,s,i,n]=this.#t,r=this.#n.subarray(4,6),a=this.#n.subarray(16,18),[l,h,c,u]=this.#p();t.push(`L${(r[0]-e)/i} ${(r[1]-s)/n} L${l} ${h} L${c} ${u} L${(a[0]-e)/i} ${(a[1]-s)/n}`)}newFreeDrawOutline(t,e,s,i,n,r){return new cc(t,e,s,i,n,r)}getOutlines(){const t=this.#r,e=this.#e,s=this.#n,[i,n,r,a]=this.#t,l=new Float32Array((this.#f?.length??0)+2);for(let u=0,d=l.length-2;u<d;u+=2)l[u]=(this.#f[u]-i)/r,l[u+1]=(this.#f[u+1]-n)/a;if(l[l.length-2]=(this.#l-i)/r,l[l.length-1]=(this.#o-n)/a,isNaN(s[6])&&!this.isEmpty())return this.#w(l);const h=new Float32Array(this.#r.length+24+this.#e.length);let c=t.length;for(let u=0;u<c;u+=2){if(isNaN(t[u])){h[u]=h[u+1]=NaN;continue}h[u]=t[u],h[u+1]=t[u+1]}c=this.#A(h,c);for(let u=e.length-6;u>=6;u-=6)for(let d=0;d<6;d+=2){if(isNaN(e[u+d])){h[c]=h[c+1]=NaN,c+=2;continue}h[c]=e[u+d],h[c+1]=e[u+d+1],c+=2}return this.#S(h,c),this.newFreeDrawOutline(h,l,this.#t,this.#d,this.#s,this.#i)}#w(t){const e=this.#n,[s,i,n,r]=this.#t,[a,l,h,c]=this.#p(),u=new Float32Array(36);return u.set([NaN,NaN,NaN,NaN,(e[2]-s)/n,(e[3]-i)/r,NaN,NaN,NaN,NaN,(e[4]-s)/n,(e[5]-i)/r,NaN,NaN,NaN,NaN,a,l,NaN,NaN,NaN,NaN,h,c,NaN,NaN,NaN,NaN,(e[16]-s)/n,(e[17]-i)/r,NaN,NaN,NaN,NaN,(e[14]-s)/n,(e[15]-i)/r],0),this.newFreeDrawOutline(u,t,this.#t,this.#d,this.#s,this.#i)}#S(t,e){const s=this.#e;return t.set([NaN,NaN,NaN,NaN,s[4],s[5]],e),e+=6}#A(t,e){const s=this.#n.subarray(4,6),i=this.#n.subarray(16,18),[n,r,a,l]=this.#t,[h,c,u,d]=this.#p();return t.set([NaN,NaN,NaN,NaN,(s[0]-n)/a,(s[1]-r)/l,NaN,NaN,NaN,NaN,h,c,NaN,NaN,NaN,NaN,u,d,NaN,NaN,NaN,NaN,(i[0]-n)/a,(i[1]-r)/l],e),e+=24}}class cc extends B{#t;#e=new Float32Array(4);#s;#i;#r;#n;#l;constructor(t,e,s,i,n,r){super(),this.#l=t,this.#r=e,this.#t=s,this.#n=i,this.#s=n,this.#i=r,this.lastPoint=[NaN,NaN],this.#o(r);const[a,l,h,c]=this.#e;for(let u=0,d=t.length;u<d;u+=2)t[u]=(t[u]-a)/h,t[u+1]=(t[u+1]-l)/c;for(let u=0,d=e.length;u<d;u+=2)e[u]=(e[u]-a)/h,e[u+1]=(e[u+1]-l)/c}toSVGPath(){const t=[`M${this.#l[4]} ${this.#l[5]}`];for(let e=6,s=this.#l.length;e<s;e+=6){if(isNaN(this.#l[e])){t.push(`L${this.#l[e+4]} ${this.#l[e+5]}`);continue}t.push(`C${this.#l[e]} ${this.#l[e+1]} ${this.#l[e+2]} ${this.#l[e+3]} ${this.#l[e+4]} ${this.#l[e+5]}`)}return t.push("Z"),t.join(" ")}serialize([t,e,s,i],n){const r=s-t,a=i-e;let l,h;switch(n){case 0:l=B._rescale(this.#l,t,i,r,-a),h=B._rescale(this.#r,t,i,r,-a);break;case 90:l=B._rescaleAndSwap(this.#l,t,e,r,a),h=B._rescaleAndSwap(this.#r,t,e,r,a);break;case 180:l=B._rescale(this.#l,s,e,-r,a),h=B._rescale(this.#r,s,e,-r,a);break;case 270:l=B._rescaleAndSwap(this.#l,s,i,-r,-a),h=B._rescaleAndSwap(this.#r,s,i,-r,-a);break}return{outline:Array.from(l),points:[Array.from(h)]}}#o(t){const e=this.#l;let s=e[4],i=e[5],n=s,r=i,a=s,l=i,h=s,c=i;const u=t?Math.max:Math.min;for(let f=6,g=e.length;f<g;f+=6){if(isNaN(e[f]))n=Math.min(n,e[f+4]),r=Math.min(r,e[f+5]),a=Math.max(a,e[f+4]),l=Math.max(l,e[f+5]),c<e[f+5]?(h=e[f+4],c=e[f+5]):c===e[f+5]&&(h=u(h,e[f+4]));else{const p=z.bezierBoundingBox(s,i,...e.slice(f,f+6));n=Math.min(n,p[0]),r=Math.min(r,p[1]),a=Math.max(a,p[2]),l=Math.max(l,p[3]),c<p[3]?(h=p[2],c=p[3]):c===p[3]&&(h=u(h,p[2]))}s=e[f+4],i=e[f+5]}const d=this.#e;d[0]=n-this.#s,d[1]=r-this.#s,d[2]=a-n+2*this.#s,d[3]=l-r+2*this.#s,this.lastPoint=[h,c]}get box(){return this.#e}newOutliner(t,e,s,i,n,r=0){return new Rs(t,e,s,i,n,r)}getNewOutline(t,e){const[s,i,n,r]=this.#e,[a,l,h,c]=this.#t,u=n*h,d=r*c,f=s*h+a,g=i*c+l,p=this.newOutliner({x:this.#r[0]*u+f,y:this.#r[1]*d+g},this.#t,this.#n,t,this.#i,e??this.#s);for(let v=2;v<this.#r.length;v+=2)p.add({x:this.#r[v]*u+f,y:this.#r[v+1]*d+g});return p.getOutlines()}}class Wa{#t;#e;#s=[];#i=[];constructor(t,e=0,s=0,i=!0){let n=1/0,r=-1/0,a=1/0,l=-1/0;const h=10**-4;for(const{x:v,y:m,width:b,height:_}of t){const w=Math.floor((v-e)/h)*h,C=Math.ceil((v+b+e)/h)*h,T=Math.floor((m-e)/h)*h,E=Math.ceil((m+_+e)/h)*h,k=[w,T,E,!0],O=[C,T,E,!1];this.#s.push(k,O),n=Math.min(n,w),r=Math.max(r,C),a=Math.min(a,T),l=Math.max(l,E)}const c=r-n+2*s,u=l-a+2*s,d=n-s,f=a-s,g=this.#s.at(i?-1:-2),p=[g[0],g[2]];for(const v of this.#s){const[m,b,_]=v;v[0]=(m-d)/c,v[1]=(b-f)/u,v[2]=(_-f)/u}this.#t=new Float32Array([d,f,c,u]),this.#e=p}getOutlines(){this.#s.sort((e,s)=>e[0]-s[0]||e[1]-s[1]||e[2]-s[2]);const t=[];for(const e of this.#s)e[3]?(t.push(...this.#c(e)),this.#l(e)):(this.#o(e),t.push(...this.#c(e)));return this.#r(t)}#r(t){const e=[],s=new Set;for(const r of t){const[a,l,h]=r;e.push([a,l,r],[a,h,r])}e.sort((r,a)=>r[1]-a[1]||r[0]-a[0]);for(let r=0,a=e.length;r<a;r+=2){const l=e[r][2],h=e[r+1][2];l.push(h),h.push(l),s.add(l),s.add(h)}const i=[];let n;for(;s.size>0;){const r=s.values().next().value;let[a,l,h,c,u]=r;s.delete(r);let d=a,f=l;for(n=[a,h],i.push(n);;){let g;if(s.has(c))g=c;else if(s.has(u))g=u;else break;s.delete(g),[a,l,h,c,u]=g,d!==a&&(n.push(d,f,a,f===l?l:h),d=a),f=f===l?h:l}n.push(d,f)}return new bp(i,this.#t,this.#e)}#n(t){const e=this.#i;let s=0,i=e.length-1;for(;s<=i;){const n=s+i>>1,r=e[n][0];if(r===t)return n;r<t?s=n+1:i=n-1}return i+1}#l([,t,e]){const s=this.#n(t);this.#i.splice(s,0,[t,e])}#o([,t,e]){const s=this.#n(t);for(let i=s;i<this.#i.length;i++){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}for(let i=s-1;i>=0;i--){const[n,r]=this.#i[i];if(n!==t)break;if(n===t&&r===e){this.#i.splice(i,1);return}}}#c(t){const[e,s,i]=t,n=[[e,s,i]],r=this.#n(i);for(let a=0;a<r;a++){const[l,h]=this.#i[a];for(let c=0,u=n.length;c<u;c++){const[,d,f]=n[c];if(!(h<=d||f<=l)){if(d>=l){if(f>h)n[c][1]=h;else{if(u===1)return[];n.splice(c,1),c--,u--}continue}n[c][2]=l,f>h&&n.push([e,h,f])}}}return n}}class bp extends B{#t;#e;constructor(t,e,s){super(),this.#e=t,this.#t=e,this.lastPoint=s}toSVGPath(){const t=[];for(const e of this.#e){let[s,i]=e;t.push(`M${s} ${i}`);for(let n=2;n<e.length;n+=2){const r=e[n],a=e[n+1];r===s?(t.push(`V${a}`),i=a):a===i&&(t.push(`H${r}`),s=r)}t.push("Z")}return t.join(" ")}serialize([t,e,s,i],n){const r=[],a=s-t,l=i-e;for(const h of this.#e){const c=new Array(h.length);for(let u=0;u<h.length;u+=2)c[u]=t+h[u]*a,c[u+1]=i-h[u+1]*l;r.push(c)}return r}get box(){return this.#t}get classNamesForOutlining(){return["highlightOutline"]}}class Xa extends Rs{newFreeDrawOutline(t,e,s,i,n,r){return new yp(t,e,s,i,n,r)}}class yp extends cc{newOutliner(t,e,s,i,n,r=0){return new Xa(t,e,s,i,n,r)}}class ye{#t=null;#e=null;#s;#i=null;#r=!1;#n=!1;#l=null;#o;#c=null;#h=null;#d;static#u=null;static get _keyboardManager(){return tt(this,"_keyboardManager",new Li([[["Escape","mac+Escape"],ye.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],ye.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],ye.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],ye.prototype._moveToPrevious],[["Home","mac+Home"],ye.prototype._moveToBeginning],[["End","mac+End"],ye.prototype._moveToEnd]]))}constructor({editor:t=null,uiManager:e=null}){t?(this.#n=!1,this.#d=st.HIGHLIGHT_COLOR,this.#l=t):(this.#n=!0,this.#d=st.HIGHLIGHT_DEFAULT_COLOR),this.#h=t?._uiManager||e,this.#o=this.#h._eventBus,this.#s=t?.color||this.#h?.highlightColors.values().next().value||"#FFFF98",ye.#u||=Object.freeze({blue:"pdfjs-editor-colorpicker-blue",green:"pdfjs-editor-colorpicker-green",pink:"pdfjs-editor-colorpicker-pink",red:"pdfjs-editor-colorpicker-red",yellow:"pdfjs-editor-colorpicker-yellow"})}renderButton(){const t=this.#t=document.createElement("button");t.className="colorPicker",t.tabIndex="0",t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),t.setAttribute("aria-haspopup",!0);const e=this.#h._signal;t.addEventListener("click",this.#m.bind(this),{signal:e}),t.addEventListener("keydown",this.#g.bind(this),{signal:e});const s=this.#e=document.createElement("span");return s.className="swatch",s.setAttribute("aria-hidden",!0),s.style.backgroundColor=this.#s,t.append(s),t}renderMainDropdown(){const t=this.#i=this.#f();return t.setAttribute("aria-orientation","horizontal"),t.setAttribute("aria-labelledby","highlightColorPickerLabel"),t}#f(){const t=document.createElement("div"),e=this.#h._signal;t.addEventListener("contextmenu",Oe,{signal:e}),t.className="dropdown",t.role="listbox",t.setAttribute("aria-multiselectable",!1),t.setAttribute("aria-orientation","vertical"),t.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(const[s,i]of this.#h.highlightColors){const n=document.createElement("button");n.tabIndex="0",n.role="option",n.setAttribute("data-color",i),n.title=s,n.setAttribute("data-l10n-id",ye.#u[s]);const r=document.createElement("span");n.append(r),r.className="swatch",r.style.backgroundColor=i,n.setAttribute("aria-selected",i===this.#s),n.addEventListener("click",this.#a.bind(this,i),{signal:e}),t.append(n)}return t.addEventListener("keydown",this.#g.bind(this),{signal:e}),t}#a(t,e){e.stopPropagation(),this.#o.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:t})}_colorSelectFromKeyboard(t){if(t.target===this.#t){this.#m(t);return}const e=t.target.getAttribute("data-color");e&&this.#a(e,t)}_moveToNext(t){if(!this.#v){this.#m(t);return}if(t.target===this.#t){this.#i.firstChild?.focus();return}t.target.nextSibling?.focus()}_moveToPrevious(t){if(t.target===this.#i?.firstChild||t.target===this.#t){this.#v&&this._hideDropdownFromKeyboard();return}this.#v||this.#m(t),t.target.previousSibling?.focus()}_moveToBeginning(t){if(!this.#v){this.#m(t);return}this.#i.firstChild?.focus()}_moveToEnd(t){if(!this.#v){this.#m(t);return}this.#i.lastChild?.focus()}#g(t){ye._keyboardManager.exec(this,t)}#m(t){if(this.#v){this.hideDropdown();return}if(this.#r=t.detail===0,this.#c||(this.#c=new AbortController,window.addEventListener("pointerdown",this.#p.bind(this),{signal:this.#h.combinedSignal(this.#c)})),this.#i){this.#i.classList.remove("hidden");return}const e=this.#i=this.#f();this.#t.append(e)}#p(t){this.#i?.contains(t.target)||this.hideDropdown()}hideDropdown(){this.#i?.classList.add("hidden"),this.#c?.abort(),this.#c=null}get#v(){return this.#i&&!this.#i.classList.contains("hidden")}_hideDropdownFromKeyboard(){if(!this.#n){if(!this.#v){this.#l?.unselect();return}this.hideDropdown(),this.#t.focus({preventScroll:!0,focusVisible:this.#r})}}updateColor(t){if(this.#e&&(this.#e.style.backgroundColor=t),!this.#i)return;const e=this.#h.highlightColors.values();for(const s of this.#i.children)s.setAttribute("aria-selected",e.next().value===t)}destroy(){this.#t?.remove(),this.#t=null,this.#e=null,this.#i?.remove(),this.#i=null}}class At extends G{#t=null;#e=0;#s;#i=null;#r=null;#n=null;#l=null;#o=0;#c=null;#h=null;#d=null;#u=!1;#f=null;#a;#g=null;#m="";#p;#v="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _type="highlight";static _editorType=J.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){const t=At.prototype;return tt(this,"_keyboardManager",new Li([[["ArrowLeft","mac+ArrowLeft"],t._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],t._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],t._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],t._moveCaret,{args:[3]}]]))}constructor(t){super({...t,name:"highlightEditor"}),this.color=t.color||At._defaultColor,this.#p=t.thickness||At._defaultThickness,this.#a=t.opacity||At._defaultOpacity,this.#s=t.boxes||null,this.#v=t.methodOfCreation||"",this.#m=t.text||"",this._isDraggable=!1,t.highlightId>-1?(this.#u=!0,this.#b(t),this.#P()):this.#s&&(this.#t=t.anchorNode,this.#e=t.anchorOffset,this.#l=t.focusNode,this.#o=t.focusOffset,this.#_(),this.#P(),this.rotate(this.rotation))}get telemetryInitialData(){return{action:"added",type:this.#u?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:this.#p,methodOfCreation:this.#v}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(t){return{numberOfColors:t.get("color").size}}#_(){const t=new Wa(this.#s,.001);this.#h=t.getOutlines(),[this.x,this.y,this.width,this.height]=this.#h.box;const e=new Wa(this.#s,.0025,.001,this._uiManager.direction==="ltr");this.#n=e.getOutlines();const{lastPoint:s}=this.#n;this.#f=[(s[0]-this.x)/this.width,(s[1]-this.y)/this.height]}#b({highlightOutlines:t,highlightId:e,clipPathId:s}){this.#h=t;const i=1.5;if(this.#n=t.getNewOutline(this.#p/2+i,.0025),e>=0)this.#d=e,this.#i=s,this.parent.drawLayer.finalizeDraw(e,{bbox:t.box,path:{d:t.toSVGPath()}}),this.#g=this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},!0);else if(this.parent){const c=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(this.#d,{bbox:At.#x(this.#h.box,(c-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(this.#g,{bbox:At.#x(this.#n.box,c),path:{d:this.#n.toSVGPath()}})}const[n,r,a,l]=t.box;switch(this.rotation){case 0:this.x=n,this.y=r,this.width=a,this.height=l;break;case 90:{const[c,u]=this.parentDimensions;this.x=r,this.y=1-n,this.width=a*u/c,this.height=l*c/u;break}case 180:this.x=1-n,this.y=1-r,this.width=a,this.height=l;break;case 270:{const[c,u]=this.parentDimensions;this.x=1-r,this.y=n,this.width=a*u/c,this.height=l*c/u;break}}const{lastPoint:h}=this.#n;this.#f=[(h[0]-n)/a,(h[1]-r)/l]}static initialize(t,e){G.initialize(t,e),At._defaultColor||=e.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(t,e){switch(t){case st.HIGHLIGHT_DEFAULT_COLOR:At._defaultColor=e;break;case st.HIGHLIGHT_THICKNESS:At._defaultThickness=e;break}}translateInPage(t,e){}get toolbarPosition(){return this.#f}updateParams(t,e){switch(t){case st.HIGHLIGHT_COLOR:this.#w(e);break;case st.HIGHLIGHT_THICKNESS:this.#S(e);break}}static get defaultPropertiesToUpdate(){return[[st.HIGHLIGHT_DEFAULT_COLOR,At._defaultColor],[st.HIGHLIGHT_THICKNESS,At._defaultThickness]]}get propertiesToUpdate(){return[[st.HIGHLIGHT_COLOR,this.color||At._defaultColor],[st.HIGHLIGHT_THICKNESS,this.#p||At._defaultThickness],[st.HIGHLIGHT_FREE,this.#u]]}#w(t){const e=(n,r)=>{this.color=n,this.#a=r,this.parent?.drawLayer.updateProperties(this.#d,{root:{fill:n,"fill-opacity":r}}),this.#r?.updateColor(n)},s=this.color,i=this.#a;this.addCommands({cmd:e.bind(this,t,At._defaultOpacity),undo:e.bind(this,s,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(t)},!0)}#S(t){const e=this.#p,s=i=>{this.#p=i,this.#A(i)};this.addCommands({cmd:s.bind(this,t),undo:s.bind(this,e),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:st.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)}async addEditToolbar(){const t=await super.addEditToolbar();return t?(this._uiManager.highlightColors&&(this.#r=new ye({editor:this}),t.addColorPicker(this.#r)),t):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(this.#O())}getBaseTranslation(){return[0,0]}getRect(t,e){return super.getRect(t,e,this.#O())}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){this.#E(),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#P(),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?this.#E():t&&(this.#P(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),this.show(this._isVisible),e&&this.select()}#A(t){if(!this.#u)return;this.#b({highlightOutlines:this.#h.getNewOutline(t/2)}),this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}#E(){this.#d===null||!this.parent||(this.parent.drawLayer.remove(this.#d),this.#d=null,this.parent.drawLayer.remove(this.#g),this.#g=null)}#P(t=this.parent){this.#d===null&&({id:this.#d,clipPathId:this.#i}=t.drawLayer.draw({bbox:this.#h.box,root:{viewBox:"0 0 1 1",fill:this.color,"fill-opacity":this.#a},rootClass:{highlight:!0,free:this.#u},path:{d:this.#h.toSVGPath()}},!1,!0),this.#g=t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:this.#u},bbox:this.#n.box,path:{d:this.#n.toSVGPath()}},this.#u),this.#c&&(this.#c.style.clipPath=this.#i))}static#x([t,e,s,i],n){switch(n){case 90:return[1-e-i,t,i,s];case 180:return[1-t-s,1-e-i,s,i];case 270:return[e,1-t-s,i,s]}return[t,e,s,i]}rotate(t){const{drawLayer:e}=this.parent;let s;this.#u?(t=(t-this.rotation+360)%360,s=At.#x(this.#h.box,t)):s=At.#x([this.x,this.y,this.width,this.height],t),e.updateProperties(this.#d,{bbox:s,root:{"data-main-rotation":t}}),e.updateProperties(this.#g,{bbox:At.#x(this.#n.box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();this.#m&&(t.setAttribute("aria-label",this.#m),t.setAttribute("role","mark")),this.#u?t.classList.add("free"):this.div.addEventListener("keydown",this.#k.bind(this),{signal:this._uiManager._signal});const e=this.#c=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal",e.style.clipPath=this.#i;const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),tr(this,this.#c,["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!0}})}pointerleave(){this.isSelected||this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1}})}#k(t){At._keyboardManager.exec(this,t)}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:this.#T(!0);break;case 1:case 3:this.#T(!1);break}}#T(t){if(!this.#t)return;const e=window.getSelection();t?e.setPosition(this.#t,this.#e):e.setPosition(this.#l,this.#o)}select(){super.select(),this.#g&&this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{hovered:!1,selected:!0}})}unselect(){super.unselect(),this.#g&&(this.parent?.drawLayer.updateProperties(this.#g,{rootClass:{selected:!1}}),this.#u||this.#T(!1))}get _mustFixPosition(){return!this.#u}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(this.#d,{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(this.#g,{rootClass:{hidden:!t}}))}#O(){return this.#u?this.rotation:0}#F(){if(this.#u)return null;const[t,e]=this.pageDimensions,[s,i]=this.pageTranslation,n=this.#s,r=new Float32Array(n.length*8);let a=0;for(const{x:l,y:h,width:c,height:u}of n){const d=l*t+s,f=(1-h)*e+i;r[a]=r[a+4]=d,r[a+1]=r[a+3]=f,r[a+2]=r[a+6]=d+c*t,r[a+5]=r[a+7]=f-u*e,a+=8}return r}#I(t){return this.#h.serialize(t,this.#O())}static startHighlighting(t,e,{target:s,x:i,y:n}){const{x:r,y:a,width:l,height:h}=s.getBoundingClientRect(),c=new AbortController,u=t.combinedSignal(c),d=f=>{c.abort(),this.#y(t,f)};window.addEventListener("blur",d,{signal:u}),window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("pointerdown",ge,{capture:!0,passive:!1,signal:u}),window.addEventListener("contextmenu",Oe,{signal:u}),s.addEventListener("pointermove",this.#C.bind(this,t),{signal:u}),this._freeHighlight=new Xa({x:i,y:n},[r,a,l,h],t.scale,this._defaultThickness/2,e,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=t.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:this._defaultColor,"fill-opacity":this._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:this._freeHighlight.toSVGPath()}},!0,!0)}static#C(t,e){this._freeHighlight.add(e)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})}static#y(t,e){this._freeHighlight.isEmpty()?t.drawLayer.remove(this._freeHighlightId):t.createAndAddNewEditor(e,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""}static async deserialize(t,e,s){let i=null;if(t instanceof lc){const{data:{quadPoints:g,rect:p,rotation:v,id:m,color:b,opacity:_,popupRef:w},parent:{page:{pageNumber:C}}}=t;i=t={annotationType:J.HIGHLIGHT,color:Array.from(b),opacity:_,quadPoints:g,boxes:null,pageIndex:C-1,rect:p.slice(0),rotation:v,id:m,deleted:!1,popupRef:w}}else if(t instanceof Ga){const{data:{inkLists:g,rect:p,rotation:v,id:m,color:b,borderStyle:{rawWidth:_},popupRef:w},parent:{page:{pageNumber:C}}}=t;i=t={annotationType:J.HIGHLIGHT,color:Array.from(b),thickness:_,inkLists:g,boxes:null,pageIndex:C-1,rect:p.slice(0),rotation:v,id:m,deleted:!1,popupRef:w}}const{color:n,quadPoints:r,inkLists:a,opacity:l}=t,h=await super.deserialize(t,e,s);h.color=z.makeHexColor(...n),h.#a=l||1,a&&(h.#p=t.thickness),h.annotationElementId=t.id||null,h._initialData=i;const[c,u]=h.pageDimensions,[d,f]=h.pageTranslation;if(r){const g=h.#s=[];for(let p=0;p<r.length;p+=8)g.push({x:(r[p]-d)/c,y:1-(r[p+1]-f)/u,width:(r[p+2]-r[p])/c,height:(r[p+1]-r[p+5])/u});h.#_(),h.#P(),h.rotate(h.rotation)}else if(a){h.#u=!0;const g=a[0],p={x:g[0]-d,y:u-(g[1]-f)},v=new Xa(p,[0,0,c,u],1,h.#p/2,!0,.001);for(let _=0,w=g.length;_<w;_+=2)p.x=g[_]-d,p.y=u-(g[_+1]-f),v.add(p);const{id:m,clipPathId:b}=e.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:h.color,"fill-opacity":h._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:v.toSVGPath()}},!0,!0);h.#b({highlightOutlines:v.getOutlines(),highlightId:m,clipPathId:b}),h.#P()}return h}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const e=this.getRect(0,0),s=G._colorManager.convert(this.color),i={annotationType:J.HIGHLIGHT,color:s,opacity:this.#a,thickness:this.#p,quadPoints:this.#F(),outlines:this.#I(e),pageIndex:this.pageIndex,rect:e,rotation:this.#O(),structTreeParentId:this._structTreeParentId};return this.annotationElementId&&!this.#R(i)?null:(i.id=this.annotationElementId,i)}#R(t){const{color:e}=this._initialData;return t.color.some((s,i)=>s!==e[i])}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class _p{#t=Object.create(null);updateProperty(t,e){this[t]=e,this.updateSVGProperty(t,e)}updateProperties(t){if(t)for(const[e,s]of Object.entries(t))this.updateProperty(e,s)}updateSVGProperty(t,e){this.#t[t]=e}toSVGProperties(){const t=this.#t;return this.#t=Object.create(null),{root:t}}reset(){this.#t=Object.create(null)}updateAll(t=this){this.updateProperties(t)}clone(){ut("Not implemented")}}class W extends G{#t=null;#e;_drawId=null;static _currentDrawId=-1;static _currentParent=null;static#s=null;static#i=null;static#r=null;static#n=NaN;static#l=null;static#o=null;static#c=NaN;static _INNER_MARGIN=3;constructor(t){super(t),this.#e=t.mustBeCommitted||!1,t.drawOutlines&&(this.#h(t),this.#f())}#h({drawOutlines:t,drawId:e,drawingOptions:s}){this.#t=t,this._drawingOptions||=s,e>=0?(this._drawId=e,this.parent.drawLayer.finalizeDraw(e,t.defaultProperties)):this._drawId=this.#d(t,this.parent),this.#m(t.box)}#d(t,e){const{id:s}=e.drawLayer.draw(W._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return s}static _mergeSVGProperties(t,e){const s=new Set(Object.keys(t));for(const[i,n]of Object.entries(e))s.has(i)?Object.assign(t[i],n):t[i]=n;return t}static getDefaultDrawingOptions(t){ut("Not implemented")}static get typesMap(){ut("Not implemented")}static get isDrawer(){return!0}static get supportMultipleDrawings(){return!1}static updateDefaultParams(t,e){const s=this.typesMap.get(t);s&&this._defaultDrawingOptions.updateProperty(s,e),this._currentParent&&(W.#s.updateProperty(s,e),this._currentParent.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}updateParams(t,e){const s=this.constructor.typesMap.get(t);s&&this._updateProperty(t,s,e)}static get defaultPropertiesToUpdate(){const t=[],e=this._defaultDrawingOptions;for(const[s,i]of this.typesMap)t.push([s,e[i]]);return t}get propertiesToUpdate(){const t=[],{_drawingOptions:e}=this;for(const[s,i]of this.constructor.typesMap)t.push([s,e[i]]);return t}_updateProperty(t,e,s){const i=this._drawingOptions,n=i[e],r=a=>{i.updateProperty(e,a);const l=this.#t.updateProperty(e,a);l&&this.#m(l),this.parent?.drawLayer.updateProperties(this._drawId,i.toSVGProperties())};this.addCommands({cmd:r.bind(this,s),undo:r.bind(this,n),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:t,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){this.parent?.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties(this.#t.getPathResizingSVGProperties(this.#g()),{bbox:this.#p()}))}_onResized(){this.parent?.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties(this.#t.getPathResizedSVGProperties(this.#g()),{bbox:this.#p()}))}_onTranslating(t,e){this.parent?.drawLayer.updateProperties(this._drawId,{bbox:this.#p(t,e)})}_onTranslated(){this.parent?.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties(this.#t.getPathTranslatedSVGProperties(this.#g(),this.parentDimensions),{bbox:this.#p()}))}_onStartDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!0}})}_onStopDragging(){this.parent?.drawLayer.updateProperties(this._drawId,{rootClass:{moving:!1}})}commit(){super.commit(),this.disableEditMode(),this.disableEditing()}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}getBaseTranslation(){return[0,0]}get isResizable(){return!0}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),this._isDraggable=!0,this.#e&&(this.#e=!1,this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){this.#u(),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.#f(),this.#m(this.#t.box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){let e=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),this.#u()):t&&(this._uiManager.addShouldRescale(this),this.#f(t),e=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(t),e&&this.select()}#u(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())}#f(t=this.parent){if(!(this._drawId!==null&&this.parent===t)){if(this._drawId!==null){this.parent.drawLayer.updateParent(this._drawId,t.drawLayer);return}this._drawingOptions.updateAll(),this._drawId=this.#d(this.#t,t)}}#a([t,e,s,i]){const{parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[e,1-t,s*(r/n),i*(n/r)];case 180:return[1-t,1-e,s,i];case 270:return[1-e,t,s*(r/n),i*(n/r)];default:return[t,e,s,i]}}#g(){const{x:t,y:e,width:s,height:i,parentDimensions:[n,r],rotation:a}=this;switch(a){case 90:return[1-e,t,s*(n/r),i*(r/n)];case 180:return[1-t,1-e,s,i];case 270:return[e,1-t,s*(n/r),i*(r/n)];default:return[t,e,s,i]}}#m(t){if([this.x,this.y,this.width,this.height]=this.#a(t),this.div){this.fixAndSetPosition();const[e,s]=this.parentDimensions;this.setDims(this.width*e,this.height*s)}this._onResized()}#p(){const{x:t,y:e,width:s,height:i,rotation:n,parentRotation:r,parentDimensions:[a,l]}=this;switch((n*4+r)/90){case 1:return[1-e-i,t,i,s];case 2:return[1-t-s,1-e-i,s,i];case 3:return[e,1-t-s,i,s];case 4:return[t,e-s*(a/l),i*(l/a),s*(a/l)];case 5:return[1-e,t,s*(a/l),i*(l/a)];case 6:return[1-t-i*(l/a),1-e,i*(l/a),s*(a/l)];case 7:return[e-s*(a/l),1-t-i*(l/a),s*(a/l),i*(l/a)];case 8:return[t-s,e-i,s,i];case 9:return[1-e,t-s,i,s];case 10:return[1-t,1-e,s,i];case 11:return[e-i,1-t,i,s];case 12:return[t-i*(l/a),e,i*(l/a),s*(a/l)];case 13:return[1-e-s*(a/l),t-i*(l/a),s*(a/l),i*(l/a)];case 14:return[1-t,1-e-s*(a/l),i*(l/a),s*(a/l)];case 15:return[e,1-t,s*(a/l),i*(l/a)];default:return[t,e,s,i]}}rotate(){this.parent&&this.parent.drawLayer.updateProperties(this._drawId,W._mergeSVGProperties({bbox:this.#p()},this.#t.updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&this.#m(this.#t.updateParentDimensions(this.parentDimensions,this.parent.scale))}static onScaleChangingWhenDrawing(){}render(){if(this.div)return this.div;const t=super.render();t.classList.add("draw");const e=document.createElement("div");t.append(e),e.setAttribute("aria-hidden","true"),e.className="internal";const[s,i]=this.parentDimensions;return this.setDims(this.width*s,this.height*i),this._uiManager.addShouldRescale(this),this.disableEditing(),t}static createDrawerInstance(t,e,s,i,n){ut("Not implemented")}static startDrawing(t,e,s,i){const{target:n,offsetX:r,offsetY:a,pointerId:l,pointerType:h}=i;if(W.#l&&W.#l!==h)return;const{viewport:{rotation:c}}=t,{width:u,height:d}=n.getBoundingClientRect(),f=W.#i=new AbortController,g=t.combinedSignal(f);if(W.#n||=l,W.#l??=h,window.addEventListener("pointerup",p=>{W.#n===p.pointerId?this._endDraw(p):W.#o?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointercancel",p=>{W.#n===p.pointerId?this._currentParent.endDrawingSession():W.#o?.delete(p.pointerId)},{signal:g}),window.addEventListener("pointerdown",p=>{W.#l===p.pointerType&&((W.#o||=new Set).add(p.pointerId),W.#s.isCancellable()&&(W.#s.removeLastElement(),W.#s.isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:g}),window.addEventListener("contextmenu",Oe,{signal:g}),n.addEventListener("pointermove",this._drawMove.bind(this),{signal:g}),n.addEventListener("touchmove",p=>{p.timeStamp===W.#c&&ge(p)},{signal:g}),t.toggleDrawing(),e._editorUndoBar?.hide(),W.#s){t.drawLayer.updateProperties(this._currentDrawId,W.#s.startNew(r,a,u,d,c));return}e.updateUIForDefaultProperties(this),W.#s=this.createDrawerInstance(r,a,u,d,c),W.#r=this.getDefaultDrawingOptions(),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(W.#r.toSVGProperties(),W.#s.defaultSVGProperties),!0,!1)}static _drawMove(t){if(W.#c=-1,!W.#s)return;const{offsetX:e,offsetY:s,pointerId:i}=t;if(W.#n===i){if(W.#o?.size>=1){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,W.#s.add(e,s)),W.#c=t.timeStamp,ge(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,W.#s=null,W.#r=null,W.#l=null,W.#c=NaN),W.#i&&(W.#i.abort(),W.#i=null,W.#n=NaN,W.#o=null)}static _endDraw(t){const e=this._currentParent;if(e){if(e.toggleDrawing(!0),this._cleanup(!1),t&&e.drawLayer.updateProperties(this._currentDrawId,W.#s.end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const s=W.#s,i=this._currentDrawId,n=s.getLastElement();e.addCommands({cmd:()=>{e.drawLayer.updateProperties(i,s.setLastElement(n))},undo:()=>{e.drawLayer.updateProperties(i,s.removeLastElement())},mustExec:!1,type:st.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const e=this._currentParent;if(!e)return null;if(e.toggleDrawing(!0),e.cleanUndoStack(st.DRAW_STEP),!W.#s.isEmpty()){const{pageDimensions:[s,i],scale:n}=e,r=e.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:W.#s.getOutlines(s*n,i*n,n,this._INNER_MARGIN),drawingOptions:W.#r,mustBeCommitted:!t});return this._cleanup(!0),r}return e.drawLayer.remove(this._currentDrawId),this._cleanup(!0),null}createDrawingOptions(t){}static deserializeDraw(t,e,s,i,n,r){ut("Not implemented")}static async deserialize(t,e,s){const{rawDims:{pageWidth:i,pageHeight:n,pageX:r,pageY:a}}=e.viewport,l=this.deserializeDraw(r,a,i,n,this._INNER_MARGIN,t),h=await super.deserialize(t,e,s);return h.createDrawingOptions(t),h.#h({drawOutlines:l}),h.#f(),h.onScaleChanging(),h.rotate(),h}serializeDraw(t){const[e,s]=this.pageTranslation,[i,n]=this.pageDimensions;return this.#t.serialize([e,s,i,n],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}static canCreateNewEmptyEditor(){return!1}}class wp{#t=new Float64Array(6);#e;#s;#i;#r;#n;#l="";#o=0;#c=new lr;#h;#d;constructor(t,e,s,i,n,r){this.#h=s,this.#d=i,this.#i=n,this.#r=r,[t,e]=this.#u(t,e);const a=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e],this.#s=[{line:a,points:this.#n}],this.#t.set(a,0)}updateProperty(t,e){t==="stroke-width"&&(this.#r=e)}#u(t,e){return B._normalizePoint(t,e,this.#h,this.#d,this.#i)}isEmpty(){return!this.#s||this.#s.length===0}isCancellable(){return this.#n.length<=10}add(t,e){[t,e]=this.#u(t,e);const[s,i,n,r]=this.#t.subarray(2,6),a=t-n,l=e-r;return Math.hypot(this.#h*a,this.#d*l)<=2?null:(this.#n.push(t,e),isNaN(s)?(this.#t.set([n,r,t,e],2),this.#e.push(NaN,NaN,NaN,NaN,t,e),{path:{d:this.toSVGPath()}}):(isNaN(this.#t[0])&&this.#e.splice(6,6),this.#t.set([s,i,n,r,t,e],0),this.#e.push(...B.createBezierPoints(s,i,n,r,t,e)),{path:{d:this.toSVGPath()}}))}end(t,e){const s=this.add(t,e);return s||(this.#n.length===2?{path:{d:this.toSVGPath()}}:null)}startNew(t,e,s,i,n){this.#h=s,this.#d=i,this.#i=n,[t,e]=this.#u(t,e);const r=this.#e=[NaN,NaN,NaN,NaN,t,e];this.#n=[t,e];const a=this.#s.at(-1);return a&&(a.line=new Float32Array(a.line),a.points=new Float32Array(a.points)),this.#s.push({line:r,points:this.#n}),this.#t.set(r,0),this.#o=0,this.toSVGPath(),null}getLastElement(){return this.#s.at(-1)}setLastElement(t){return this.#s?(this.#s.push(t),this.#e=t.line,this.#n=t.points,this.#o=0,{path:{d:this.toSVGPath()}}):this.#c.setLastElement(t)}removeLastElement(){if(!this.#s)return this.#c.removeLastElement();this.#s.pop(),this.#l="";for(let t=0,e=this.#s.length;t<e;t++){const{line:s,points:i}=this.#s[t];this.#e=s,this.#n=i,this.#o=0,this.toSVGPath()}return{path:{d:this.#l}}}toSVGPath(){const t=B.svgRound(this.#e[4]),e=B.svgRound(this.#e[5]);if(this.#n.length===2)return this.#l=`${this.#l} M ${t} ${e} Z`,this.#l;if(this.#n.length<=6){const i=this.#l.lastIndexOf("M");this.#l=`${this.#l.slice(0,i)} M ${t} ${e}`,this.#o=6}if(this.#n.length===4){const i=B.svgRound(this.#e[10]),n=B.svgRound(this.#e[11]);return this.#l=`${this.#l} L ${i} ${n}`,this.#o=12,this.#l}const s=[];this.#o===0&&(s.push(`M ${t} ${e}`),this.#o=6);for(let i=this.#o,n=this.#e.length;i<n;i+=6){const[r,a,l,h,c,u]=this.#e.slice(i,i+6).map(B.svgRound);s.push(`C${r} ${a} ${l} ${h} ${c} ${u}`)}return this.#l+=s.join(" "),this.#o=this.#e.length,this.#l}getOutlines(t,e,s,i){const n=this.#s.at(-1);return n.line=new Float32Array(n.line),n.points=new Float32Array(n.points),this.#c.build(this.#s,t,e,s,this.#i,this.#r,i),this.#t=null,this.#e=null,this.#s=null,this.#l=null,this.#c}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}class lr extends B{#t;#e=0;#s;#i;#r;#n;#l;#o;#c;build(t,e,s,i,n,r,a){this.#r=e,this.#n=s,this.#l=i,this.#o=n,this.#c=r,this.#s=a??0,this.#i=t,this.#u()}setLastElement(t){return this.#i.push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return this.#i.pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:e}of this.#i){if(t.push(`M${B.svgRound(e[4])} ${B.svgRound(e[5])}`),e.length===6){t.push("Z");continue}if(e.length===12){t.push(`L${B.svgRound(e[10])} ${B.svgRound(e[11])}`);continue}for(let s=6,i=e.length;s<i;s+=6){const[n,r,a,l,h,c]=e.subarray(s,s+6).map(B.svgRound);t.push(`C${n} ${r} ${a} ${l} ${h} ${c}`)}}return t.join("")}serialize([t,e,s,i],n){const r=[],a=[],[l,h,c,u]=this.#d();let d,f,g,p,v,m,b,_,w;switch(this.#o){case 0:w=B._rescale,d=t,f=e+i,g=s,p=-i,v=t+l*s,m=e+(1-h-u)*i,b=t+(l+c)*s,_=e+(1-h)*i;break;case 90:w=B._rescaleAndSwap,d=t,f=e,g=s,p=i,v=t+h*s,m=e+l*i,b=t+(h+u)*s,_=e+(l+c)*i;break;case 180:w=B._rescale,d=t+s,f=e,g=-s,p=i,v=t+(1-l-c)*s,m=e+h*i,b=t+(1-l)*s,_=e+(h+u)*i;break;case 270:w=B._rescaleAndSwap,d=t+s,f=e+i,g=-s,p=-i,v=t+(1-h-u)*s,m=e+(1-l-c)*i,b=t+(1-h)*s,_=e+(1-l)*i;break}for(const{line:C,points:T}of this.#i)r.push(w(C,d,f,g,p,n?new Array(C.length):null)),a.push(w(T,d,f,g,p,n?new Array(T.length):null));return{lines:r,points:a,rect:[v,m,b,_]}}static deserialize(t,e,s,i,n,{paths:{lines:r,points:a},rotation:l,thickness:h}){const c=[];let u,d,f,g,p;switch(l){case 0:p=B._rescale,u=-t/s,d=e/i+1,f=1/s,g=-1/i;break;case 90:p=B._rescaleAndSwap,u=-e/i,d=-t/s,f=1/i,g=1/s;break;case 180:p=B._rescale,u=t/s+1,d=-e/i,f=-1/s,g=1/i;break;case 270:p=B._rescaleAndSwap,u=e/i+1,d=t/s+1,f=-1/i,g=-1/s;break}if(!r){r=[];for(const m of a){const b=m.length;if(b===2){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1]]));continue}if(b===4){r.push(new Float32Array([NaN,NaN,NaN,NaN,m[0],m[1],NaN,NaN,NaN,NaN,m[2],m[3]]));continue}const _=new Float32Array(3*(b-2));r.push(_);let[w,C,T,E]=m.subarray(0,4);_.set([NaN,NaN,NaN,NaN,w,C],0);for(let k=4;k<b;k+=2){const O=m[k],H=m[k+1];_.set(B.createBezierPoints(w,C,T,E,O,H),(k-2)*3),[w,C,T,E]=[T,E,O,H]}}}for(let m=0,b=r.length;m<b;m++)c.push({line:p(r[m].map(_=>_??NaN),u,d,f,g),points:p(a[m].map(_=>_??NaN),u,d,f,g)});const v=new lr;return v.build(c,s,i,1,l,h,n),v}#h(t=this.#c){const e=this.#s+t/2*this.#l;return this.#o%180===0?[e/this.#r,e/this.#n]:[e/this.#n,e/this.#r]}#d(){const[t,e,s,i]=this.#t,[n,r]=this.#h(0);return[t+n,e+r,s-2*n,i-2*r]}#u(){const t=this.#t=new Float32Array([1/0,1/0,-1/0,-1/0]);for(const{line:i}of this.#i){if(i.length<=12){for(let a=4,l=i.length;a<l;a+=6){const[h,c]=i.subarray(a,a+2);t[0]=Math.min(t[0],h),t[1]=Math.min(t[1],c),t[2]=Math.max(t[2],h),t[3]=Math.max(t[3],c)}continue}let n=i[4],r=i[5];for(let a=6,l=i.length;a<l;a+=6){const[h,c,u,d,f,g]=i.subarray(a,a+6);z.bezierBoundingBox(n,r,h,c,u,d,f,g,t),n=f,r=g}}const[e,s]=this.#h();t[0]=Math.min(1,Math.max(0,t[0]-e)),t[1]=Math.min(1,Math.max(0,t[1]-s)),t[2]=Math.min(1,Math.max(0,t[2]+e)),t[3]=Math.min(1,Math.max(0,t[3]+s)),t[2]-=t[0],t[3]-=t[1]}get box(){return this.#t}updateProperty(t,e){return t==="stroke-width"?this.#f(e):null}#f(t){const[e,s]=this.#h();this.#c=t;const[i,n]=this.#h(),[r,a]=[i-e,n-s],l=this.#t;return l[0]-=r,l[1]-=a,l[2]+=2*r,l[3]+=2*a,l}updateParentDimensions([t,e],s){const[i,n]=this.#h();this.#r=t,this.#n=e,this.#l=s;const[r,a]=this.#h(),l=r-i,h=a-n,c=this.#t;return c[0]-=l,c[1]-=h,c[2]+=2*l,c[3]+=2*h,c}updateRotation(t){return this.#e=t,{path:{transform:this.rotationTransform}}}get viewBox(){return this.#t.map(B.svgRound).join(" ")}get defaultProperties(){const[t,e]=this.#t;return{root:{viewBox:this.viewBox},path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`}}}get rotationTransform(){const[,,t,e]=this.#t;let s=0,i=0,n=0,r=0,a=0,l=0;switch(this.#e){case 90:i=e/t,n=-t/e,a=t;break;case 180:s=-1,r=-1,a=t,l=e;break;case 270:i=-e/t,n=t/e,l=e;break;default:return""}return`matrix(${s} ${i} ${n} ${r} ${B.svgRound(a)} ${B.svgRound(l)})`}getPathResizingSVGProperties([t,e,s,i]){const[n,r]=this.#h(),[a,l,h,c]=this.#t;if(Math.abs(h-n)<=B.PRECISION||Math.abs(c-r)<=B.PRECISION){const p=t+s/2-(a+h/2),v=e+i/2-(l+c/2);return{path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`,transform:`${this.rotationTransform} translate(${p} ${v})`}}}const u=(s-2*n)/(h-2*n),d=(i-2*r)/(c-2*r),f=h/s,g=c/i;return{path:{"transform-origin":`${B.svgRound(a)} ${B.svgRound(l)}`,transform:`${this.rotationTransform} scale(${f} ${g}) translate(${B.svgRound(n)} ${B.svgRound(r)}) scale(${u} ${d}) translate(${B.svgRound(-n)} ${B.svgRound(-r)})`}}}getPathResizedSVGProperties([t,e,s,i]){const[n,r]=this.#h(),a=this.#t,[l,h,c,u]=a;if(a[0]=t,a[1]=e,a[2]=s,a[3]=i,Math.abs(c-n)<=B.PRECISION||Math.abs(u-r)<=B.PRECISION){const v=t+s/2-(l+c/2),m=e+i/2-(h+u/2);for(const{line:b,points:_}of this.#i)B._translate(b,v,m,b),B._translate(_,v,m,_);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const d=(s-2*n)/(c-2*n),f=(i-2*r)/(u-2*r),g=-d*(l+n)+t+n,p=-f*(h+r)+e+r;if(d!==1||f!==1||g!==0||p!==0)for(const{line:v,points:m}of this.#i)B._rescale(v,g,p,d,f,v),B._rescale(m,g,p,d,f,m);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,e],s){const[i,n]=s,r=this.#t,a=t-r[0],l=e-r[1];if(this.#r===i&&this.#n===n)for(const{line:h,points:c}of this.#i)B._translate(h,a,l,h),B._translate(c,a,l,c);else{const h=this.#r/i,c=this.#n/n;this.#r=i,this.#n=n;for(const{line:u,points:d}of this.#i)B._rescale(u,a,l,h,c,u),B._rescale(d,a,l,h,c,d);r[2]*=h,r[3]*=c}return r[0]=t,r[1]=e,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${B.svgRound(t)} ${B.svgRound(e)}`}}}get defaultSVGProperties(){const t=this.#t;return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${B.svgRound(t[0])} ${B.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}class Ua extends _p{#t;constructor(t){super(),this.#t=t,super.updateProperties({fill:"none",stroke:G._defaultLineColor,"stroke-opacity":1,"stroke-width":1,"stroke-linecap":"round","stroke-linejoin":"round","stroke-miterlimit":10})}updateSVGProperty(t,e){t==="stroke-width"&&(e??=this["stroke-width"],e*=this.#t.realScale),super.updateSVGProperty(t,e)}clone(){const t=new Ua(this.#t);return t.updateAll(this),t}}class Ya extends W{static _type="ink";static _editorType=J.INK;static _defaultDrawingOptions=null;constructor(t){super({...t,name:"inkEditor"}),this._willKeepAspectRatio=!0}static initialize(t,e){G.initialize(t,e),this._defaultDrawingOptions=new Ua(e.viewParameters)}static getDefaultDrawingOptions(t){const e=this._defaultDrawingOptions.clone();return e.updateProperties(t),e}static get supportMultipleDrawings(){return!0}static get typesMap(){return tt(this,"typesMap",new Map([[st.INK_THICKNESS,"stroke-width"],[st.INK_COLOR,"stroke"],[st.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,e,s,i,n){return new wp(t,e,s,i,n,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,e,s,i,n,r){return lr.deserialize(t,e,s,i,n,r)}static async deserialize(t,e,s){let i=null;if(t instanceof Ga){const{data:{inkLists:r,rect:a,rotation:l,id:h,color:c,opacity:u,borderStyle:{rawWidth:d},popupRef:f},parent:{page:{pageNumber:g}}}=t;i=t={annotationType:J.INK,color:Array.from(c),thickness:d,opacity:u,paths:{points:r},boxes:null,pageIndex:g-1,rect:a.slice(0),rotation:l,id:h,deleted:!1,popupRef:f}}const n=await super.deserialize(t,e,s);return n.annotationElementId=t.id||null,n._initialData=i,n}onScaleChanging(){if(!this.parent)return;super.onScaleChanging();const{_drawId:t,_drawingOptions:e,parent:s}=this;e.updateSVGProperty("stroke-width"),s.drawLayer.updateProperties(t,e.toSVGProperties())}static onScaleChangingWhenDrawing(){const t=this._currentParent;t&&(super.onScaleChangingWhenDrawing(),this._defaultDrawingOptions.updateSVGProperty("stroke-width"),t.drawLayer.updateProperties(this._currentDrawId,this._defaultDrawingOptions.toSVGProperties()))}createDrawingOptions({color:t,thickness:e,opacity:s}){this._drawingOptions=Ya.getDefaultDrawingOptions({stroke:z.makeHexColor(...t),"stroke-width":e,"stroke-opacity":s})}serialize(t=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const{lines:e,points:s,rect:i}=this.serializeDraw(t),{_drawingOptions:{stroke:n,"stroke-opacity":r,"stroke-width":a}}=this,l={annotationType:J.INK,color:G._colorManager.convert(n),opacity:r,thickness:a,paths:{lines:e,points:s},pageIndex:this.pageIndex,rect:i,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return t?l:this.annotationElementId&&!this.#t(l)?null:(l.id=this.annotationElementId,l)}#t(t){const{color:e,thickness:s,opacity:i,pageIndex:n}=this._initialData;return this._hasBeenMoved||this._hasBeenResized||t.color.some((r,a)=>r!==e[a])||t.thickness!==s||t.opacity!==i||t.pageIndex!==n}renderAnnotationElement(t){const{points:e,rect:s}=this.serializeDraw(!1);return t.updateEdited({rect:s,thickness:this._drawingOptions["stroke-width"],points:e}),null}}class $a extends G{#t=null;#e=null;#s=null;#i=null;#r=null;#n="";#l=null;#o=null;#c=!1;#h=!1;static _type="stamp";static _editorType=J.STAMP;constructor(t){super({...t,name:"stampEditor"}),this.#i=t.bitmapUrl,this.#r=t.bitmapFile}static initialize(t,e){G.initialize(t,e)}static get supportedTypes(){return tt(this,"supportedTypes",["apng","avif","bmp","gif","jpeg","png","svg+xml","webp","x-icon"].map(e=>`image/${e}`))}static get supportedTypesStr(){return tt(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(t){return this.supportedTypes.includes(t)}static paste(t,e){e.pasteEditor(J.STAMP,{bitmapFile:t.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){return{type:"stamp",hasAltText:!!this.altTextData?.altText}}static computeTelemetryFinalData(t){const e=t.get("hasAltText");return{hasAltText:e.get(!0)??0,hasNoAltText:e.get(!1)??0}}#d(t,e=!1){if(!t){this.remove();return}this.#t=t.bitmap,e||(this.#e=t.id,this.#c=t.isSvg),t.file&&(this.#n=t.file.name),this.#a()}#u(){if(this.#s=null,this._uiManager.enableWaiting(!1),!!this.#l){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&this.#t){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}}async mlGuessAltText(t=null,e=!0){if(this.hasAltTextData())return null;const{mlManager:s}=this._uiManager;if(!s)throw new Error("No ML.");if(!await s.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:n,height:r}=t||this.copyCanvas(null,null,!0).imageData,a=await s.guess({name:"altText",request:{data:i,width:n,height:r,channels:i.length/(n*r)}});if(!a)throw new Error("No response from the AI service.");if(a.error)throw new Error("Error from the AI service.");if(a.cancel)return null;if(!a.output)throw new Error("No valid response from the AI service.");const l=a.output;return await this.setGuessedAltText(l),e&&!this.hasAltTextData()&&(this.altTextData={alt:l,decorative:!1}),l}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then(s=>this.#d(s,!0)).finally(()=>this.#u());return}if(this.#i){const s=this.#i;this.#i=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromUrl(s).then(i=>this.#d(i)).finally(()=>this.#u());return}if(this.#r){const s=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#s=this._uiManager.imageManager.getFromFile(s).then(i=>this.#d(i)).finally(()=>this.#u());return}const t=document.createElement("input");t.type="file",t.accept=$a.supportedTypesStr;const e=this._uiManager._signal;this.#s=new Promise(s=>{t.addEventListener("change",async()=>{if(!t.files||t.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(t.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),this.#d(i)}s()},{signal:e}),t.addEventListener("cancel",()=>{this.remove(),s()},{signal:e})}).finally(()=>this.#u()),t.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#l?.remove(),this.#l=null,this.#o&&(clearTimeout(this.#o),this.#o=null)),super.remove()}rebuild(){if(!this.parent){this.#e&&this.#f();return}super.rebuild(),this.div!==null&&(this.#e&&this.#l===null&&this.#f(),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(this.#s||this.#t||this.#i||this.#r||this.#e)}get isResizable(){return!0}render(){if(this.div)return this.div;let t,e;if(this.width&&(t=this.x,e=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),this.#t?this.#a():this.#f(),this.width&&!this.annotationElementId){const[s,i]=this.parentDimensions;this.setAt(t*s,e*i,this.width*s,this.height*i)}return this._uiManager.addShouldRescale(this),this.div}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;this.#o!==null&&clearTimeout(this.#o);const t=200;this.#o=setTimeout(()=>{this.#o=null,this.#m()},t)}#a(){const{div:t}=this;let{width:e,height:s}=this.#t;const[i,n]=this.pageDimensions,r=.75;if(this.width)e=this.width*i,s=this.height*n;else if(e>r*i||s>r*n){const c=Math.min(r*i/e,r*n/s);e*=c,s*=c}const[a,l]=this.parentDimensions;this.setDims(e*a/i,s*l/n),this._uiManager.enableWaiting(!1);const h=this.#l=document.createElement("canvas");h.setAttribute("role","img"),this.addContainer(h),this.width=e/i,this.height=s/n,this._initialOptions?.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(t.hidden=!1),this.#m(),this.#h||(this.parent.addUndoableEditor(this),this.#h=!0),this._reportTelemetry({action:"inserted_image"}),this.#n&&h.setAttribute("aria-label",this.#n)}copyCanvas(t,e,s=!1){t||(t=224);const{width:i,height:n}=this.#t,r=new Pa;let a=this.#t,l=i,h=n,c=null;if(e){if(i>e||n>e){const T=Math.min(e/i,e/n);l=Math.floor(i*T),h=Math.floor(n*T)}c=document.createElement("canvas");const d=c.width=Math.ceil(l*r.sx),f=c.height=Math.ceil(h*r.sy);this.#c||(a=this.#g(d,f));const g=c.getContext("2d");g.filter=this._uiManager.hcmFilter;let p="white",v="#cfcfd8";this._uiManager.hcmFilter!=="none"?v="black":window.matchMedia?.("(prefers-color-scheme: dark)").matches&&(p="#8f8f9d",v="#42414d");const m=15,b=m*r.sx,_=m*r.sy,w=new OffscreenCanvas(b*2,_*2),C=w.getContext("2d");C.fillStyle=p,C.fillRect(0,0,b*2,_*2),C.fillStyle=v,C.fillRect(0,0,b,_),C.fillRect(b,_,b,_),g.fillStyle=g.createPattern(w,"repeat"),g.fillRect(0,0,d,f),g.drawImage(a,0,0,a.width,a.height,0,0,d,f)}let u=null;if(s){let d,f;if(r.symmetric&&a.width<t&&a.height<t)d=a.width,f=a.height;else if(a=this.#t,i>t||n>t){const v=Math.min(t/i,t/n);d=Math.floor(i*v),f=Math.floor(n*v),this.#c||(a=this.#g(d,f))}const p=new OffscreenCanvas(d,f).getContext("2d",{willReadFrequently:!0});p.drawImage(a,0,0,a.width,a.height,0,0,d,f),u={width:d,height:f,data:p.getImageData(0,0,d,f).data}}return{canvas:c,width:l,height:h,imageData:u}}#g(t,e){const{width:s,height:i}=this.#t;let n=s,r=i,a=this.#t;for(;n>2*t||r>2*e;){const l=n,h=r;n>2*t&&(n=n>=16384?Math.floor(n/2)-1:Math.ceil(n/2)),r>2*e&&(r=r>=16384?Math.floor(r/2)-1:Math.ceil(r/2));const c=new OffscreenCanvas(n,r);c.getContext("2d").drawImage(a,0,0,l,h,0,0,n,r),a=c.transferToImageBitmap()}return a}#m(){const[t,e]=this.parentDimensions,{width:s,height:i}=this,n=new Pa,r=Math.ceil(s*t*n.sx),a=Math.ceil(i*e*n.sy),l=this.#l;if(!l||l.width===r&&l.height===a)return;l.width=r,l.height=a;const h=this.#c?this.#t:this.#g(r,a),c=l.getContext("2d");c.filter=this._uiManager.hcmFilter,c.drawImage(h,0,0,h.width,h.height,0,0,r,a)}getImageForAltText(){return this.#l}#p(t){if(t){if(this.#c){const i=this._uiManager.imageManager.getSvgUrl(this.#e);if(i)return i}const e=document.createElement("canvas");return{width:e.width,height:e.height}=this.#t,e.getContext("2d").drawImage(this.#t,0,0),e.toDataURL()}if(this.#c){const[e,s]=this.pageDimensions,i=Math.round(this.width*e*ti.PDF_TO_CSS_UNITS),n=Math.round(this.height*s*ti.PDF_TO_CSS_UNITS),r=new OffscreenCanvas(i,n);return r.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,i,n),r.transferToImageBitmap()}return structuredClone(this.#t)}static async deserialize(t,e,s){let i=null;if(t instanceof hc){const{data:{rect:g,rotation:p,id:v,structParent:m,popupRef:b},container:_,parent:{page:{pageNumber:w}}}=t,C=_.querySelector("canvas"),T=s.imageManager.getFromCanvas(_.id,C);C.remove();const E=(await e._structTree.getAriaAttributes(`${Aa}${v}`))?.get("aria-label")||"";i=t={annotationType:J.STAMP,bitmapId:T.id,bitmap:T.bitmap,pageIndex:w-1,rect:g.slice(0),rotation:p,id:v,deleted:!1,accessibilityData:{decorative:!1,altText:E},isSvg:!1,structParent:m,popupRef:b}}const n=await super.deserialize(t,e,s),{rect:r,bitmap:a,bitmapUrl:l,bitmapId:h,isSvg:c,accessibilityData:u}=t;h&&s.imageManager.isValidId(h)?(n.#e=h,a&&(n.#t=a)):n.#i=l,n.#c=c;const[d,f]=n.pageDimensions;return n.width=(r[2]-r[0])/d,n.height=(r[3]-r[1])/f,n.annotationElementId=t.id||null,u&&(n.altTextData=u),n._initialData=i,n.#h=!!i,n}serialize(t=!1,e=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const s={annotationType:J.STAMP,bitmapId:this.#e,pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:this.#c,structTreeParentId:this._structTreeParentId};if(t)return s.bitmapUrl=this.#p(!0),s.accessibilityData=this.serializeAltText(!0),s;const{decorative:i,altText:n}=this.serializeAltText(!1);if(!i&&n&&(s.accessibilityData={type:"Figure",alt:n}),this.annotationElementId){const a=this.#v(s);if(a.isSame)return null;a.isSameAltText?delete s.accessibilityData:s.accessibilityData.structParent=this._initialData.structParent??-1}if(s.id=this.annotationElementId,e===null)return s;e.stamps||=new Map;const r=this.#c?(s.rect[2]-s.rect[0])*(s.rect[3]-s.rect[1]):null;if(!e.stamps.has(this.#e))e.stamps.set(this.#e,{area:r,serialized:s}),s.bitmap=this.#p(!1);else if(this.#c){const a=e.stamps.get(this.#e);r>a.area&&(a.area=r,a.serialized.bitmap.close(),a.serialized.bitmap=this.#p(!1))}return s}#v(t){const{pageIndex:e,accessibilityData:{altText:s}}=this._initialData,i=t.pageIndex===e,n=(t.accessibilityData?.alt||"")===s;return{isSame:!this._hasBeenMoved&&!this._hasBeenResized&&i&&n,isSameAltText:n}}renderAnnotationElement(t){return t.updateEdited({rect:this.getRect(0,0)}),null}}class ss{#t;#e=!1;#s=null;#i=null;#r=null;#n=new Map;#l=!1;#o=!1;#c=!1;#h=null;#d=null;#u=null;#f=null;#a;static _initialized=!1;static#g=new Map([It,Ya,$a,At].map(t=>[t._editorType,t]));constructor({uiManager:t,pageIndex:e,div:s,structTreeLayer:i,accessibilityManager:n,annotationLayer:r,drawLayer:a,textLayer:l,viewport:h,l10n:c}){const u=[...ss.#g.values()];if(!ss._initialized){ss._initialized=!0;for(const d of u)d.initialize(c,t)}t.registerEditorTypes(u),this.#a=t,this.pageIndex=e,this.div=s,this.#t=n,this.#s=r,this.viewport=h,this.#u=l,this.drawLayer=a,this._structTree=i,this.#a.addLayer(this)}get isEmpty(){return this.#n.size===0}get isInvisible(){return this.isEmpty&&this.#a.getMode()===J.NONE}updateToolbar(t){this.#a.updateToolbar(t)}updateMode(t=this.#a.getMode()){switch(this.#b(),t){case J.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case J.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case J.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:e}=this.div;for(const s of ss.#g.values())e.toggle(`${s._type}Editing`,t===s._editorType);this.div.hidden=!1}hasTextLayer(t){return t===this.#u?.div}setEditingState(t){this.#a.setEditingState(t)}addCommands(t){this.#a.addCommands(t)}cleanUndoStack(t){this.#a.cleanUndoStack(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){this.#s?.div.classList.toggle("disabled",!t)}async enable(){this.#c=!0,this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const s of this.#n.values())s.enableEditing(),s.show(!0),s.annotationElementId&&(this.#a.removeChangedExistingAnnotation(s),t.add(s.annotationElementId));if(!this.#s){this.#c=!1;return}const e=this.#s.getEditableAnnotations();for(const s of e){if(s.hide(),this.#a.isDeletedAnnotationElement(s.data.id)||t.has(s.data.id))continue;const i=await this.deserialize(s);i&&(this.addOrRebuild(i),i.enableEditing())}this.#c=!1}disable(){this.#o=!0,this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,e=new Map;for(const i of this.#n.values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else e.set(i.annotationElementId,i);this.getEditableAnnotation(i.annotationElementId)?.show(),i.remove()}if(this.#s){const i=this.#s.getEditableAnnotations();for(const n of i){const{id:r}=n.data;if(this.#a.isDeletedAnnotationElement(r))continue;let a=e.get(r);if(a){a.resetAnnotationElement(n),a.show(!1),n.show();continue}a=t.get(r),a&&(this.#a.addChangedExistingAnnotation(a),a.renderAnnotationElement(n)&&a.show(!1)),n.show()}}this.#b(),this.isEmpty&&(this.div.hidden=!0);const{classList:s}=this.div;for(const i of ss.#g.values())s.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),this.#o=!1}getEditableAnnotation(t){return this.#s?.getEditableAnnotation(t)||null}setActiveEditor(t){this.#a.getActive()!==t&&this.#a.setActiveEditor(t)}enableTextSelection(){if(this.div.tabIndex=-1,this.#u?.div&&!this.#f){this.#f=new AbortController;const t=this.#a.combinedSignal(this.#f);this.#u.div.addEventListener("pointerdown",this.#m.bind(this),{signal:t}),this.#u.div.classList.add("highlighting")}}disableTextSelection(){this.div.tabIndex=0,this.#u?.div&&this.#f&&(this.#f.abort(),this.#f=null,this.#u.div.classList.remove("highlighting"))}#m(t){this.#a.unselectAll();const{target:e}=t;if(e===this.#u.div||(e.getAttribute("role")==="img"||e.classList.contains("endOfContent"))&&this.#u.div.contains(e)){const{isMac:s}=Qt.platform;if(t.button!==0||t.ctrlKey&&s)return;this.#a.showAllEditors("highlight",!0,!0),this.#u.div.classList.add("free"),this.toggleDrawing(),At.startHighlighting(this,this.#a.direction==="ltr",{target:this.#u.div,x:t.x,y:t.y}),this.#u.div.addEventListener("pointerup",()=>{this.#u.div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:this.#a._signal}),t.preventDefault()}}enableClick(){if(this.#i)return;this.#i=new AbortController;const t=this.#a.combinedSignal(this.#i);this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t});const e=this.pointerup.bind(this);this.div.addEventListener("pointerup",e,{signal:t}),this.div.addEventListener("pointercancel",e,{signal:t})}disableClick(){this.#i?.abort(),this.#i=null}attach(t){this.#n.set(t.id,t);const{annotationElementId:e}=t;e&&this.#a.isDeletedAnnotationElement(e)&&this.#a.removeDeletedAnnotationElement(t)}detach(t){this.#n.delete(t.id),this.#t?.removePointerInTextLayer(t.contentDiv),!this.#o&&t.annotationElementId&&this.#a.addDeletedAnnotationElement(t)}remove(t){this.detach(t),this.#a.removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1}changeParent(t){t.parent!==this&&(t.parent&&t.annotationElementId&&(this.#a.addDeletedAnnotationElement(t.annotationElementId),G.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),t.parent?.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),this.#a.addEditor(t),this.attach(t),!t.isAttachedToDOM){const e=t.render();this.div.append(e),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(!this.#c),this.#a.addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){if(!t.isAttachedToDOM)return;const{activeElement:e}=document;t.div.contains(e)&&!this.#r&&(t._focusEventsAllowed=!1,this.#r=setTimeout(()=>{this.#r=null,t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this.#a._signal}),e.focus())},0)),t._structTreeParentId=this.#t?.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||=this,t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const e=()=>t._uiManager.rebuild(t),s=()=>{t.remove()};this.addCommands({cmd:e,undo:s,mustExec:!1})}getNextId(){return this.#a.getId()}get#p(){return ss.#g.get(this.#a.getMode())}combinedSignal(t){return this.#a.combinedSignal(t)}#v(t){const e=this.#p;return e?new e.prototype.constructor(t):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(t,e){this.#a.updateToolbar(t),this.#a.updateMode(t);const{offsetX:s,offsetY:i}=this.#_(),n=this.getNextId(),r=this.#v({parent:this,id:n,x:s,y:i,uiManager:this.#a,isCentered:!0,...e});r&&this.add(r)}async deserialize(t){return await ss.#g.get(t.annotationType??t.annotationEditorType)?.deserialize(t,this,this.#a)||null}createAndAddNewEditor(t,e,s={}){const i=this.getNextId(),n=this.#v({parent:this,id:i,x:t.offsetX,y:t.offsetY,uiManager:this.#a,isCentered:e,...s});return n&&this.add(n),n}#_(){const{x:t,y:e,width:s,height:i}=this.div.getBoundingClientRect(),n=Math.max(0,t),r=Math.max(0,e),a=Math.min(window.innerWidth,t+s),l=Math.min(window.innerHeight,e+i),h=(n+a)/2-t,c=(r+l)/2-e,[u,d]=this.viewport.rotation%180===0?[h,c]:[c,h];return{offsetX:u,offsetY:d}}addNewEditor(){this.createAndAddNewEditor(this.#_(),!0)}setSelected(t){this.#a.setSelected(t)}toggleSelected(t){this.#a.toggleSelected(t)}unselect(t){this.#a.unselect(t)}pointerup(t){const{isMac:e}=Qt.platform;if(!(t.button!==0||t.ctrlKey&&e)&&t.target===this.div&&this.#l&&(this.#l=!1,!(this.#p?.isDrawer&&this.#p.supportMultipleDrawings))){if(!this.#e){this.#e=!0;return}if(this.#a.getMode()===J.STAMP){this.#a.unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(this.#a.getMode()===J.HIGHLIGHT&&this.enableTextSelection(),this.#l){this.#l=!1;return}const{isMac:e}=Qt.platform;if(t.button!==0||t.ctrlKey&&e||t.target!==this.div)return;if(this.#l=!0,this.#p?.isDrawer){this.startDrawingSession(t);return}const s=this.#a.getActive();this.#e=!s||s.isEmpty()}startDrawingSession(t){if(this.div.focus(),this.#h){this.#p.startDrawing(this,this.#a,!1,t);return}this.#a.setCurrentDrawingSession(this),this.#h=new AbortController;const e=this.#a.combinedSignal(this.#h);this.div.addEventListener("blur",({relatedTarget:s})=>{s&&!this.div.contains(s)&&(this.#d=null,this.commitOrRemove())},{signal:e}),this.#p.startDrawing(this,this.#a,!1,t)}pause(t){if(t){const{activeElement:e}=document;this.div.contains(e)&&(this.#d=e);return}this.#d&&setTimeout(()=>{this.#d?.focus(),this.#d=null},0)}endDrawingSession(t=!1){return this.#h?(this.#a.setCurrentDrawingSession(null),this.#h.abort(),this.#h=null,this.#d=null,this.#p.endDrawing(t)):null}findNewParent(t,e,s){const i=this.#a.findParent(e,s);return i===null||i===this?!1:(i.changeParent(t),!0)}commitOrRemove(){return this.#h?(this.endDrawingSession(),!0):!1}onScaleChanging(){this.#h&&this.#p.onScaleChangingWhenDrawing(this)}destroy(){this.commitOrRemove(),this.#a.getActive()?.parent===this&&(this.#a.commitOrRemove(),this.#a.setActiveEditor(null)),this.#r&&(clearTimeout(this.#r),this.#r=null);for(const t of this.#n.values())this.#t?.removePointerInTextLayer(t.contentDiv),t.setParent(null),t.isAttachedToDOM=!1,t.div.remove();this.div=null,this.#n.clear(),this.#a.removeLayer(this)}#b(){for(const t of this.#n.values())t.isEmpty()&&t.remove()}render({viewport:t}){this.viewport=t,Ms(this.div,t);for(const e of this.#a.getEditors(this.pageIndex))this.add(e),e.rebuild();this.updateMode()}update({viewport:t}){this.#a.commitOrRemove(),this.#b();const e=this.viewport.rotation,s=t.rotation;if(this.viewport=t,Ms(this.div,{rotation:s}),e!==s)for(const i of this.#n.values())i.rotate(s)}get pageDimensions(){const{pageWidth:t,pageHeight:e}=this.viewport.rawDims;return[t,e]}get scale(){return this.#a.viewParameters.realScale}}class te{#t=null;#e=0;#s=new Map;#i=new Map;constructor({pageIndex:t}){this.pageIndex=t}setParent(t){if(!this.#t){this.#t=t;return}if(this.#t!==t){if(this.#s.size>0)for(const e of this.#s.values())e.remove(),t.append(e);this.#t=t}}static get _svgFactory(){return tt(this,"_svgFactory",new za)}static#r(t,[e,s,i,n]){const{style:r}=t;r.top=`${100*s}%`,r.left=`${100*e}%`,r.width=`${100*i}%`,r.height=`${100*n}%`}#n(){const t=te._svgFactory.create(1,1,!0);return this.#t.append(t),t.setAttribute("aria-hidden",!0),t}#l(t,e){const s=te._svgFactory.createElement("clipPath");t.append(s);const i=`clip_${e}`;s.setAttribute("id",i),s.setAttribute("clipPathUnits","objectBoundingBox");const n=te._svgFactory.createElement("use");return s.append(n),n.setAttribute("href",`#${e}`),n.classList.add("clip"),i}#o(t,e){for(const[s,i]of Object.entries(e))i===null?t.removeAttribute(s):t.setAttribute(s,i)}draw(t,e=!1,s=!1){const i=this.#e++,n=this.#n(),r=te._svgFactory.createElement("defs");n.append(r);const a=te._svgFactory.createElement("path");r.append(a);const l=`path_p${this.pageIndex}_${i}`;a.setAttribute("id",l),a.setAttribute("vector-effect","non-scaling-stroke"),e&&this.#i.set(i,a);const h=s?this.#l(r,l):null,c=te._svgFactory.createElement("use");return n.append(c),c.setAttribute("href",`#${l}`),this.updateProperties(n,t),this.#s.set(i,n),{id:i,clipPathId:`url(#${h})`}}drawOutline(t,e){const s=this.#e++,i=this.#n(),n=te._svgFactory.createElement("defs");i.append(n);const r=te._svgFactory.createElement("path");n.append(r);const a=`path_p${this.pageIndex}_${s}`;r.setAttribute("id",a),r.setAttribute("vector-effect","non-scaling-stroke");let l;if(e){const u=te._svgFactory.createElement("mask");n.append(u),l=`mask_p${this.pageIndex}_${s}`,u.setAttribute("id",l),u.setAttribute("maskUnits","objectBoundingBox");const d=te._svgFactory.createElement("rect");u.append(d),d.setAttribute("width","1"),d.setAttribute("height","1"),d.setAttribute("fill","white");const f=te._svgFactory.createElement("use");u.append(f),f.setAttribute("href",`#${a}`),f.setAttribute("stroke","none"),f.setAttribute("fill","black"),f.setAttribute("fill-rule","nonzero"),f.classList.add("mask")}const h=te._svgFactory.createElement("use");i.append(h),h.setAttribute("href",`#${a}`),l&&h.setAttribute("mask",`url(#${l})`);const c=h.cloneNode();return i.append(c),h.classList.add("mainOutline"),c.classList.add("secondaryOutline"),this.updateProperties(i,t),this.#s.set(s,i),s}finalizeDraw(t,e){this.#i.delete(t),this.updateProperties(t,e)}updateProperties(t,e){if(!e)return;const{root:s,bbox:i,rootClass:n,path:r}=e,a=typeof t=="number"?this.#s.get(t):t;if(a){if(s&&this.#o(a,s),i&&te.#r(a,i),n){const{classList:l}=a;for(const[h,c]of Object.entries(n))l.toggle(h,c)}if(r){const h=a.firstChild.firstChild;this.#o(h,r)}}}updateParent(t,e){if(e===this)return;const s=this.#s.get(t);s&&(e.#t.append(s),this.#s.delete(t),e.#s.set(t,s))}remove(t){this.#i.delete(t),this.#t!==null&&(this.#s.get(t).remove(),this.#s.delete(t))}destroy(){this.#t=null;for(const t of this.#s.values())t.remove();this.#s.clear(),this.#i.clear()}}globalThis.pdfjsTestingUtils={HighlightOutliner:Wa},X.AbortException,X.AnnotationEditorLayer,X.AnnotationEditorParamsType,X.AnnotationEditorType,X.AnnotationEditorUIManager,X.AnnotationLayer,X.AnnotationMode,X.ColorPicker,X.DOMSVGFactory,X.DrawLayer,X.FeatureTest;var xp=X.GlobalWorkerOptions;X.ImageKind,X.InvalidPDFException,X.MissingPDFException,X.OPS,X.OutputScale,X.PDFDataRangeTransport,X.PDFDateString,X.PDFWorker,X.PasswordResponses,X.PermissionFlag,X.PixelsPerInch,X.RenderingCancelledException,X.TextLayer,X.TouchManager,X.UnexpectedResponseException,X.Util,X.VerbosityLevel,X.XfaLayer,X.build,X.createValidAbsoluteUrl,X.fetchData;var Sp=X.getDocument;X.getFilenameFromUrl,X.getPdfFilenameFromUrl,X.getXfaPageViewport,X.isDataScheme,X.isPdfFile,X.noContextMenu,X.normalizeUnicode,X.setLayerDimensions,X.shadow,X.stopEvent,X.version;const Cp={"pdfjs-dist":"4.10.38"};function Ap(o){return new Promise((t,e)=>{const s=new FileReader;s.addEventListener("load",()=>t(s.result)),s.addEventListener("error",e),s.readAsDataURL(o)})}const Tp=Cp["pdfjs-dist"].replace("^","");xp.workerSrc=`https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${Tp}/pdf.worker.min.mjs`;async function Ep(o){const t="data:application/pdf;base64,",e=await Ap(o);if(typeof e=="string")return window.atob(e.slice(t.length))}function kp(o,t){return Sp({data:o,password:t}).promise}const le=new Map;function Pp(o){const t=new aa(o);return le.set(o,t),t}function Mp(o,t){const e=Date.now();return{PDFId:`${o.name}-${e}`,name:o.name.replace(/.pdf/,""),updateDate:e,PDFBase64:t}}function Op(o,t){const e=o.getViewport({scale:t}),s=document.createElement("canvas"),i=s.getContext("2d"),n=yf()/window.devicePixelRatio;s.width=Math.floor(e.width*n),s.height=Math.floor(e.height*n);const r={canvasContext:i,viewport:e,transform:[n,0,0,n,0,0]},a=o.render(r);return{canvas:s,renderTask:a}}async function Dp({src:o},t,e){if(!o||!e)return null;const{objects:s,options:i}=await of(o),n=s.filter(a=>a!==null),r=xd.groupSVGElements(n,i);return n.forEach(a=>{a.stroke=e}),r.hoverCursor="pointer",r.stroke=`${e}-${t}`,r}function Rp(o,t){if(!le.get(o))return;const s=1/3,i=Hp(t,s);dc(o,i,s)}async function Fp(o,t){const e=await wf(t),s=Date.now(),n={PDFId:`${t.name}${s}`,name:t.name.replace(/.png|.jpg|.jpeg/,""),updateDate:s,PDFBase64:e};return uc(o,{url:e}),{...n,pages:1}}async function uc(o,{url:t,scale:e=.5}){if(!le.get(o))return;const i=await Vt.fromURL(t);i.scale(e),dc(o,i,e)}function dc(o,t,e){const s=le.get(o);s&&(s.setWidth(t.width*e),s.setHeight(t.height*e),s.backgroundImage=t,s.renderAll())}function Lp(o,t){if(!t)return;const{oCoords:e}=o;if(!e)return;const{x:s,y:i}=e.tl.touchCorner.tl,{height:n,width:r,scaleY:a,scaleX:l}=t;t.top=i-n*a/2,t.left=s-r*l/2,t.setCoords()}function Ip(o,t,e){!e||!o||(e.scale(1/t),Lp(o,e))}function jp(o,t){if(!o)return;const e=o._cornerSize||6;o.borderScaleFactor=1/t,o.cornerSize=e*(1/t),o.touchCornerSize=e*4*(1/t),o.setCoords()}function Np(o){const t=le.get(o);t&&(t.discardActiveObject(),t.renderAll())}function Bp(o){const t=le.get(o);t&&(t.clear(),le.delete(o))}function Hp(o,t){return new Vt(o,{scaleX:t,scaleY:t})}function qa(o,t){if(!t)return;const{left:e,top:s,scaleX:i,scaleY:n,width:r,height:a}=o,l=t.x*r*i,h=t.y*a*n;o.set({left:e-l,top:s-h})}function fc(o,t,e){const s=o.type;return{"application/pdf":zp,"image/png":pc,"image/jpeg":pc}[s]?.(o,t,e)??Promise.reject(new Error(`Unsupported ${s} file type.`))}async function zp(o,t,e){const s=await Ep(o);if(!s)return;const i=Mp(o,s);try{const n=await gc({page:1,PDFBase64:s,scale:.8,password:t},e);return{...i,pages:n}}catch(n){return Promise.reject(n)}}async function gc({page:o,PDFBase64:t,scale:e,password:s},i){try{const n=await kp(t,s),r=await n.getPage(o),{renderTask:a,canvas:l}=Op(r,e);return a.promise.then(()=>(i&&Rp(i,l),n.numPages))}catch(n){return Promise.reject(n)}}async function pc(o,t,e){if(e)return await Fp(e,o)}async function Vp(o,t){const e=le.get(o);if(!e)return;const s=e?.getActiveObject();if(!s)return;const i=await s.clone(zc);i instanceof me?i.forEachObject(n=>{e.add(n),t(e,n)}):(e.add(i),t(e,i)),qa(i,{x:-.1,y:-.1}),e.setActiveObject(i)}function Gp(o){const t=le.get(o);if(!t)return;const e=t.getActiveObject();e&&(e instanceof me?(e.forEachObject(s=>{t.remove(s)}),t.discardActiveObject()):t.remove(e))}function mc(o){const{id:t="",selectionOptions:e,pointerDown:s,pointerMove:i,pointerUp:n,selectionCreated:r,selectionCleared:a}=o||{},l=Z.useRef(null),h=Z.useRef(null),c=Z.useRef(1),u=Z.useRef({...Hc});function d(){if(!t||le.has(t))return;const P=Pp(t);return P.on("selection:created",R=>{if(r?.(R),R.selected.length<=1)return;const F=P.getActiveObject();F&&(h.current=F,e?.value&&h.current.set(e.value),h.current._cornerSize=h.current.cornerSize,C(c.current))}),P.on("selection:cleared",R=>{a?.(R),E(P)}),s&&P.on("mouse:down",s),i&&P.on("mouse:move",i),n&&P.on("mouse:up",n),P}function f(P,R){return fc(P,R,t)}function g(P){return gc(P,t)}function p({url:P,scale:R=.5}){return uc(t,{url:P,scale:R})}async function v(P,R,F){const V=le.get(t);if(!V)return;const M=await Vt.fromURL(P,{},{...jc,...R});qa(M,F),V.add(M),b(V,M),V.setActiveObject(M)}function m(P,R,F){const V=le.get(t);if(!V)return;const M=new zt(P,{...Nc,...R});qa(M,F),V.add(M),b(V,M),V.setActiveObject(M)}function b(P,R){R.on("selected",F=>_({canvas:P,target:F.target})),R.on("modified",F=>_({canvas:P,target:F.target})),R.on("scaling",()=>E(P)),R.on("moving",()=>E(P)),R.on("rotating",()=>E(P)),R._cornerSize=R._cornerSize??R.cornerSize}async function _({canvas:P,target:R,stroke:F=u.current.stroke,uuid:V=Date.now()}){if(P.getActiveObjects().length>1||l.current?.stroke===`${F}-${V}`)return;const L=await Dp(u.current,V,F);E(P),l.current=L,h.current=R,w(P,R,V),C(c.current,!0),L&&P.add(L)}function w(P,R,F){l.current&&(l.current.on("selected",()=>{P.remove(R),E(P)}),l.current.on("mouseover",()=>{_({canvas:P,target:R,stroke:u.current.hoverStroke,uuid:F})}),l.current.on("mouseout",()=>{_({canvas:P,target:R,stroke:u.current.stroke,uuid:F})}))}function C(P,R=!1){const F=le.get(t);c.current=P,F&&(jp(h.current,P),Ip(h.current,P,l.current),!R&&F.renderAll())}function T(P){if(!P)return;u.current={...u.current,...P};const R=le.get(t);!l||!h.current||!R||_({target:h.current,canvas:R})}function E(P){h.current=null,l.current&&(P.remove(l.current),l.current=null)}function k(){Np(t)}function O(){Bp(t)}function H(){return Vp(t,b)}function N(){Gp(t)}return{createCanvas:d,loadFile:f,specifyPage:g,renderImage:p,addFabric:v,addTextFabric:m,clearActive:k,deleteCanvas:O,scaleFabric:C,setCloseSvgOptions:T,copyActiveFabric:H,deleteActiveFabric:N}}function Wp(o){let t=0;const e=_f(()=>{t!==window.innerWidth&&(t=window.innerWidth,o())});Z.useEffect(()=>(window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)),[])}const Xp=Z.forwardRef(Up);function Up({file:o,page:t=1,canvasId:e="PDF-canvas",fileZoom:s=1,fileScale:i=1,canvasScale:n=1,canvasClass:r="",isDrop:a=!1,password:l,dropTextOptions:h,dropImageOptions:c,closeSvgOptions:u,selectionOptions:d,manualReload:f,onLoaded:g,onReload:p,onPointerDown:v,onPointerMove:m,onPointerUp:b,onSelectionCreated:_,onSelectionCleared:w},C){const T=Z.useRef(null),E=`${e}-${t-1}`,k=Z.useMemo(()=>s*n,[s,n]),O=Z.useMemo(()=>({...Bc,...d}),[d]),{createCanvas:H,specifyPage:N,addFabric:P,addTextFabric:R,renderImage:F,clearActive:V,deleteCanvas:M,scaleFabric:L,setCloseSvgOptions:Y,copyActiveFabric:ft,deleteActiveFabric:bt}=mc({id:E,selectionOptions:O,pointerDown:v,pointerMove:m,pointerUp:b,selectionCreated:_,selectionCleared:w});Wp(ee);async function _t(){window.requestAnimationFrame(async()=>{if(H(),o.PDFBase64.startsWith("data:image")||o.canvas){const{canvas:K}=o,$=K?7:3,Tt=K?.length?K[t-1]:o.PDFBase64;F({url:Tt,scale:i/$});return}await N({page:t,PDFBase64:o.PDFBase64,scale:i,password:l}),g?.()})}function gt(K){if(K.preventDefault(),K.stopPropagation(),!a||!K.dataTransfer)return;const{dataTransfer:$,nativeEvent:Tt}=K,{offsetX:_e,offsetY:Nt}=Tt,cr=$.getData("text/plain"),Gi=$.getData("text/uri-list"),ur=$.getData("custom/offset"),dr=ur?JSON.parse(ur):null,Is={top:Nt,left:_e},fs={x:dr?.offsetX??0,y:dr?.offsetY??0};Gi?rt(Gi,Is,fs):cr&&Dt(cr,Is,fs)}function rt(K,$,Tt){P(K,{...c,...$},Tt)}function Dt(K,$,Tt){R(K,{...h,...$},Tt)}function ee(){f||_t(),p?.()}return Z.useImperativeHandle(C,()=>({reload:_t,addImage:rt,addText:Dt,clearActive:V,deleteCanvas:M,copyActiveFabric:ft,deleteActiveFabric:bt,canvasRef:T})),Z.useEffect(()=>{ee()},[i,t,o,l]),Z.useEffect(()=>{L(k)},[k]),Z.useEffect(()=>{Y(u)},[u]),Z.useEffect(()=>()=>M(),[]),ro.jsx("div",{style:{transform:`scale(${k})`},onDragOver:K=>K.preventDefault(),onDragEnter:K=>K.preventDefault(),onDrop:gt,children:ro.jsx("canvas",{id:E,ref:T,className:r})})}at.default=Xp,at.loadFile=fc,at.useFabric=mc,Object.defineProperties(at,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|