web-to-print 0.1.0

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.
Files changed (92) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/app-globals-V2Kpy_OQ.js +5 -0
  3. package/dist/cjs/canvas-helpers-A6rp5rPD.js +765 -0
  4. package/dist/cjs/index-IFGFRm-i.js +1649 -0
  5. package/dist/cjs/index.cjs.js +232 -0
  6. package/dist/cjs/loader.cjs.js +13 -0
  7. package/dist/cjs/logo-BUX-b45R.js +18 -0
  8. package/dist/cjs/web-to-print.cjs.js +25 -0
  9. package/dist/cjs/wtp-editor_2.cjs.entry.js +12386 -0
  10. package/dist/cjs/wtp-logo-renderer.cjs.entry.js +353 -0
  11. package/dist/cjs/wtp-print-area-editor.cjs.entry.js +431 -0
  12. package/dist/collection/collection-manifest.json +16 -0
  13. package/dist/collection/components/wtp-editor/wtp-editor.css +124 -0
  14. package/dist/collection/components/wtp-editor/wtp-editor.js +1114 -0
  15. package/dist/collection/components/wtp-logo-renderer/wtp-logo-renderer.css +30 -0
  16. package/dist/collection/components/wtp-logo-renderer/wtp-logo-renderer.js +455 -0
  17. package/dist/collection/components/wtp-logo-upload/wtp-logo-upload.css +428 -0
  18. package/dist/collection/components/wtp-logo-upload/wtp-logo-upload.js +573 -0
  19. package/dist/collection/components/wtp-print-area-editor/wtp-print-area-editor.css +20 -0
  20. package/dist/collection/components/wtp-print-area-editor/wtp-print-area-editor.js +600 -0
  21. package/dist/collection/examples/schaeffler--big.svg +1 -0
  22. package/dist/collection/index.js +8 -0
  23. package/dist/collection/types/editor.js +1 -0
  24. package/dist/collection/types/index.js +2 -0
  25. package/dist/collection/types/labels.js +30 -0
  26. package/dist/collection/types/logo.js +13 -0
  27. package/dist/collection/utils/background-removal.js +717 -0
  28. package/dist/collection/utils/canvas-helpers.js +380 -0
  29. package/dist/collection/utils/format-detection.js +48 -0
  30. package/dist/collection/utils/html-render-helpers.js +106 -0
  31. package/dist/collection/utils/image-preview.js +54 -0
  32. package/dist/collection/utils/logo-validation.js +141 -0
  33. package/dist/collection/utils/pdf-export.js +224 -0
  34. package/dist/components/index.d.ts +35 -0
  35. package/dist/components/index.js +1 -0
  36. package/dist/components/p-5qCsRzlt.js +1 -0
  37. package/dist/components/p-Bn9gR_8e.js +1 -0
  38. package/dist/components/p-D8pVJRuX.js +1 -0
  39. package/dist/components/wtp-editor.d.ts +11 -0
  40. package/dist/components/wtp-editor.js +1 -0
  41. package/dist/components/wtp-logo-renderer.d.ts +11 -0
  42. package/dist/components/wtp-logo-renderer.js +1 -0
  43. package/dist/components/wtp-logo-upload.d.ts +11 -0
  44. package/dist/components/wtp-logo-upload.js +1 -0
  45. package/dist/components/wtp-print-area-editor.d.ts +11 -0
  46. package/dist/components/wtp-print-area-editor.js +1 -0
  47. package/dist/esm/app-globals-DQuL1Twl.js +3 -0
  48. package/dist/esm/canvas-helpers-CK8OAq2J.js +748 -0
  49. package/dist/esm/index-CUetmLbL.js +1641 -0
  50. package/dist/esm/index.js +228 -0
  51. package/dist/esm/loader.js +11 -0
  52. package/dist/esm/logo-D8pVJRuX.js +15 -0
  53. package/dist/esm/web-to-print.js +21 -0
  54. package/dist/esm/wtp-editor_2.entry.js +12383 -0
  55. package/dist/esm/wtp-logo-renderer.entry.js +351 -0
  56. package/dist/esm/wtp-print-area-editor.entry.js +429 -0
  57. package/dist/index.cjs.js +1 -0
  58. package/dist/index.js +1 -0
  59. package/dist/types/components/wtp-editor/wtp-editor.d.ts +101 -0
  60. package/dist/types/components/wtp-logo-renderer/wtp-logo-renderer.d.ts +55 -0
  61. package/dist/types/components/wtp-logo-upload/wtp-logo-upload.d.ts +76 -0
  62. package/dist/types/components/wtp-print-area-editor/wtp-print-area-editor.d.ts +43 -0
  63. package/dist/types/components.d.ts +507 -0
  64. package/dist/types/index.d.ts +11 -0
  65. package/dist/types/stencil-public-runtime.d.ts +1860 -0
  66. package/dist/types/types/editor.d.ts +79 -0
  67. package/dist/types/types/index.d.ts +5 -0
  68. package/dist/types/types/labels.d.ts +30 -0
  69. package/dist/types/types/logo.d.ts +47 -0
  70. package/dist/types/utils/background-removal.d.ts +95 -0
  71. package/dist/types/utils/canvas-helpers.d.ts +60 -0
  72. package/dist/types/utils/format-detection.d.ts +4 -0
  73. package/dist/types/utils/html-render-helpers.d.ts +44 -0
  74. package/dist/types/utils/image-preview.d.ts +13 -0
  75. package/dist/types/utils/logo-validation.d.ts +2 -0
  76. package/dist/types/utils/pdf-export.d.ts +32 -0
  77. package/dist/web-to-print/index.esm.js +1 -0
  78. package/dist/web-to-print/p-611ec561.entry.js +1 -0
  79. package/dist/web-to-print/p-703e4c52.entry.js +1 -0
  80. package/dist/web-to-print/p-CK8OAq2J.js +1 -0
  81. package/dist/web-to-print/p-CUetmLbL.js +2 -0
  82. package/dist/web-to-print/p-D8pVJRuX.js +1 -0
  83. package/dist/web-to-print/p-DQuL1Twl.js +1 -0
  84. package/dist/web-to-print/p-b532777b.entry.js +1 -0
  85. package/dist/web-to-print/web-to-print.esm.js +1 -0
  86. package/loader/cdn.js +1 -0
  87. package/loader/index.cjs.js +1 -0
  88. package/loader/index.d.ts +24 -0
  89. package/loader/index.es2017.js +1 -0
  90. package/loader/index.js +2 -0
  91. package/package.json +68 -0
  92. package/readme.md +490 -0
@@ -0,0 +1 @@
1
+ function t(e){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t(e)}function e(e){var i=function(e){if("object"!=t(e)||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var s=i.call(e,"string");if("object"!=t(s))return s;throw TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==t(i)?i:i+""}function i(t,i,s){return(i=e(i))in t?Object.defineProperty(t,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):t[i]=s,t}var s=class{constructor(){i(this,"browserShadowBlurConstant",1),i(this,"DPI",96),i(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),i(this,"perfLimitSizeTotal",2097152),i(this,"maxCacheSideLimit",4096),i(this,"minCacheSideLimit",256),i(this,"disableStyleCopyPaste",!1),i(this,"enableGLFiltering",!0),i(this,"textureSize",4096),i(this,"forceGLPutImageData",!1),i(this,"cachesBoundsOfCurve",!1),i(this,"fontPaths",{}),i(this,"NUM_FRACTION_DIGITS",4)}};const r=new class extends s{constructor(t){super(),this.configure(t)}configure(t={}){Object.assign(this,t)}addFonts(t={}){this.fontPaths={...this.fontPaths,...t}}removeFonts(t=[]){t.forEach((t=>{delete this.fontPaths[t]}))}clearFonts(){this.fontPaths={}}restoreDefaults(t){let e=new s,i=(null==t?void 0:t.reduce(((t,i)=>(t[i]=e[i],t)),{}))||e;this.configure(i)}},h=(t,...e)=>console[t]("fabric",...e);var n=class extends Error{constructor(t,e){super(`fabric: ${t}`,e)}},o=class extends n{constructor(t){super(`${t} 'options.signal' is in 'aborted' state`)}},a=class{},l=class extends a{testPrecision(t,e){let i=`precision ${e} float;\nvoid main(){}`,s=t.createShader(t.FRAGMENT_SHADER);return!!s&&(t.shaderSource(s,i),t.compileShader(s),!!t.getShaderParameter(s,t.COMPILE_STATUS))}queryWebGL(t){let e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find((t=>this.testPrecision(e,t))),e.getExtension("WEBGL_lose_context").loseContext(),h("log",`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}};const u={};let c;const d=()=>c||(c={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new l,dispose(){},copyPasteData:u}),f=()=>d().document,g=()=>d().window,p=()=>{var t;return Math.max(null==(t=r.devicePixelRatio)?g().devicePixelRatio:t,1)},m=new class{constructor(){i(this,"boundsOfCurveCache",{}),this.charWidthsCache=new Map}getFontCache({fontFamily:t,fontStyle:e,fontWeight:i}){t=t.toLowerCase();let s=this.charWidthsCache;s.has(t)||s.set(t,new Map);let r=s.get(t),h=`${e.toLowerCase()}_${(i+"").toLowerCase()}`;return r.has(h)||r.set(h,new Map),r.get(h)}clearFontCache(t){t?this.charWidthsCache.delete((t||"").toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(t){let{perfLimitSizeTotal:e}=r,i=Math.sqrt(e*t);return[Math.floor(i),Math.floor(e/i)]}},v="7.4.0";function y(){}const x=Math.PI/2,w=Math.PI/4,b=2*Math.PI,C=Math.PI/180,S=Object.freeze([1,0,0,1,0,0]),_="center",T="left",M="bottom",k="right",F="none",D=/\r?\n/,O="moving",$="scaling",j="rotating",A="rotate",P="skewing",E="resizing",L="modifyPoly",B="changed",R="scale",I="scaleX",X="scaleY",Y="skewX",z="skewY",W="fill",G="stroke",N="modified",H="normal",V="json",U=new class{constructor(){this[V]=new Map,this.svg=new Map}has(t){return this[V].has(t)}getClass(t){let e=this[V].get(t);if(!e)throw new n(`No class registered for ${t}`);return e}setClass(t,e){e?this[V].set(e,t):(this[V].set(t.type,t),this[V].set(t.type.toLowerCase(),t))}getSVGClass(t){return this.svg.get(t)}setSVGClass(t,e){this.svg.set(null==e?t.type.toLowerCase():e,t)}},q=new class extends Array{remove(t){let e=this.indexOf(t);e>-1&&this.splice(e,1)}cancelAll(){let t=this.splice(0);return t.forEach((t=>t.abort())),t}cancelByCanvas(t){if(!t)return[];let e=this.filter((e=>{var i;return e.target===t||"object"==typeof e.target&&(null==(i=e.target)?void 0:i.canvas)===t}));return e.forEach((t=>t.abort())),e}cancelByTarget(t){if(!t)return[];let e=this.filter((e=>e.target===t));return e.forEach((t=>t.abort())),e}};var K=class{constructor(){i(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),"object"==typeof t)return Object.entries(t).forEach((([t,e])=>{this.on(t,e)})),()=>this.off(t);if(e){let i=t;return this.__eventListeners[i]||(this.__eventListeners[i]=[]),this.__eventListeners[i].push(e),()=>this.off(i,e)}return()=>!1}once(t,e){if("object"==typeof t){let e=[];return Object.entries(t).forEach((([t,i])=>{e.push(this.once(t,i))})),()=>e.forEach((t=>t()))}if(e){let i=this.on(t,(function(...t){e.call(this,...t),i()}));return i}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){let i=this.__eventListeners[t],s=i.indexOf(e);s>-1&&i.splice(s,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(void 0===t)for(let t in this.__eventListeners)this._removeEventListener(t);else"object"==typeof t?Object.entries(t).forEach((([t,e])=>{this._removeEventListener(t,e)})):this._removeEventListener(t,e)}fire(t,e){var i;if(!this.__eventListeners)return;let s=null==(i=this.__eventListeners[t])?void 0:i.concat();if(s)for(let t=0;t<s.length;t++)s[t].call(this,e||{})}};const J=(t,e)=>{let i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},Z=t=>{if(0===t)return 1;switch(Math.abs(t)/x){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},Q=t=>{if(0===t)return 0;let e=t/x,i=Math.sign(t);switch(e){case 1:return i;case 2:return 0;case 3:return-i}return Math.sin(t)};var tt=class t{constructor(t=0,e=0){"object"==typeof t?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(e){return new t(this.x+e.x,this.y+e.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(e){return new t(this.x+e,this.y+e)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(e){return new t(this.x-e.x,this.y-e.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(e){return new t(this.x-e,this.y-e)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(e){return new t(this.x*e.x,this.y*e.y)}scalarMultiply(e){return new t(this.x*e,this.y*e)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(e){return new t(this.x/e.x,this.y/e.y)}scalarDivide(e){return new t(this.x/e,this.y/e)}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(e,i=.5){return i=Math.max(Math.min(1,i),0),new t(this.x+(e.x-this.x)*i,this.y+(e.y-this.y)*i)}distanceFrom(t){let e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}midPointFrom(t){return this.lerp(t)}min(e){return new t(Math.min(this.x,e.x),Math.min(this.y,e.y))}max(e){return new t(Math.max(this.x,e.x),Math.max(this.y,e.y))}toString(){return`${this.x},${this.y}`}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){let e=this.x,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i}clone(){return new t(this.x,this.y)}rotate(e,i=et){let s=Q(e),r=Z(e),h=this.subtract(i);return new t(h.x*r-h.y*s,h.x*s+h.y*r).add(i)}transform(e,i=!1){return new t(e[0]*this.x+e[2]*this.y+(i?0:e[4]),e[1]*this.x+e[3]*this.y+(i?0:e[5]))}};const et=new tt(0,0),it=t=>!!t&&Array.isArray(t._objects);function st(t){class e extends t{constructor(...t){super(...t),i(this,"_objects",[])}_onObjectAdded(t){}_onObjectRemoved(t){}_onStackOrderChanged(t){}add(...t){let e=this._objects.push(...t);return t.forEach((t=>this._onObjectAdded(t))),e}insertAt(t,...e){return this._objects.splice(t,0,...e),e.forEach((t=>this._onObjectAdded(t))),this._objects.length}remove(...t){let e=this._objects,i=[];return t.forEach((t=>{let s=e.indexOf(t);-1!==s&&(e.splice(s,1),i.push(t),this._onObjectRemoved(t))})),i}forEachObject(t){this.getObjects().forEach(((e,i,s)=>t(e,i,s)))}getObjects(...t){return 0===t.length?[...this._objects]:this._objects.filter((e=>e.isType(...t)))}item(t){return this._objects[t]}isEmpty(){return 0===this._objects.length}size(){return this._objects.length}contains(t,i){return!!this._objects.includes(t)||!!i&&this._objects.some((i=>i instanceof e&&i.contains(t,!0)))}complexity(){return this._objects.reduce(((t,e)=>t+(e.complexity?e.complexity():0)),0)}sendObjectToBack(t){return!(!t||t===this._objects[0]||(J(this._objects,t),this._objects.unshift(t),this._onStackOrderChanged(t),0))}bringObjectToFront(t){return!(!t||t===this._objects[this._objects.length-1]||(J(this._objects,t),this._objects.push(t),this._onStackOrderChanged(t),0))}sendObjectBackwards(t,e){if(!t)return!1;let i=this._objects.indexOf(t);if(0!==i){let s=this.findNewLowerIndex(t,i,e);return J(this._objects,t),this._objects.splice(s,0,t),this._onStackOrderChanged(t),!0}return!1}bringObjectForward(t,e){if(!t)return!1;let i=this._objects.indexOf(t);if(i!==this._objects.length-1){let s=this.findNewUpperIndex(t,i,e);return J(this._objects,t),this._objects.splice(s,0,t),this._onStackOrderChanged(t),!0}return!1}moveObjectTo(t,e){return t!==this._objects[e]&&(J(this._objects,t),this._objects.splice(e,0,t),this._onStackOrderChanged(t),!0)}findNewLowerIndex(t,e,i){let s;if(i){s=e;for(let i=e-1;i>=0;--i)if(t.isOverlapping(this._objects[i])){s=i;break}}else s=e-1;return s}findNewUpperIndex(t,e,i){let s;if(i){s=e;for(let i=e+1;i<this._objects.length;++i)if(t.isOverlapping(this._objects[i])){s=i;break}}else s=e+1;return s}collectObjects({left:t,top:e,width:i,height:s},{includeIntersecting:r=!0}={}){let h=[],n=new tt(t,e),o=n.add(new tt(i,s));for(let t=this._objects.length-1;t>=0;t--){let e=this._objects[t];e.selectable&&e.visible&&(r&&e.intersectsWithRect(n,o)||e.isContainedWithinRect(n,o)||r&&e.containsPoint(n)||r&&e.containsPoint(o))&&h.push(e)}return h}}return e}var rt=class extends K{_setOptions(t={}){for(let e in t)this.set(e,t[e])}_setObject(t){for(let e in t)this._set(e,t[e])}set(t,e){return"object"==typeof t?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){let e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this}get(t){return this[t]}};function ht(t){return g().requestAnimationFrame(t)}let nt=0;const ot=()=>nt++,at=()=>{let t=f().createElement("canvas");if(!t||void 0===t.getContext)throw new n("Failed to create `canvas` element");return t},lt=t=>{let e=at();return e.width=t.width,e.height=t.height,e},ut=(t,e,i)=>t.toDataURL(`image/${e}`,i),ct=(t,e,i)=>new Promise((s=>{t.toBlob(s,`image/${e}`,i)})),dt=t=>t*C,ft=t=>t/C,gt=(t,e,i)=>new tt(t).transform(e,i),pt=t=>{let e=1/(t[0]*t[3]-t[1]*t[2]),i=[e*t[3],-e*t[1],-e*t[2],e*t[0],0,0],{x:s,y:r}=new tt(t[4],t[5]).transform(i,!0);return i[4]=-s,i[5]=-r,i},mt=(t,e,i)=>[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],i?0:t[0]*e[4]+t[2]*e[5]+t[4],i?0:t[1]*e[4]+t[3]*e[5]+t[5]],vt=(t,e)=>t.reduceRight(((t,i)=>i&&t?mt(i,t,e):i||t),void 0)||S.concat(),yt=([t,e])=>Math.atan2(e,t),xt=([t,e])=>Math.sqrt(t*t+e*e),wt=([,,t,e])=>Math.sqrt(t*t+e*e),bt=t=>{let e=yt(t),i=t[0]**2+t[1]**2,s=Math.sqrt(i),r=(t[0]*t[3]-t[2]*t[1])/s,h=Math.atan2(t[0]*t[2]+t[1]*t[3],i);return{angle:ft(e),scaleX:s,scaleY:r,skewX:ft(h),skewY:0,translateX:t[4]||0,translateY:t[5]||0}},Ct=(t,e=0)=>[1,0,0,1,t,e];function St({angle:t=0}={},{x:e=0,y:i=0}={}){let s=dt(t),r=Z(s),h=Q(s);return[r,h,-h,r,e?e-(r*e-h*i):0,i?i-(h*e+r*i):0]}const _t=(t,e=t)=>[t,0,0,e,0,0],Tt=t=>Math.tan(dt(t)),Mt=t=>[1,0,Tt(t),1,0,0],kt=t=>[1,Tt(t),0,1,0,0],Ft=({scaleX:t=1,scaleY:e=1,flipX:i=!1,flipY:s=!1,skewX:r=0,skewY:h=0})=>{let n=_t(i?-t:t,s?-e:e);return r&&(n=mt(n,Mt(r),!0)),h&&(n=mt(n,kt(h),!0)),n},Dt=(t,{signal:e,crossOrigin:i=null}={})=>new Promise((function(s,r){if(e&&e.aborted)return r(new o("loadImage"));let h,a=f().createElement("img");e&&(h=function(t){a.src="",r(t)},e.addEventListener("abort",h,{once:!0}));let l=function(){a.onload=a.onerror=null,h&&(null==e||e.removeEventListener("abort",h)),s(a)};t?(a.onload=l,a.onerror=function(){h&&(null==e||e.removeEventListener("abort",h)),r(new n(`Error loading ${a.src}`))},i&&(a.crossOrigin=i),a.src=t):l()})),Ot=(t,{signal:e,reviver:i=y}={})=>new Promise(((s,r)=>{let h=[];e&&e.addEventListener("abort",r,{once:!0}),Promise.allSettled(t.map((t=>U.getClass(t.type).fromObject(t,{signal:e})))).then((async e=>{for(let[s,r]of e.entries())if("fulfilled"===r.status&&(await i(t[s],r.value),h.push(r.value)),"rejected"===r.status){let e=await i(t[s],void 0,r.reason);e&&h.push(e)}s(h)})).catch((t=>{h.forEach((t=>{t.dispose&&t.dispose()})),r(t)})).finally((()=>{e&&e.removeEventListener("abort",r)}))})),$t=(t,{signal:e}={})=>new Promise(((i,s)=>{let r=[];e&&e.addEventListener("abort",s,{once:!0});let h=Object.values(t).map((t=>t&&t.type&&U.has(t.type)?Ot([t],{signal:e}).then((([t])=>(r.push(t),t))):t)),n=Object.keys(t);Promise.all(h).then((t=>t.reduce(((t,e,i)=>(t[n[i]]=e,t)),{}))).then(i).catch((t=>{r.forEach((t=>{t.dispose&&t.dispose()})),s(t)})).finally((()=>{e&&e.removeEventListener("abort",s)}))})),jt=(t,e=[])=>e.reduce(((e,i)=>(i in t&&(e[i]=t[i]),e)),{}),At=(t,e)=>Object.keys(t).reduce(((i,s)=>(e(t[s],s,t)&&(i[s]=t[s]),i)),{}),Pt=(t,e)=>parseFloat(Number(t).toFixed(e)),Et=t=>"matrix("+t.map((t=>Pt(t,r.NUM_FRACTION_DIGITS))).join(" ")+")",Lt=t=>!!t&&void 0!==t.toLive,Bt=t=>!!t&&"function"==typeof t.toObject,Rt=t=>!!t&&void 0!==t.offsetX&&"source"in t,It=t=>!!t&&"multiSelectionStacking"in t;function Xt(t){let e=t&&Yt(t),i=0,s=0;if(!t||!e)return{left:i,top:s};let r=t,h=e.documentElement,n=e.body||{scrollLeft:0,scrollTop:0};for(;r&&(r.parentNode||r.host)&&(r=r.parentNode||r.host,r===e?(i=n.scrollLeft||h.scrollLeft||0,s=n.scrollTop||h.scrollTop||0):(i+=r.scrollLeft||0,s+=r.scrollTop||0),1!==r.nodeType||"fixed"!==r.style.position););return{left:i,top:s}}const Yt=t=>t.ownerDocument||null,zt=t=>{var e;return(null==(e=t.ownerDocument)?void 0:e.defaultView)||null},Wt=(t,e,{width:i,height:s},r=1)=>{t.width=i,t.height=s,r>1&&(t.setAttribute("width",(i*r).toString()),t.setAttribute("height",(s*r).toString()),e.scale(r,r))},Gt=(t,{width:e,height:i})=>{e&&(t.style.width="number"==typeof e?`${e}px`:e),i&&(t.style.height="number"==typeof i?`${i}px`:i)};function Nt(t){return void 0!==t.onselectstart&&(t.onselectstart=()=>!1),t.style.userSelect=F,t}var Ht=class{constructor(t){i(this,"_originalCanvasStyle",void 0),i(this,"lower",void 0);let e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){let e=(i=t)&&void 0!==i.getContext?t:t&&f().getElementById(t)||at();var i;if(e.hasAttribute("data-fabric"))throw new n("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({width:t,height:e}){let{el:i}=this.lower;i.classList.remove("lower-canvas"),i.removeAttribute("data-fabric"),i.setAttribute("width",`${t}`),i.setAttribute("height",`${e}`),i.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){let{el:i,ctx:s}=this.lower;Wt(i,s,t,e)}setCSSDimensions(t){Gt(this.lower.el,t)}calcOffset(){return function(t){var e;let i=t&&Yt(t),s={left:0,top:0};if(!i)return s;let r=(null==(e=zt(t))?void 0:e.getComputedStyle(t,null))||{};s.left+=parseInt(r.borderLeftWidth,10)||0,s.top+=parseInt(r.borderTopWidth,10)||0,s.left+=parseInt(r.paddingLeft,10)||0,s.top+=parseInt(r.paddingTop,10)||0;let h={left:0,top:0},n=i.documentElement;void 0!==t.getBoundingClientRect&&(h=t.getBoundingClientRect());let o=Xt(t);return{left:h.left+o.left-(n.clientLeft||0)+s.left,top:h.top+o.top-(n.clientTop||0)+s.top}}(this.lower.el)}dispose(){d().dispose(this.lower.el),delete this.lower}};const Vt={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...S],patternQuality:"best"},Ut=t=>t.toString().replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let qt;const Kt=t=>{if(qt||qt||(qt="Intl"in g()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),qt){let e=qt.segment(t);return Array.from(e).map((({segment:t})=>t))}return Jt(t)},Jt=t=>{let e=[];for(let i,s=0;s<t.length;s++)!1!==(i=Zt(t,s))&&e.push(i);return e},Zt=(t,e)=>{let i=t.charCodeAt(e);if(isNaN(i))return"";if(i<55296||i>57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";let i=t.charCodeAt(e+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";let s=t.charCodeAt(e-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var Qt=class t extends(st(rt)){get lowerCanvasEl(){var t;return null==(t=this.elements.lower)?void 0:t.el}get contextContainer(){var t;return null==(t=this.elements.lower)?void 0:t.ctx}static getDefaults(){return t.ownDefaults}constructor(t,e={}){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 Ht(t)}add(...t){let e=super.add(...t);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),e}insertAt(t,...e){let i=super.insertAt(t,...e);return e.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),i}remove(...t){let e=super.remove(...t);return e.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),e}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(h("warn","Canvas is trying to add an object that belongs to a different canvas.\nResulting 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?p():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(t,{cssOnly:e=!1,backstoreOnly:i=!1}={}){if(!e){let e={width:this.width,height:this.height,...t};this.elements.setDimensions(e,this.getRetinaScaling()),this.hasLostContext=!0,this.width=e.width,this.height=e.height}i||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return xt(this.viewportTransform)}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){let i=t,s=[...this.viewportTransform],r=gt(t,pt(s));s[0]=e,s[3]=e;let h=gt(r,s);s[4]+=i.x-h.x,s[5]+=i.y-h.y,this.setViewportTransform(s)}setZoom(t){this.zoomToPoint(new tt(0,0),t)}absolutePan(t){let e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new tt(-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=ht((()=>this.renderAndReset())))}calcViewportBoundaries(){let t=this.width,e=this.height,i=pt(this.viewportTransform),s=gt({x:0,y:0},i),r=gt({x:t,y:e},i),h=s.min(r),n=s.max(r);return this.vptCoords={tl:h,tr:new tt(n.x,h.y),bl:new tt(h.x,n.y),br:n}}cancelRequestedRender(){this.nextRenderHandle&&(function(t){g().cancelAnimationFrame(t)}(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;let i=this.viewportTransform,s=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality=this.patternQuality,this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),s&&(s._set("canvas",this),s.shouldCache(),s._transformDone=!0,s.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,s)),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){let i=this.viewportTransform;t.save(),t.transform(...i),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 i=0,s=e.length;i<s;++i)e[i]&&e[i].render(t)}_renderBackgroundOrOverlay(t,e){let i=this[`${e}Color`],s=this[`${e}Image`],r=this.viewportTransform,h=this[`${e}Vpt`];if(!i&&!s)return;let n=Lt(i);if(i){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=n?i.toLive(t):i,h&&t.transform(...r),n){t.transform(1,0,0,1,i.offsetX||0,i.offsetY||0);let e=i.gradientTransform||i.patternTransform;e&&t.transform(...e)}t.fill(),t.restore()}if(s){t.save();let{skipOffscreen:e}=this;this.skipOffscreen=h,h&&t.transform(...r),s.render(t),this.skipOffscreen=e,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenterPoint(){return new tt(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new tt(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new tt(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 tt(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new tt(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return gt(this.getCenterPoint(),pt(this.viewportTransform))}_centerObject(t,e){t.setXY(e,_,_),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){let i=this.clipPath,s=i&&!i.excludeFromExport?this._toObject(i,t,e):null;return{version:v,...jt(this,e),objects:this._objects.filter((t=>!t.excludeFromExport)).map((i=>this._toObject(i,t,e))),...this.__serializeBgOverlay(t,e),...s?{clipPath:s}:null}}_toObject(t,e,i){let s;this.includeDefaultValues||(s=t.includeDefaultValues,t.includeDefaultValues=!1);let r=t[e](i);return this.includeDefaultValues||(t.includeDefaultValues=!!s),r}__serializeBgOverlay(t,e){let i={},s=this.backgroundImage,r=this.overlayImage,h=this.backgroundColor,n=this.overlayColor;return Lt(h)?h.excludeFromExport||(i.background=h.toObject(e)):h&&(i.background=h),Lt(n)?n.excludeFromExport||(i.overlay=n.toObject(e)):n&&(i.overlay=n),s&&!s.excludeFromExport&&(i.backgroundImage=this._toObject(s,t,e)),r&&!r.excludeFromExport&&(i.overlayImage=this._toObject(r,t,e)),i}toSVG(t={},e){t.reviver=e;let i=[];var s;return this._setSVGPreamble(i,t),this._setSVGHeader(i,t),this.clipPath&&i.push(`<g clip-path="url(#${Ut(null==(s=this.clipPath.clipPathId)?"":s)})" >\n`),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("</g>\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push("</svg>"),i.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')}_setSVGHeader(t,e){let i,s=e.width||`${this.width}`,h=e.height||`${this.height}`,n=r.NUM_FRACTION_DIGITS,o=e.viewBox;if(o)i=`viewBox="${o.x} ${o.y} ${o.width} ${o.height}" `;else if(this.svgViewportTransformation){let t=this.viewportTransform;i=`viewBox="${Pt(-t[4]/t[0],n)} ${Pt(-t[5]/t[3],n)} ${Pt(this.width/t[0],n)} ${Pt(this.height/t[3],n)}" `}else i=`viewBox="0 0 ${this.width} ${this.height}" `;t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',h,'" ',i,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",v,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),"</defs>\n")}createSVGClipPathMarkup(t){let e=this.clipPath;return e?(e.clipPathId=`CLIPPATH_${ot()}`,`<clipPath id="${e.clipPathId}" >\n${e.toClipPathSVG(t.reviver)}</clipPath>\n`):""}createSVGRefElementsMarkup(){return["background","overlay"].map((t=>{let e=this[`${t}Color`];if(Lt(e)){let i=this[`${t}Vpt`],s=this.viewportTransform;return e.toSVG({isType:()=>!1,width:this.width/(i?s[0]:1),height:this.height/(i?s[3]:1)},{additionalTransform:i?Et(s):""})}})).join("")}createSVGFontFacesMarkup(){let t=[],e={},i=r.fontPaths;this._objects.forEach((function e(i){t.push(i),it(i)&&i._objects.forEach(e)})),t.forEach((t=>{if(!(s=t)||"function"!=typeof s._renderText)return;var s;let{styles:r,fontFamily:h}=t;!e[h]&&i[h]&&(e[h]=!0,r&&Object.values(r).forEach((t=>{Object.values(t).forEach((({fontFamily:t=""})=>{!e[t]&&i[t]&&(e[t]=!0)}))})))}));let s=Object.keys(e).map((t=>`\t\t@font-face {\n\t\t\tfont-family: '${t}';\n\t\t\tsrc: url('${i[t]}');\n\t\t}\n`)).join("");return s?`\t<style type="text/css"><![CDATA[\n${s}]]></style>\n`:""}_setSVGObjects(t,e){this.forEachObject((i=>{i.excludeFromExport||this._setSVGObject(t,i,e)}))}_setSVGObject(t,e,i){t.push(e.toSVG(i))}_setSVGBgOverlayImage(t,e,i){let s=this[e];s&&!s.excludeFromExport&&s.toSVG&&t.push(s.toSVG(i))}_setSVGBgOverlayColor(t,e){let i=this[`${e}Color`];if(i)if(Lt(i)){let s=i.repeat||"",r=this.width,h=this.height,n=this[`${e}Vpt`]?Et(pt(this.viewportTransform)):"";t.push(`<rect transform="${n} translate(${r/2},${h/2})" x="${i.offsetX-r/2}" y="${i.offsetY-h/2}" width="${"repeat-y"!==s&&"no-repeat"!==s||!Rt(i)?r:i.source.width}" height="${"repeat-x"!==s&&"no-repeat"!==s||!Rt(i)?h:i.source.height}" fill="url(#SVGID_${i.id})"></rect>\n`)}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',i,'"',"></rect>\n")}loadFromJSON(t,e,{signal:i}={}){if(!t)return Promise.reject(new n("`json` is undefined"));let{objects:s=[],...r}="string"==typeof t?JSON.parse(t):t,{backgroundImage:h,background:o,overlayImage:a,overlay:l,clipPath:u}=r,c=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Ot(s,{reviver:e,signal:i}),$t({backgroundImage:h,backgroundColor:o,overlayImage:a,overlayColor:l,clipPath:u},{signal:i})]).then((([t,e])=>(this.clear(),this.add(...t),this.set(r),this.set(e),this.renderOnAddRemove=c,this)))}clone(t){let e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){let t=lt(this);return new this.constructor(t)}toDataURL(t={}){let{format:e="png",quality:i=1,multiplier:s=1,enableRetinaScaling:r=!1}=t,h=s*(r?this.getRetinaScaling():1);return ut(this.toCanvasElement(h,t),e,i)}toBlob(t={}){let{format:e="png",quality:i=1,multiplier:s=1,enableRetinaScaling:r=!1}=t,h=s*(r?this.getRetinaScaling():1);return ct(this.toCanvasElement(h,t),e,i)}toCanvasElement(t=1,{width:e,height:i,left:s,top:r,filter:h}={}){let n=(e||this.width)*t,o=(i||this.height)*t,a=this.getZoom(),l=this.width,u=this.height,c=this.skipControlsDrawing,d=a*t,f=this.viewportTransform,g=[d,0,0,d,(f[4]-(s||0))*t,(f[5]-(r||0))*t],p=this.enableRetinaScaling,m=lt({width:n,height:o}),v=h?this._objects.filter((t=>h(t))):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=g,this.width=n,this.height=o,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(m.getContext("2d"),v),this.viewportTransform=f,this.width=l,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=p,this.skipControlsDrawing=c,m}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),q.cancelByCanvas(this),this.disposed=!0,new Promise(((t,e)=>{let i=()=>{this.destroy(),t(!0)};i.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=i:i()}))}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject((t=>t.dispose())),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return`#<Canvas (${this.complexity()}): { objects: ${this._objects.length} }>`}};i(Qt,"ownDefaults",Vt);const te=["touchstart","touchmove","touchend"],ee=t=>te.includes(t.type)||"touch"===t.pointerType,ie=t=>{t.preventDefault(),t.stopPropagation()},se=t=>{let e=0,i=0,s=0,r=0;for(let h=0,n=t.length;h<n;h++){let{x:n,y:o}=t[h];(n>s||!h)&&(s=n),(n<e||!h)&&(e=n),(o>r||!h)&&(r=o),(o<i||!h)&&(i=o)}return{left:e,top:i,width:s-e,height:r-i}},re=(t,e)=>{let{translateX:i,translateY:s,scaleX:r,scaleY:h,...n}=bt(e),o=new tt(i,s);t.flipX=!1,t.flipY=!1,Object.assign(t,n),t.set({scaleX:r,scaleY:h}),t.setPositionByOrigin(o,_,_)},he=t=>({scaleX:t.scaleX,scaleY:t.scaleY,skewX:t.skewX,skewY:t.skewY,angle:t.angle,left:t.left,flipX:t.flipX,flipY:t.flipY,top:t.top}),ne=(t,e,i)=>{let s=t/2,r=e/2,h=se([new tt(-s,-r),new tt(s,-r),new tt(-s,r),new tt(s,r)].map((t=>t.transform(i))));return new tt(h.width,h.height)},oe=(t=S,e=S)=>mt(pt(e),t),ae=(t,e=S,i=S)=>t.transform(oe(e,i)),le={left:-.5,top:-.5,center:0,bottom:.5,right:.5},ue=t=>"string"==typeof t?le[t]:t-.5,ce=new tt(1,0),de=new tt,fe=(t,e)=>t.rotate(e),ge=(t,e)=>new tt(e).subtract(t),pe=t=>t.distanceFrom(de),me=(t,e)=>Math.atan2(we(t,e),be(t,e)),ve=t=>me(ce,t),ye=t=>t.eq(de)?t:t.scalarDivide(pe(t)),xe=(t,e=!0)=>ye(new tt(-t.y,t.x).scalarMultiply(e?1:-1)),we=(t,e)=>t.x*e.y-t.y*e.x,be=(t,e)=>t.x*e.x+t.y*e.y,Ce=(t,e,i)=>{if(t.eq(e)||t.eq(i))return!0;let s=we(e,i),r=we(e,t),h=we(i,t);return s>=0?r>=0&&h<=0:!(r<=0&&h>=0)},Se="not-allowed";function _e(t){return ue(t.originX)===ue("center")&&ue(t.originY)===ue("center")}function Te(t){return.5-ue(t)}const Me=(t,e)=>t[e],ke=(t,e,i,s)=>({e:t,transform:e,pointer:new tt(i,s)});function Fe(t,e,i){let s=i,r=ve(ge(ae(t.getCenterPoint(),t.canvas.viewportTransform,void 0),s))+b;return Math.round(r%b/w)}function De({target:t,corner:e},i,s,r,h){var n;let o=t.controls[e],a=(null==(n=t.canvas)?void 0:n.getZoom())||1,l=t.padding/a,u=function(t,e,i,s){let r=t.getRelativeCenterPoint(),h=void 0!==i&&void 0!==s?t.translateToGivenOrigin(r,_,_,i,s):new tt(t.left,t.top);return(t.angle?e.rotate(-dt(t.angle),r):e).subtract(h)}(t,new tt(r,h),i,s);return u.x>=l&&(u.x-=l),u.x<=-l&&(u.x+=l),u.y>=l&&(u.y-=l),u.y<=l&&(u.y+=l),u.x-=o.offsetX,u.y-=o.offsetY,u}const Oe=new RegExp(String.raw`[\0-\x1F\x7F;<>\\]|\/\*|\*\/|url\s*\(|expression\s*\(|(?:java|vb)script\s*:|data\s*:|@import\b`,"iu"),$e=t=>"string"==typeof t&&t.trim().length>0&&!Oe.test(t),je=(t,e="")=>{let i=Number(t);return Number.isFinite(i)?`${i}`:e},Ae=(t,e="")=>"string"==typeof t&&$e(t)?t:e,Pe=t=>t.replace(/\s+/g," "),Ee={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"},Le=(t,e,i)=>(i<0&&(i+=1),i>1&&--i,i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t),Be=(t,e,i,s)=>{t/=255,e/=255,i/=255;let r,h,n=Math.max(t,e,i),o=Math.min(t,e,i),a=(n+o)/2;if(n===o)r=h=0;else{let s=n-o;switch(h=a>.5?s/(2-n-o):s/(n+o),n){case t:r=(e-i)/s+(e<i?6:0);break;case e:r=(i-t)/s+2;break;case i:r=(t-e)/s+4}r/=6}return[Math.round(360*r),Math.round(100*h),Math.round(100*a),s]},Re=(t="1")=>parseFloat(t)/(t.endsWith("%")?100:1),Ie=t=>Math.min(Math.round(t),255).toString(16).toUpperCase().padStart(2,"0"),Xe=([t,e,i,s=1])=>{let r=Math.round(.3*t+.59*e+.11*i);return[r,r,r,s]};var Ye=class t{constructor(e){if(i(this,"isUnrecognised",!1),e)if(e instanceof t)this.setSource([...e._source]);else if(Array.isArray(e)){let[t,i,s,r=1]=e;this.setSource([t,i,s,r])}else this.setSource(this._tryParsingColor(e));else this.setSource([0,0,0,1])}_tryParsingColor(e){return(e=e.toLowerCase())in Ee&&(e=Ee[e]),"transparent"===e?[255,255,255,0]:t.sourceFromHex(e)||t.sourceFromRgb(e)||t.sourceFromHsl(e)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){let[t,e,i]=this.getSource();return`rgb(${t},${e},${i})`}toRgba(){return`rgba(${this.getSource().join(",")})`}toHsl(){let[t,e,i]=Be(...this.getSource());return`hsl(${t},${e}%,${i}%)`}toHsla(){let[t,e,i,s]=Be(...this.getSource());return`hsla(${t},${e}%,${i}%,${s})`}toHex(){return this.toHexa().slice(0,6)}toHexa(){let[t,e,i,s]=this.getSource();return`${Ie(t)}${Ie(e)}${Ie(i)}${Ie(Math.round(255*s))}`}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(Xe(this.getSource())),this}toBlackWhite(t){let[e,,,i]=Xe(this.getSource()),s=e<(t||127)?0:255;return this.setSource([s,s,s,i]),this}overlayWith(e){e instanceof t||(e=new t(e));let i=this.getSource(),s=e.getSource(),[r,h,n]=i.map(((t,e)=>Math.round(.5*t+.5*s[e])));return this.setSource([r,h,n,i[3]]),this}static fromRgb(e){return t.fromRgba(e)}static fromRgba(e){return new t(t.sourceFromRgb(e))}static sourceFromRgb(t){let e=Pe(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){let[t,i,s]=e.slice(1,4).map((t=>{let e=parseFloat(t);return t.endsWith("%")?Math.round(2.55*e):e}));return[t,i,s,Re(e[4])]}}static fromHsl(e){return t.fromHsla(e)}static fromHsla(e){return new t(t.sourceFromHsl(e))}static sourceFromHsl(e){let i=Pe(e).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(!i)return;let s,r,h,n=(t.parseAngletoDegrees(i[1])%360+360)%360/360,o=parseFloat(i[2])/100,a=parseFloat(i[3])/100;if(0===o)s=r=h=a;else{let t=a<=.5?a*(o+1):a+o-a*o,e=2*a-t;s=Le(e,t,n+1/3),r=Le(e,t,n),h=Le(e,t,n-1/3)}return[Math.round(255*s),Math.round(255*r),Math.round(255*h),Re(i[4])]}static fromHex(e){return new t(t.sourceFromHex(e))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){let e,i=t.slice(t.indexOf("#")+1);e=i.length<=4?i.split("").map((t=>t+t)):i.match(/.{2}/g);let[s,r,h,n=255]=e.map((t=>parseInt(t,16)));return[s,r,h,n/255]}}static parseAngletoDegrees(t){let e=t.toLowerCase(),i=parseFloat(e);return e.includes("rad")?ft(i):e.includes("turn")?360*i:i}};const ze=(t,e=16)=>{let i=/\D{0,2}$/.exec(t),s=parseFloat(t),h=r.DPI;switch(null==i?void 0:i[0]){case"mm":return s*h/25.4;case"cm":return s*h/2.54;case"in":return s*h;case"pt":return s*h/72;case"pc":return s*h/72*12;case"em":return s*e;default:return s}},We=(t,e,i=!0)=>{let s,r;if(e)if(e.toLive)s=`url(#SVGID_${Ut(e.id)})`;else{let t=String(e);if($e(t)){let e=new Ye(t),i=e.getAlpha();s=e.toRgb(),1!==i&&(r=i.toString())}else s=new Ye("black").toRgb()}else s="none";return i?`${t}: ${s}; ${r?`${t}-opacity: ${r}; `:""}`:`${t}="${s}" ${r?`${t}-opacity="${r}" `:""}`};var Ge=class{getSvgStyles(t){let e=null==this.fillRule?"nonzero":Ae(this.fillRule),i=null==this.strokeWidth?"0":je(this.strokeWidth),s=null==this.strokeDashArray?F:this.strokeDashArray.every((t=>Number.isFinite(Number(t))))?this.strokeDashArray.join(" "):"",r=null==this.strokeDashOffset?"0":je(this.strokeDashOffset),h=null==this.strokeLineCap?"butt":Ae(this.strokeLineCap),n=null==this.strokeLineJoin?"miter":Ae(this.strokeLineJoin),o=null==this.strokeMiterLimit?"4":je(this.strokeMiterLimit),a=null==this.opacity?"1":je(this.opacity),l=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),c=We(W,this.fill);return[We(G,this.stroke),i?`stroke-width: ${i}; `:"",s?`stroke-dasharray: ${s}; `:"",h?`stroke-linecap: ${h}; `:"",r?`stroke-dashoffset: ${r}; `:"",n?`stroke-linejoin: ${n}; `:"",o?`stroke-miterlimit: ${o}; `:"",c,e?`fill-rule: ${e}; `:"",a?`opacity: ${a};`:"",u,l].map((t=>Ut(t))).join("")}getSvgFilter(){return this.shadow?`filter: url(#SVGID_${Ut(this.shadow.id)});`:""}getSvgCommons(){return[this.id?`id="${Ut(String(this.id))}" `:"",this.clipPath?`clip-path="url(#${Ut(this.clipPath.clipPathId)})" `:""].join("")}getSvgTransform(t,e=""){return`transform="${Et(t?this.calcTransformMatrix():this.calcOwnMatrix())}${e}" `}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t,{reviver:e,additionalTransform:i=""}={}){let s=[this.getSvgTransform(!0,i),this.getSvgCommons()].join(""),r=t.indexOf("COMMON_PARTS");return t[r]=s,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t,{noStyle:e,reviver:i,withShadow:s,additionalTransform:r}={}){let h,n=e?"":`style="${this.getSvgStyles()}" `,o=s?`style="${this.getSvgFilter()}" `:"",a=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",u=a&&a.absolutePositioned,c=this.stroke,d=this.fill,f=this.shadow,g=[],p=t.indexOf("COMMON_PARTS");return a&&(a.clipPathId=`CLIPPATH_${ot()}`,h=`<clipPath id="${a.clipPathId}" >\n${a.toClipPathSVG(i)}</clipPath>\n`),u&&g.push("<g ",o,this.getSvgCommons()," >\n"),g.push("<g ",this.getSvgTransform(!1),u?"":o+this.getSvgCommons()," >\n"),t[p]=[n,l,e?"":this.addPaintOrder()," ",r?`transform="${r}" `:""].join(""),Lt(d)&&g.push(d.toSVG(this)),Lt(c)&&g.push(c.toSVG(this)),f&&g.push(f.toSVG(this)),a&&g.push(h),g.push(t.join("")),g.push("</g>\n"),u&&g.push("</g>\n"),i?i(g.join("")):g.join("")}addPaintOrder(){return"fill"===this.paintFirst?"":` paint-order="${Ut(this.paintFirst)}" `}};function Ne(t){return RegExp("^("+t.join("|")+")\\b","i")}const He="textDecorationThickness",Ve="textDecorationColor",Ue=["fontSize","fontWeight","fontFamily","fontStyle"],qe=["underline","overline","linethrough"],Ke=[...Ue,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],Je=[...Ke,...qe,"textBackgroundColor","direction",He,Ve],Ze=[...Ue,...qe,G,"strokeWidth",W,"deltaY","textBackgroundColor",He,Ve],Qe={_reNewline:D,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:H,fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:T,fontStyle:H,lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:T,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,[He]:66.667},ti="justify",ei=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,ii=RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+ei+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+ei+"))?\\s+(.*)"),si={cx:T,x:T,r:"radius",cy:"top",y:"top",display:"visible",visibility:"visible",transform:"transformMatrix","fill-opacity":"fillOpacity","fill-rule":"fillRule","font-family":"fontFamily","font-size":"fontSize","font-style":"fontStyle","font-weight":"fontWeight","letter-spacing":"charSpacing","paint-order":"paintFirst","stroke-dasharray":"strokeDashArray","stroke-dashoffset":"strokeDashOffset","stroke-linecap":"strokeLineCap","stroke-linejoin":"strokeLineJoin","stroke-miterlimit":"strokeMiterLimit","stroke-opacity":"strokeOpacity","stroke-width":"strokeWidth","text-decoration":"textDecoration","text-anchor":"textAnchor",opacity:"opacity","clip-path":"clipPath","clip-rule":"clipRule","vector-effect":"strokeUniform","image-rendering":"imageSmoothing","text-decoration-thickness":He,"text-decoration-color":Ve},ri="font-size",hi="clip-path";Ne(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Ne(["symbol","image","marker","pattern","view","svg"]);const ni=Ne(["symbol","g","a","svg","clipPath","defs"]),oi="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",ai=RegExp("(?:\\s|^)"+oi+oi+"("+ei+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");var li=class t{constructor(e={}){let i="string"==typeof e?t.parseShadow(e):e;Object.assign(this,t.ownDefaults,i),this.id=ot()}static parseShadow(t){let e=t.trim(),[,i=0,s=0,r=0]=(ai.exec(e)||[]).map((t=>parseFloat(t)||0));return{color:(e.replace(ai,"")||"rgb(0,0,0)").trim(),offsetX:i,offsetY:s,blur:r}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){let e=fe(new tt(this.offsetX,this.offsetY),dt(-t.angle)),i=r.NUM_FRACTION_DIGITS,s=new Ye(this.color),h=40,n=40;return t.width&&t.height&&(h=100*Pt((Math.abs(e.x)+this.blur)/t.width,i)+20,n=100*Pt((Math.abs(e.y)+this.blur)/t.height,i)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),`<filter id="SVGID_${Ut(this.id)}" y="-${n}%" height="${100+2*n}%" x="-${h}%" width="${100+2*h}%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="${Pt(this.blur?this.blur/2:0,i)}"></feGaussianBlur>\n\t<feOffset dx="${Pt(e.x,i)}" dy="${Pt(e.y,i)}" result="oBlur" ></feOffset>\n\t<feFlood flood-color="${s.toRgb()}" flood-opacity="${s.getAlpha()}"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n`}toObject(){let e={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},i=t.ownDefaults;return this.includeDefaultValues?e:At(e,((t,e)=>t!==i[e]))}static async fromObject(t){return new this(t)}};i(li,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),i(li,"type","shadow"),U.setClass(li,"shadow");const ui=(t,e,i)=>Math.max(t,Math.min(e,i)),ci=["top",T,I,X,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Y,z],di=[W,G,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],fi={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:_,originY:_,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:W,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},gi=(t,e,i,s)=>-i*Math.cos(t/s*x)+i+e,pi=()=>!1;var mi=class{constructor({startValue:t,byValue:e,duration:s=500,delay:r=0,easing:h=gi,onStart:n=y,onChange:o=y,onComplete:a=y,abort:l=pi,target:u}){i(this,"_state","pending"),i(this,"durationProgress",0),i(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=s,this.delay=r,this.easing=h,this._onStart=n,this._onChange=o,this._onComplete=a,this._abort=l,this.target=u,this.startValue=t,this.byValue=e,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return"aborted"===this._state||"completed"===this._state}start(){let t=t=>{"pending"===this._state&&(this.startTime=t||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?this.timeout=g().setTimeout((()=>ht(t)),this.delay):ht(t)}tick(t){let e=(t||+new Date)-this.startTime,i=Math.min(e,this.duration);this.durationProgress=i/this.duration;let{value:s,valueProgress:r}=this.calculate(i);this.value=Object.freeze(s),this.valueProgress=r,"aborted"!==this._state&&(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.timeout=null):(this._onChange(this.value,this.valueProgress,this.durationProgress),ht(this.tick)))}register(){q.push(this)}unregister(){q.remove(this)}abort(){this._state="aborted",this.unregister(),this.timeout&&g().clearTimeout(this.timeout)}},vi=class extends mi{constructor({startValue:t=0,endValue:e=100,...i}){super({...i,startValue:t,byValue:e-t})}calculate(t){let e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}},yi=class extends mi{constructor({startValue:t=[0],endValue:e=[100],...i}){super({...i,startValue:t,byValue:e.map(((e,i)=>e-t[i]))})}calculate(t){let e=this.startValue.map(((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i)));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}};const xi=(t,e,i,s)=>e+i*(1-Math.cos(t/s*x)),wi=t=>t&&((e,i,s)=>t(new Ye(e).toRgba(),i,s));var bi=class extends mi{constructor({startValue:t,endValue:e,easing:i=xi,onChange:s,onComplete:r,abort:h,...n}){let o=new Ye(t).getSource(),a=new Ye(e).getSource();super({...n,startValue:o,byValue:a.map(((t,e)=>t-o[e])),easing:i,onChange:wi(s),onComplete:wi(r),abort:wi(h)})}calculate(t){let[e,i,s,r]=this.startValue.map(((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i))),h=[...[e,i,s].map(Math.round),ui(0,r,1)];return{value:h,valueProgress:h.map(((t,e)=>0===this.byValue[e]?0:Math.abs((t-this.startValue[e])/this.byValue[e]))).find((t=>0!==t))||0}}};function Ci(t){let e=(t=>Array.isArray(t.startValue)||Array.isArray(t.endValue))(t)?new yi(t):new vi(t);return e.start(),e}var Si=class t{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some((e=>e.eq(t)))}append(...t){return this.points=this.points.concat(t.filter((t=>!this.includes(t)))),this}static isPointContained(t,e,i,s=!1){if(e.eq(i))return t.eq(e);if(e.x===i.x)return t.x===e.x&&(s||t.y>=Math.min(e.y,i.y)&&t.y<=Math.max(e.y,i.y));if(e.y===i.y)return t.y===e.y&&(s||t.x>=Math.min(e.x,i.x)&&t.x<=Math.max(e.x,i.x));{let r=ge(e,i),h=ge(e,t).divide(r);return s?Math.abs(h.x)===Math.abs(h.y):h.x===h.y&&h.x>=0&&h.x<=1}}static isPointInPolygon(t,e){let i=new tt(t).setX(Math.min(t.x-1,...e.map((t=>t.x)))),s=0;for(let r=0;r<e.length;r++){let h=this.intersectSegmentSegment(e[r],e[(r+1)%e.length],t,i);if(h.includes(t))return!0;s+=Number("Intersection"===h.status)}return s%2==1}static intersectLineLine(e,i,s,r,h=!0,n=!0){let o=i.x-e.x,a=i.y-e.y,l=r.x-s.x,u=r.y-s.y,c=e.x-s.x,d=e.y-s.y,f=l*d-u*c,g=o*d-a*c,p=u*o-l*a;if(0!==p){let i=f/p,s=g/p;return(h||0<=i&&i<=1)&&(n||0<=s&&s<=1)?new t("Intersection").append(new tt(e.x+i*o,e.y+i*a)):new t}return new t(0===f||0===g?h||n||t.isPointContained(e,s,r)||t.isPointContained(i,s,r)||t.isPointContained(s,e,i)||t.isPointContained(r,e,i)?"Coincident":void 0:"Parallel")}static intersectSegmentLine(e,i,s,r){return t.intersectLineLine(e,i,s,r,!1,!0)}static intersectSegmentSegment(e,i,s,r){return t.intersectLineLine(e,i,s,r,!1,!1)}static intersectLinePolygon(e,i,s,r=!0){let h=new t,n=s.length;for(let o,a,l,u=0;u<n;u++){if(o=s[u],a=s[(u+1)%n],l=t.intersectLineLine(e,i,o,a,r,!1),"Coincident"===l.status)return l;h.append(...l.points)}return h.points.length>0&&(h.status="Intersection"),h}static intersectSegmentPolygon(e,i,s){return t.intersectLinePolygon(e,i,s,!1)}static intersectPolygonPolygon(e,i){let s=new t,r=e.length,h=[];for(let n=0;n<r;n++){let o=e[n],a=e[(n+1)%r],l=t.intersectSegmentPolygon(o,a,i);"Coincident"===l.status?(h.push(l),s.append(o,a)):s.append(...l.points)}return h.length>0&&h.length===e.length?new t("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(e,i,s){let r=i.min(s),h=i.max(s),n=new tt(h.x,r.y),o=new tt(r.x,h.y);return t.intersectPolygonPolygon(e,[r,n,h,o])}},_i=class extends rt{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(){let t=this.getRelativeXY();return this.group?gt(t,this.group.calcTransformMatrix()):t}setXY(t,e,i){this.group&&(t=gt(t,pt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,i)}getRelativeXY(){return new tt(this.left,this.top)}setRelativeXY(t,e=this.originX,i=this.originY){this.setPositionByOrigin(t,e,i)}isStrokeAccountedForInDimensions(){return!1}getCoords(){let{tl:t,tr:e,br:i,bl:s}=this.aCoords||(this.aCoords=this.calcACoords()),r=[t,e,i,s];if(this.group){let t=this.group.calcTransformMatrix();return r.map((e=>gt(e,t)))}return r}intersectsWithRect(t,e){return"Intersection"===Si.intersectPolygonRectangle(this.getCoords(),t,e).status}intersectsWithObject(t){let e=Si.intersectPolygonPolygon(this.getCoords(),t.getCoords());return"Intersection"===e.status||"Coincident"===e.status||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every((e=>t.containsPoint(e)))}isContainedWithinRect(t,e){let{left:i,top:s,width:r,height:h}=this.getBoundingRect();return i>=t.x&&i+r<=e.x&&s>=t.y&&s+h<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return Si.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;let{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some((i=>i.x<=e.x&&i.x>=t.x&&i.y<=e.y&&i.y>=t.y))||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;let{tl:t,br:e}=this.canvas.vptCoords;return!!this.intersectsWithRect(t,e)||this.getCoords().every((i=>(i.x>=e.x||i.x<=t.x)&&(i.y>=e.y||i.y<=t.y)))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return se(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(I,t),this._set(X,t),this.setCoords()}scaleToWidth(t){let e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){let e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return(null==(t=this.canvas)?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?ft(yt(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return(null==(t=this.canvas)?void 0:t.viewportTransform)||S.concat()}calcACoords(){let t=St({angle:this.angle}),{x:e,y:i}=this.getRelativeCenterPoint(),s=mt(Ct(e,i),t),r=this._getTransformedDimensions(),h=r.x/2,n=r.y/2;return{tl:gt({x:-h,y:-n},s),tr:gt({x:h,y:-n},s),bl:gt({x:-h,y:n},s),br:gt({x:h,y:n},s)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(t=!1){let 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,ue(this.originX),ue(this.originY)),e}calcTransformMatrix(t=!1){let e=this.calcOwnMatrix();if(t||!this.group)return e;let i=this.transformMatrixKey(t),s=this.matrixCache;return s&&s.key.every(((t,e)=>t===i[e]))?s.value:(this.group&&(e=mt(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:i,value:e},e)}calcOwnMatrix(){let t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key.every(((e,i)=>e===t[i])))return e.value;let i=this.getRelativeCenterPoint(),s=(t=>{let{translateX:e=0,translateY:i=0,angle:s=0}=t,r=Ct(e,i);s&&(r=mt(r,St({angle:s})));let h=Ft(t);return(t=>t.every(((t,e)=>t===S[e])))(h)||(r=mt(r,h)),r})({angle:this.angle,translateX:i.x,translateY:i.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY});return this.ownMatrixCache={key:t,value:s},s}_getNonTransformedDimensions(){return new tt(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){var e;let i=null==(e=this.canvas)?void 0:e.viewportTransform,s=this._getTransformedDimensions(t);return i?s.multiply(new tt(xt(i),wt(i))).scalarAdd(2*this.padding):s.scalarAdd(2*this.padding)}_getTransformedDimensions(t={}){let e={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth,...t},i=e.strokeWidth,s=i,r=0;this.strokeUniform&&(s=0,r=i);let h,n=e.width+s,o=e.height+s;return h=0===e.skewX&&0===e.skewY?new tt(n*e.scaleX,o*e.scaleY):ne(n,o,Ft(e)),h.scalarAdd(r)}translateToGivenOrigin(t,e,i,s,r){let h=t.x,n=t.y,o=ue(s)-ue(e),a=ue(r)-ue(i);if(o||a){let t=this._getTransformedDimensions();h+=o*t.x,n+=a*t.y}return new tt(h,n)}translateToCenterPoint(t,e,i){if("center"===e&&"center"===i)return t;let s=this.translateToGivenOrigin(t,e,i,_,_);return this.angle?s.rotate(dt(this.angle),t):s}translateToOriginPoint(t,e,i){let s=this.translateToGivenOrigin(t,_,_,e,i);return this.angle?s.rotate(dt(this.angle),t):s}getCenterPoint(){let t=this.getRelativeCenterPoint();return this.group?gt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new tt(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.getPositionByOrigin(t,e)}getPositionByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,i){let s=this.translateToCenterPoint(t,e,i),r=this.translateToOriginPoint(s,this.originX,this.originY);this.set({left:r.x,top:r.y})}_getLeftTopCoords(){return this.getPositionByOrigin(T,"top")}positionByLeftTop(t){return this.setPositionByOrigin(t,T,"top")}},Ti=class t extends _i{static getDefaults(){return t.ownDefaults}get type(){let t=this.constructor.type;return"FabricObject"===t?"object":t.toLowerCase()}set type(t){h("warn","Setting type has no effect",t)}constructor(e){super(),i(this,"_cacheContext",null),Object.assign(this,t.ownDefaults),this.setOptions(e)}_createCacheCanvas(){this._cacheCanvas=at(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){let e=t.width,i=t.height,s=r.maxCacheSideLimit,h=r.minCacheSideLimit;if(e<=s&&i<=s&&e*i<=r.perfLimitSizeTotal)return e<h&&(t.width=h),i<h&&(t.height=h),t;let n=e/i,[o,a]=m.limitDimsByArea(n),l=ui(h,o,s),u=ui(h,a,s);return e>l&&(t.zoomX/=e/l,t.width=l,t.capped=!0),i>u&&(t.zoomY/=i/u,t.height=u,t.capped=!0),t}_getCacheCanvasDimensions(){let t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),i=e.x*t.x/this.scaleX,s=e.y*t.y/this.scaleY;return{width:Math.ceil(i+2),height:Math.ceil(s+2),zoomX:t.x,zoomY:t.y,x:i,y:s}}_updateCacheCanvas(){let t=this._cacheCanvas,e=this._cacheContext,{width:i,height:s,zoomX:r,zoomY:h,x:n,y:o}=this._limitCacheSize(this._getCacheCanvasDimensions());if(!t||!e)return!1;if(i!==t.width||s!==t.height||this.zoomX!==r||this.zoomY!==h){i!==t.width||s!==t.height?(t.width=i,t.height=s):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));let a=n/2,l=o/2;return this.cacheTranslationX=Math.round(t.width/2-a)+a,this.cacheTranslationY=Math.round(t.height/2-l)+l,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(r,h),this.zoomX=r,this.zoomY=h,!0}return!1}setOptions(t={}){this._setOptions(t)}transform(t){let e=this.calcTransformMatrix(!(this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop));t.transform(e[0],e[1],e[2],e[3],e[4],e[5])}getObjectScaling(){if(!this.group)return new tt(Math.abs(this.scaleX),Math.abs(this.scaleY));let t=bt(this.calcTransformMatrix());return new tt(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){let t=this.getObjectScaling();if(this.canvas){let e=this.canvas.getZoom(),i=this.getCanvasRetinaScaling();return t.scalarMultiply(e*i)}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:0===t?1e-4:t}_set(t,e){"scaleX"!==t&&"scaleY"!==t||(e=this._constrainScale(e)),"scaleX"===t&&e<0?(this.flipX=!this.flipX,e*=-1):"scaleY"===t&&e<0?(this.flipY=!this.flipY,e*=-1):"shadow"!==t||!e||e instanceof li||(e=new li(e));let i=this[t]!==e;return this[t]=e,i&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||i&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!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){let{zoomX:e,zoomY:i,cacheTranslationX:s,cacheTranslationY:r}=this,{width:h,height:n}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:i,cacheTranslationX:s,cacheTranslationY:r,width:h,height:n,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return!!this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth}hasFill(){return!!this.fill&&"transparent"!==this.fill}needsItsOwnCache(){return!!("stroke"===this.paintFirst&&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&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)}drawClipPathOnCache(t,e,i){t.save(),t.globalCompositeOperation=e.inverted?"destination-out":"destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(i,0,0),t.restore()}drawObject(t,e,i){let s=this.fill,r=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this.fire("before:render",{ctx:t}),this._render(t),this._drawClipPath(t,this.clipPath,i),this.fill=s,this.stroke=r}createClipPathLayer(t,e){let i=lt(e),s=i.getContext("2d");if(s.translate(e.cacheTranslationX,e.cacheTranslationY),s.scale(e.zoomX,e.zoomY),t._cacheCanvas=i,e.parentClipPaths.forEach((t=>{t.transform(s)})),e.parentClipPaths.push(t),t.absolutePositioned){let t=pt(this.calcTransformMatrix());s.transform(t[0],t[1],t[2],t[3],t[4],t[5])}return t.transform(s),t.drawObject(s,!0,e),i}_drawClipPath(t,e,i){if(!e)return;e._transformDone=!0;let s=this.createClipPathLayer(e,i);this.drawClipPathOnCache(t,e,s)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(t=!1){if(this.isNotVisible())return!1;let e=this._cacheCanvas,i=this._cacheContext;return!(!e||!i||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&i&&!t&&(i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,e.width,e.height),i.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;let 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){let i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,Lt(i)?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)}_setFillStyles(t,{fill:e}){e&&(Lt(e)?(t.fillStyle=e.toLive(t),this._applyPatternGradientTransform(t,e)):t.fillStyle=e)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&0!==e.length&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;let e=this.shadow,i=this.canvas,s=this.getCanvasRetinaScaling(),[h,,,n]=(null==i?void 0:i.viewportTransform)||S,o=h*s,a=n*s,l=e.nonScaling?new tt(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*r.browserShadowBlurConstant*(o+a)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*o*l.x,t.shadowOffsetY=e.offsetY*a*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!Lt(e))return{offsetX:0,offsetY:0};let i=e.gradientTransform||e.patternTransform,s=-this.width/2+e.offsetX||0,r=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,s,r):t.transform(1,0,0,1,s,r),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:s,offsetY:r}}_renderPaintInOrder(t){"stroke"===this.paintFirst?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){let 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 i;let s=this._limitCacheSize(this._getCacheCanvasDimensions()),r=this.getCanvasRetinaScaling(),h=s.x/this.scaleX/r,n=s.y/this.scaleY/r,o=lt({width:Math.ceil(h),height:Math.ceil(n)}),a=o.getContext("2d");a&&(a.beginPath(),a.moveTo(0,0),a.lineTo(h,0),a.lineTo(h,n),a.lineTo(0,n),a.closePath(),a.translate(h/2,n/2),a.scale(s.zoomX/this.scaleX/r,s.zoomY/this.scaleY/r),this._applyPatternGradientTransform(a,e),a.fillStyle=e.toLive(t),a.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(r*this.scaleX/s.zoomX,r*this.scaleY/s.zoomY),t.strokeStyle=null==(i=a.createPattern(o,"no-repeat"))?"":i)}_findCenterFromElement(){return new tt(this.left+this.width/2,this.top+this.height/2)}clone(t){let e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){let e=this.toCanvasElement(t);return new(U.getClass("image"))(e)}toCanvasElement(t={}){let e=he(this),i=this.group,s=this.shadow,r=Math.abs,h=t.enableRetinaScaling?p():1,n=(t.multiplier||1)*h,o=t.canvasProvider||(t=>new Qt(t,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&(t=>{t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.rotate(0)})(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&((t,e)=>{let i=oe(e,void 0);re(t,mt(i,t.calcOwnMatrix()))})(this,this.getViewportTransform()),this.setCoords();let a=at(),l=this.getBoundingRect(),u=this.shadow,c=new tt;if(u){let t=u.blur,e=u.nonScaling?new tt(1,1):this.getObjectScaling();c.x=2*Math.round(r(u.offsetX)+t)*r(e.x),c.y=2*Math.round(r(u.offsetY)+t)*r(e.y)}let d=l.height+c.y;a.width=Math.ceil(l.width+c.x),a.height=Math.ceil(d);let f=o(a);"jpeg"===t.format&&(f.backgroundColor="#fff"),this.setPositionByOrigin(new tt(f.width/2,f.height/2),_,_);let g=this.canvas;f._objects=[this],this.set("canvas",f),this.setCoords();let m=f.toCanvasElement(n||1,t);return this.set("canvas",g),this.shadow=s,i&&(this.group=i),this.set(e),this.setCoords(),f._objects=[],f.destroy(),m}toDataURL(t={}){return ut(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(t={}){return ct(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(...t){return t.includes(this.constructor.type)||t.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){let{centeredRotation:e,originX:i,originY:s}=this;if(e){let{x:t,y:e}=this.getRelativeCenterPoint();this.originX=_,this.originY=_,this.left=t,this.top=e}if(this.set("angle",t),e){let{x:t,y:e}=this.getPositionByOrigin(i,s);this.left=t,this.top=e,this.originX=i,this.originY=s}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){q.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&d().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce(((t,[i,s])=>(t[i]=this._animate(i,s,e),t)),{})}_animate(t,e,i={}){let s=t.split("."),r=this.constructor.colorProperties.includes(s[s.length-1]),{abort:h,startValue:n,onChange:o,onComplete:a}=i,l={...i,target:this,startValue:null==n?s.reduce(((t,e)=>t[e]),this):n,endValue:e,abort:null==h?void 0:h.bind(this),onChange:(t,e,i)=>{s.reduce(((e,i,r)=>(r===s.length-1&&(e[i]=t),e[i])),this),o&&o(t,e,i)},onComplete:(t,e,i)=>{this.setCoords(),a&&a(t,e,i)}};return r?function(t){let e=new bi(t);return e.start(),e}(l):Ci(l)}isDescendantOf(t){let{parent:e,group:i}=this;return e===t||i===t||!!e&&e.isDescendantOf(t)||!!i&&i!==e&&i.isDescendantOf(t)}getAncestors(){let t=[],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()]};let e=this.getAncestors(),i=t.getAncestors();if(0===e.length&&i.length>0&&this===i[i.length-1])return{fork:[],otherFork:[t,...i.slice(0,i.length-1)],common:[this]};for(let s,r=0;r<e.length;r++){if(s=e[r],s===t)return{fork:[this,...e.slice(0,r)],otherFork:[],common:e.slice(r)};for(let h=0;h<i.length;h++){if(this===i[h])return{fork:[],otherFork:[t,...i.slice(0,h)],common:[this,...e]};if(s===i[h])return{fork:[this,...e.slice(0,r)],otherFork:[t,...i.slice(0,h)],common:e.slice(r)}}}return{fork:[this,...e],otherFork:[t,...i],common:[]}}hasCommonAncestors(t){let e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;let e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;let i=e.common[0]||this.canvas;if(!i)return;let s=e.fork.pop(),r=e.otherFork.pop(),h=i._objects.indexOf(s),n=i._objects.indexOf(r);return h>-1&&h>n}toObject(e=[]){let i,s=e.concat(t.customProperties,this.constructor.customProperties||[]),h=r.NUM_FRACTION_DIGITS,{clipPath:n,fill:o,stroke:a,shadow:l,strokeDashArray:u,left:c,top:d,originX:f,originY:g,width:p,height:m,strokeWidth:y,strokeLineCap:x,strokeDashOffset:w,strokeLineJoin:b,strokeUniform:C,strokeMiterLimit:S,scaleX:_,scaleY:T,angle:M,flipX:k,flipY:F,opacity:D,visible:O,backgroundColor:$,fillRule:j,paintFirst:A,globalCompositeOperation:P,skewX:E,skewY:L}=this;n&&!n.excludeFromExport&&(i=n.toObject(s.concat("inverted","absolutePositioned")));let B=t=>Pt(t,h),R={...jt(this,s),type:this.constructor.type,version:v,originX:f,originY:g,left:B(c),top:B(d),width:B(p),height:B(m),fill:Bt(o)?o.toObject():o,stroke:Bt(a)?a.toObject():a,strokeWidth:B(y),strokeDashArray:u&&u.concat(),strokeLineCap:x,strokeDashOffset:w,strokeLineJoin:b,strokeUniform:C,strokeMiterLimit:B(S),scaleX:B(_),scaleY:B(T),angle:B(M),flipX:k,flipY:F,opacity:B(D),shadow:l&&l.toObject(),visible:O,backgroundColor:$,fillRule:j,paintFirst:A,globalCompositeOperation:P,skewX:B(E),skewY:B(L),...i?{clipPath:i}:null};return this.includeDefaultValues?R:this._removeDefaultValues(R)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){let e=this.constructor.getDefaults(),i=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return At(t,((t,e)=>{if("left"===e||"top"===e||"type"===e)return!0;let s=i[e];return t!==s&&!(Array.isArray(t)&&Array.isArray(s)&&0===t.length&&0===s.length)}))}toString(){return`#<${this.constructor.type}>`}static _fromObject({type:t,...e},{extraParam:i,...s}={}){return $t(e,s).then((t=>i?(delete t[i],new this(e[i],t)):new this(t)))}static fromObject(t,e){return this._fromObject(t,e)}};i(Ti,"stateProperties",ci),i(Ti,"cacheProperties",di),i(Ti,"ownDefaults",fi),i(Ti,"type","FabricObject"),i(Ti,"colorProperties",[W,G,"backgroundColor"]),i(Ti,"customProperties",[]),U.setClass(Ti),U.setClass(Ti,"object");const Mi=(t,e)=>{var i;let{transform:{target:s}}=e;null==(i=s.canvas)||i.fire(`object:${t}`,{...e,target:s}),s.fire(t,e)},ki=(t,e,i)=>(s,r,h,n)=>{let o=e(s,r,h,n);return o&&Mi(t,{...ke(s,r,h,n),...i}),o};function Fi(t){return(e,i,s,r)=>{let{target:h,originX:n,originY:o}=i,a=h.getPositionByOrigin(n,o),l=t(e,i,s,r);return h.setPositionByOrigin(a,i.originX,i.originY),l}}const Di=((t,e,i,s)=>(e,i,r,h)=>{let n=De(i,i.originX,i.originY,r,h).x,o=ue(i.originX);if(0===o||o>0&&n<0||o<0&&n>0){let{target:e}=i,r=e.strokeWidth/(e.strokeUniform?e[s]:1),h=_e(i)?2:1,o=e[t],a=Math.abs(n*h/e[s])-r;return e.set(t,Math.max(a,1)),o!==e[t]}return!1})("width",0,0,"scaleX"),Oi=ki(E,Fi(Di));function $i(t,e,i,s,r){t.save();let{stroke:h,xSize:n,ySize:o,opName:a}=this.commonRenderProps(t,e,i,r,s),l=n;n>o?t.scale(1,o/n):o>n&&(l=o,t.scale(n/o,1)),t.beginPath(),t.arc(0,0,l/2,0,b,!1),t[a](),h&&t.stroke(),t.restore()}function ji(t,e,i,s,r){t.save();let{stroke:h,xSize:n,ySize:o,opName:a}=this.commonRenderProps(t,e,i,r,s),l=n/2,u=o/2;t[`${a}Rect`](-l,-u,n,o),h&&t.strokeRect(-l,-u,n,o),t.restore()}var Ai=class{constructor(t){i(this,"visible",!0),i(this,"actionName",R),i(this,"angle",0),i(this,"x",0),i(this,"y",0),i(this,"offsetX",0),i(this,"offsetY",0),i(this,"sizeX",0),i(this,"sizeY",0),i(this,"touchSizeX",0),i(this,"touchSizeY",0),i(this,"cursorStyle","crosshair"),i(this,"withConnection",!1),Object.assign(this,t)}getTransformAnchorPoint(){var t;return null==(t=this.transformAnchorPoint)?new tt(.5-this.x,.5-this.y):t}shouldActivate(t,e,i,{tl:s,tr:r,br:h,bl:n}){var o;return(null==(o=e.canvas)?void 0:o.getActiveObject())===e&&e.isControlVisible(t)&&Si.isPointInPolygon(i,[s,r,h,n])}getActionHandler(t,e,i){return this.actionHandler}getMouseDownHandler(t,e,i){return this.mouseDownHandler}getMouseUpHandler(t,e,i){return this.mouseUpHandler}cursorStyleHandler(t,e,i,s){return e.cursorStyle}getActionName(t,e,i){return e.actionName}getVisibility(t,e){var i,s;return null==(i=null==(s=t._controlsVisibility)?void 0:s[e])?this.visible:i}setVisibility(t,e,i){this.visible=t}positionHandler(t,e,i,s){return new tt(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,i,s,r,h){let n=vt([Ct(i,s),St({angle:t}),_t((r?this.touchSizeX:this.sizeX)||e,(r?this.touchSizeY:this.sizeY)||e)]);return{tl:new tt(-.5,-.5).transform(n),tr:new tt(.5,-.5).transform(n),br:new tt(.5,.5).transform(n),bl:new tt(-.5,.5).transform(n)}}commonRenderProps(t,e,i,s,r={}){let{cornerSize:h,cornerColor:n,transparentCorners:o,cornerStrokeColor:a}=r,l=h||s.cornerSize,u=this.sizeX||l,c=this.sizeY||l,d=void 0===o?s.transparentCorners:o,f=d?G:W,g=a||s.cornerStrokeColor,p=!d&&!!g;return t.fillStyle=n||s.cornerColor||"",t.strokeStyle=g||"",t.translate(e,i),t.rotate(dt(s.getTotalAngle())),{stroke:p,xSize:u,ySize:c,transparentCorners:d,opName:f}}render(t,e,i,s,r){"circle"===((s=s||{}).cornerStyle||r.cornerStyle)?$i.call(this,t,e,i,s,r):ji.call(this,t,e,i,s,r)}};const Pi=(t,e,i)=>i.lockRotation?Se:e.cursorStyle,Ei=ki(j,Fi(((t,{target:e,ex:i,ey:s,theta:r,originX:h,originY:n},o,a)=>{let l=e.getPositionByOrigin(h,n);if(Me(e,"lockRotation"))return!1;let u=Math.atan2(s-l.y,i-l.x),c=ft(Math.atan2(a-l.y,o-l.x)-u+r);if(e.snapAngle&&e.snapAngle>0){let t=e.snapAngle,i=e.snapThreshold||t,s=Math.ceil(c/t)*t,r=Math.floor(c/t)*t;Math.abs(c-r)<i?c=r:Math.abs(c-s)<i&&(c=s)}c<0&&(c=360+c),c%=360;let d=e.angle!==c;return e.angle=c,d})));function Li(t,e){let i=e.canvas,s=t[i.uniScaleKey];return i.uniformScaling&&!s||!i.uniformScaling&&s}function Bi(t,e,i){let s=Me(t,"lockScalingX"),r=Me(t,"lockScalingY");if(s&&r||!e&&(s||r)&&i||s&&"x"===e||r&&"y"===e)return!0;let{width:h,height:n,strokeWidth:o}=t;return 0===h&&0===o&&"y"!==e||0===n&&0===o&&"x"!==e}const Ri=["e","se","s","sw","w","nw","n","ne","e"],Ii=(t,e,i,s)=>{let r=Li(t,i);return Bi(i,0!==e.x&&0===e.y?"x":0===e.x&&0!==e.y?"y":"",r)?Se:`${Ri[Fe(i,0,s)]}-resize`};function Xi(t,e,i,s,r={}){let h,n,o,a,l,u,c=e.target,d=r.by,f=Li(t,c);if(Bi(c,d,f))return!1;if(e.gestureScale)n=e.scaleX*e.gestureScale,o=e.scaleY*e.gestureScale;else{if(h=De(e,e.originX,e.originY,i,s),l="y"===d?1:Math.sign(h.x||e.signX||1),u="x"===d?1:Math.sign(h.y||e.signY||1),e.signX||(e.signX=l),e.signY||(e.signY=u),Me(c,"lockScalingFlip")&&(e.signX!==l||e.signY!==u))return!1;if(a=c._getTransformedDimensions(),f&&!d){let t=Math.abs(h.x)+Math.abs(h.y),{original:i}=e,s=t/(Math.abs(a.x*i.scaleX/c.scaleX)+Math.abs(a.y*i.scaleY/c.scaleY));n=i.scaleX*s,o=i.scaleY*s}else n=Math.abs(h.x*c.scaleX/a.x),o=Math.abs(h.y*c.scaleY/a.y);_e(e)&&(n*=2,o*=2),e.signX!==l&&"y"!==d&&(e.originX=Te(e.originX),n*=-1,e.signX=l),e.signY!==u&&"x"!==d&&(e.originY=Te(e.originY),o*=-1,e.signY=u)}let g=c.scaleX,p=c.scaleY;return d?("x"===d&&c.set("scaleX",n),"y"===d&&c.set("scaleY",o)):(!Me(c,"lockScalingX")&&c.set("scaleX",n),!Me(c,"lockScalingY")&&c.set("scaleY",o)),g!==c.scaleX||p!==c.scaleY}const Yi=ki($,Fi(((t,e,i,s)=>Xi(t,e,i,s)))),zi=ki($,Fi(((t,e,i,s)=>Xi(t,e,i,s,{by:"x"})))),Wi=ki($,Fi(((t,e,i,s)=>Xi(t,e,i,s,{by:"y"})))),Gi={x:{counterAxis:"y",scale:I,skew:Y,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:X,skew:z,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Ni=["ns","nesw","ew","nwse"];function Hi(t,e,i,s,r){let{target:h}=i,{counterAxis:n,origin:o,lockSkewing:a,skew:l,flip:u}=Gi[t];if(Me(h,a))return!1;let{origin:c,flip:d}=Gi[n],f=ue(i[c])*(h[d]?-1:1),g=-Math.sign(f)*(h[u]?-1:1),p=-(0===h[l]&&De(i,"center","center",s,r)[t]>0||h[l]>0?1:-1)*g*.5+.5;return ki(P,Fi(((e,i,s,r)=>function(t,{target:e,ex:i,ey:s,skewingSide:r,...h},n){let{skew:o}=Gi[t],a=n.subtract(new tt(i,s)).divide(new tt(e.scaleX,e.scaleY))[t],l=e[o],u=Math.tan(dt(h[o])),c="y"===t?e._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:e._getTransformedDimensions({scaleX:1,scaleY:1}).y,d=2*a*r/Math.max(c,1)+u,f=ft(Math.atan(d));e.set(o,f);let g=l!==e[o];if(g&&"y"===t){let{skewX:t,scaleX:i}=e,s=e._getTransformedDimensions({skewY:l}),r=e._getTransformedDimensions(),h=0===t?1:s.x/r.x;1!==h&&e.set("scaleX",h*i)}return g}(t,i,new tt(s,r)))))(e,{...i,[o]:p,skewingSide:g},s,r)}function Vi(t,e){return t[e.canvas.altActionKey]}const Ui=(t,e,i)=>{let s=Vi(t,i);return 0===e.x?s?Y:X:0===e.y?s?z:I:""},qi=(t,e,i,s)=>Vi(t,i)?((t,e,i,s)=>0!==e.x&&Me(i,"lockSkewingY")||0!==e.y&&Me(i,"lockSkewingX")?Se:`${Ni[Fe(i,0,s)%4]}-resize`)(0,e,i,s):Ii(t,e,i,s),Ki=(t,e,i,s)=>Vi(t,e.target)?((t,e,i,s)=>Hi("y",t,e,i,s))(t,e,i,s):zi(t,e,i,s),Ji=(t,e,i,s)=>Vi(t,e.target)?((t,e,i,s)=>Hi("x",t,e,i,s))(t,e,i,s):Wi(t,e,i,s),Zi=()=>({ml:new Ai({x:-.5,y:0,cursorStyleHandler:qi,actionHandler:Ki,getActionName:Ui}),mr:new Ai({x:.5,y:0,cursorStyleHandler:qi,actionHandler:Ki,getActionName:Ui}),mb:new Ai({x:0,y:.5,cursorStyleHandler:qi,actionHandler:Ji,getActionName:Ui}),mt:new Ai({x:0,y:-.5,cursorStyleHandler:qi,actionHandler:Ji,getActionName:Ui}),tl:new Ai({x:-.5,y:-.5,cursorStyleHandler:Ii,actionHandler:Yi}),tr:new Ai({x:.5,y:-.5,cursorStyleHandler:Ii,actionHandler:Yi}),bl:new Ai({x:-.5,y:.5,cursorStyleHandler:Ii,actionHandler:Yi}),br:new Ai({x:.5,y:.5,cursorStyleHandler:Ii,actionHandler:Yi}),mtr:new Ai({x:0,y:-.5,actionHandler:Ei,cursorStyleHandler:Pi,offsetY:-40,withConnection:!0,actionName:A})});var Qi=class t extends Ti{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e){super(),Object.assign(this,this.constructor.createControls(),t.ownDefaults),this.setOptions(e)}static createControls(){return{controls:Zi()}}_updateCacheCanvas(){let t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){let e=t._currentTransform,i=e.action;if(this===e.target&&i&&i.startsWith("scale"))return!1}return super._updateCacheCanvas()}getActiveControl(){let t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t,e=!1){if(!this.hasControls||!this.canvas)return;this.__corner=void 0;let i=Object.entries(this.oCoords);for(let s=i.length-1;s>=0;s--){let[r,h]=i[s],n=this.controls[r];if(n.shouldActivate(r,this,t,e?h.touchCorner:h.corner))return this.__corner=r,{key:r,control:n,coord:this.oCoords[r]}}}calcOCoords(){let t=this.getViewportTransform(),e=xt(t),i=wt(t),s=this.getCenterPoint(),r=mt(mt(t,mt(Ct(s.x,s.y),St({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}))),[1/e,0,0,1/i,0,0]),h=this.group?bt(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));let n=this._calculateCurrentDimensions(h),o={};return this.forEachControl(((t,e)=>{let i=t.positionHandler(n,r,this,t);o[e]=Object.assign(i,this._calcCornerCoords(t,i))})),o}_calcCornerCoords(t,e){let i=this.getTotalAngle();return{corner:t.calcCornerCoords(i,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(i,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(let e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();let e=this.getRelativeCenterPoint(),i=this._calculateCurrentDimensions(),s=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/s[0],1/s[3]),t.rotate(dt(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-i.x/2,-i.y/2,i.x,i.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e,i={}){let s={hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray,...i};t.save(),t.strokeStyle=s.borderColor,this._setLineDash(t,s.borderDashArray),this.strokeBorders(t,e),s.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t,e={}){let{hasBorders:i,hasControls:s}=this,r={hasBorders:i,hasControls:s,...e},h=this.getViewportTransform(),n=r.hasBorders,o=r.hasControls,a=bt(mt(h,this.calcTransformMatrix()));t.save(),t.translate(a.translateX,a.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(a.angle-=180);let l=yt(h);t.rotate(this.group?dt(a.angle):dt(this.angle)+l),n&&this.drawBorders(t,a,e),o&&this.drawControls(t,e),t.restore()}drawBorders(t,e,i){let s;if(i&&i.forActiveSelection||this.group){let t=ne(this.width,this.height,Ft(e)),i=this.isStrokeAccountedForInDimensions()?et:(this.strokeUniform?(new tt).scalarAdd(this.canvas?this.canvas.getZoom():1):new tt(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);s=t.add(i).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else s=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,s,i)}drawControlsConnectingLines(t,e){let i=!1;t.beginPath(),this.forEachControl(((s,r)=>{s.withConnection&&s.getVisibility(this,r)&&(i=!0,t.moveTo(s.x*e.x,s.y*e.y),t.lineTo(s.x*e.x+s.offsetX,s.y*e.y+s.offsetY))})),i&&t.stroke()}drawControls(t,e={}){t.save();let i=this.getCanvasRetinaScaling(),{cornerStrokeColor:s,cornerDashArray:r,cornerColor:h}=this,n={cornerStrokeColor:s,cornerDashArray:r,cornerColor:h,...e};t.setTransform(i,0,0,i,0,0),t.strokeStyle=t.fillStyle=n.cornerColor,this.transparentCorners||(t.strokeStyle=n.cornerStrokeColor),this._setLineDash(t,n.cornerDashArray),this.forEachControl(((e,i)=>{if(e.getVisibility(this,i)){let s=this.oCoords[i];e.render(t,s.x,s.y,n,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(t={}){Object.entries(t).forEach((([t,e])=>this.setControlVisible(t,e)))}clearContextTop(t){if(!this.canvas)return;let e=this.canvas.contextTop;if(!e)return;let i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e);let s=this.width+4,r=this.height+4;return e.clearRect(-s/2,-r/2,s,r),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 ts(t,e){return e.forEach((e=>{Object.getOwnPropertyNames(e.prototype).forEach((i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i)||Object.create(null))}))})),t}i(Qi,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});var es=class extends Qi{};ts(es,[Ge]),U.setClass(es),U.setClass(es,"object");var is=class{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new tt(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new tt(1/this.options.scaleX,1/this.options.scaleY):new tt(1,1)}createSideVector(t,e){let i=ge(t,e);return this.options.strokeUniform?i.multiply(this.scale):i}projectOrthogonally(t,e,i){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,i)))}isSkewed(){return 0!==this.options.skewX||0!==this.options.skewY}applySkew(t){let e=new tt(t);return e.y+=e.x*Math.tan(dt(this.options.skewY)),e.x+=e.y*Math.tan(dt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}};const ss=new tt;var rs=class t extends is{static getOrthogonalRotationFactor(t,e){let i=e?me(t,e):ve(t);return Math.abs(i)<x?-1:1}constructor(t,e,s,r){super(r),i(this,"AB",void 0),i(this,"AC",void 0),i(this,"alpha",void 0),i(this,"bisector",void 0),this.A=new tt(t),this.B=new tt(e),this.C=new tt(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=me(this.AB,this.AC),this.bisector=ye(fe(this.AB.eq(ss)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(e,i,s=this.strokeProjectionMagnitude){let r=xe(this.createSideVector(e,i)),h=t.getOrthogonalRotationFactor(r,this.bisector);return this.scaleUnitVector(r,s*h)}projectBevel(){let t=[];return(this.alpha%b==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(){let t=[],e=Math.abs(this.alpha),i=1/Math.sin(e/2),s=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*i),r=this.options.strokeUniform?pe(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return pe(s)/this.strokeProjectionMagnitude<=r&&t.push(this.applySkew(this.A.add(s))),t.push(...this.projectBevel()),t}projectRoundNoSkew(e,i){let s=[],r=new tt(t.getOrthogonalRotationFactor(this.bisector),t.getOrthogonalRotationFactor(new tt(this.bisector.y,this.bisector.x)));return[new tt(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r),new tt(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r)].forEach((t=>{Ce(t,e,i)&&s.push(this.A.add(t))})),s}projectRoundWithSkew(t,e){let i=[],{skewX:s,skewY:r,scaleX:h,scaleY:n,strokeUniform:o}=this.options,a=new tt(Math.tan(dt(s)),Math.tan(dt(r))),l=this.strokeProjectionMagnitude,u=o?l/n/Math.sqrt(1/n**2+1/h**2*a.y**2):l/Math.sqrt(1+a.y**2),c=new tt(Math.sqrt(Math.max(l**2-u**2,0)),u),d=o?l/Math.sqrt(1+a.x**2*(1/n)**2/(1/h+1/h*a.x*a.y)**2):l/Math.sqrt(1+a.x**2/(1+a.x*a.y)**2),f=new tt(d,Math.sqrt(Math.max(l**2-d**2,0)));return[f,f.scalarMultiply(-1),c,c.scalarMultiply(-1)].map((t=>this.applySkew(o?t.multiply(this.strokeUniformScalar):t))).forEach((s=>{Ce(s,t,e)&&i.push(this.applySkew(this.A).add(s))})),i}projectRound(){let t=[];t.push(...this.projectBevel());let e=this.alpha%b==0,i=this.applySkew(this.A),s=t[e?0:2].subtract(i),r=t[+!!e].subtract(i),h=we(s,this.applySkew(e?this.AB.scalarMultiply(-1):this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)))>0,n=h?s:r,o=h?r:s;return this.isSkewed()?t.push(...this.projectRoundWithSkew(n,o)):t.push(...this.projectRoundNoSkew(n,o)),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})))}},hs=class extends is{constructor(t,e,i){super(i),this.A=new tt(t),this.T=new tt(e)}calcOrthogonalProjection(t,e,i=this.strokeProjectionMagnitude){let s=this.createSideVector(t,e);return this.scaleUnitVector(xe(s),i)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){let t=[];if(!this.isSkewed()&&this.A.eq(this.T)){let e=new tt(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 rs(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){let t=[];if(this.A.eq(this.T)){let e=new tt(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{let e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),i=this.scaleUnitVector(ye(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),s=this.A.add(i);t.push(s.add(e),s.subtract(e))}return t.map((t=>this.applySkew(t)))}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 ns=t=>{let e={};return Object.keys(t).forEach((i=>{e[i]={},Object.keys(t[i]).forEach((s=>{e[i][s]={...t[i][s]}}))})),e},os=(t,e,i=!1)=>t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle||t.textDecorationThickness!==e.textDecorationThickness||t.textDecorationColor!==e.textDecorationColor||t.textBackgroundColor!==e.textBackgroundColor||t.deltaY!==e.deltaY||i&&(t.overline!==e.overline||t.underline!==e.underline||t.linethrough!==e.linethrough),as=(t,e)=>{let i=e.split("\n"),s=[],r=-1,h={};t=ns(t);for(let e=0;e<i.length;e++){let n=Kt(i[e]);if(t[e])for(let i=0;i<n.length;i++){r++;let n=t[e][i];n&&Object.keys(n).length>0&&(os(h,n,!0)?s.push({start:r,end:r+1,style:n}):s[s.length-1].end++),h=n||{}}else r+=n.length,h={}}return s},ls=(t,e)=>{if(!Array.isArray(t))return ns(t);let i=e.split(D),s={},r=-1,h=0;for(let e=0;e<i.length;e++){let n=Kt(i[e]);for(let i=0;i<n.length;i++)r++,t[h]&&t[h].start<=r&&r<t[h].end&&(s[e]=s[e]||{},s[e][i]={...t[h].style},r===t[h].end-1&&h++)}return s},us=["display","transform",W,"fill-opacity","fill-rule","opacity",G,"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 cs(t,e){let i,s=t.nodeName,r=t.getAttribute("class"),h=t.getAttribute("id"),n="(?![a-zA-Z\\-]+)";if(i=RegExp("^"+s,"i"),e=e.replace(i,""),h&&e.length&&(i=RegExp("#"+h+n,"i"),e=e.replace(i,"")),r&&e.length){let t=r.split(" ");for(let s=t.length;s--;)i=RegExp("\\."+t[s]+n,"i"),e=e.replace(i,"")}return 0===e.length}function ds(t,e){let i=!0,s=cs(t,e.pop());return s&&e.length&&(i=function(t,e){let i,s=!0;for(;t.parentElement&&1===t.parentElement.nodeType&&e.length;)s&&(i=e.pop()),s=cs(t=t.parentElement,i);return 0===e.length}(t,e)),s&&i&&0===e.length}function fs(t,e={}){let i={};for(let s in e)ds(t,s.split(" "))&&(i={...i,...e[s]});return i}const gs=t=>{var e;return null==(e=si[t])?t:e},ps=RegExp(`(${ei})`,"gi"),ms=`(${ei})`,vs=String.raw`(skewX)\(${ms}\)`,ys=String.raw`(skewY)\(${ms}\)`,xs=String.raw`(rotate)\(${ms}(?: ${ms} ${ms})?\)`,ws=String.raw`(scale)\(${ms}(?: ${ms})?\)`,bs=String.raw`(translate)\(${ms}(?: ${ms})?\)`,Cs=`(?:${String.raw`(matrix)\(${ms} ${ms} ${ms} ${ms} ${ms} ${ms}\)`}|${bs}|${xs}|${ws}|${vs}|${ys})`,Ss=String.raw`^\s*(?:${`(?:${Cs}*)`}?)\s*$`,_s=new RegExp(Ss),Ts=new RegExp(Cs),Ms=new RegExp(Cs,"g");function ks(t){let e=[];if(!(t=(t=>Pe(t.replace(ps," $1 ").replace(/,/gi," ")))(t).replace(/\s*([()])\s*/gi,"$1"))||t&&!_s.test(t))return[...S];for(let i of t.matchAll(Ms)){let t=Ts.exec(i[0]);if(!t)continue;let s=S,[,r,...h]=t.filter((t=>!!t)),[n,o,a,l,u,c]=h.map((t=>parseFloat(t)));switch(r){case"translate":s=Ct(n,o);break;case A:s=St({angle:n},{x:o,y:a});break;case R:s=_t(n,o);break;case Y:s=Mt(n);break;case z:s=kt(n);break;case"matrix":s=[n,o,a,l,u,c]}e.push(s)}return vt(e)}function Fs(t,e,i,s){let r,h=Array.isArray(e),n=e;if("fill"!==t&&"stroke"!==t||"none"!==e){if("strokeUniform"===t)return"non-scaling-stroke"===e;if("strokeDashArray"===t)n="none"===e?null:e.replace(/,/g," ").split(/\s+/).map(parseFloat);else if("transformMatrix"===t)n=i&&i.transformMatrix?mt(i.transformMatrix,ks(e)):ks(e);else if("visible"===t)n="none"!==e&&"hidden"!==e,i&&!1===i.visible&&(n=!1);else if("opacity"===t)n=parseFloat(e),i&&void 0!==i.opacity&&(n*=i.opacity);else if("textAnchor"===t)n="start"===e?T:"end"===e?k:_;else if("charSpacing"===t||"textDecorationThickness"===t)r=ze(e,s)/s*1e3;else if("paintFirst"===t){let t=e.indexOf(W),i=e.indexOf(G);n=W,(t>-1&&i>-1&&i<t||-1===t&&i>-1)&&(n=G)}else{if("href"===t||"xlink:href"===t||"font"===t||"id"===t)return e;if("imageSmoothing"===t)return"optimizeQuality"===e;r=h?e.map(ze):ze(e,s)}}else n="";return!h&&isNaN(r)?n:r}function Ds(t){let e={},i=t.getAttribute("style");return i&&("string"==typeof i?function(t,e){t.replace(/;\s*$/,"").split(";").forEach((t=>{if(!t)return;let[i,s]=t.split(":");e[i.trim().toLowerCase()]=s.trim()}))}(i,e):function(t,e){Object.entries(t).forEach((([t,i])=>{void 0!==i&&(e[t.toLowerCase()]=i)}))}(i,e)),e}const Os={stroke:"strokeOpacity",fill:"fillOpacity"};function $s(t,e,i){if(!t)return{};let s,r={},h=16;t.parentNode&&ni.test(t.parentNode.nodeName)&&(r=$s(t.parentElement,e,i),r.fontSize&&(s=h=ze(r.fontSize)));let n={...e.reduce(((e,i)=>{let s=t.getAttribute(i);return s&&(e[i]=s),e}),{}),...fs(t,i),...Ds(t)};n["clip-path"]&&t.setAttribute(hi,n[hi]),n["font-size"]&&(s=ze(n[ri],h),n[ri]=`${s}`);let o={};for(let t in n){let e=gs(t);o[e]=Fs(e,n[t],r,s)}o&&o.font&&function(t,e){let i=t.match(ii);if(!i)return;let s=i[1],r=i[3],h=i[4],n=i[5],o=i[6];s&&(e.fontStyle=s),r&&(e.fontWeight=isNaN(parseFloat(r))?r:parseFloat(r)),h&&(e.fontSize=ze(h)),o&&(e.fontFamily=o),n&&(e.lineHeight="normal"===n?1:n)}(o.font,o);let a={...r,...o};return ni.test(t.nodeName)?a:function(t){let e=es.getDefaults();return Object.entries(Os).forEach((([i,s])=>{if(void 0===t[s]||""===t[i])return;if(void 0===t[i]){if(!e[i])return;t[i]=e[i]}if(0===t[i].indexOf("url("))return;let r=new Ye(t[i]);t[i]=r.setAlpha(Pt(r.getAlpha()*t[s],2)).toRgba()})),t}(a)}const js=["rx","ry"];var As=class t extends es{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e){super(),Object.assign(this,t.ownDefaults),this.setOptions(e),this._initRxRy()}_initRxRy(){let{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){let{width:e,height:i}=this,s=-e/2,r=-i/2,h=this.rx?Math.min(this.rx,e/2):0,n=this.ry?Math.min(this.ry,i/2):0,o=0!==h||0!==n;t.beginPath(),t.moveTo(s+h,r),t.lineTo(s+e-h,r),o&&t.bezierCurveTo(s+e-.4477152502*h,r,s+e,r+.4477152502*n,s+e,r+n),t.lineTo(s+e,r+i-n),o&&t.bezierCurveTo(s+e,r+i-.4477152502*n,s+e-.4477152502*h,r+i,s+e-h,r+i),t.lineTo(s+h,r+i),o&&t.bezierCurveTo(s+.4477152502*h,r+i,s,r+i-.4477152502*n,s,r+i-n),t.lineTo(s,r+n),o&&t.bezierCurveTo(s,r+.4477152502*n,s+.4477152502*h,r,s+h,r),t.closePath(),this._renderPaintInOrder(t)}toObject(t=[]){return super.toObject([...js,...t])}_toSVG(){let{width:t,height:e,rx:i,ry:s}=this;return["<rect ","COMMON_PARTS",`x="${-t/2}" y="${-e/2}" rx="${Ut(i)}" ry="${Ut(s)}" width="${Ut(t)}" height="${Ut(e)}" />\n`]}static async fromElement(t,e,i){let{left:s=0,top:r=0,width:h=0,height:n=0,visible:o=!0,...a}=$s(t,this.ATTRIBUTE_NAMES,i);return new this({...e,...a,left:s,top:r,width:h,height:n,visible:!!(o&&h&&n)})}};i(As,"type","Rect"),i(As,"cacheProperties",[...di,...js]),i(As,"ownDefaults",{rx:0,ry:0}),i(As,"ATTRIBUTE_NAMES",[...us,"x","y","rx","ry","width","height"]),U.setClass(As),U.setSVGClass(As);const Ps="initialization",Es="added",Ls=(t,e)=>{let{strokeUniform:i,strokeWidth:s,width:r,height:h,group:n}=e,o=n&&n!==t?oe(n.calcTransformMatrix(),t.calcTransformMatrix()):null,a=o?e.getRelativeCenterPoint().transform(o):e.getRelativeCenterPoint(),l=!e.isStrokeAccountedForInDimensions(),u=i&&l?((t,e=S,i=S)=>t.transform(oe(e,i),!0))(new tt(s,s),void 0,t.calcTransformMatrix()):et,c=!i&&l?s:0,d=ne(r+c,h+c,vt([o,e.calcOwnMatrix()],!0)).add(u).scalarDivide(2);return[a.subtract(d),a.add(d)]};var Bs=class{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout({type:t,prevStrategy:e,strategy:i}){return"initialization"===t||"imperative"===t||!!e&&i!==e}shouldLayoutClipPath({type:t,target:{clipPath:e}}){return"initialization"!==t&&e&&!e.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){let{type:i,target:s}=e;if("imperative"===i&&e.overrides)return e.overrides;if(0===t.length)return;let{left:r,top:h,width:n,height:o}=se(t.map((t=>Ls(s,t))).reduce(((t,e)=>t.concat(e)),[])),a=new tt(n,o),l=new tt(r,h).add(a.scalarDivide(2));if("initialization"===i){let t=this.getInitialSize(e,{size:a,center:l});return{center:l,relativeCorrection:new tt(0,0),size:t}}return{center:l.transform(s.calcOwnMatrix()),size:a}}};i(Bs,"type","strategy");var Rs=class extends Bs{shouldPerformLayout(t){return!0}};i(Rs,"type","fit-content"),U.setClass(Rs);const Is="layoutManager";var Xs=class{constructor(t=new Rs){i(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){let e={bubbles:!0,strategy:this.strategy,...t,prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}};this.onBeforeLayout(e);let i=this.getLayoutResult(e);i&&this.commitLayout(e,i),this.onAfterLayout(e,i),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){let{target:i}=e;return[N,O,E,j,$,P,B,L,"modifyPath"].map((e=>t.on(e,(t=>this.performLayout("modified"===e?{type:"object_modified",trigger:e,e:t,target:i}:{type:"object_modifying",trigger:e,e:t,target:i})))))}subscribe(t,e){this.unsubscribe(t,e);let i=this.attachHandlers(t,e);this._subscriptions.set(t,i)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach((t=>t())),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){let{target:e,type:i}=t,{canvas:s}=e;if("initialization"===i||"added"===i?this.subscribeTargets(t):"removed"===i&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),s&&s.fire("object:layout:before",{target:e,context:t}),"imperative"===i&&t.deep){let{strategy:i,...s}=t;e.forEachObject((t=>t.layoutManager&&t.layoutManager.performLayout({...s,bubbles:!1,target:t})))}}getLayoutResult(t){let{target:e,strategy:i,type:s}=t,r=i.calcLayoutResult(t,e.getObjects());if(!r)return;let h="initialization"===s?new tt:e.getRelativeCenterPoint(),{center:n,correction:o=new tt,relativeCorrection:a=new tt}=r;return{result:r,prevCenter:h,nextCenter:n,offset:h.subtract(n).add(o).transform("initialization"===s?S:pt(e.calcOwnMatrix()),!0).add(a)}}commitLayout(t,e){let{target:i}=t,{result:{size:s},nextCenter:r}=e;var h,n;i.set({width:s.x,height:s.y}),this.layoutObjects(t,e),"initialization"===t.type?i.set({left:null==(h=t.x)?r.x+s.x*ue(i.originX):h,top:null==(n=t.y)?r.y+s.y*ue(i.originY):n}):(i.setPositionByOrigin(r,_,_),i.setCoords(),i.set("dirty",!0))}layoutObjects(t,e){let{target:i}=t;i.forEachObject((s=>{s.group===i&&this.layoutObject(t,e,s)})),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,i.clipPath)}layoutObject(t,{offset:e},i){i.set({left:i.left+e.x,top:i.top+e.y})}onAfterLayout(t,e){let{target:i,strategy:s,bubbles:r,prevStrategy:h,...n}=t,{canvas:o}=i;i.fire("layout:after",{context:t,result:e}),o&&o.fire("object:layout:after",{context:t,result:e,target:i});let a=i.parent;r&&null!=a&&a.layoutManager&&((n.path||(n.path=[])).push(i),a.layoutManager.performLayout({...n,target:a})),i.set("dirty",!0)}dispose(){let{_subscriptions:t}=this;t.forEach((t=>t.forEach((t=>t())))),t.clear()}toObject(){return{type:Is,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}};U.setClass(Xs,Is);var Ys=class extends Xs{performLayout(){}},zs=class t extends(st(es)){static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e=[],s={}){super(),i(this,"_activeObjects",[]),i(this,"__objectSelectionTracker",void 0),i(this,"__objectSelectionDisposer",void 0),Object.assign(this,t.ownDefaults),this.setOptions(s),this.groupInit(e,s)}groupInit(t,e){var i;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject((t=>{this.enterGroup(t,!1)})),this.layoutManager=null==(i=e.layoutManager)?new Xs:i,this.layoutManager.performLayout({type:Ps,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(h("error","Group: circular object trees are not supported, this call has no effect"),!1):-1===this._objects.indexOf(t)||(h("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter(((t,e,i)=>this.canEnterGroup(t)&&i.indexOf(t)===e))}add(...t){let e=this._filterObjectsBeforeEnteringGroup(t),i=super.add(...e);return this._onAfterObjectsChange(Es,e),i}insertAt(t,...e){let i=this._filterObjectsBeforeEnteringGroup(e),s=super.insertAt(t,...i);return this._onAfterObjectsChange(Es,i),s}remove(...t){let e=super.remove(...t);return this._onAfterObjectsChange("removed",e),e}_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){let i=this[t];return super._set(t,e),"canvas"===t&&i!==e&&(this._objects||[]).forEach((i=>{i._set(t,e)})),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,{target:e}){let i=this._activeObjects;if(t)i.push(e),this._set("dirty",!0);else if(i.length>0){let t=i.indexOf(e);t>-1&&(i.splice(t,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&&re(t,mt(pt(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);let i=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();i&&(i===t||t.isDescendantOf(i))&&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||(re(t,mt(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);let i=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;i>-1&&this._activeObjects.splice(i,1)}shouldCache(){let t=es.prototype.shouldCache.call(this);if(t)for(let t=0;t<this._objects.length;t++)if(this._objects[t].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,i){this._renderBackground(t);for(let e=0;e<this._objects.length;e++){var s;let i=this._objects[e];null!=(s=this.canvas)&&s.preserveObjectStacking&&i.group!==this?(t.save(),t.transform(...pt(this.calcTransformMatrix())),i.render(t),t.restore()):i.group===this&&i.render(t)}this._drawClipPath(t,this.clipPath,i)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject((t=>t.setCoords()))}triggerLayout(t={}){this.layoutManager.performLayout({target:this,type:"imperative",...t})}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){let i=this.includeDefaultValues;return this._objects.filter((function(t){return!t.excludeFromExport})).map((function(s){let r=s.includeDefaultValues;s.includeDefaultValues=i;let h=s[t||"toObject"](e);return s.includeDefaultValues=r,h}))}toObject(t=[]){let e=this.layoutManager.toObject();return{...super.toObject(["subTargetCheck","interactive",...t]),..."fit-content"!==e.strategy||this.includeDefaultValues?{layoutManager:e}:{},objects:this.__serializeObjects("toObject",t)}}toString(){return`#<Group: (${this.complexity()})>`}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject((t=>{this._watchObject(!1,t),t.dispose()})),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";let e=As.prototype._toSVG.call(this),i=e.indexOf("COMMON_PARTS");e[i]='for="group" ';let s=e.join("");return t?t(s):s}_toSVG(t){let e=["<g ","COMMON_PARTS"," >\n"],i=this._createSVGBgRect(t);i&&e.push("\t\t",i);for(let i=0;i<this._objects.length;i++)e.push("\t\t",this._objects[i].toSVG(t));return e.push("</g>\n"),e}getSvgStyles(){let t=void 0!==this.opacity&&1!==this.opacity?`opacity: ${Ut(this.opacity)};`:"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){let e=[],i=this._createSVGBgRect(t);i&&e.push("\t",i);for(let i=0;i<this._objects.length;i++)e.push("\t",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject({type:t,objects:e=[],layoutManager:i,...s},r){return Promise.all([Ot(e,r),$t(s,r)]).then((([t,e])=>{let r=new this(t,{...s,...e,layoutManager:new Ys});return r.layoutManager=i?new(U.getClass(i.type))(new(U.getClass(i.strategy))):new Xs,r.layoutManager.subscribeTargets({type:Ps,target:r,targets:r.getObjects()}),r.setCoords(),r}))}};i(zs,"type","Group"),i(zs,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),U.setClass(zs);const Ws="\\s*,?\\s*",Gs=`${Ws}(${ei})`,Ns=`${Gs}${Gs}${Gs}${Ws}([01])${Ws}([01])${Gs}${Gs}`,Hs={m:"l",M:"L"},Vs=(t,e,i,s,r,h,n,o,a,l,u)=>{let c=Z(t),d=Q(t),f=Z(e),g=Q(e),p=i*r*f-s*h*g+n,m=s*r*f+i*h*g+o;return["C",l+a*(-i*r*d-s*h*c),u+a*(-s*r*d+i*h*c),p+a*(i*r*g+s*h*f),m+a*(s*r*g-i*h*f),p,m]},Us=(t,e,i,s)=>{let r=Math.atan2(e,t),h=Math.atan2(s,i);return h>=r?h-r:2*Math.PI-(r-h)};function qs(t,e,i,s,h,n,o,a){let l;if(r.cachesBoundsOfCurve&&(l=[...arguments].join(),m.boundsOfCurveCache[l]))return m.boundsOfCurveCache[l];let u=Math.sqrt,c=Math.abs,d=[],f=[[0,0],[0,0]],g=6*t-12*i+6*h,p=-3*t+9*i-9*h+3*o,v=3*i-3*t;for(let t=0;t<2;++t){if(t>0&&(g=6*e-12*s+6*n,p=-3*e+9*s-9*n+3*a,v=3*s-3*e),c(p)<1e-12){if(c(g)<1e-12)continue;let t=-v/g;0<t&&t<1&&d.push(t);continue}let i=g*g-4*v*p;if(i<0)continue;let r=u(i),h=(-g+r)/(2*p);0<h&&h<1&&d.push(h);let o=(-g-r)/(2*p);0<o&&o<1&&d.push(o)}let y=d.length,x=y,w=Zs(t,e,i,s,h,n,o,a);for(;y--;){let{x:t,y:e}=w(d[y]);f[0][y]=t,f[1][y]=e}f[0][x]=t,f[1][x]=e,f[0][x+1]=o,f[1][x+1]=a;let b=[new tt(Math.min(...f[0]),Math.min(...f[1])),new tt(Math.max(...f[0]),Math.max(...f[1]))];return r.cachesBoundsOfCurve&&(m.boundsOfCurveCache[l]=b),b}const Ks=(t,e,[i,s,r,h,n,o,a,l])=>{let u=((t,e,i,s,r,h,n)=>{if(0===i||0===s)return[];let o=0,a=0,l=0,u=Math.PI,c=n*C,d=Q(c),f=Z(c),g=.5*(-f*t-d*e),p=.5*(-f*e+d*t),m=i**2,v=s**2,y=p**2,x=g**2,w=m*v-m*y-v*x,b=Math.abs(i),S=Math.abs(s);if(w<0){let t=Math.sqrt(1-w/(m*v));b*=t,S*=t}else l=(r===h?-1:1)*Math.sqrt(w/(m*y+v*x));let _=l*b*p/S,T=-l*S*g/b,M=f*_-d*T+.5*t,k=d*_+f*T+.5*e,F=Us(1,0,(g-_)/b,(p-T)/S),D=Us((g-_)/b,(p-T)/S,(-g-_)/b,(-p-T)/S);0===h&&D>0?D-=2*u:1===h&&D<0&&(D+=2*u);let O=Math.ceil(Math.abs(D/u*2)),$=[],j=D/O,A=8/3*Math.sin(j/4)*Math.sin(j/4)/Math.sin(j/2),P=F+j;for(let t=0;t<O;t++)$[t]=Vs(F,P,f,d,b,S,M,k,A,o,a),o=$[t][5],a=$[t][6],F=P,P+=j;return $})(a-t,l-e,s,r,n,o,h);for(let i=0,s=u.length;i<s;i++)u[i][1]+=t,u[i][2]+=e,u[i][3]+=t,u[i][4]+=e,u[i][5]+=t,u[i][6]+=e;return u},Js=(t,e,i,s)=>Math.sqrt((i-t)**2+(s-e)**2),Zs=(t,e,i,s,r,h,n,o)=>a=>{let l=a**3,u=(t=>3*t**2*(1-t))(a),c=(t=>3*t*(1-t)**2)(a),d=(t=>(1-t)**3)(a);return new tt(n*l+r*u+i*c+t*d,o*l+h*u+s*c+e*d)},Qs=t=>t**2,tr=t=>2*t*(1-t),er=t=>(1-t)**2,ir=(t,e,i,s,r,h,n,o)=>a=>{let l=Qs(a),u=tr(a),c=er(a);return Math.atan2(3*(c*(s-e)+u*(h-s)+l*(o-h)),3*(c*(i-t)+u*(r-i)+l*(n-r)))},sr=(t,e,i,s,r,h)=>n=>{let o=Qs(n),a=tr(n),l=er(n);return new tt(r*o+i*a+t*l,h*o+s*a+e*l)},rr=(t,e,i,s,r,h)=>n=>{let o=1-n;return Math.atan2(2*(o*(s-e)+n*(h-s)),2*(o*(i-t)+n*(r-i)))},hr=(t,e,i)=>{let s=new tt(e,i),r=0;for(let e=1;e<=100;e+=1){let i=t(e/100);r+=Js(s.x,s.y,i.x,i.y),s=i}return r},nr=t=>{let e,i,s=0,r=0,h=0,n=0,o=0,a=[];for(let l of t){let t={x:r,y:h,command:l[0],length:0};switch(l[0]){case"M":i=t,i.x=n=r=l[1],i.y=o=h=l[2];break;case"L":i=t,i.length=Js(r,h,l[1],l[2]),r=l[1],h=l[2];break;case"C":e=Zs(r,h,l[1],l[2],l[3],l[4],l[5],l[6]),i=t,i.iterator=e,i.angleFinder=ir(r,h,l[1],l[2],l[3],l[4],l[5],l[6]),i.length=hr(e,r,h),r=l[5],h=l[6];break;case"Q":e=sr(r,h,l[1],l[2],l[3],l[4]),i=t,i.iterator=e,i.angleFinder=rr(r,h,l[1],l[2],l[3],l[4]),i.length=hr(e,r,h),r=l[3],h=l[4];break;case"Z":i=t,i.destX=n,i.destY=o,i.length=Js(r,h,n,o),r=n,h=o}s+=i.length,a.push(i)}return a.push({length:s,x:r,y:h}),a},or=RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),ar=new RegExp(Ns,"g"),lr=new RegExp(ei,"gi"),ur={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},cr=(t,e)=>t.map((t=>t.map(((t,i)=>0===i||void 0===e?t:Pt(t,e))).join(" "))).join(" ");function dr(t,e){let i=t.style;i&&Object.entries(e).forEach((([t,e])=>i.setProperty(t,e)))}var fr=class extends Ht{constructor(t,{allowTouchScrolling:e=!1,containerClass:s=""}={}){super(t),i(this,"upper",void 0),i(this,"container",void 0);let{el:r}=this.lower,h=this.createUpperCanvas();this.upper={el:h,ctx:h.getContext("2d")},this.applyCanvasStyle(r,{allowTouchScrolling:e}),this.applyCanvasStyle(h,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});let n=this.createContainerElement();n.classList.add(s),r.parentNode&&r.parentNode.replaceChild(n,r),n.append(r,h),this.container=n}createUpperCanvas(){let{el:t}=this.lower,e=at();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(){let t=f().createElement("div");return t.setAttribute("data-fabric","wrapper"),dr(t,{position:"relative"}),Nt(t),t}applyCanvasStyle(t,e){let{styles:i,allowTouchScrolling:s}=e;dr(t,{...i,"touch-action":s?"manipulation":F}),Nt(t)}setDimensions(t,e){super.setDimensions(t,e);let{el:i,ctx:s}=this.upper;Wt(i,s,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),Gt(this.upper.el,t),Gt(this.container,t)}cleanupDOM(t){let e=this.container,{el:i}=this.lower,{el:s}=this.upper;super.cleanupDOM(t),e.removeChild(s),e.removeChild(i),e.parentNode&&e.parentNode.replaceChild(i,e)}dispose(){super.dispose(),d().dispose(this.upper.el),delete this.upper,delete this.container}};const gr=(t,e,i,s)=>{let{target:r,offsetX:h,offsetY:n}=e,o=i-h,a=s-n,l=!Me(r,"lockMovementX")&&r.left!==o,u=!Me(r,"lockMovementY")&&r.top!==a;return l&&r.set("left",o),u&&r.set("top",a),(l||u)&&Mi(O,ke(t,e,i,s)),l||u};var pr=class t extends Qt{constructor(...t){super(...t),i(this,"_hoveredTargets",[]),i(this,"_currentTransform",null),i(this,"_groupSelector",null),i(this,"contextTopDirty",!1)}static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}get upperCanvasEl(){var t;return null==(t=this.elements.upper)?void 0:t.el}get contextTop(){var t;return null==(t=this.elements.upper)?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new fr(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(){let 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(){let t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;let e=this.getRetinaScaling(),i=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=i,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,i){let s=this.targetFindTolerance,r=this.pixelFindContext;this.clearContext(r),r.save(),r.translate(-e+s,-i+s),r.transform(...this.viewportTransform);let h=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(r),t.selectionBackgroundColor=h,r.restore();let n=Math.round(s*this.getRetinaScaling());return((t,e,i,s)=>{let r=2*(s=Math.round(s))+1,{data:h}=t.getImageData(e-s,i-s,r,r);for(let t=3;t<h.length;t+=4)if(h[t]>0)return!1;return!0})(r,n,n,n)}_isSelectionKeyPressed(t){let e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find((e=>!!e&&!0===t[e])):t[e])}_shouldClearSelection(t,e){let i=this.getActiveObjects(),s=this._activeObject;return!!(!e||e&&s&&i.length>1&&-1===i.indexOf(e)&&s!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&s&&s!==e)}_shouldCenterTransform(t,e,i){if(!t)return;let s;return"scale"===e||"scaleX"===e||"scaleY"===e||"resizing"===e?s=this.centeredScaling||t.centeredScaling:"rotate"===e&&(s=this.centeredRotation||t.centeredRotation),s?!i:i}_getOriginFromCorner(t,e){let i=e?t.controls[e].getTransformAnchorPoint():{x:t.originX,y:t.originY};return e?(["ml","tl","bl"].includes(e)?i.x=k:["mr","tr","br"].includes(e)&&(i.x=T),["tl","mt","tr"].includes(e)?i.y=M:["bl","mb","br"].includes(e)&&(i.y="top"),i):i}_setupCurrentTransform(t,e,i){var s;let r=e.group?ae(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:h="",control:n}=e.getActiveControl()||{},o=i&&n?null==(s=n.getActionHandler(t,e,n))?void 0:s.bind(n):gr,a=((t,e,i,s)=>{if(!e||!t)return"drag";let r=s.controls[e];return r.getActionName(i,r,s)})(i,h,t,e),l=t[this.centeredKey],u=this._shouldCenterTransform(e,a,l)?{x:_,y:_}:this._getOriginFromCorner(e,h),{scaleX:c,scaleY:d,skewX:f,skewY:g,left:p,top:m,angle:v,width:y,height:x,cropX:w,cropY:b}=e,C={target:e,action:a,actionHandler:o,actionPerformed:!1,corner:h,scaleX:c,scaleY:d,skewX:f,skewY:g,offsetX:r.x-p,offsetY:r.y-m,originX:u.x,originY:u.y,ex:r.x,ey:r.y,lastX:r.x,lastY:r.y,theta:dt(v),width:y,height:x,shiftKey:t.shiftKey,altKey:l,original:{...he(e),originX:u.x,originY:u.y,cropX:w,cropY:b}};this._currentTransform=C,this.fire("before:transform",{e:t,transform:C})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){let{x:e,y:i,deltaX:s,deltaY:r}=this._groupSelector,h=new tt(e,i).transform(this.viewportTransform),n=new tt(e+s,i+r).transform(this.viewportTransform),o=this.selectionLineWidth/2,a=Math.min(h.x,n.x),l=Math.min(h.y,n.y),u=Math.max(h.x,n.x),c=Math.max(h.y,n.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(a,l,u-a,c-l)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,a+=o,l+=o,u-=o,c-=o,es.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(a,l,u-a,c-l))}findTarget(t){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};let e=this.getScenePoint(t),i=this._activeObject,s=this.getActiveObjects(),r=this.searchPossibleTargets(this._objects,e),{subTargets:h,container:n,target:o}=r,a={...r,currentSubTargets:h,currentContainer:n,currentTarget:o};if(!i)return a;let l={...this.searchPossibleTargets([i],e),currentSubTargets:h,currentContainer:n,currentTarget:o};return i.findControl(this.getViewportPoint(t),ee(t))?{...l,target:i}:l.target&&(s.length>1||!this.preserveObjectStacking||this.preserveObjectStacking&&t[this.altSelectionKey])?l:a}_pointIsInObjectSelectionArea(t,e){let i=t.getCoords(),s=this.getZoom(),r=t.padding/s;if(r){let[t,e,s,h]=i,n=Math.atan2(e.y-t.y,e.x-t.x),o=Z(n)*r,a=Q(n)*r,l=o+a,u=o-a;i=[new tt(t.x-u,t.y-l),new tt(e.x+l,e.y-u),new tt(s.x+u,s.y+l),new tt(h.x-l,h.y+u)]}return Si.isPointInPolygon(e,i)}_checkTarget(t,e){if(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;{let i=e.transform(this.viewportTransform);if(!this.isTargetTransparent(t,i.x,i.y))return!0}}return!1}_searchPossibleTargets(t,e,i){let s=t.length;for(;s--;){let r=t[s];if(this._checkTarget(r,e)){if(it(r)&&r.subTargetCheck){let{target:t}=this._searchPossibleTargets(r._objects,e,i);t&&i.push(t)}return{target:r,subTargets:i}}}return{subTargets:[]}}searchPossibleTargets(t,e){let i=this._searchPossibleTargets(t,e,[]);i.container=i.target;let{container:s,subTargets:r}=i;if(s&&it(s)&&s.interactive&&r[0]){for(let t=r.length-1;t>0;t--){let e=r[t];if(!it(e)||!e.interactive)return i.target=e,i}return i.target=r[0],i}return i}getViewportPoint(t){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(t,!0)}getScenePoint(t){return this._scenePoint?this._scenePoint:this._getPointerImpl(t)}_getPointerImpl(t,e=!1){let i=this.upperCanvasEl,s=i.getBoundingClientRect(),r=(t=>{let e=Xt(t.target),i=function(t){let e=t.changedTouches;return e&&e[0]?e[0]:t}(t);return new tt(i.clientX+e.left,i.clientY+e.top)})(t),h=s.width||0,n=s.height||0;h&&n||("top"in s&&"bottom"in s&&(n=Math.abs(s.top-s.bottom)),"right"in s&&"left"in s&&(h=Math.abs(s.right-s.left))),this.calcOffset(),r.x-=this._offset.left,r.y-=this._offset.top,e||(r=ae(r,void 0,this.viewportTransform));let o=this.getRetinaScaling();1!==o&&(r.x/=o,r.y/=o);let a=0===h||0===n?new tt(1,1):new tt(i.width/h,i.height/n);return r.multiply(a)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=at(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){let t=this._activeObject;return It(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let i=!1,s=!1,r=this.getActiveObjects(),h=[],n=[];t.forEach((t=>{r.includes(t)||(i=!0,t.fire("deselected",{e,target:t}),n.push(t))})),r.forEach((s=>{t.includes(s)||(i=!0,s.fire("selected",{e,target:s}),h.push(s))})),t.length>0&&r.length>0?(s=!0,i&&this.fire("selection:updated",{e,selected:h,deselected:n})):r.length>0?(s=!0,this.fire("selection:created",{e,selected:h})):t.length>0&&(s=!0,this.fire("selection:cleared",{e,deselected:n})),s&&(this._objectsToRender=void 0)}setActiveObject(t,e){let i=this.getActiveObjects(),s=this._setActiveObject(t,e);return this._fireSelectionEvents(i,e),s}_setActiveObject(t,e){let i=this._activeObject;return!(i===t||!this._discardActiveObject(e,t)&&this._activeObject||t.onSelect({e})||(this._activeObject=t,It(t)&&i!==t&&t.set("canvas",this),t.setCoords(),0))}_discardActiveObject(t,e){let i=this._activeObject;return!!i&&!i.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===i&&this.endCurrentTransform(t),It(i)&&i===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){let e=this.getActiveObjects(),i=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[i]});let s=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),s}endCurrentTransform(t){let e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){let e=this._currentTransform,i=e.target,s={e:t,target:i,transform:e,action:e.action};i._scaling&&(i._scaling=!1),i.setCoords(),e.actionPerformed&&(this.fire("object:modified",s),i.fire(N,s))}setViewportTransform(t){super.setViewportTransform(t);let e=this._activeObject;e&&e.setCoords()}destroy(){let t=this._activeObject;It(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){let e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,i){let s=this._realizeGroupTransformOnObject(t),r=super._toObject(t,e,i);return t.set(s),r}_realizeGroupTransformOnObject(t){let{group:e}=t;if(e&&It(e)&&this._activeObject===e){let i=jt(t,["angle","flipX","flipY",T,I,X,Y,z,"top"]);return((t,e)=>{re(t,mt(e,t.calcOwnMatrix()))})(t,e.calcOwnMatrix()),i}return{}}_setSVGObject(t,e,i){let s=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,i),e.set(s)}};i(pr,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!0,fireRightClick:!0,fireMiddleClick:!0,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!0});var mr=class{constructor(t){i(this,"targets",[]),i(this,"__disposer",void 0);let e=()=>{let{hiddenTextarea:e}=t.getActiveObject()||{};e&&e.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),J(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;null!=(e=this.target)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}};const vr={passive:!1},yr=(t,e)=>({viewportPoint:t.getViewportPoint(e),scenePoint:t.getScenePoint(e)}),xr=(t,...e)=>t.addEventListener(...e),wr=(t,...e)=>t.removeEventListener(...e),br={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"}};var Cr=class extends pr{constructor(t,e={}){super(t,e),i(this,"_isClick",void 0),i(this,"textEditingManager",new mr(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach((t=>{this[t]=this[t].bind(this)})),this.addOrRemove(xr)}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e=!1){let i=this.upperCanvasEl,s=this._getEventPrefix();t(zt(i),"resize",this._onResize),t(i,s+"down",this._onMouseDown),t(i,`${s}move`,this._onMouseMove,vr),t(i,`${s}out`,this._onMouseOut),t(i,`${s}enter`,this._onMouseEnter),t(i,"wheel",this._onMouseWheel,{passive:!1}),t(i,"contextmenu",this._onContextMenu),e||(t(i,"click",this._onClick),t(i,"dblclick",this._onClick)),t(i,"dragstart",this._onDragStart),t(i,"dragend",this._onDragEnd),t(i,"dragover",this._onDragOver),t(i,"dragenter",this._onDragEnter),t(i,"dragleave",this._onDragLeave),t(i,"drop",this._onDrop),this.enablePointerEvents||t(i,"touchstart",this._onTouchStart,vr)}removeListeners(){this.addOrRemove(wr);let t=this._getEventPrefix(),e=Yt(this.upperCanvasEl);wr(e,`${t}up`,this._onMouseUp),wr(e,"touchend",this._onTouchEnd,vr),wr(e,`${t}move`,this._onMouseMove,vr),wr(e,"touchmove",this._onMouseMove,vr),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_onMouseOut(t){let e=this._hoveredTarget,i={e:t,...yr(this,t)};this.fire("mouse:out",{...i,target:e}),this._hoveredTarget=void 0,e&&e.fire("mouseout",{...i}),this._hoveredTargets.forEach((t=>{this.fire("mouse:out",{...i,target:t}),t&&t.fire("mouseout",{...i})})),this._hoveredTargets=[]}_onMouseEnter(t){let{target:e}=this.findTarget(t);this._currentTransform||e||(this.fire("mouse:over",{e:t,...yr(this,t)}),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;let e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;let i={e:t,target:e};return this.fire("dragstart",i),e.fire("dragstart",i),void xr(this.upperCanvasEl,"drag",this._onDragProgress)}ie(t)}_renderDragEffects(t,e,i){let s=!1,r=this._dropTarget;r&&r!==e&&r!==i&&(r.clearContextTop(),s=!0),null==e||e.clearContextTop(),i!==e&&(null==i||i.clearContextTop());let h=this.contextTop;h.save(),h.transform(...this.viewportTransform),e&&(h.save(),e.transform(h),e.renderDragSourceEffect(t),h.restore(),s=!0),i&&(h.save(),i.transform(h),i.renderDropTargetEffect(t),h.restore(),s=!0),h.restore(),s&&(this.contextTopDirty=!0)}_onDragEnd(t){let{currentSubTargets:e}=this.findTarget(t),i=!!t.dataTransfer&&"none"!==t.dataTransfer.dropEffect,s={e:t,target:this._dragSource,subTargets:e,dragSource:this._dragSource,didDrop:i,dropTarget:i?this._activeObject:void 0};wr(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",s),this._dragSource&&this._dragSource.fire("dragend",s),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){let e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}_onDragOver(t){let e,i="dragover",{currentContainer:s,currentSubTargets:r}=this.findTarget(t),h=this._dragSource,n={e:t,target:s,subTargets:r,dragSource:h,canDrop:!1,dropTarget:void 0};this.fire(i,n),this._fireEnterLeaveEvents(t,s,n),s&&(s.canDrop(t)&&(e=s),s.fire(i,n));for(let s=0;s<r.length;s++){let h=r[s];h.canDrop(t)&&(e=h),h.fire(i,n)}this._renderDragEffects(t,h,e),this._dropTarget=e}_onDragEnter(t){let{currentContainer:e,currentSubTargets:i}=this.findTarget(t),s={e:t,target:e,subTargets:i,dragSource:this._dragSource};this.fire("dragenter",s),this._fireEnterLeaveEvents(t,e,s)}_onDragLeave(t){let{currentSubTargets:e}=this.findTarget(t),i={e:t,target:this._draggedoverTarget,subTargets:e,dragSource:this._dragSource};this.fire("dragleave",i),this._fireEnterLeaveEvents(t,void 0,i),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(t){let{currentContainer:e,currentSubTargets:i}=this.findTarget(t),s=this._basicEventHandler("drop:before",{e:t,target:e,subTargets:i,dragSource:this._dragSource,...yr(this,t)});s.didDrop=!1,s.dropTarget=void 0,this._basicEventHandler("drop",s),this.fire("drop:after",s)}_onContextMenu(t){let{target:e,subTargets:i}=this.findTarget(t),s=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:i});return this.stopContextMenu&&ie(t),this._basicEventHandler("contextmenu",s),!1}_onClick(t){let e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),2==e&&"dblclick"===t.type&&this._handleEvent(t,"dblclick"),3==e&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}fireEventFromPointerEvent(t,e,i,s={}){this._cacheTransformEventData(t);let{target:r,subTargets:h}=this.findTarget(t),n={e:t,target:r,subTargets:h,...yr(this,t),transform:this._currentTransform,...s};this.fire(e,n),r&&r.fire(i,n);for(let t=0;t<h.length;t++)h[t]!==r&&h[t].fire(i,n);this._resetTransformEventData()}getPointerId(t){let e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){this._cacheTransformEventData(t);let e=!this.allowTouchScrolling,i=this._activeObject;void 0===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t);let{target:s}=this.findTarget(t);(this.isDrawingMode||i&&s===i)&&(e=!0),e&&t.preventDefault();let r=this.upperCanvasEl,h=this._getEventPrefix(),n=Yt(r);xr(n,"touchend",this._onTouchEnd,vr),e&&xr(n,"touchmove",this._onMouseMove,vr),wr(r,`${h}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(t){this._cacheTransformEventData(t),this.__onMouseDown(t);let e=this.upperCanvasEl,i=this._getEventPrefix();wr(e,`${i}move`,this._onMouseMove,vr);let s=Yt(e);xr(s,`${i}up`,this._onMouseUp),xr(s,`${i}move`,this._onMouseMove,vr),this._resetTransformEventData()}_onTouchEnd(t){if(t.touches.length>0)return;this._cacheTransformEventData(t),this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;let e=this._getEventPrefix(),i=Yt(this.upperCanvasEl);wr(i,"touchend",this._onTouchEnd,vr),wr(i,"touchmove",this._onMouseMove,vr),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout((()=>{xr(this.upperCanvasEl,`${e}down`,this._onMouseDown),this._willAddMouseDown=0}),400)}_onMouseUp(t){this._cacheTransformEventData(t),this.__onMouseUp(t);let e=this.upperCanvasEl,i=this._getEventPrefix();if(this._isMainEvent(t)){let t=Yt(this.upperCanvasEl);wr(t,`${i}up`,this._onMouseUp),wr(t,`${i}move`,this._onMouseMove,vr),xr(e,`${i}move`,this._onMouseMove,vr)}this._resetTransformEventData()}_onMouseMove(t){this._cacheTransformEventData(t);let e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t),this._resetTransformEventData()}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){let e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._handleEvent(t,"up:before");let i=this._currentTransform,s=this._isClick,{target:r}=this.findTarget(t),{button:h}=t;if(h)return void((this.fireMiddleClick&&1===h||this.fireRightClick&&2===h)&&this._handleEvent(t,"up"));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let n,o,a=!1;if(i&&(this._finalizeCurrentTransform(t),a=i.actionPerformed),!s){let e=r===this._activeObject;this.handleSelection(t),a||(a=this._shouldRender(r)||!e&&r===this._activeObject)}if(r){let{key:e,control:s}=r.findControl(this.getViewportPoint(t),ee(t))||{};if(o=e,r.selectable&&r!==this._activeObject&&"up"===r.activeOn)this.setActiveObject(r,t),a=!0;else if(s){let e=s.getMouseUpHandler(t,r,s);e&&(n=this.getScenePoint(t),e.call(s,t,i,n.x,n.y))}r.isMoving=!1}if(i&&(i.target!==r||i.corner!==o)){let e=i.target&&i.target.controls[i.corner],s=e&&e.getMouseUpHandler(t,i.target,e);n=n||this.getScenePoint(t),s&&s.call(e,t,i,n.x,n.y)}this._setCursorFromEvent(t,r),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,r&&(r.__corner=void 0),a?this.requestRenderAll():s||null!=(e=this._activeObject)&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){let{target:i,subTargets:s=[]}=e;this.fire(t,e),i&&i.fire(t,e);for(let r=0;r<s.length;r++)s[r]!==i&&s[r].fire(t,e);return e}_handleEvent(t,e,i){let{target:s,subTargets:r}=this.findTarget(t),h={e:t,target:s,subTargets:r,...yr(this,t),transform:this._currentTransform,..."down:before"===e||"down"===e?i:{}};"up:before"!==e&&"up"!==e||(h.isClick=this._isClick),this.fire(`mouse:${e}`,h),s&&s.fire(`mouse${e}`,h);for(let t=0;t<r.length;t++)r[t]!==s&&r[t].fire(`mouse${e}`,h)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());let 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){let e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){let e=this.getScenePoint(t);this._isCurrentlyDrawing=!!this.freeDrawingBrush&&!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}),this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._handleEvent(t,"down:before");let{target:e}=this.findTarget(t),i=!!e&&e===this._activeObject,{button:s}=t;if(s)return void((this.fireMiddleClick&&1===s||this.fireRightClick&&2===s)&&this._handleEvent(t,"down",{alreadySelected:i}));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let r=this._shouldRender(e),h=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,h=!0,r=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){let e=this.getScenePoint(t);this._groupSelector={x:e.x,y:e.y,deltaY:0,deltaX:0}}if(i=!!e&&e===this._activeObject,e){e.selectable&&"down"===e.activeOn&&this.setActiveObject(e,t);let s=e.findControl(this.getViewportPoint(t),ee(t));if(e===this._activeObject&&(s||!h)){this._setupCurrentTransform(t,e,i);let r=s?s.control:void 0,h=this.getScenePoint(t),n=r&&r.getMouseDownHandler(t,e,r);n&&n.call(r,t,this._currentTransform,h.x,h.y)}}r&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:i}),r&&this.requestRenderAll()}_resetTransformEventData(){this._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(t),this._scenePoint=ae(this._viewportPoint,void 0,this.viewportTransform),this._targetInfo=this.findTarget(t),this._currentTransform&&(this._targetInfo.target=this._currentTransform.target)}__onMouseMove(t){if(this._isClick=!1,this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;let e=this._groupSelector;if(e){let i=this.getScenePoint(t);e.deltaX=i.x-e.x,e.deltaY=i.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{let{target:e}=this.findTarget(t);this._setCursorFromEvent(t,e),this._fireOverOutEvents(t,e)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move")}_fireOverOutEvents(t,e){let{_hoveredTarget:i,_hoveredTargets:s}=this,{subTargets:r,currentTarget:h}=this.findTarget(t),n=Math.max(s.length,r.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:i,actualTarget:h,oldActualTarget:this._hoveredActualTarget,fireCanvas:!0});for(let h=0;h<n;h++)r[h]===e||s[h]&&s[h]===i||this.fireSyntheticInOutEvents("mouse",{e:t,target:r[h],oldTarget:s[h]});this._hoveredActualTarget=h,this._hoveredTarget=e,this._hoveredTargets=r}_fireEnterLeaveEvents(t,e,i){let s=this._draggedoverTarget,r=this._hoveredTargets,{subTargets:h}=this.findTarget(t),n=Math.max(r.length,h.length);this.fireSyntheticInOutEvents("drag",{...i,target:e,oldTarget:s,fireCanvas:!0});for(let t=0;t<n;t++)this.fireSyntheticInOutEvents("drag",{...i,target:h[t],oldTarget:r[t]});this._draggedoverTarget=e}fireSyntheticInOutEvents(t,{target:e,oldTarget:i,actualTarget:s,oldActualTarget:r,fireCanvas:h,e:n,...o}){let{targetIn:a,targetOut:l,canvasIn:u,canvasOut:c}=br[t],d=i!==e,f=r!==s,g=e&&d,p=s&&f,m=i&&d,v=r&&f,y={...o,e:n,...yr(this,n)},x={...y,target:i,nextTarget:e,actualTarget:r,nextActualTarget:s};(m||v)&&h&&this.fire(c,x),m&&i.fire(l,x),v&&i!==r&&r.fire(l,x);let w={...y,target:e,previousTarget:i,actualTarget:s,previousActualTarget:r};(g||p)&&h&&this.fire(u,w),g&&e.fire(a,w),p&&s!==e&&s.fire(a,w)}_transformObject(t){let e=this.getScenePoint(t),i=this._currentTransform,s=i.target,r=s.group?ae(e,void 0,s.group.calcTransformMatrix()):e;i.shiftKey=t.shiftKey,i.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,i,r),i.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,i){let{action:s,actionHandler:r,target:h}=e,n=!!r&&r(t,e,i.x,i.y);n&&h.setCoords(),"drag"===s&&n&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||n}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let i=e.hoverCursor||this.hoverCursor,s=It(this._activeObject)?this._activeObject:null,r=(!s||e.group!==s)&&e.findControl(this.getViewportPoint(t));if(r){let{control:i,coord:s}=r;this.setCursor(i.cursorStyleHandler(t,i,e,s))}else{if(e.subTargetCheck){let{subTargets:e}=this.findTarget(t);e.concat().reverse().forEach((t=>{i=t.hoverCursor||i}))}this.setCursor(i)}}handleMultiSelection(t,e){let i=this._activeObject,s=It(i);if(i&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(i!==e||s)&&(s||!e.isDescendantOf(i)&&!i.isDescendantOf(e))&&!e.onSelect({e:t})&&!i.getActiveControl()){if(s){let s=i.getObjects(),r=[];if(e===i){let i=this.getScenePoint(t),h=this.searchPossibleTargets(s,i);if(h.target?(e=h.target,r=h.subTargets):(h=this.searchPossibleTargets(this._objects,i),e=h.target,r=h.subTargets),!e||!e.selectable)return!1}e.group===i?(i.remove(e),this._hoveredTarget=e,this._hoveredTargets=r,1===i.size()&&this._setActiveObject(i.item(0),t)):(i.multiSelectAdd(e),this._hoveredTarget=i,this._hoveredTargets=r),this._fireSelectionEvents(s,t)}else{i.isEditing&&i.exitEditing();let s=new(U.getClass("ActiveSelection"))([],{canvas:this});s.multiSelectAdd(i,e),this._hoveredTarget=s,this._setActiveObject(s,t),this._fireSelectionEvents([i],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;let{x:e,y:i,deltaX:s,deltaY:r}=this._groupSelector,h=new tt(e,i),n=h.add(new tt(s,r)),o=h.min(n),a=h.max(n).subtract(o),l=this.collectObjects({left:o.x,top:o.y,width:a.x,height:a.y},{includeIntersecting:!this.selectionFullyContained}),u=h.eq(n)?l[0]?[l[0]]:[]:l.length>1?l.filter((e=>!e.onSelect({e:t}))).reverse():l;if(1===u.length)this.setActiveObject(u[0],t);else if(u.length>1){let e=U.getClass("ActiveSelection");this.setActiveObject(new e(u,{canvas:this}),t)}return this._groupSelector=null,!0}toCanvasElement(t=1,e){let{upper:i}=this.elements;i.ctx=void 0;let s=super.toCanvasElement(t,e);return i.ctx=i.el.getContext("2d"),s}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}};const Sr={x1:0,y1:0,x2:0,y2:0},_r={...Sr,r1:0,r2:0},Tr=(t,e)=>isNaN(t)&&"number"==typeof e?e:t;function Mr(t){return t&&/%$/.test(t)&&Number.isFinite(parseFloat(t))}function kr(t,e){return ui(0,Tr("number"==typeof t?t:"string"==typeof t?parseFloat(t)/(Mr(t)?100:1):NaN,e),1)}const Fr=/\s*;\s*/,Dr=/\s*:\s*/;function Or(t,e){let i,s,r=t.getAttribute("style");if(r){let t=r.split(Fr);""===t[t.length-1]&&t.pop();for(let e=t.length;e--;){let[r,h]=t[e].split(Dr).map((t=>t.trim()));"stop-color"===r?i=h:"stop-opacity"===r&&(s=h)}}i=i||t.getAttribute("stop-color")||"rgb(0,0,0)",s=Tr(parseFloat(s||t.getAttribute("stop-opacity")||""),1);let h=new Ye(i);return h.setAlpha(h.getAlpha()*s*e),{offset:kr(t.getAttribute("offset"),0),color:h.toRgba()}}function $r(t,e){let i=[],s=t.getElementsByTagName("stop"),r=kr(e,1);for(let t=s.length;t--;)i.push(Or(s[t],r));return i}function jr(t){return"linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?"linear":"radial"}function Ar(t){return"userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage"}function Pr(t,e){return t.getAttribute(e)}function Er(t,e){return function(t,{width:e,height:i,gradientUnits:s}){let r;return Object.entries(t).reduce(((t,[h,n])=>{if("Infinity"===n)r=1;else if("-Infinity"===n)r=0;else{let t="string"==typeof n;r=t?parseFloat(n):n,t&&Mr(n)&&(r*=.01,"pixels"===s&&("x1"!==h&&"x2"!==h&&"r2"!==h||(r*=e),"y1"!==h&&"y2"!==h||(r*=i)))}return t[h]=r,t}),{})}("linear"===jr(t)?function(t){return{x1:Pr(t,"x1")||0,y1:Pr(t,"y1")||0,x2:Pr(t,"x2")||"100%",y2:Pr(t,"y2")||0}}(t):function(t){return{x1:Pr(t,"fx")||Pr(t,"cx")||"50%",y1:Pr(t,"fy")||Pr(t,"cy")||"50%",r1:0,x2:Pr(t,"cx")||"50%",y2:Pr(t,"cy")||"50%",r2:Pr(t,"r")||"50%"}}(t),{...e,gradientUnits:Ar(t)})}var Lr=class{constructor(t){let{type:e="linear",gradientUnits:i="pixels",coords:s={},colorStops:r=[],offsetX:h=0,offsetY:n=0,gradientTransform:o,id:a}=t||{};Object.assign(this,{type:e,gradientUnits:i,coords:{..."radial"===e?_r:Sr,...s},colorStops:r,offsetX:h,offsetY:n,gradientTransform:o,id:a?`${a}_${ot()}`:ot()})}addColorStop(t){for(let e in t)this.colorStops.push({offset:parseFloat(e),color:t[e]});return this}toObject(t){return{...jt(this,t),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map((t=>({...t}))),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0}}toSVG(t,{additionalTransform:e}={}){let i=[],s=this.gradientTransform?this.gradientTransform.concat():S.concat(),r="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox",h=this.colorStops.map((t=>({...t}))).sort(((t,e)=>t.offset-e.offset)),n=-this.offsetX,o=-this.offsetY;var a;"objectBoundingBox"===r?(n/=t.width,o/=t.height):(n+=t.width/2,o+=t.height/2),(a=t)&&"function"==typeof a._renderPathCommands&&"percentage"!==this.gradientUnits&&(n-=t.pathOffset.x,o-=t.pathOffset.y),s[4]-=n,s[5]-=o;let l=[`id="SVGID_${Ut(String(this.id))}"`,`gradientUnits="${r}"`,`gradientTransform="${e?e+" ":""}${Et(s)}"`,""].join(" "),u=t=>parseFloat(String(t));if("linear"===this.type){let{x1:t,y1:e,x2:s,y2:r}=this.coords,h=u(t),n=u(e),o=u(s),a=u(r);i.push("<linearGradient ",l,' x1="',h,'" y1="',n,'" x2="',o,'" y2="',a,'">\n')}else if("radial"===this.type){let{x1:t,y1:e,x2:s,y2:r,r1:n,r2:o}=this.coords,a=u(t),c=u(e),d=u(s),f=u(r),g=u(n),p=u(o),m=g>p;i.push("<radialGradient ",l,' cx="',m?a:d,'" cy="',m?c:f,'" r="',m?g:p,'" fx="',m?d:a,'" fy="',m?f:c,'">\n'),m&&(h.reverse(),h.forEach((t=>{t.offset=1-t.offset})));let v=Math.min(g,p);if(v>0){let t=v/Math.max(g,p);h.forEach((e=>{e.offset+=t*(1-e.offset)}))}}return h.forEach((({color:t,offset:e})=>{let s=String(t),r=$e(s)?s:new Ye(s).toRgba();i.push(`<stop offset="${100*e}%" style="stop-color:${Ut(r)};"/>\n`)})),i.push("linear"===this.type?"</linearGradient>":"</radialGradient>","\n"),i.join("")}toLive(t){let{x1:e,y1:i,x2:s,y2:r,r1:h,r2:n}=this.coords,o="linear"===this.type?t.createLinearGradient(e,i,s,r):t.createRadialGradient(e,i,h,s,r,n);return this.colorStops.forEach((({color:t,offset:e})=>{o.addColorStop(e,t)})),o}static async fromObject(t){let{colorStops:e,gradientTransform:i}=t;return new this({...t,colorStops:e?e.map((t=>({...t}))):void 0,gradientTransform:i?[...i]:void 0})}static fromElement(t,e,i){let s=Ar(t),r=e._findCenterFromElement();return new this({id:t.getAttribute("id")||void 0,type:jr(t),coords:Er(t,{width:i.viewBoxWidth||i.width,height:i.viewBoxHeight||i.height}),colorStops:$r(t,i.opacity),gradientUnits:s,gradientTransform:ks(t.getAttribute("gradientTransform")||""),..."pixels"===s?{offsetX:e.width/2-r.x,offsetY:e.height/2-r.y}:{offsetX:0,offsetY:0}})}};i(Lr,"type","Gradient"),U.setClass(Lr,"gradient"),U.setClass(Lr,"linear"),U.setClass(Lr,"radial");var Br=class{get type(){return"pattern"}set type(t){h("warn","Setting type has no effect",t)}constructor(t){i(this,"repeat","repeat"),i(this,"offsetX",0),i(this,"offsetY",0),i(this,"crossOrigin",""),this.id=ot(),Object.assign(this,t)}isImageSource(){return!!this.source&&"string"==typeof this.source.src}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&&0!==this.source.naturalWidth&&0!==this.source.naturalHeight)?t.createPattern(this.source,this.repeat):null}toObject(t=[]){let{repeat:e,crossOrigin:i}=this;return{...jt(this,t),type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:i,offsetX:Pt(this.offsetX,r.NUM_FRACTION_DIGITS),offsetY:Pt(this.offsetY,r.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null}}toSVG({width:t,height:e}){let{source:i,repeat:s,id:r}=this,h=Tr(this.offsetX/t,0),n=Tr(this.offsetY/e,0),o="repeat-y"===s||"no-repeat"===s?1+Math.abs(h||0):Tr(i.width/t,0),a="repeat-x"===s||"no-repeat"===s?1+Math.abs(n||0):Tr(i.height/e,0);return[`<pattern id="SVGID_${Ut(r)}" x="${h}" y="${n}" width="${o}" height="${a}">`,`<image x="0" y="0" width="${i.width}" height="${i.height}" xlink:href="${Ut(this.sourceToString())}"></image>`,"</pattern>",""].join("\n")}static async fromObject({type:t,source:e,patternTransform:i,...s},r){let h=await Dt(e,{...r,crossOrigin:s.crossOrigin});return new this({...s,patternTransform:i&&i.slice(0),source:h})}};i(Br,"type","Pattern"),U.setClass(Br),U.setClass(Br,"pattern");var Rr=class t extends es{constructor(e,{path:i,left:s,top:r,...h}={}){super(),Object.assign(this,t.ownDefaults),this.setOptions(h),this._setPath(e||[],!0),"number"==typeof s&&this.set("left",s),"number"==typeof r&&this.set("top",r)}_setPath(t,e){this.path=(t=>{let e,i=0,s=0,r=0,h=0,n=[],o=0,a=0;for(let l of t){let t,u=[...l];switch(u[0]){case"l":u[1]+=i,u[2]+=s;case"L":i=u[1],s=u[2],t=["L",i,s];break;case"h":u[1]+=i;case"H":i=u[1],t=["L",i,s];break;case"v":u[1]+=s;case"V":s=u[1],t=["L",i,s];break;case"m":u[1]+=i,u[2]+=s;case"M":i=u[1],s=u[2],r=u[1],h=u[2],t=["M",i,s];break;case"c":u[1]+=i,u[2]+=s,u[3]+=i,u[4]+=s,u[5]+=i,u[6]+=s;case"C":o=u[3],a=u[4],i=u[5],s=u[6],t=["C",u[1],u[2],o,a,i,s];break;case"s":u[1]+=i,u[2]+=s,u[3]+=i,u[4]+=s;case"S":"C"===e?(o=2*i-o,a=2*s-a):(o=i,a=s),i=u[3],s=u[4],t=["C",o,a,u[1],u[2],i,s],o=t[3],a=t[4];break;case"q":u[1]+=i,u[2]+=s,u[3]+=i,u[4]+=s;case"Q":o=u[1],a=u[2],i=u[3],s=u[4],t=["Q",o,a,i,s];break;case"t":u[1]+=i,u[2]+=s;case"T":"Q"===e?(o=2*i-o,a=2*s-a):(o=i,a=s),i=u[1],s=u[2],t=["Q",o,a,i,s];break;case"a":u[6]+=i,u[7]+=s;case"A":Ks(i,s,u).forEach((t=>n.push(t))),i=u[6],s=u[7];break;case"z":case"Z":i=r,s=h,t=["Z"]}t?(n.push(t),e=t[0]):e=""}return n})(Array.isArray(t)?t:(t=>{var e;let i=[],s=null==(e=t.match(or))?[]:e;for(let t of s){let e=t[0];if("z"===e||"Z"===e){i.push([e]);continue}let s=ur[e.toLowerCase()],r=[];if("a"===e||"A"===e){let e;for(ar.lastIndex=0;e=ar.exec(t);)r.push(...e.slice(1))}else r=t.match(lr)||[];for(let t=0;t<r.length;t+=s){let h=Array(s),n=Hs[e];h[0]=t>0&&n?n:e;for(let e=0;e<s;e++)h[e+1]=parseFloat(r[t+e]);i.push(h)}}return i})(t)),this.setBoundingBox(e)}_findCenterFromElement(){let t=this._calcBoundsFromPath();return new tt(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){let e=-this.pathOffset.x,i=-this.pathOffset.y;t.beginPath();for(let s of this.path)switch(s[0]){case"L":t.lineTo(s[1]+e,s[2]+i);break;case"M":t.moveTo(s[1]+e,s[2]+i);break;case"C":t.bezierCurveTo(s[1]+e,s[2]+i,s[3]+e,s[4]+i,s[5]+e,s[6]+i);break;case"Q":t.quadraticCurveTo(s[1]+e,s[2]+i,s[3]+e,s[4]+i);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return`#<Path (${this.complexity()}): { "top": ${this.top}, "left": ${this.left} }>`}toObject(t=[]){return{...super.toObject(t),path:this.path.map((t=>t.slice()))}}toDatalessObject(t=[]){let e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){return["<path ","COMMON_PARTS",`d="${cr(this.path,r.NUM_FRACTION_DIGITS)}" stroke-linecap="round" />\n`]}_getOffsetTransform(){let t=r.NUM_FRACTION_DIGITS;return` translate(${Pt(-this.pathOffset.x,t)}, ${Pt(-this.pathOffset.y,t)})`}toClipPathSVG(t){let e=this._getOffsetTransform();return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){let e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){let{width:e,height:i,pathOffset:s}=this._calcDimensions();this.set({width:e,height:i,pathOffset:s}),t&&this.setPositionByOrigin(s,"center","center")}_calcBoundsFromPath(){let t=[],e=0,i=0,s=0,r=0;for(let h of this.path)switch(h[0]){case"L":s=h[1],r=h[2],t.push({x:e,y:i},{x:s,y:r});break;case"M":s=h[1],r=h[2],e=s,i=r;break;case"C":t.push(...qs(s,r,h[1],h[2],h[3],h[4],h[5],h[6])),s=h[5],r=h[6];break;case"Q":t.push(...qs(s,r,h[1],h[2],h[1],h[2],h[3],h[4])),s=h[3],r=h[4];break;case"Z":s=e,r=i}return se(t)}_calcDimensions(){let t=this._calcBoundsFromPath();return{...t,pathOffset:new tt(t.left+t.width/2,t.top+t.height/2)}}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,i){let{d:s,...r}=$s(t,this.ATTRIBUTE_NAMES,i);return new this(s,{...r,...e,left:void 0,top:void 0})}};i(Rr,"type","Path"),i(Rr,"cacheProperties",[...di,"path","fillRule"]),i(Rr,"ATTRIBUTE_NAMES",[...us,"d"]),U.setClass(Rr),U.setSVGClass(Rr);const Ir=["radius","startAngle","endAngle","counterClockwise"];var Xr=class t extends es{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e){super(),Object.assign(this,t.ownDefaults),this.setOptions(e)}_set(t,e){return super._set(t,e),"radius"===t&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,dt(this.startAngle),dt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(I)}getRadiusY(){return this.get("radius")*this.get(X)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(t=[]){return super.toObject([...Ir,...t])}_toSVG(){let{radius:t,startAngle:e,endAngle:i}=this,s=(i-e)%360;if(0===s)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',`${Ut(t)}`,'" />\n'];{let r=dt(e),h=dt(i),n=Z(r)*t,o=Q(r)*t,a=Z(h)*t,l=Q(h)*t;return[`<path d="M ${n} ${o} A ${t} ${t} 0 ${+(s>180)} ${+!this.counterClockwise} ${a} ${l}" `,"COMMON_PARTS"," />\n"]}}static async fromElement(t,e,i){let{left:s=0,top:r=0,radius:h=0,...n}=$s(t,this.ATTRIBUTE_NAMES,i);return new this({...n,radius:h,left:s-h,top:r-h})}static fromObject(t){return super._fromObject(t)}};i(Xr,"type","Circle"),i(Xr,"cacheProperties",[...di,...Ir]),i(Xr,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),i(Xr,"ATTRIBUTE_NAMES",["cx","cy","r",...us]),U.setClass(Xr),U.setSVGClass(Xr);const Yr=["x1","x2","y1","y2"];var zr=class t extends es{constructor([e,i,s,r]=[0,0,0,0],h={}){super(),Object.assign(this,t.ownDefaults),this.setOptions(h),this.x1=e,this.x2=s,this.y1=i,this.y2=r,this._setWidthHeight();let{left:n,top:o}=h;"number"==typeof n&&this.set("left",n),"number"==typeof o&&this.set("top",o)}_setWidthHeight(){let{x1:t,y1:e,x2:i,y2:s}=this;this.width=Math.abs(i-t),this.height=Math.abs(s-e);let{left:r,top:h,width:n,height:o}=se([{x:t,y:e},{x:i,y:s}]),a=new tt(r+n/2,h+o/2);this.setPositionByOrigin(a,_,_)}_set(t,e){return super._set(t,e),Yr.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();let e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;let i=t.strokeStyle;var s;t.strokeStyle=Lt(this.stroke)?this.stroke.toLive(t):null==(s=this.stroke)?t.fillStyle:s,this.stroke&&this._renderStroke(t),t.strokeStyle=i}_findCenterFromElement(){return new tt((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(t=[]){return{...super.toObject(t),...this.calcLinePoints()}}_getNonTransformedDimensions(){let t=super._getNonTransformedDimensions();return"butt"===this.strokeLineCap&&(0===this.width&&(t.y-=this.strokeWidth),0===this.height&&(t.x-=this.strokeWidth)),t}calcLinePoints(){let{x1:t,x2:e,y1:i,y2:s,width:r,height:h}=this,n=t<=e?-.5:.5,o=i<=s?-.5:.5;return{x1:n*r,x2:n*-r,y1:o*h,y2:o*-h}}_toSVG(){let{x1:t,x2:e,y1:i,y2:s}=this.calcLinePoints();return["<line ","COMMON_PARTS",`x1="${t}" y1="${i}" x2="${e}" y2="${s}" />\n`]}static async fromElement(t,e,i){let{x1:s=0,y1:r=0,x2:h=0,y2:n=0,...o}=$s(t,this.ATTRIBUTE_NAMES,i);return new this([s,r,h,n],o)}static fromObject({x1:t,y1:e,x2:i,y2:s,...r}){return this._fromObject({...r,points:[t,e,i,s]},{extraParam:"points"})}};i(zr,"type","Line"),i(zr,"cacheProperties",[...di,...Yr]),i(zr,"ATTRIBUTE_NAMES",us.concat(Yr)),U.setClass(zr),U.setSVGClass(zr);var Wr=class t extends es{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e){super(),Object.assign(this,t.ownDefaults),this.setOptions(e)}_render(t){let e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){let t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',`${-t} ${e},0 ${-e},${t} ${e}`,'" />']}};i(Wr,"type","Triangle"),i(Wr,"ownDefaults",{width:100,height:100}),U.setClass(Wr),U.setSVGClass(Wr);const Gr=["rx","ry"];var Nr=class t extends es{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e){super(),Object.assign(this,t.ownDefaults),this.setOptions(e)}_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(I)}getRy(){return this.get("ry")*this.get(X)}toObject(t=[]){return super.toObject([...Gr,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",`cx="0" cy="0" rx="${Ut(this.rx)}" ry="${Ut(this.ry)}" />\n`]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,b,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,i){let s=$s(t,this.ATTRIBUTE_NAMES,i);return s.left=(s.left||0)-s.rx,s.top=(s.top||0)-s.ry,new this(s)}};i(Nr,"type","Ellipse"),i(Nr,"cacheProperties",[...di,...Gr]),i(Nr,"ownDefaults",{rx:0,ry:0}),i(Nr,"ATTRIBUTE_NAMES",[...us,"cx","cy","rx","ry"]),U.setClass(Nr),U.setSVGClass(Nr);const Hr={exactBoundingBox:!1};var Vr=class t extends es{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e=[],s={}){super(),i(this,"strokeDiff",void 0),Object.assign(this,t.ownDefaults),this.setOptions(s),this.points=e;let{left:r,top:h}=s;this.initialized=!0,this.setBoundingBox(!0),"number"==typeof r&&this.set("left",r),"number"==typeof h&&this.set("top",h)}isOpen(){return!0}_projectStrokeOnPoints(t){return((t,e,i=!1)=>{let s=[];if(0===t.length)return s;let r=t.reduce(((t,e)=>(t[t.length-1].eq(e)||t.push(new tt(e)),t)),[new tt(t[0])]);if(1===r.length)i=!0;else if(!i){let t=r[0],e=((t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i]))return i;return-1})(r,(e=>!e.eq(t)));r.splice(e+1)}return r.forEach(((t,r,h)=>{let n,o;0===r?(o=h[1],n=i?t:h[h.length-1]):r===h.length-1?(n=h[r-1],o=i?t:h[0]):(n=h[r-1],o=h[r+1]),i&&1===h.length?s.push(...new hs(t,t,e).project()):!i||0!==r&&r!==h.length-1?s.push(...new rs(t,n,o,e).project()):s.push(...new hs(t,0===r?o:n,e).project())})),s})(this.points,t,this.isOpen())}_calcDimensions(t){t={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth,...t||{}};let e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map((t=>t.projectedPoint)):this.points;if(0===e.length)return{left:0,top:0,width:0,height:0,pathOffset:new tt,strokeOffset:new tt,strokeDiff:new tt};let i=se(e),s=Ft({...t,scaleX:1,scaleY:1}),r=se(this.points.map((t=>gt(t,s,!0)))),h=new tt(this.scaleX,this.scaleY),n=i.left+i.width/2,o=i.top+i.height/2;return this.exactBoundingBox&&(n-=o*Math.tan(dt(this.skewX)),o-=n*Math.tan(dt(this.skewY))),{...i,pathOffset:new tt(n,o),strokeOffset:new tt(r.left,r.top).subtract(new tt(i.left,i.top)).multiply(h),strokeDiff:new tt(i.width,i.height).subtract(new tt(r.width,r.height)).multiply(h)}}_findCenterFromElement(){let t=se(this.points);return new tt(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){let{left:e,top:i,width:s,height:r,pathOffset:h,strokeOffset:n,strokeDiff:o}=this._calcDimensions();this.set({width:s,height:r,pathOffset:h,strokeOffset:n,strokeDiff:o}),t&&this.setPositionByOrigin(new tt(e+s/2,i+r/2),"center","center")}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new tt(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(t={}){if(this.exactBoundingBox){let h;if(Object.keys(t).some((t=>this.strokeUniform||this.constructor.layoutProperties.includes(t)))){var e,i;let{width:s,height:r}=this._calcDimensions(t);h=new tt(null==(e=t.width)?s:e,null==(i=t.height)?r:i)}else{var s,r;h=new tt(null==(s=t.width)?this.width:s,null==(r=t.height)?this.height:r)}return h.multiply(new tt(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){let i=this.initialized&&this[t]!==e,s=super._set(t,e);return this.exactBoundingBox&&i&&(("scaleX"===t||"scaleY"===t)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),s}toObject(t=[]){return{...super.toObject(t),points:this.points.map((({x:t,y:e})=>({x:t,y:e})))}}_toSVG(){let t=this.pathOffset.x,e=this.pathOffset.y,i=r.NUM_FRACTION_DIGITS,s=this.points.map((({x:s,y:r})=>`${Pt(s-t,i)},${Pt(r-e,i)}`)).join(" ");return[`<${Ut(this.constructor.type).toLowerCase()} `,"COMMON_PARTS",`points="${s}" />\n`]}_render(t){let e=this.points.length,i=this.pathOffset.x,s=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-i,this.points[0].y-s);for(let r=0;r<e;r++){let e=this.points[r];t.lineTo(e.x-i,e.y-s)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,i){let s=function(t){if(!t)return[];let e=t.replace(/,/g," ").trim().split(/\s+/),i=[];for(let t=0;t<e.length;t+=2)i.push({x:parseFloat(e[t]),y:parseFloat(e[t+1])});return i}(t.getAttribute("points")),{left:r,top:h,...n}=$s(t,this.ATTRIBUTE_NAMES,i);return new this(s,{...n,...e})}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}};i(Vr,"ownDefaults",Hr),i(Vr,"type","Polyline"),i(Vr,"layoutProperties",[Y,z,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),i(Vr,"cacheProperties",[...di,"points"]),i(Vr,"ATTRIBUTE_NAMES",[...us]),U.setClass(Vr),U.setSVGClass(Vr);var Ur=class extends Vr{isOpen(){return!1}};i(Ur,"ownDefaults",Hr),i(Ur,"type","Polygon"),U.setClass(Ur),U.setSVGClass(Ur);var qr=class extends es{isEmptyStyles(t){if(!this.styles||void 0!==t&&!this.styles[t])return!0;let e=void 0===t?this.styles:{line:this.styles[t]};for(let t in e)for(let i in e[t])for(let s in e[t][i])return!1;return!0}styleHas(t,e){if(!this.styles||void 0!==e&&!this.styles[e])return!1;let i=void 0===e?this.styles:{0:this.styles[e]};for(let e in i)for(let s in i[e])if(void 0!==i[e][s][t])return!0;return!1}cleanStyle(t){if(!this.styles)return!1;let e,i,s=this.styles,r=0,h=!0,n=0;for(let n in s){e=0;for(let o in s[n]){let a=s[n][o]||{};r++,void 0===a[t]?h=!1:(i?a[t]!==i&&(h=!1):i=a[t],a[t]===this[t]&&delete a[t]),0===Object.keys(a).length?delete s[n][o]:e++}0===e&&delete s[n]}for(let t=0;t<this._textLines.length;t++)n+=this._textLines[t].length;h&&r===n&&(this[t]=i,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;let e,i,s,r=this.styles;for(i in r){for(s in e=r[i],e)delete e[s][t],0===Object.keys(e[s]).length&&delete e[s];0===Object.keys(e).length&&delete r[i]}}_extendStyles(t,e){let{lineIndex:i,charIndex:s}=this.get2DCursorLocation(t);this._getLineStyle(i)||this._setLineStyle(i);let r=At({...this._getStyleDeclaration(i,s),...e},(t=>void 0!==t));this._setStyleDeclaration(i,s,r)}getSelectionStyles(t,e,i){let s=[];for(let r=t;r<(e||t);r++)s.push(this.getStyleAtPosition(r,i));return s}getStyleAtPosition(t,e){let{lineIndex:i,charIndex:s}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(i,s):this._getStyleDeclaration(i,s)}setSelectionStyles(t,e,i){for(let s=e;s<(i||e);s++)this._extendStyles(s,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var i;let s=this.styles&&this.styles[t];return s&&null!=(i=s[e])?i:{}}getCompleteStyleDeclaration(t,e){return{...jt(this,this.constructor._styleProperties),...this._getStyleDeclaration(t,e)}}_setStyleDeclaration(t,e,i){this.styles[t][e]=i}_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]}};i(qr,"_styleProperties",Ze);const Kr=/ +/g,Jr=/"/g;function Zr(t,e,i,s,h){return`\t\t${((t,{left:e,top:i,width:s,height:h},n=r.NUM_FRACTION_DIGITS)=>{let o=We(W,t,!1),[a,l,u,c]=[e,i,s,h].map((t=>Pt(t,n)));return`<rect ${o} x="${a}" y="${l}" width="${u}" height="${c}"></rect>`})(t,{left:e,top:i,width:s,height:h})}\n`}let Qr;var th=class t extends qr{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e,s){super(),i(this,"__charBounds",[]),Object.assign(this,t.ownDefaults),this.setOptions(s),this.styles||(this.styles={}),this.text=e,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){let t=this.path;t&&(t.segmentsInfo=nr(t.path))}_splitText(){let 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("justify")&&this.enlargeSpaces()}enlargeSpaces(){let t,e,i,s,r,h,n;for(let o=0,a=this._textLines.length;o<a;o++)if(("justify"===this.textAlign||o!==a-1&&!this.isEndOfWrapping(o))&&(s=0,r=this._textLines[o],e=this.getLineWidth(o),e<this.width&&(n=this.textLines[o].match(this._reSpacesAndTabs)))){i=n.length,t=(this.width-e)/i;for(let e=0;e<=r.length;e++)h=this.__charBounds[o][e],this._reSpaceAndTab.test(r[e])?(h.width+=t,h.kernedWidth+=t,h.left+=s,s+=t):h.left+=s}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){let i,s=e?this._unwrappedTextLines:this._textLines;for(i=0;i<s.length;i++){if(t<=s[i].length)return{lineIndex:i,charIndex:t};t-=s[i].length+this.missingNewlineOffset(i,e)}return{lineIndex:i-1,charIndex:s[i-1].length<t?s[i-1].length:t}}toString(){return`#<Text (${this.complexity()}): { "text": "${this.text}", "fontFamily": "${this.fontFamily}" }>`}_getCacheCanvasDimensions(){let t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){let 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){"stroke"===this.paintFirst?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,i){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case _:t.textBaseline="middle";break;case"ascender":t.textBaseline="top";break;case"descender":t.textBaseline=M}t.font=this._getFontDeclaration(e,i)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,i=this._textLines.length;e<i;e++){let i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,i,s,r,h){this._renderChars(t,e,i,s,r,h)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;let e=t.fillStyle,i=this._getLeftOffset(),s=this._getTopOffset();for(let e=0,r=this._textLines.length;e<r;e++){let r=this.getHeightOfLine(e);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",e)){s+=r;continue}let h,n,o=this._textLines[e].length,a=this._getLineLeftOffset(e),l=0,u=0,c=this.getValueOfPropertyAt(e,0,"textBackgroundColor"),d=this.getHeightOfLineImpl(e);for(let r=0;r<o;r++){let o=this.__charBounds[e][r];n=this.getValueOfPropertyAt(e,r,"textBackgroundColor"),this.path?(t.save(),t.translate(o.renderLeft,o.renderTop),t.rotate(o.angle),t.fillStyle=n,n&&t.fillRect(-o.width/2,-d*(1-this._fontSizeFraction),o.width,d),t.restore()):n===c?l+=o.kernedWidth:(h=i+a+u,"rtl"===this.direction&&(h=this.width-h-l),t.fillStyle=c,c&&t.fillRect(h,s,l,d),u=o.left,l=o.width,c=n)}n&&!this.path&&(h=i+a+u,"rtl"===this.direction&&(h=this.width-h-l),t.fillStyle=n,t.fillRect(h,s,l,d)),s+=r}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,i,s){let r,h,n,o,a=m.getFontCache(e),l=this._getFontDeclaration(e),u=i?i+t:t,c=i&&l===this._getFontDeclaration(s),d=e.fontSize/this.CACHE_FONT_SIZE;if(i&&a.has(i)&&(n=a.get(i)),a.has(t)&&(o=r=a.get(t)),c&&a.has(u)&&(h=a.get(u),o=h-n),void 0===r||void 0===n||void 0===h){let s=(Qr||(Qr=lt({width:0,height:0}).getContext("2d")),Qr);this._setTextStyles(s,e,!0),void 0===r&&(o=r=s.measureText(t).width,a.set(t,r)),void 0===n&&c&&i&&(n=s.measureText(i).width,a.set(i,n)),c&&void 0===h&&(h=s.measureText(u).width,a.set(u,h),o=h-n)}return{width:r*d,kernedWidth:o*d}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){let e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,i,s=0,r=this.pathSide===k,h=this.path,n=this._textLines[t],o=n.length,a=Array(o);this.__charBounds[t]=a;for(let r=0;r<o;r++){let h=n[r];i=this._getGraphemeBox(h,t,r,e),a[r]=i,s+=i.kernedWidth,e=h}if(a[o]={left:i?i.left+i.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},h&&h.segmentsInfo){let t=0,e=h.segmentsInfo[h.segmentsInfo.length-1].length;switch(this.textAlign){case T:t=r?e-s:0;break;case _:t=(e-s)/2;break;case k:t=r?0:e-s}t+=this.pathStartOffset*(r?-1:1);for(let s=r?o-1:0;r?s>=0:s<o;r?s--:s++)i=a[s],t>e?t%=e:t<0&&(t+=e),this._setGraphemeOnPath(t,i),t+=i.kernedWidth}return{width:s,numOfSpaces:0}}_setGraphemeOnPath(t,e){let i=this.path,s=((t,e,i=nr(t))=>{let s=0;for(;e-i[s].length>0&&s<i.length-2;)e-=i[s].length,s++;let r=i[s],h=e/r.length,n=t[s];switch(r.command){case"M":return{x:r.x,y:r.y,angle:0};case"Z":return{...new tt(r.x,r.y).lerp(new tt(r.destX,r.destY),h),angle:Math.atan2(r.destY-r.y,r.destX-r.x)};case"L":return{...new tt(r.x,r.y).lerp(new tt(n[1],n[2]),h),angle:Math.atan2(n[2]-r.y,n[1]-r.x)};case"C":case"Q":return((t,e)=>{let i,s=0,r=0,h={x:t.x,y:t.y},n={...h},o=.01,a=0,l=t.iterator,u=t.angleFinder;for(;r<e&&o>1e-4;)n=l(s),a=s,i=Js(h.x,h.y,n.x,n.y),i+r>e?(s-=o,o/=2):(h=n,s+=o,r+=i);return{...n,angle:u(a)}})(r,e)}})(i.path,t+e.kernedWidth/2,i.segmentsInfo);e.renderLeft=s.x-i.pathOffset.x,e.renderTop=s.y-i.pathOffset.y,e.angle=s.angle+("right"===this.pathSide?Math.PI:0)}_getGraphemeBox(t,e,i,s,r){let h,n=this.getCompleteStyleDeclaration(e,i),o=s?this.getCompleteStyleDeclaration(e,i-1):{},a=this._measureChar(t,n,s,o),l=a.kernedWidth,u=a.width;0!==this.charSpacing&&(h=this._getWidthOfCharSpacing(),u+=h,l+=h);let c={width:u,left:0,height:n.fontSize,kernedWidth:l,deltaY:n.deltaY};if(i>0&&!r){let t=this.__charBounds[e][i-1];c.left=t.left+t.width+a.kernedWidth-a.width}return c}getHeightOfLineImpl(t){let e=this.__lineHeights;if(e[t])return e[t];let i=this.getHeightOfChar(t,0);for(let e=1,s=this._textLines[t].length;e<s;e++)i=Math.max(this.getHeightOfChar(t,e),i);return e[t]=i*this._fontSizeMult}getHeightOfLine(t){return this.getHeightOfLineImpl(t)*this.lineHeight}calcTextHeight(){let t=0;for(let e=0,i=this._textLines.length;e<i;e++)t+=e===i-1?this.getHeightOfLineImpl(e):this.getHeightOfLine(e);return t}_getLeftOffset(){return"ltr"===this.direction?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let i=0,s=this._getLeftOffset(),r=this._getTopOffset();for(let h=0,n=this._textLines.length;h<n;h++)this._renderTextLine(e,t,this._textLines[h],s+this._getLineLeftOffset(h),r+i+this.getHeightOfLineImpl(h),h),i+=this.getHeightOfLine(h);t.restore()}_renderTextFill(t){(this.fill||this.styleHas("fill"))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&0!==this.strokeWidth||!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,i,s,r,h){let n,o,a,l,u,c=this.textAlign.includes(ti),d=this.path,f=!c&&0===this.charSpacing&&this.isEmptyStyles(h)&&!d,g="ltr"===this.direction,p="ltr"===this.direction?1:-1,m=e.direction,v="",y=0;if(e.save(),m!==this.direction&&(e.canvas.setAttribute("dir",g?"ltr":"rtl"),e.direction=g?"ltr":"rtl",e.textAlign=g?T:k),r-=this.getHeightOfLineImpl(h)*this._fontSizeFraction,f)return this._renderChar(t,e,h,0,i.join(""),s,r),void e.restore();for(let f=0,g=i.length-1;f<=g;f++)l=f===g||this.charSpacing||d,v+=i[f],a=this.__charBounds[h][f],0===y?(s+=p*(a.kernedWidth-a.width),y+=a.width):y+=a.kernedWidth,c&&!l&&this._reSpaceAndTab.test(i[f])&&(l=!0),l||(n=n||this.getCompleteStyleDeclaration(h,f),o=this.getCompleteStyleDeclaration(h,f+1),l=os(n,o,!1)),l&&(d?(e.save(),e.translate(a.renderLeft,a.renderTop),e.rotate(a.angle),this._renderChar(t,e,h,f,v,-y/2,0),e.restore()):(u=s,this._renderChar(t,e,h,f,v,u,r)),v="",n=o,s+=p*y,y=0);e.restore()}_applyPatternGradientTransformText(t){let e=this.width+this.strokeWidth,i=this.height+this.strokeWidth,s=lt({width:e,height:i}),r=s.getContext("2d");return s.width=e,s.height=i,r.beginPath(),r.moveTo(0,0),r.lineTo(e,0),r.lineTo(e,i),r.lineTo(0,i),r.closePath(),r.translate(e/2,i/2),r.fillStyle=t.toLive(r),this._applyPatternGradientTransform(r,t),r.fill(),r.createPattern(s,"no-repeat")}handleFiller(t,e,i){let s,r;return Lt(i)?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?(s=-this.width/2,r=-this.height/2,t.translate(s,r),t[e]=this._applyPatternGradientTransformText(i),{offsetX:s,offsetY:r}):(t[e]=i.toLive(t),this._applyPatternGradientTransform(t,i)):(t[e]=i,{offsetX:0,offsetY:0})}_setStrokeStyles(t,{stroke:e,strokeWidth:i}){return t.lineWidth=i,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",e)}_setFillStyles(t,{fill:e}){return this.handleFiller(t,"fillStyle",e)}_renderChar(t,e,i,s,r,h,n){let o=this._getStyleDeclaration(i,s),a=this.getCompleteStyleDeclaration(i,s),l="fillText"===t&&a.fill,u="strokeText"===t&&a.stroke&&a.strokeWidth;if(u||l){if(e.save(),e.font=this._getFontDeclaration(a),o.textBackgroundColor&&this._removeShadow(e),o.deltaY&&(n+=o.deltaY),l){let t=this._setFillStyles(e,a);e.fillText(r,h-t.offsetX,n-t.offsetY)}if(u){let t=this._setStrokeStyles(e,a);e.strokeText(r,h-t.offsetX,n-t.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,i){let s=this.get2DCursorLocation(t,!0),r=this.getValueOfPropertyAt(s.lineIndex,s.charIndex,"fontSize"),h=this.getValueOfPropertyAt(s.lineIndex,s.charIndex,"deltaY");this.setSelectionStyles({fontSize:r*i.size,deltaY:h+r*i.baseline},t,e)}_getLineLeftOffset(t){let e=this.getLineWidth(t),i=this.width-e,s=this.textAlign,r=this.direction,h=this.isEndOfWrapping(t),n=0;return"justify"===s||"justify-center"===s&&!h||"justify-right"===s&&!h||"justify-left"===s&&!h?0:("center"===s&&(n=i/2),"right"===s&&(n=i),"justify-center"===s&&(n=i/2),"justify-right"===s&&(n=i),"rtl"===r&&("right"===s||"justify-right"===s?n=0:"left"===s||"justify-left"===s?n=-i:"center"!==s&&"justify-center"!==s||(n=-i/2)),n)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(void 0!==this.__lineWidths[t])return this.__lineWidths[t];let{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return 0===this.charSpacing?0:this.fontSize*this.charSpacing/1e3}getValueOfPropertyAt(t,e,i){var s;return null==(s=this._getStyleDeclaration(t,e)[i])?this[i]:s}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let i=this._getTopOffset(),s=this._getLeftOffset(),r=this.path,h=this._getWidthOfCharSpacing(),n="linethrough"===e?.5:+("overline"===e),o=this.offsets[e];for(let a=0,l=this._textLines.length;a<l;a++){let l=this.getHeightOfLine(a);if(!this[e]&&!this.styleHas(e,a)){i+=l;continue}let u,c=this._textLines[a],d=l/this.lineHeight,f=this._getLineLeftOffset(a),g=0,p=0,m=this.getValueOfPropertyAt(a,0,e),v=this.getValueOfPropertyAt(a,0,W),y=this.getValueOfPropertyAt(a,0,"textDecorationColor")||v,x=this.getValueOfPropertyAt(a,0,He),w=m,b=y,C=x,S=i+d*(1-this._fontSizeFraction),_=this.getHeightOfChar(a,0),T=this.getValueOfPropertyAt(a,0,"deltaY");for(let i=0,h=c.length;i<h;i++){let h=this.__charBounds[a][i];w=this.getValueOfPropertyAt(a,i,e),u=this.getValueOfPropertyAt(a,i,W),b=this.getValueOfPropertyAt(a,i,"textDecorationColor")||u,C=this.getValueOfPropertyAt(a,i,He);let l=this.getHeightOfChar(a,i),c=this.getValueOfPropertyAt(a,i,"deltaY");if(r&&w&&u){let e=this.fontSize*C/1e3;t.save(),t.fillStyle=b,t.translate(h.renderLeft,h.renderTop),t.rotate(h.angle),t.fillRect(-h.kernedWidth/2,o*l+c-n*e,h.kernedWidth,e),t.restore()}else if((w!==m||u!==v||b!==y||l!==_||C!==x||c!==T)&&p>0){let e=this.fontSize*x/1e3,i=s+f+g;"rtl"===this.direction&&(i=this.width-i-p),m&&y&&x&&(t.fillStyle=y,t.fillRect(i,S+o*_+T-n*e,p,e)),g=h.left,p=h.width,m=w,y=b,x=C,v=u,_=l,T=c}else p+=h.kernedWidth}let M=s+f+g;"rtl"===this.direction&&(M=this.width-M-p),t.fillStyle=b;let k=this.fontSize*C/1e3;w&&b&&C&&t.fillRect(M,S+o*_+T-n*k,p-h,k),i+=l}this._removeShadow(t)}_getFontDeclaration({fontFamily:e=this.fontFamily,fontStyle:i=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:r=this.fontSize}={},h){let n=e.includes("'")||e.includes('"')||e.includes(",")||t.genericFonts.includes(e.toLowerCase())?e:`"${e}"`;return[i,s,`${h?this.CACHE_FONT_SIZE:r}px`,n].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return Kt(t)}_splitTextIntoLines(t){let e=t.split(this._reNewline),i=Array(e.length),s=["\n"],r=[];for(let t=0;t<e.length;t++)i[t]=this.graphemeSplit(e[t]),r=r.concat(i[t],s);return r.pop(),{_unwrappedLines:i,lines:e,graphemeText:r,graphemeLines:i}}toObject(t=[]){return{...super.toObject([...Je,...t]),styles:as(this.styles,this.text),...this.path?{path:this.path.toObject()}:{}}}set(t,e){let{textLayoutProperties:i}=this.constructor;super.set(t,e);let s=!1,r=!1;if("object"==typeof t)for(let e in t)"path"===e&&this.setPathInfo(),s=s||i.includes(e),r=r||"path"===e;else s=i.includes(t),r="path"===t;return r&&this.setPathInfo(),s&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(e,i,s){let r=$s(e,t.ATTRIBUTE_NAMES,s),{textAnchor:h=T,textDecoration:n="",dx:o=0,dy:a=0,top:l=0,left:u=0,fontSize:c=16,strokeWidth:d=1,...f}={...i,...r},g=new this(Pe(e.textContent||"").trim(),{left:u+o,top:l+a,underline:n.includes("underline"),overline:n.includes("overline"),linethrough:n.includes("line-through"),strokeWidth:0,fontSize:c,...f}),p=g.getScaledHeight()/g.height,m=((g.height+g.strokeWidth)*g.lineHeight-g.height)*p,v=g.getScaledHeight()+m,y=0;return"center"===h&&(y=g.getScaledWidth()/2),"right"===h&&(y=g.getScaledWidth()),g.set({left:g.left-y,top:g.top-(v-g.fontSize*(.07+g._fontSizeFraction))/g.lineHeight,strokeWidth:d}),g}static fromObject(t){return this._fromObject({...t,styles:ls(t.styles||{},t.text)},{extraParam:"text"})}};i(th,"textLayoutProperties",Ke),i(th,"cacheProperties",[...di,...Je]),i(th,"ownDefaults",Qe),i(th,"type","Text"),i(th,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),i(th,"ATTRIBUTE_NAMES",us.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-decoration-thickness","text-decoration-color","text-anchor")),ts(th,[class extends Ge{_toSVG(){let t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)}toSVG(t){let e=this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0}),i=this.path;return i?e+i._createBaseSVGMarkup(i._toSVG(),{reviver:t,withShadow:!0,additionalTransform:Et(this.calcOwnMatrix())}):e}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg({textBgRects:t,textSpans:e}){let i=this.getSvgTextDecoration(this);return[t.join(""),'\t\t<text xml:space="preserve" ',`font-family="${Ut(this.fontFamily.replace(Jr,"'"))}" `,`font-size="${Ut(this.fontSize)}" `,this.fontStyle?`font-style="${Ut(this.fontStyle)}" `:"",this.fontWeight?`font-weight="${Ut(this.fontWeight)}" `:"",i?`text-decoration="${i}" `:"","rtl"===this.direction?'direction="rtl" ':"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),"</text>\n"]}_getSVGTextAndBg(t,e){let i,s=[],r=[],h=t;this.backgroundColor&&r.push(Zr(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let t=0,n=this._textLines.length;t<n;t++)i=this._getLineLeftOffset(t),"rtl"===this.direction&&(i+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",t))&&this._setSVGTextLineBg(r,t,e+i,h),this._setSVGTextLineText(s,t,e+i,h),h+=this.getHeightOfLine(t);return{textSpans:s,textBgRects:r}}_createTextCharSpan(t,e,i,s,h){let n=r.NUM_FRACTION_DIGITS,o=this.getSvgSpanStyles(e,t!==t.trim()||!!t.match(Kr)),a=o?`style="${o}"`:"",l=e.deltaY,u=l?` dy="${Pt(l,n)}" `:"",{angle:c,renderLeft:d,renderTop:f,width:g}=h,p="";if(void 0!==d){let t=g/2;c&&(p=` rotate="${Pt(ft(c),n)}"`);let e=St({angle:ft(c)});e[4]=d,e[5]=f;let r=new tt(-t,0).transform(e);i=r.x,s=r.y}return`<tspan x="${Pt(i,n)}" y="${Pt(s,n)}" ${u}${p}${a}>${Ut(t)}</tspan>`}_setSVGTextLineText(t,e,i,s){let r,h,n,o,a,l=this.getHeightOfLine(e),u=this.textAlign.includes(ti),c=this._textLines[e],d="",f=0;s+=l*(1-this._fontSizeFraction)/this.lineHeight;for(let l=0,g=c.length-1;l<=g;l++)a=l===g||this.charSpacing||this.path,d+=c[l],n=this.__charBounds[e][l],0===f?(i+=n.kernedWidth-n.width,f+=n.width):f+=n.kernedWidth,u&&!a&&this._reSpaceAndTab.test(c[l])&&(a=!0),a||(r=r||this.getCompleteStyleDeclaration(e,l),h=this.getCompleteStyleDeclaration(e,l+1),a=os(r,h,!0)),a&&(o=this._getStyleDeclaration(e,l),t.push(this._createTextCharSpan(d,o,i,s,n)),d="",r=h,"rtl"===this.direction?i-=f:i+=f,f=0)}_setSVGTextLineBg(t,e,i,s){let r,h=this._textLines[e],n=this.getHeightOfLine(e)/this.lineHeight,o=0,a=0,l=this.getValueOfPropertyAt(e,0,"textBackgroundColor");for(let u=0;u<h.length;u++){let{left:h,width:c,kernedWidth:d}=this.__charBounds[e][u];r=this.getValueOfPropertyAt(e,u,"textBackgroundColor"),r===l?o+=d:(l&&t.push(Zr(l,i+a,s,o,n)),a=h,o=c,l=r)}r&&t.push(Zr(l,i+a,s,o,n))}getSvgStyles(t){let e=$e(this.textDecorationColor)?` text-decoration-color: ${Ut(this[Ve])};`:"";return`${super.getSvgStyles(t)} text-decoration-thickness: ${Pt(this.textDecorationThickness*this.getObjectScaling().y/10,r.NUM_FRACTION_DIGITS)}%;${e} white-space: pre;`}getSvgSpanStyles(t,e){let{fontFamily:i,strokeWidth:s,stroke:h,fill:n,fontSize:o,fontStyle:a,fontWeight:l,textDecorationThickness:u,textDecorationColor:c,linethrough:d,overline:f,underline:g}=t,p=this.getSvgTextDecoration({underline:null==g?this.underline:g,overline:null==f?this.overline:f,linethrough:null==d?this.linethrough:d}),m=u||this.textDecorationThickness,v=c||this.textDecorationColor,y=je(s),x=Ae(i),w=je(o),b=Ae(a),C=je(l)||Ae(l),S=Ae(v);return[h?We(G,h):"",y?`stroke-width: ${Ut(y)}; `:"",x?`font-family: ${x.includes("'")||x.includes('"')?Ut(x):`'${Ut(x)}'`}; `:"",w?`font-size: ${Ut(w)}px; `:"",b?`font-style: ${Ut(b)}; `:"",C?`font-weight: ${Ut(C)}; `:"",p?`text-decoration: ${p}; text-decoration-thickness: ${Pt(m*this.getObjectScaling().y/10,r.NUM_FRACTION_DIGITS)}%;${S?` text-decoration-color: ${Ut(S)};`:""} `:"",n?We(W,n):"",e?"white-space: pre; ":""].join("")}getSvgTextDecoration(t){return["overline","underline","line-through"].filter((e=>t[e.replace("-","")])).join(" ")}}]),U.setClass(th),U.setSVGClass(th);var eh=class{constructor(t){i(this,"target",void 0),i(this,"__mouseDownInPlace",!1),i(this,"__dragStartFired",!1),i(this,"__isDraggingOver",!1),i(this,"__dragStartSelection",void 0),i(this,"__dragImageDisposer",void 0),i(this,"_dispose",void 0),this.target=t;let 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((t=>t())),this._dispose=void 0}}isPointerOverSelection(t){let e=this.target,i=e.getSelectionStartFromPointer(t);return e.isEditing&&i>=e.selectionStart&&i<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){let 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,{selectionStart:e,selectionEnd:i}){var s;let r=this.target,h=r.canvas,n=new tt(r.flipX?-1:1,r.flipY?-1:1),o=r._getCursorBoundaries(e),a=new tt(o.left+o.leftOffset,o.top+o.topOffset).multiply(n).transform(r.calcTransformMatrix()),l=h.getScenePoint(t).subtract(a),u=r.getCanvasRetinaScaling(),c=r.getBoundingRect(),d=a.subtract(new tt(c.left,c.top)),f=h.viewportTransform,g=d.add(l).transform(f,!0),p=r.backgroundColor,m=ns(r.styles);r.backgroundColor="";let v={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(v,0,e),r.setSelectionStyles(v,i,r.text.length),r.dirty=!0;let y=r.toCanvasElement({enableRetinaScaling:h.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=p,r.styles=m,r.dirty=!0,dr(y,{position:"fixed",left:-y.width+"px",border:F,width:y.width/u+"px",height:y.height/u+"px"}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{y.remove()},Yt(t.target||this.target.hiddenTextarea).body.appendChild(y),null==(s=t.dataTransfer)||s.setDragImage(y,g.x,g.y)}onDragStart(t){this.__dragStartFired=!0;let e=this.target,i=this.isActive();if(i&&t.dataTransfer){let i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},s=e._text.slice(i.selectionStart,i.selectionEnd).join(""),r={text:e.text,value:s,...i};t.dataTransfer.setData("text/plain",s),t.dataTransfer.setData("application/fabric",JSON.stringify({value:s,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,r)}return e.abortCursorAnimation(),i}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){let e=this.target.getSelectionStartFromPointer(t),i=this.__dragStartSelection;return e<i.selectionStart||e>i.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler({e:t}){let e=this.targetCanDrop(t);!this.__isDraggingOver&&e&&(this.__isDraggingOver=!0)}dragOverHandler(t){let{e}=t,i=this.targetCanDrop(e);!this.__isDraggingOver&&i?this.__isDraggingOver=!0:this.__isDraggingOver&&!i&&(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;let{e:i}=t,s=i.defaultPrevented;this.__isDraggingOver=!1,i.preventDefault();let r=null==(e=i.dataTransfer)?void 0:e.getData("text/plain");if(r&&!s){let e=this.target,s=e.canvas,h=e.getSelectionStartFromPointer(i),{styles:n}=i.dataTransfer.types.includes("application/fabric")?JSON.parse(i.dataTransfer.getData("application/fabric")):{},o=r[Math.max(0,r.length-1)];if(this.__dragStartSelection){let t=this.__dragStartSelection.selectionStart,i=this.__dragStartSelection.selectionEnd;h>t&&h<=i?h=t:h>i&&(h-=i-t),e.removeChars(t,i),delete this.__dragStartSelection}e._reNewline.test(o)&&(e._reNewline.test(e._text[h])||h===e._text.length)&&(r=r.trimEnd()),t.didDrop=!0,t.dropTarget=e,e.insertChars(r,n,h),s.setActiveObject(e),e.enterEditing(i),e.selectionStart=Math.min(h+0,e._text.length),e.selectionEnd=Math.min(e.selectionStart+r.length,e._text.length),e.hiddenTextarea.value=e.text,e._updateTextarea(),e.hiddenTextarea.focus(),e.fire(B,{index:h+0,action:"drop"}),s.fire("text:changed",{target:e}),s.contextTopDirty=!0,s.requestRenderAll()}}dragEndHandler({e:t}){if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var e;let i=this.target,s=this.target.canvas,{selectionStart:r,selectionEnd:h}=this.__dragStartSelection,n=(null==(e=t.dataTransfer)?void 0:e.dropEffect)||"none";"none"===n?(i.selectionStart=r,i.selectionEnd=h,i._updateTextarea(),i.hiddenTextarea.focus()):(i.clearContextTop(),"move"===n&&(i.removeChars(r,h),i.selectionStart=i.selectionEnd=r,i.hiddenTextarea&&(i.hiddenTextarea.value=i.text),i._updateTextarea(),i.fire(B,{index:r,action:"dragend"}),s.fire("text:changed",{target:i}),s.requestRenderAll()),i.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}};const ih=/[ \n\.,;!\?\-]/;var sh=class extends th{constructor(...t){super(...t),i(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({toValue:t,duration:e,delay:i,onComplete:s}){return Ci({startValue:this._currentCursorOpacity,endValue:t,duration:e,delay:i,onComplete:s,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:t=>{this._currentCursorOpacity=t,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;null==(t=this._currentTickCompleteState)||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,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/\S/.test(this._text[i])&&i>-1;)e++,i--;return t-e}findWordBoundaryRight(t){let e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/\S/.test(this._text[i])&&i<this._text.length;)e++,i++;return t+e}findLineBoundaryLeft(t){let e=0,i=t-1;for(;!/\n/.test(this._text[i])&&i>-1;)e++,i--;return t-e}findLineBoundaryRight(t){let e=0,i=t;for(;!/\n/.test(this._text[i])&&i<this._text.length;)e++,i++;return t+e}searchWordBoundary(t,e){let i=this._text,s=t>0&&this._reSpace.test(i[t])&&(-1===e||!D.test(i[t-1]))?t-1:t,r=i[s];for(;s>0&&s<i.length&&!ih.test(r);)s+=e,r=i[s];return-1===e&&ih.test(r)&&s++,s}selectWord(t){var e;t=null==(e=t)?this.selectionStart:e;let i=this.searchWordBoundary(t,-1),s=Math.max(i,this.searchWordBoundary(t,1));this.selectionStart=i,this.selectionEnd=s,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=null==(e=t)?this.selectionStart:e;let i=this.findLineBoundaryLeft(t),s=this.findLineBoundaryRight(t);this.selectionStart=i,this.selectionEnd=s,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;let e=this.hiddenTextarea;Yt(e).activeElement!==e&&e.focus();let i=this.getSelectionStartFromPointer(t),s=this.selectionStart,r=this.selectionEnd;(i===this.__selectionStartOnMouseDown&&s!==r||s!==i&&r!==i)&&(i>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=i):(this.selectionStart=i,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===s&&this.selectionEnd===r||(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,i){let s=i.slice(0,t),r=this.graphemeSplit(s).length;if(t===e)return{selectionStart:r,selectionEnd:r};let h=i.slice(t,e);return{selectionStart:r,selectionEnd:r+this.graphemeSplit(h).length}}fromGraphemeToStringSelection(t,e,i){let s=i.slice(0,t).join("").length;return t===e?{selectionStart:s,selectionEnd:s}:{selectionStart:s,selectionEnd:s+i.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){let t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){let{hiddenTextarea:t,direction:e,textAlign:i,inCompositionMode:s}=this;if(!t)return;let r="justify"===i?"ltr"===e?T:k:i.replace("justify-",""),h=this.getPositionByOrigin(r,"top");this.cursorOffsetCache={},this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setPositionByOrigin(h,r,"top"),this.setCoords();let n=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=n.selectionEnd,s||(this.selectionStart=n.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){let t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};let t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),s=this.getValueOfPropertyAt(i.lineIndex,i.charIndex,"fontSize")*this.lineHeight,r=e.leftOffset,h=this.getCanvasRetinaScaling(),n=this.canvas.upperCanvasEl,o=n.width/h,a=n.height/h,l=o-s,u=a-s,c=new tt(e.left+r,e.top+e.topOffset+s).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new tt(n.clientWidth/o,n.clientHeight/a));return c.x<0&&(c.x=0),c.x>l&&(c.x=l),c.y<0&&(c.y=0),c.y>u&&(c.y=u),c.x+=this.canvas._offset.left,c.y+=this.canvas._offset.top,{left:`${c.x}px`,top:`${c.y}px`,fontSize:`${s}px`,charHeight:s}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}exitEditingImpl(){let t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){let t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire("modified"),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(let t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){let{lineIndex:i,charIndex:s}=this.get2DCursorLocation(t,!0),{lineIndex:r,charIndex:h}=this.get2DCursorLocation(e,!0);if(i!==r){if(this.styles[i])for(let t=s;t<this._unwrappedTextLines[i].length;t++)delete this.styles[i][t];if(this.styles[r])for(let t=h;t<this._unwrappedTextLines[r].length;t++){let e=this.styles[r][t];e&&(this.styles[i]||(this.styles[i]={}),this.styles[i][s+t-h]=e)}for(let t=i+1;t<=r;t++)delete this.styles[t];this.shiftLineStyles(r,i-r)}else if(this.styles[i]){let t=this.styles[i],e=h-s;for(let e=s;e<h;e++)delete t[e];for(let s in this.styles[i]){let i=parseInt(s,10);i>=h&&(t[i-e]=t[s],delete t[s])}}}shiftLineStyles(t,e){let i=Object.assign({},this.styles);for(let s in this.styles){let r=parseInt(s,10);r>t&&(this.styles[r+e]=i[r],i[r-e]||delete this.styles[r])}}insertNewlineStyleObject(t,e,i,s){let r={},h=this._unwrappedTextLines[t].length,n=h===e,o=!1;i||(i=1),this.shiftLineStyles(t,i);let a=this.styles[t]?this.styles[t][0===e?e:e-1]:void 0;for(let i in this.styles[t]){let s=parseInt(i,10);s>=e&&(o=!0,r[s-e]=this.styles[t][i],n&&0===e||delete this.styles[t][i])}let l=!1;for(o&&!n&&(this.styles[t+i]=r,l=!0),(l||h>e)&&i--;i>0;)s&&s[i-1]?this.styles[t+i]={0:{...s[i-1]}}:a?this.styles[t+i]={0:{...a}}:delete this.styles[t+i],i--;this._forceClearCache=!0}insertCharStyleObject(t,e,i,s){this.styles||(this.styles={});let r=this.styles[t],h=r?{...r}:{};i||(i=1);for(let t in h){let s=parseInt(t,10);s>=e&&(r[s+i]=h[s],h[s-i]||delete r[s])}if(this._forceClearCache=!0,s){for(;i--;)Object.keys(s[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]={...s[i]});return}if(!r)return;let n=r[e?e-1:1];for(;n&&i--;)this.styles[t][e+i]={...n}}insertNewStyleBlock(t,e,i){let s,r=this.get2DCursorLocation(e,!0),h=[0],n=0;for(let e=0;e<t.length;e++)"\n"===t[e]?(n++,h[n]=0):h[n]++;for(h[0]>0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,h[0],i),i=i&&i.slice(h[0]+1)),n&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+h[0],n),s=1;s<n;s++)h[s]>0?this.insertCharStyleObject(r.lineIndex+s,0,h[s],i):i&&this.styles[r.lineIndex+s]&&i[0]&&(this.styles[r.lineIndex+s][0]=i[0]),i=i&&i.slice(h[s]+1);h[s]>0&&this.insertCharStyleObject(r.lineIndex+s,0,h[s],i)}removeChars(t,e=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,i,s=i){s>i&&this.removeStyleFromTo(i,s);let r=this.graphemeSplit(t);this.insertNewStyleBlock(r,i,e),this._text=[...this._text.slice(0,i),...r,...this._text.slice(s)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,i){i<=t?(e===t?this._selectionDirection=T:"right"===this._selectionDirection&&(this._selectionDirection=T,this.selectionEnd=t),this.selectionStart=i):i>t&&i<e?"right"===this._selectionDirection?this.selectionEnd=i:this.selectionStart=i:(e===t?this._selectionDirection=k:"left"===this._selectionDirection&&(this._selectionDirection=k,this.selectionStart=e),this.selectionEnd=i)}},rh=class extends sh{initHiddenTextarea(){let t=this.canvas&&Yt(this.canvas.getElement())||f(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off",name:"fabricTextarea"}).map((([t,i])=>e.setAttribute(t,i)));let{top:i,left:s,fontSize:r}=this._calcTextareaPosition();e.style.cssText=`position: absolute; top: ${i}; left: ${s}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${r};`,(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((([t,i])=>e.addEventListener(t,this[i].bind(this)))),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;let e="rtl"===this.direction?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){let e=this.fromPaste,{value:i,selectionStart:s,selectionEnd:h}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;let n=()=>{this.updateFromTextArea(),this.fire(B),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(""===this.hiddenTextarea.value)return this.styles={},void n();let o,a,l,u,c=this._splitTextIntoLines(i).graphemeText,f=this._text.length,g=c.length,p=this.selectionStart,m=this.selectionEnd,v=p!==m,y=g-f,x=this.fromStringToGraphemeSelection(s,h,i),w=p>x.selectionStart;v?(a=this._text.slice(p,m),y+=m-p):g<f&&(a=w?this._text.slice(m+y,m):this._text.slice(p,p-y));let b=c.slice(x.selectionEnd-y,x.selectionEnd);if(a&&a.length&&(b.length&&(o=this.getSelectionStyles(p,p+1,!1),o=b.map((()=>o[0]))),v?(l=p,u=m):w?(l=m-a.length,u=m):(l=m,u=m+a.length),this.removeStyleFromTo(l,u)),b.length){let{copyPasteData:t}=d();e&&b.join("")===t.copiedText&&!r.disableStyleCopyPaste&&(o=t.copiedTextStyle),this.insertNewStyleBlock(b,p,o)}n()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate({target:t}){let{selectionStart:e,selectionEnd:i}=t;this.compositionStart=e,this.compositionEnd=i,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;let{copyPasteData:t}=d();t.copiedText=this.getSelectedText(),t.copiedTextStyle=r.disableStyleCopyPaste?void 0:this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let i,s=this._getLineLeftOffset(t);return e>0&&(i=this.__charBounds[t][e-1],s+=i.left+i.width),s}getDownCursorOffset(t,e){let i=this._getSelectionForOffset(t,e),s=this.get2DCursorLocation(i),r=s.lineIndex;if(r===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;let h=s.charIndex,n=this._getWidthBeforeCursor(r,h),o=this._getIndexOnLine(r+1,n);return this._textLines[r].slice(h).length+o+1+this.missingNewlineOffset(r)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){let i=this._getSelectionForOffset(t,e),s=this.get2DCursorLocation(i),r=s.lineIndex;if(0===r||t.metaKey||33===t.keyCode)return-i;let h=s.charIndex,n=this._getWidthBeforeCursor(r,h),o=this._getIndexOnLine(r-1,n),a=this._textLines[r].slice(0,h),l=this.missingNewlineOffset(r-1);return-this._textLines[r-1].length+o-a.length+(1-l)}_getIndexOnLine(t,e){let i,s,r=this._textLines[t],h=this._getLineLeftOffset(t),n=0;for(let o=0,a=r.length;o<a;o++)if(i=this.__charBounds[t][o].width,h+=i,h>e){s=!0;let t=h,r=Math.abs(h-i-e);n=Math.abs(t-e)<r?o:o-1;break}return s||(n=r.length-1),n}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){let i=this[`get${t}CursorOffset`](e,this._selectionDirection===k);if(e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i){let t=this.text.length;this.selectionStart=ui(0,this.selectionStart,t),this.selectionEnd=ui(0,this.selectionEnd,t),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,"left"===this._selectionDirection?this.selectionStart+t:this.selectionEnd+t),0!==t}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t}moveCursorLeft(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)}_move(t,e,i){let s;if(t.altKey)s=this[`findWordBoundary${i}`](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;s=this[`findLineBoundary${i}`](this[e])}return void 0!==s&&this[e]!==s&&(this[e]=s,!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=T,this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return"right"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0===this.selectionStart?void 0:(this._selectionDirection=T,this._moveLeft(t,"selectionStart"))}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){let i=`moveCursor${t}${e.shiftKey?"WithShift":"WithoutShift"}`;this._currentCursorOpacity=1,this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return"left"===this._selectionDirection&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd===this._text.length?void 0:(this._selectionDirection=k,this._moveRight(t,"selectionEnd"))}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=k,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}};const hh=t=>!!t.button;var nh=class extends rh{constructor(...t){super(...t),i(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 eh(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({e:t,alreadySelected:e}){this.canvas&&this.editable&&!hh(t)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(t)||(this.canvas.textEditingManager.register(this),e&&(this.inCompositionMode=!1,this.setCursorByClick(t)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=e||this.isEditing)))}mouseUpHandler({e:t,transform:e}){let i=this.draggableTextDelegate.end(t);if(this.canvas){this.canvas.textEditingManager.unregister(this);let t=this.canvas._activeObject;if(t&&t!==this)return}!this.editable||this.group&&!this.group.interactive||e&&e.actionPerformed||hh(t)||i||this.selected&&!this.getActiveControl()&&(this.enterEditing(t),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){let e=this.getSelectionStartFromPointer(t);t.shiftKey?this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){let e=this.canvas.getScenePoint(t).transform(pt(this.calcTransformMatrix())).add(new tt(-this._getLeftOffset(),-this._getTopOffset())),i=0,s=0,r=0;for(let t=0;t<this._textLines.length&&i<=e.y;t++)i+=this.getHeightOfLine(t),r=t,t>0&&(s+=this._textLines[t-1].length+this.missingNewlineOffset(t-1));let h=Math.abs(this._getLineLeftOffset(r)),n=this._textLines[r].length,o=this.__charBounds[r];for(let t=0;t<n;t++){let i=h+o[t].kernedWidth;if(e.x<=i){Math.abs(e.x-i)<=Math.abs(e.x-h)&&s++;break}h=i,s++}return Math.min(this.flipX?n-s:s,this._text.length)}};const oh="moveCursorUp",ah="moveCursorDown",lh="moveCursorLeft",uh="moveCursorRight",ch="exitEditing",dh=(t,e)=>{let i=e.getRetinaScaling();t.setTransform(i,0,0,i,0,0);let s=e.viewportTransform;t.transform(s[0],s[1],s[2],s[3],s[4],s[5])},fh={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:ch,27:ch,33:oh,34:ah,35:uh,36:lh,37:lh,38:oh,39:uh,40:ah},keysMapRtl:{9:ch,27:ch,33:oh,34:ah,35:lh,36:uh,37:uh,38:oh,39:lh,40:ah},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"},_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1};var gh=class t extends nh{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}get type(){let t=super.type;return"itext"===t?"i-text":t}constructor(e,i){super(e,{...t.ownDefaults,...i}),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):("canvas"===t&&(this.canvas instanceof Cr&&this.canvas.textEditingManager.remove(this),e instanceof Cr&&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(t=this.selectionStart||0,e=this.selectionEnd,i){return super.getSelectionStyles(t,e,i)}setSelectionStyles(t,e=this.selectionStart||0,i=this.selectionEnd){return super.setSelectionStyles(t,e,i)}get2DCursorLocation(t=this.selectionStart,e){return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){let e=this.isEditing;this.isEditing=!1;let i=super.toCanvasElement(t);return this.isEditing=e,i}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;let t=this.clearContextTop(!0);if(!t)return;let e,i=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),r=s.length>0,h=t;if(r){e=lt(t.canvas),h=e.getContext("2d"),dh(h,this.canvas);let i=this.calcTransformMatrix();h.transform(i[0],i[1],i[2],i[3],i[4],i[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(h,i):this.renderCursor(h,i),r)for(let e of s){let i=e.clipPath,s=lt(t.canvas),r=s.getContext("2d");if(dh(r,this.canvas),!i.absolutePositioned){let t=e.calcTransformMatrix();r.transform(t[0],t[1],t[2],t[3],t[4],t[5])}i.transform(r),i.drawObject(r,!0,{}),this.drawClipPathOnCache(h,i,s)}r&&(t.setTransform(1,0,0,1,0,0),t.drawImage(e,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){let t=[],e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(t=this.selectionStart,e){let i=this._getLeftOffset(),s=this._getTopOffset(),r=this._getCursorBoundariesOffsets(t,e);return{left:i,top:s,leftOffset:r.left,topOffset:r.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,i=0,{charIndex:s,lineIndex:r}=this.get2DCursorLocation(t),{textAlign:h,direction:n}=this;for(let t=0;t<r;t++)e+=this.getHeightOfLine(t);let o=this._getLineLeftOffset(r),a=this.__charBounds[r][s];a&&(i=a.left),0!==this.charSpacing&&s===this._textLines[r].length&&(i-=this._getWidthOfCharSpacing());let l=o+(i>0?i:0);return"rtl"===n&&("right"===h||"justify"===h||"justify-right"===h?l*=-1:"left"===h||"justify-left"===h?l=o-(i>0?i:0):"center"!==h&&"justify-center"!==h||(l=o-(i>0?i:0))),{top:e,left:l}}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(t=this.selectionStart,e=this._getCursorBoundaries(t)){let i=this.get2DCursorLocation(t),s=i.lineIndex,r=i.charIndex>0?i.charIndex-1:0,h=this.getValueOfPropertyAt(s,r,"fontSize"),n=this.getObjectScaling().x*this.canvas.getZoom(),o=this.cursorWidth/n,a=this.getValueOfPropertyAt(s,r,"deltaY"),l=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(s)/this.lineHeight-h*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(s,r,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-o/2,top:l+e.top+a,width:o,height:h}}_renderCursor(t,e,i){let{color:s,opacity:r,left:h,top:n,width:o,height:a}=this.getCursorRenderingData(i,e);t.fillStyle=s,t.globalAlpha=r,t.fillRect(h,n,o,a)}renderSelection(t,e){this._renderSelection(t,{selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd},e)}renderDragSourceEffect(){let t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){let e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,i){let{textAlign:s,direction:r}=this,h=e.selectionStart,n=e.selectionEnd,o=s.includes(ti),a=this.get2DCursorLocation(h),l=this.get2DCursorLocation(n),u=a.lineIndex,c=l.lineIndex,d=a.charIndex<0?0:a.charIndex,f=l.charIndex<0?0:l.charIndex;for(let e=u;e<=c;e++){let h=this._getLineLeftOffset(e)||0,n=this.getHeightOfLine(e),a=0,l=0;if(e===u&&(a=this.__charBounds[u][d].left),e>=u&&e<c)l=o&&!this.isEndOfWrapping(e)?this.width:this.getLineWidth(e)||5;else if(e===c)if(0===f)l=this.__charBounds[c][f].left;else{let t=this._getWidthOfCharSpacing();l=this.__charBounds[c][f-1].left+this.__charBounds[c][f-1].width-t}let g=n;(this.lineHeight<1||e===c&&this.lineHeight>1)&&(n/=this.lineHeight);let p=i.left+h+a,m=n,v=0,y=l-a;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",m=1,v=n):t.fillStyle=this.selectionColor,"rtl"===r&&("right"===s||"justify"===s||"justify-right"===s?p=this.width-p-y:"left"===s||"justify-left"===s?p=i.left+h-l:"center"!==s&&"justify-center"!==s||(p=i.left+h-l)),t.fillRect(p,i.top+i.topOffset+v,y,m),i.topOffset+=g}}getCurrentCharFontSize(){let t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){let t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,W)}_getCurrentCharIndex(){let t=this.get2DCursorLocation(this.selectionStart,!0);return{l:t.lineIndex,c:t.charIndex>0?t.charIndex-1:0}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}};i(gh,"ownDefaults",fh),i(gh,"type","IText"),U.setClass(gh),U.setClass(gh,"i-text");var ph=class t extends gh{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e,i){super(e,{...t.ownDefaults,...i})}static createControls(){return{controls:{...Zi(),mr:new Ai({x:.5,y:0,actionHandler:Oi,cursorStyleHandler:qi,actionName:E}),ml:new Ai({x:-.5,y:0,actionHandler:Oi,cursorStyleHandler:qi,actionName:E})}}}initDimensions(){this.initialized&&(this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0,this._styleMap=this._generateStyleMap(this._splitText()),this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this.textAlign.includes("justify")&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,i=0,s=0,r={};for(let h=0;h<t.graphemeLines.length;h++)"\n"===t.graphemeText[s]&&h>0?(i=0,s++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[s])&&h>0&&(i++,s++),r[h]={line:e,offset:i},s+=t.graphemeLines[h].length,i+=t.graphemeLines[h].length;return r}styleHas(t,e){if(this._styleMap&&!this.isWrapping){let t=this._styleMap[e];t&&(e=t.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,i,s=0,r=!1,h=this._styleMap[t],n=this._styleMap[t+1];h&&(t=h.line,s=h.offset),n&&(e=n.line,r=e===t,i=n.offset);let o=void 0===t?this.styles:{line:this.styles[t]};for(let t in o)for(let e in o[t]){let h=parseInt(e,10);if(h>=s&&(!r||h<i))for(let i in o[t][e])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){let i=this._styleMap[t];if(!i)return{};t=i.line,e=i.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,i){let s=this._styleMap[t];super._setStyleDeclaration(s.line,s.offset+e,i)}_deleteStyleDeclaration(t,e){let i=this._styleMap[t];super._deleteStyleDeclaration(i.line,i.offset+e)}_getLineStyle(t){return!!this.styles[this._styleMap[t].line]}_setLineStyle(t){super._setLineStyle(this._styleMap[t].line)}_wrapText(t,e){this.isWrapping=!0;let i=this.getGraphemeDataForRender(t),s=[];for(let t=0;t<i.wordsData.length;t++)s.push(...this._wrapLine(t,e,i));return this.isWrapping=!1,s}getGraphemeDataForRender(t){let e=this.splitByGrapheme,i=e?"":" ",s=0;return{wordsData:t.map(((t,r)=>{let h=0,n=e?this.graphemeSplit(t):this.wordSplit(t);return 0===n.length?[{word:[],width:0}]:n.map((t=>{let n=e?[t]:this.graphemeSplit(t),o=this._measureWord(n,r,h);return s=Math.max(o,s),h+=n.length+i.length,{word:n,width:o}}))})),largestWordWidth:s}}_measureWord(t,e,i=0){let s,r=0;for(let h=0,n=t.length;h<n;h++)r+=this._getGraphemeBox(t[h],e,h+i,s,!0).kernedWidth,s=t[h];return r}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,{largestWordWidth:i,wordsData:s},r=0){let h,n=this._getWidthOfCharSpacing(),o=this.splitByGrapheme,a=[],l=o?"":" ",u=0,c=[],d=0,f=0,g=!0,p=Math.max(e-=r,i,this.dynamicMinWidth),m=s[t];for(h=0;h<m.length;h++){let{word:e,width:i}=m[h];d+=e.length,u+=f+i-n,u>p&&!g?(a.push(c),c=[],u=i,g=!0):u+=n,g||o||c.push(l),c=c.concat(e),f=o?0:this._measureWord([l],t,d),d++,g=!1}return h&&a.push(c),i+r>this.dynamicMinWidth&&(this.dynamicMinWidth=i-n+r),a}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}_splitTextIntoLines(t){let e=super._splitTextIntoLines(t),i=this._wrapText(e.lines,this.width),s=Array(i.length);for(let t=0;t<i.length;t++)s[t]=i[t].join("");return e.lines=s,e.graphemeLines=i,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){let t=new Map;for(let e in this._styleMap){let i=parseInt(e,10);this._textLines[i]&&t.set(`${this._styleMap[e].line}`,!0)}for(let e in this.styles)t.has(e)||delete this.styles[e]}toObject(t=[]){return super.toObject(["minWidth","splitByGrapheme",...t])}};i(ph,"type","Textbox"),i(ph,"textLayoutProperties",[...gh.textLayoutProperties,"width"]),i(ph,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),U.setClass(ph);var mh=class extends Bs{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){let{target:i}=t,{clipPath:s,group:r}=i;if(!s||!this.shouldPerformLayout(t))return;let{width:h,height:n}=se(Ls(i,s)),o=new tt(h,n);if(s.absolutePositioned)return{center:ae(s.getRelativeCenterPoint(),void 0,r?r.calcTransformMatrix():void 0),size:o};{let r=s.getRelativeCenterPoint().transform(i.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){let{center:i=new tt,correction:s=new tt}=this.calcBoundingBox(e,t)||{};return{center:i.add(r),correction:s.subtract(r),size:o}}return{center:i.getRelativeCenterPoint().add(r),size:o}}}};i(mh,"type","clip-path"),U.setClass(mh);var vh=class extends Bs{getInitialSize({target:t},{size:e}){return new tt(t.width||e.x,t.height||e.y)}};i(vh,"type","fixed"),U.setClass(vh);var yh=class extends Xs{subscribeTargets(t){let e=t.target;t.targets.reduce(((t,e)=>(e.parent&&t.add(e.parent),t)),new Set).forEach((t=>{t.layoutManager.subscribeTargets({target:t,targets:[e]})}))}unsubscribeTargets(t){let e=t.target,i=e.getObjects();t.targets.reduce(((t,e)=>(e.parent&&t.add(e.parent),t)),new Set).forEach((t=>{!i.some((e=>e.parent===t))&&t.layoutManager.unsubscribeTargets({target:t,targets:[e]})}))}},xh=class t extends zs{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e=[],i={}){super(),Object.assign(this,t.ownDefaults),this.setOptions(i);let{left:s,top:r,layoutManager:h}=i;this.groupInit(e,{left:s,top:r,layoutManager:null==h?new yh:h})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(...t){"selection-order"===this.multiSelectionStacking?this.add(...t):t.forEach((t=>{let e=this._objects.findIndex((e=>e.isInFrontOf(t))),i=-1===e?this.size():e;this.insertAt(i,t)}))}canEnterGroup(t){return this.getObjects().some((e=>e.isDescendantOf(t)||t.isDescendantOf(e)))?(h("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);let i=new Set;e.forEach((t=>{let{parent:e}=t;e&&i.add(e)})),i.forEach("removed"===t?t=>{t._onAfterObjectsChange(Es,e)}:t=>{t._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return`#<ActiveSelection: (${this.complexity()})>`}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;let s={hasControls:!1,...i,forActiveSelection:!0};for(let e=0;e<this._objects.length;e++)this._objects[e]._renderControls(t,s);super._renderControls(t,e),t.restore()}};i(xh,"type","ActiveSelection"),i(xh,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),U.setClass(xh),U.setClass(xh,"activeSelection");var wh=class{constructor(){i(this,"resources",{})}applyFilters(t,e,i,s,r){let h=r.getContext("2d",{willReadFrequently:!0,desynchronized:!0});if(!h)return;h.drawImage(e,0,0,i,s);let n={sourceWidth:i,sourceHeight:s,imageData:h.getImageData(0,0,i,s),originalEl:e,originalImageData:h.getImageData(0,0,i,s),canvasEl:r,ctx:h,filterBackend:this};t.forEach((t=>{t.applyTo(n)}));let{imageData:o}=n;return o.width===i&&o.height===s||(r.width=o.width,r.height=o.height),h.putImageData(o,0,0),n}},bh=class{constructor({tileSize:t=r.textureSize}={}){i(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),i(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){let i=lt({width:t,height:e}),s=i.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});s&&(s.clearColor(0,0,0,0),this.canvas=i,this.gl=s)}applyFilters(t,e,i,s,r,h){let n,o=this.gl,a=r.getContext("2d");if(!o||!a)return;h&&(n=this.getCachedTexture(h,e));let l={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:i,sourceHeight:s,destinationWidth:i,destinationHeight:s,context:o,sourceTexture:this.createTexture(o,i,s,n?void 0:e),targetTexture:this.createTexture(o,i,s),originalTexture:n||this.createTexture(o,i,s,n?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:r},u=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,u),t.forEach((t=>{t&&t.applyTo(l)})),function(t){let e=t.targetCanvas,i=t.destinationWidth,s=t.destinationHeight;e.width===i&&e.height===s||(e.width=i,e.height=s)}(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(u),a.setTransform(1,0,0,1,0,0),l}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,i,s,r){let{NEAREST:h,TEXTURE_2D:n,RGBA:o,UNSIGNED_BYTE:a,CLAMP_TO_EDGE:l,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:c,TEXTURE_WRAP_S:d,TEXTURE_WRAP_T:f}=t,g=t.createTexture();return t.bindTexture(n,g),t.texParameteri(n,u,r||h),t.texParameteri(n,c,r||h),t.texParameteri(n,d,l),t.texParameteri(n,f,l),s?t.texImage2D(n,0,o,o,a,s):t.texImage2D(n,0,o,e,i,0,o,a,null),g}getCachedTexture(t,e,i){let{textureCache:s}=this;if(s[t])return s[t];{let r=this.createTexture(this.gl,e.width,e.height,e,i);return r&&(s[t]=r),r}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){let i=t.canvas,s=e.targetCanvas,r=s.getContext("2d");r&&(r.translate(0,s.height),r.scale(1,-1),r.drawImage(i,0,i.height-s.height,s.width,s.height,0,0,s.width,s.height))}copyGLTo2DPutImageData(t,e){let i=e.targetCanvas.getContext("2d"),s=e.destinationWidth,r=e.destinationHeight,h=s*r*4;if(!i)return;let n=new Uint8Array(this.imageBuffer,0,h),o=new Uint8ClampedArray(this.imageBuffer,0,h);t.readPixels(0,0,s,r,t.RGBA,t.UNSIGNED_BYTE,n);let a=new ImageData(o,s,r);i.putImageData(a,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;let t=this.gl,e={renderer:"",vendor:""};if(!t)return e;let i=t.getExtension("WEBGL_debug_renderer_info");if(i){let s=t.getParameter(i.UNMASKED_RENDERER_WEBGL),r=t.getParameter(i.UNMASKED_VENDOR_WEBGL);s&&(e.renderer=s.toLowerCase()),r&&(e.vendor=r.toLowerCase())}return this.gpuInfo=e,e}};let Ch;function Sh(t=!0){return!Ch&&t&&(Ch=function(){let{WebGLProbe:t}=d();return t.queryWebGL(at()),r.enableGLFiltering&&t.isSupported(r.textureSize)?new bh({tileSize:r.textureSize}):new wh}()),Ch}const _h=["cropX","cropY"];var Th=class t extends es{static getDefaults(){return{...super.getDefaults(),...t.ownDefaults}}constructor(e,s){super(),i(this,"_lastScaleX",1),i(this,"_lastScaleY",1),i(this,"_filterScalingX",1),i(this,"_filterScalingY",1),this.filters=[],Object.assign(this,t.ownDefaults),this.setOptions(s),this.cacheKey=`texture${ot()}`,this.setElement("string"==typeof e?(this.canvas&&Yt(this.canvas.getElement())||f()).getElementById(e):e,s)}getElement(){return this._element}setElement(t,e={}){this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._element=t,this._originalElement=t,this._setWidthHeight(e),0!==this.filters.length&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){let e=Sh(!1);e instanceof bh&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach((t=>{let e=this[t];e&&d().dispose(e),this[t]=void 0}))}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){let t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||0===this.strokeWidth)return;let e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,-i),t.lineTo(e,-i),t.lineTo(e,i),t.lineTo(-e,i),t.lineTo(-e,-i),t.closePath()}toObject(t=[]){let e=[];return this.filters.forEach((t=>{t&&e.push(t.toObject())})),{...super.toObject([..._h,...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(){let t=[],e=this._element,i=-this.width/2,s=-this.height/2,r=[],h=[],n="",o="";if(!e)return[];if(this.hasCrop()){let t=ot();r.push('<clipPath id="imageCrop_'+t+'">\n','\t<rect x="'+i+'" y="'+s+'" width="'+Ut(this.width)+'" height="'+Ut(this.height)+'" />\n',"</clipPath>\n"),n=' clip-path="url(#imageCrop_'+t+')" '}if(this.imageSmoothing||(o=' image-rendering="optimizeSpeed"'),t.push("\t<image ","COMMON_PARTS",`xlink:href="${Ut(this.getSrc(!0))}" x="${i-this.cropX}" y="${s-this.cropY}" width="${e.width||e.naturalWidth}" height="${e.height||e.naturalHeight}"${o}${n}></image>\n`),this.stroke||this.strokeDashArray){let t=this.fill;this.fill=null,h=[`\t<rect x="${i}" y="${s}" width="${Ut(this.width)}" height="${Ut(this.height)}" style="${this.getSvgStyles()}" />\n`],this.fill=t}return r="fill"===this.paintFirst?r.concat(t,h):r.concat(h,t),r}getSrc(t){let 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,{crossOrigin:e,signal:i}={}){return Dt(t,{crossOrigin:e,signal:i}).then((t=>{void 0!==e&&this.set({crossOrigin:e}),this.setElement(t)}))}toString(){return`#<Image: { src: "${this.getSrc()}" }>`}applyResizeFilters(){let t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),s=i.x,r=i.y,h=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||s>e&&r>e)return this._element=h,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=s,void(this._lastScaleY=r);let n=lt(h),{width:o,height:a}=h;this._element=n,this._lastScaleX=t.scaleX=s,this._lastScaleY=t.scaleY=r,Sh().applyFilters([t],h,o,a,this._element),this._filterScalingX=n.width/this._originalElement.width,this._filterScalingY=n.height/this._originalElement.height}applyFilters(t=this.filters||[]){if(t=t.filter((t=>t&&!t.isNeutralState())),this.set("dirty",!0),this.removeTexture(`${this.cacheKey}_filtered`),0===t.length)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);let e=this._originalElement,i=e.naturalWidth||e.width,s=e.naturalHeight||e.height;if(this._element===this._originalElement){let t=lt({width:i,height:s});this._element=t,this._filteredEl=t}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,s),this._lastScaleX=1,this._lastScaleY=1);Sh().applyFilters(t,this._originalElement,i,s,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,!0!==this.isMoving&&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){let e=this._element;if(!e)return;let i=this._filterScalingX,s=this._filterScalingY,r=this.width,h=this.height,n=Math.max(this.cropX,0),o=Math.max(this.cropY,0),a=e.naturalWidth||e.width,l=e.naturalHeight||e.height,u=n*i,c=o*s,d=Math.min(r*i,a-u),f=Math.min(h*s,l-c),g=-r/2,p=-h/2,m=Math.min(r,a/i-n),v=Math.min(h,l/s-o);e&&t.drawImage(e,u,c,d,f,g,p,m,v)}_needsResize(){let t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight({width:t,height:e}={}){let i=this.getOriginalSize();this.width=t||i.width,this.height=e||i.height}parsePreserveAspectRatioAttribute(){let t,e=(t=>{let[e,i]=t.trim().split(" "),[s,r]=(h=e)&&"none"!==h?[h.slice(1,4),h.slice(5,8)]:"none"===h?[h,h]:["Mid","Mid"];var h;return{meetOrSlice:i||"meet",alignX:s,alignY:r}})(this.preserveAspectRatio||""),i=this.width,s=this.height,r={width:i,height:s},h=this._element.width,n=this._element.height,o=1,a=1,l=0,u=0,c=0,d=0;return!e||"none"===e.alignX&&"none"===e.alignY?(o=i/h,a=s/n):("meet"===e.meetOrSlice&&(o=a=((t,e)=>Math.min(e.width/t.width,e.height/t.height))(this._element,r),t=(i-h*o)/2,"Min"===e.alignX&&(l=-t),"Max"===e.alignX&&(l=t),t=(s-n*a)/2,"Min"===e.alignY&&(u=-t),"Max"===e.alignY&&(u=t)),"slice"===e.meetOrSlice&&(o=a=((t,e)=>Math.max(e.width/t.width,e.height/t.height))(this._element,r),t=h-i/o,"Mid"===e.alignX&&(c=t/2),"Max"===e.alignX&&(c=t),t=n-s/a,"Mid"===e.alignY&&(d=t/2),"Max"===e.alignY&&(d=t),h=i/o,n=s/a)),{width:h,height:n,scaleX:o,scaleY:a,offsetLeft:l,offsetTop:u,cropX:c,cropY:d}}static fromObject({filters:t,resizeFilter:e,src:i,crossOrigin:s,type:r,...h},n){return Promise.all([Dt(i,{...n,crossOrigin:s}),t&&Ot(t,n),e?Ot([e],n):[],$t(h,n)]).then((([t,e=[],[s],r={}])=>new this(t,{...h,src:i,filters:e,resizeFilter:s,...r})))}static fromURL(t,{crossOrigin:e=null,signal:i}={},s){return Dt(t,{crossOrigin:e,signal:i}).then((t=>new this(t,s)))}static async fromElement(t,e={},i){let s=$s(t,this.ATTRIBUTE_NAMES,i);return this.fromURL(s["xlink:href"]||s.href,e,s).catch((t=>(h("log","Unable to parse Image",t),null)))}};i(Th,"type","Image"),i(Th,"cacheProperties",[...di,..._h]),i(Th,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),i(Th,"ATTRIBUTE_NAMES",[...us,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),U.setClass(Th),U.setSVGClass(Th),Ne(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);const Mh=t=>void 0!==t.webgl,kh="precision highp float",Fh=`\n ${kh};\n varying vec2 vTexCoord;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n }`,Dh=new RegExp(kh,"g");var Oh=class{get type(){return this.constructor.type}constructor({type:t,...e}={}){Object.assign(this,this.constructor.defaults,e)}getFragmentSource(){return Fh}getVertexSource(){return"\n attribute vec2 aPosition;\n varying vec2 vTexCoord;\n void main() {\n vTexCoord = aPosition;\n gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n }"}createProgram(t,e=this.getFragmentSource(),i=this.getVertexSource()){let{WebGLProbe:{GLPrecision:s="highp"}}=d();"highp"!==s&&(e=e.replace(Dh,kh.replace("highp",s)));let r=t.createShader(t.VERTEX_SHADER),h=t.createShader(t.FRAGMENT_SHADER),o=t.createProgram();if(!r||!h||!o)throw new n("Vertex, fragment shader or program creation error");if(t.shaderSource(r,i),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new n(`Vertex shader compile error for ${this.type}: ${t.getShaderInfoLog(r)}`);if(t.shaderSource(h,e),t.compileShader(h),!t.getShaderParameter(h,t.COMPILE_STATUS))throw new n(`Fragment shader compile error for ${this.type}: ${t.getShaderInfoLog(h)}`);if(t.attachShader(o,r),t.attachShader(o,h),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new n(`Shader link error for "${this.type}" ${t.getProgramInfoLog(o)}`);let a=this.getUniformLocations(t,o)||{};return a.uStepW=t.getUniformLocation(o,"uStepW"),a.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:a}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){let i=this.constructor.uniformLocations,s={};for(let r=0;r<i.length;r++)s[i[r]]=t.getUniformLocation(e,i[r]);return s}sendAttributeData(t,e,i){let s=e.aPosition,r=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,r),t.enableVertexAttribArray(s),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)}_setupFrameBuffer(t){let e=t.context;if(t.passes>1){let i=t.destinationWidth,s=t.destinationHeight;t.sourceWidth===i&&t.sourceHeight===s||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,i,s)),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++;let e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){Mh(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){let e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){let e=t.context,i=this.retrieveShader(t);e.bindTexture(e.TEXTURE_2D,0===t.pass&&t.originalTexture?t.originalTexture:t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,i){t.activeTexture(i),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){let{sourceWidth:e,sourceHeight:i}=t;t.helpLayer=lt({width:e,height:i})}}toObject(){let t=Object.keys(this.constructor.defaults||{});return{type:this.type,...t.reduce(((t,e)=>(t[e]=this[e],t)),{})}}toJSON(){return this.toObject()}static async fromObject({type:t,...e},i){return new this(e)}};i(Oh,"type","BaseFilter"),i(Oh,"uniformLocations",[]);const $h={multiply:"gl_FragColor.rgb *= uColor.rgb;\n",screen:"gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",add:"gl_FragColor.rgb += uColor.rgb;\n",difference:"gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",subtract:"gl_FragColor.rgb -= uColor.rgb;\n",lighten:"gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",darken:"gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",exclusion:"gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",overlay:"\n if (uColor.r < 0.5) {\n gl_FragColor.r *= 2.0 * uColor.r;\n } else {\n gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n }\n if (uColor.g < 0.5) {\n gl_FragColor.g *= 2.0 * uColor.g;\n } else {\n gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n }\n if (uColor.b < 0.5) {\n gl_FragColor.b *= 2.0 * uColor.b;\n } else {\n gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n }\n ",tint:"\n gl_FragColor.rgb *= (1.0 - uColor.a);\n gl_FragColor.rgb += uColor.rgb;\n "};var jh=class extends Oh{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n gl_FragColor = color;\n if (color.a > 0.0) {\n ${$h[this.mode]}\n }\n }\n `}applyTo2d({imageData:{data:t}}){let e=new Ye(this.color).getSource(),i=this.alpha,s=e[0]*i,r=e[1]*i,h=e[2]*i,n=1-i;for(let e=0;e<t.length;e+=4){let i,o,a,l=t[e],u=t[e+1],c=t[e+2];switch(this.mode){case"multiply":i=l*s/255,o=u*r/255,a=c*h/255;break;case"screen":i=255-(255-l)*(255-s)/255,o=255-(255-u)*(255-r)/255,a=255-(255-c)*(255-h)/255;break;case"add":i=l+s,o=u+r,a=c+h;break;case"difference":i=Math.abs(l-s),o=Math.abs(u-r),a=Math.abs(c-h);break;case"subtract":i=l-s,o=u-r,a=c-h;break;case"darken":i=Math.min(l,s),o=Math.min(u,r),a=Math.min(c,h);break;case"lighten":i=Math.max(l,s),o=Math.max(u,r),a=Math.max(c,h);break;case"overlay":i=s<128?2*l*s/255:255-2*(255-l)*(255-s)/255,o=r<128?2*u*r/255:255-2*(255-u)*(255-r)/255,a=h<128?2*c*h/255:255-2*(255-c)*(255-h)/255;break;case"exclusion":i=s+l-2*s*l/255,o=r+u-2*r*u/255,a=h+c-2*h*c/255;break;case"tint":i=s+l*n,o=r+u*n,a=h+c*n}t[e]=i,t[e+1]=o,t[e+2]=a}}sendUniformData(t,e){let i=new Ye(this.color).getSource();i[0]=this.alpha*i[0]/255,i[1]=this.alpha*i[1]/255,i[2]=this.alpha*i[2]/255,i[3]=this.alpha,t.uniform4fv(e.uColor,i)}};i(jh,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),i(jh,"type","BlendColor"),i(jh,"uniformLocations",["uColor"]),U.setClass(jh);const Ah={multiply:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform sampler2D uImage;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec4 color2 = texture2D(uImage, vTexCoord2);\n color.rgba *= color2.rgba;\n gl_FragColor = color;\n }\n ",mask:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform sampler2D uImage;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec4 color2 = texture2D(uImage, vTexCoord2);\n color.a = color2.a;\n gl_FragColor = color;\n }\n "};var Ph=class extends Oh{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Ah[this.mode]}getVertexSource(){return"\n attribute vec2 aPosition;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n uniform mat3 uTransformMatrix;\n void main() {\n vTexCoord = aPosition;\n vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\n gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n }\n "}applyToWebGL(t){let e=t.context,i=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,i,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){let t=this.image,{width:e,height:i}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/i,1]}applyTo2d({imageData:{data:t,width:e,height:i},filterBackend:{resources:s}}){let r=this.image;s.blendImage||(s.blendImage=at());let h=s.blendImage,n=h.getContext("2d");h.width!==e||h.height!==i?(h.width=e,h.height=i):n.clearRect(0,0,e,i),n.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),n.drawImage(r.getElement(),0,0,e,i);let o=n.getImageData(0,0,e,i).data;for(let e=0;e<t.length;e+=4){let i=t[e],s=t[e+1],r=t[e+2],h=t[e+3],n=o[e],a=o[e+1],l=o[e+2],u=o[e+3];switch(this.mode){case"multiply":t[e]=i*n/255,t[e+1]=s*a/255,t[e+2]=r*l/255,t[e+3]=h*u/255;break;case"mask":t[e+3]=u}}}sendUniformData(t,e){let i=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,i)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject({type:t,image:e,...i},s){return Th.fromObject(e,s).then((t=>new this({...i,image:t})))}};i(Ph,"type","BlendImage"),i(Ph,"defaults",{mode:"multiply",alpha:1}),i(Ph,"uniformLocations",["uTransformMatrix","uImage"]),U.setClass(Ph);var Eh=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n const float nSamples = 15.0;\n vec3 v3offset = vec3(12.9898, 78.233, 151.7182);\n float random(vec3 scale) {\n /* use the fragment position for a different seed per-pixel */\n return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n }\n void main() {\n vec4 color = vec4(0.0);\n float totalC = 0.0;\n float totalA = 0.0;\n float offset = random(v3offset);\n for (float t = -nSamples; t <= nSamples; t++) {\n float percent = (t + offset - 0.5) / nSamples;\n vec4 sample = texture2D(uTexture, vTexCoord + uDelta * percent);\n float weight = 1.0 - abs(percent);\n float alpha = weight * sample.a;\n color.rgb += sample.rgb * alpha;\n color.a += alpha;\n totalA += weight;\n totalC += alpha;\n }\n gl_FragColor.rgb = color.rgb / totalC;\n gl_FragColor.a = color.a / totalA;\n }\n "}applyTo(t){Mh(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({imageData:{data:t,width:e,height:i}}){this.aspectRatio=e/i,this.horizontal=!0;let s=this.getBlurValue()*e,r=new Uint8ClampedArray(t),h=4*e;for(let e=0;e<t.length;e+=4){let i=0,n=0,o=0,a=0,l=0,u=e-e%h,c=u+h;for(let r=-14;r<15;r++){let h=r/15,d=4*Math.floor(s*h),f=1-Math.abs(h),g=e+d;g<u?g=u:g>c&&(g=c);let p=t[g+3]*f;i+=t[g]*p,n+=t[g+1]*p,o+=t[g+2]*p,a+=p,l+=f}r[e]=i/a,r[e+1]=n/a,r[e+2]=o/a,r[e+3]=a/l}this.horizontal=!1,s=this.getBlurValue()*i;for(let e=0;e<r.length;e+=4){let i=0,n=0,o=0,a=0,l=0,u=e%h,c=r.length-h+u;for(let t=-14;t<15;t++){let d=t/15,f=Math.floor(s*d)*h,g=1-Math.abs(d),p=e+f;p<u?p=u:p>c&&(p=c);let m=r[p+3]*g;i+=r[p]*m,n+=r[p+1]*m,o+=r[p+2]*m,a+=m,l+=g}t[e]=i/a,t[e+1]=n/a,t[e+2]=o/a,t[e+3]=a/l}}sendUniformData(t,e){let i=this.chooseRightDelta();t.uniform2fv(e.uDelta,i)}isNeutralState(){return 0===this.blur}getBlurValue(){let t=1,{horizontal:e,aspectRatio:i}=this;return e?i>1&&(t=1/i):i<1&&(t=i),t*this.blur*.12}chooseRightDelta(){let t=this.getBlurValue();return this.horizontal?[t,0]:[0,t]}};i(Eh,"type","Blur"),i(Eh,"defaults",{blur:0}),i(Eh,"uniformLocations",["uDelta"]),U.setClass(Eh);var Lh=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uBrightness;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color.rgb += uBrightness;\n gl_FragColor = color;\n }\n"}applyTo2d({imageData:{data:t}}){let e=Math.round(255*this.brightness);for(let i=0;i<t.length;i+=4)t[i]+=e,t[i+1]+=e,t[i+2]+=e}isNeutralState(){return 0===this.brightness}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}};i(Lh,"type","Brightness"),i(Lh,"defaults",{brightness:0}),i(Lh,"uniformLocations",["uBrightness"]),U.setClass(Lh);const Bh={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};var Rh=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n varying vec2 vTexCoord;\n uniform mat4 uColorMatrix;\n uniform vec4 uConstants;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color *= uColorMatrix;\n color += uConstants;\n gl_FragColor = color;\n }"}applyTo2d(t){let e=t.imageData.data,i=this.matrix,s=this.colorsOnly;for(let t=0;t<e.length;t+=4){let r=e[t],h=e[t+1],n=e[t+2];if(e[t]=r*i[0]+h*i[1]+n*i[2]+255*i[4],e[t+1]=r*i[5]+h*i[6]+n*i[7]+255*i[9],e[t+2]=r*i[10]+h*i[11]+n*i[12]+255*i[14],!s){let s=e[t+3];e[t]+=s*i[3],e[t+1]+=s*i[8],e[t+2]+=s*i[13],e[t+3]=r*i[15]+h*i[16]+n*i[17]+s*i[18]+255*i[19]}}}sendUniformData(t,e){let i=this.matrix,s=[i[4],i[9],i[14],i[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,[i[0],i[1],i[2],i[3],i[5],i[6],i[7],i[8],i[10],i[11],i[12],i[13],i[15],i[16],i[17],i[18]]),t.uniform4fv(e.uConstants,s)}toObject(){return{...super.toObject(),matrix:[...this.matrix]}}};function Ih(t,e){var s;let r=(i(s=class extends Rh{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",t),i(s,"defaults",{colorsOnly:!1,matrix:e}),s);return U.setClass(r,t),r}i(Rh,"type","ColorMatrix"),i(Rh,"defaults",Bh),i(Rh,"uniformLocations",["uColorMatrix","uConstants"]),U.setClass(Rh),Ih("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),Ih("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),Ih("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),Ih("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),Ih("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),Ih("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),Ih("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]);var Xh=class extends Oh{constructor(t={}){super(t),this.subFilters=t.subFilters||[]}applyTo(t){Mh(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((t=>U.getClass(t.type).fromObject(t,e)))).then((t=>new this({subFilters:t})))}};i(Xh,"type","Composed"),U.setClass(Xh);var Yh=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uContrast;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\n color.rgb = contrastF * (color.rgb - 0.5) + 0.5;\n gl_FragColor = color;\n }"}isNeutralState(){return 0===this.contrast}applyTo2d({imageData:{data:t}}){let e=Math.floor(255*this.contrast),i=259*(e+255)/(255*(259-e));for(let e=0;e<t.length;e+=4)t[e]=i*(t[e]-128)+128,t[e+1]=i*(t[e+1]-128)+128,t[e+2]=i*(t[e+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}};i(Yh,"type","Contrast"),i(Yh,"defaults",{contrast:0}),i(Yh,"uniformLocations",["uContrast"]),U.setClass(Yh);const zh={Convolute_3_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[9];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 3.0; h+=1.0) {\n for (float w = 0.0; w < 3.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_3_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[9];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 3.0; h+=1.0) {\n for (float w = 0.0; w < 3.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_5_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[25];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 5.0; h+=1.0) {\n for (float w = 0.0; w < 5.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_5_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[25];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 5.0; h+=1.0) {\n for (float w = 0.0; w < 5.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_7_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[49];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 7.0; h+=1.0) {\n for (float w = 0.0; w < 7.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_7_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[49];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 7.0; h+=1.0) {\n for (float w = 0.0; w < 7.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_9_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[81];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 9.0; h+=1.0) {\n for (float w = 0.0; w < 9.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_9_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[81];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 9.0; h+=1.0) {\n for (float w = 0.0; w < 9.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n "};var Wh=class extends Oh{getCacheKey(){return`${this.type}_${Math.sqrt(this.matrix.length)}_${+!!this.opaque}`}getFragmentSource(){return zh[this.getCacheKey()]}applyTo2d(t){let e,i,s,r,h,n,o,a,l,u,c,d,f,g=t.imageData,p=g.data,m=this.matrix,v=Math.round(Math.sqrt(m.length)),y=Math.floor(v/2),x=g.width,w=g.height,b=t.ctx.createImageData(x,w),C=b.data,S=+!!this.opaque;for(c=0;c<w;c++)for(u=0;u<x;u++){for(h=4*(c*x+u),e=0,i=0,s=0,r=0,f=0;f<v;f++)for(d=0;d<v;d++)o=c+f-y,n=u+d-y,o<0||o>=w||n<0||n>=x||(a=4*(o*x+n),l=m[f*v+d],e+=p[a]*l,i+=p[a+1]*l,s+=p[a+2]*l,S||(r+=p[a+3]*l));C[h]=e,C[h+1]=i,C[h+2]=s,C[h+3]=S?p[h+3]:r}t.imageData=b}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return{...super.toObject(),opaque:this.opaque,matrix:[...this.matrix]}}};i(Wh,"type","Convolute"),i(Wh,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),i(Wh,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),U.setClass(Wh);const Gh="Gamma";var Nh=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec3 uGamma;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec3 correction = (1.0 / uGamma);\n color.r = pow(color.r, correction.r);\n color.g = pow(color.g, correction.g);\n color.b = pow(color.b, correction.b);\n gl_FragColor = color;\n gl_FragColor.rgb *= color.a;\n }\n"}constructor(t={}){super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d({imageData:{data:t}}){let e=this.gamma,i=1/e[0],s=1/e[1],r=1/e[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});let h=this.rgbValues;for(let t=0;t<256;t++)h.r[t]=255*(t/255)**i,h.g[t]=255*(t/255)**s,h.b[t]=255*(t/255)**r;for(let e=0;e<t.length;e+=4)t[e]=h.r[t[e]],t[e+1]=h.g[t[e+1]],t[e+2]=h.b[t[e+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){let{gamma:t}=this;return 1===t[0]&&1===t[1]&&1===t[2]}toObject(){return{type:Gh,gamma:this.gamma.concat()}}};i(Nh,"type",Gh),i(Nh,"defaults",{gamma:[1,1,1]}),i(Nh,"uniformLocations",["uGamma"]),U.setClass(Nh);const Hh={average:"\n precision highp float;\n uniform sampler2D uTexture;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float average = (color.r + color.b + color.g) / 3.0;\n gl_FragColor = vec4(average, average, average, color.a);\n }\n ",lightness:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uMode;\n varying vec2 vTexCoord;\n void main() {\n vec4 col = texture2D(uTexture, vTexCoord);\n float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\n gl_FragColor = vec4(average, average, average, col.a);\n }\n ",luminosity:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uMode;\n varying vec2 vTexCoord;\n void main() {\n vec4 col = texture2D(uTexture, vTexCoord);\n float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\n gl_FragColor = vec4(average, average, average, col.a);\n }\n "};var Vh=class extends Oh{applyTo2d({imageData:{data:t}}){for(let e,i=0;i<t.length;i+=4){let s=t[i],r=t[i+1],h=t[i+2];switch(this.mode){case"average":e=(s+r+h)/3;break;case"lightness":e=(Math.min(s,r,h)+Math.max(s,r,h))/2;break;case"luminosity":e=.21*s+.72*r+.07*h}t[i+2]=t[i+1]=t[i]=e}}getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Hh[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}};i(Vh,"type","Grayscale"),i(Vh,"defaults",{mode:"average"}),i(Vh,"uniformLocations",["uMode"]),U.setClass(Vh);const Uh={...Bh,rotation:0};var qh=class extends Rh{calculateMatrix(){let t=this.rotation*Math.PI,e=Z(t),i=Q(t),s=1/3,r=Math.sqrt(s)*i,h=1-e;this.matrix=[e+h/3,s*h-r,s*h+r,0,0,s*h+r,e+s*h,s*h-r,0,0,s*h-r,s*h+r,e+s*h,0,0,0,0,0,1,0]}isNeutralState(){return 0===this.rotation}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}};i(qh,"type","HueRotation"),i(qh,"defaults",Uh),U.setClass(qh);var Kh=class extends Oh{applyTo2d({imageData:{data:t}}){for(let e=0;e<t.length;e+=4)t[e]=255-t[e],t[e+1]=255-t[e+1],t[e+2]=255-t[e+2],this.alpha&&(t[e+3]=255-t[e+3])}getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uInvert;\n uniform int uAlpha;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n if (uInvert == 1) {\n if (uAlpha == 1) {\n gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,1.0 -color.a);\n } else {\n gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n }\n } else {\n gl_FragColor = color;\n }\n }\n"}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}};i(Kh,"type","Invert"),i(Kh,"defaults",{alpha:!1,invert:!0}),i(Kh,"uniformLocations",["uInvert","uAlpha"]),U.setClass(Kh);var Jh=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uStepH;\n uniform float uNoise;\n uniform float uSeed;\n varying vec2 vTexCoord;\n float rand(vec2 co, float seed, float vScale) {\n return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n }\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\n gl_FragColor = color;\n }\n"}applyTo2d({imageData:{data:t}}){let e=this.noise;for(let i=0;i<t.length;i+=4){let s=(.5-Math.random())*e;t[i]+=s,t[i+1]+=s,t[i+2]+=s}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return 0===this.noise}};i(Jh,"type","Noise"),i(Jh,"defaults",{noise:0}),i(Jh,"uniformLocations",["uNoise","uSeed"]),U.setClass(Jh);var Zh=class extends Oh{applyTo2d({imageData:{data:t,width:e,height:i}}){for(let s=0;s<i;s+=this.blocksize)for(let r=0;r<e;r+=this.blocksize){let h=4*s*e+4*r,n=t[h],o=t[h+1],a=t[h+2],l=t[h+3];for(let h=s;h<Math.min(s+this.blocksize,i);h++)for(let i=r;i<Math.min(r+this.blocksize,e);i++){let s=4*h*e+4*i;t[s]=n,t[s+1]=o,t[s+2]=a,t[s+3]=l}}}isNeutralState(){return 1===this.blocksize}getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uBlocksize;\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n float blockW = uBlocksize * uStepW;\n float blockH = uBlocksize * uStepH;\n int posX = int(vTexCoord.x / blockW);\n int posY = int(vTexCoord.y / blockH);\n float fposX = float(posX);\n float fposY = float(posY);\n vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\n vec4 color = texture2D(uTexture, squareCoords);\n gl_FragColor = color;\n }\n"}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}};i(Zh,"type","Pixelate"),i(Zh,"defaults",{blocksize:4}),i(Zh,"uniformLocations",["uBlocksize"]),U.setClass(Zh);var Qh=class extends Oh{getFragmentSource(){return"\nprecision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\n gl_FragColor.a = 0.0;\n }\n}\n"}applyTo2d({imageData:{data:t}}){let e=255*this.distance,i=new Ye(this.color).getSource(),s=[i[0]-e,i[1]-e,i[2]-e],r=[i[0]+e,i[1]+e,i[2]+e];for(let e=0;e<t.length;e+=4){let i=t[e],h=t[e+1],n=t[e+2];i>s[0]&&h>s[1]&&n>s[2]&&i<r[0]&&h<r[1]&&n<r[2]&&(t[e+3]=0)}}sendUniformData(t,e){let i=new Ye(this.color).getSource(),s=this.distance,r=[i[0]/255+s,i[1]/255+s,i[2]/255+s,1];t.uniform4fv(e.uLow,[0+i[0]/255-s,0+i[1]/255-s,0+i[2]/255-s,1]),t.uniform4fv(e.uHigh,r)}};i(Qh,"type","RemoveColor"),i(Qh,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),i(Qh,"uniformLocations",["uLow","uHigh"]),U.setClass(Qh);var tn=class extends Oh{sendUniformData(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)}getFilterWindow(){return Math.ceil(this.lanczosLobes/this.tempScale)}getCacheKey(){let t=this.getFilterWindow();return`${this.type}_${t}`}getFragmentSource(){let t=this.getFilterWindow();return this.generateShader(t)}getTaps(){let t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,i=this.getFilterWindow(),s=Array(i);for(let r=1;r<=i;r++)s[r-1]=t(r*e);return s}generateShader(t){let e=Array(t);for(let i=1;i<=t;i++)e[i-1]=`${i}.0 * uDelta`;return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n uniform float uTaps[${t}];\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float sum = 1.0;\n ${e.map(((t,e)=>`\n color += texture2D(uTexture, vTexCoord + ${t}) * uTaps[${e}] + texture2D(uTexture, vTexCoord - ${t}) * uTaps[${e}];\n sum += 2.0 * uTaps[${e}];\n `)).join("\n")}\n gl_FragColor = color / sum;\n }\n `}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){Mh(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return 1===this.scaleX&&1===this.scaleY}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;let i=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(i)/i}}applyTo2d(t){let e=t.imageData,i=this.scaleX,s=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/s;let r,h=e.width,n=e.height,o=Math.round(h*i),a=Math.round(n*s);r="sliceHack"===this.resizeType?this.sliceByTwo(t,h,n,o,a):"hermite"===this.resizeType?this.hermiteFastResize(t,h,n,o,a):"bilinear"===this.resizeType?this.bilinearFiltering(t,h,n,o,a):"lanczos"===this.resizeType?this.lanczosResize(t,h,n,o,a):new ImageData(o,a),t.imageData=r}sliceByTwo(t,e,i,s,r){let h=t.imageData,n=.5,o=!1,a=!1,l=e*n,u=i*n,c=t.filterBackend.resources,d=0,f=0,g=e,p=0;c.sliceByTwo||(c.sliceByTwo=at());let m=c.sliceByTwo;(m.width<1.5*e||m.height<i)&&(m.width=1.5*e,m.height=i);let v=m.getContext("2d");for(v.clearRect(0,0,1.5*e,i),v.putImageData(h,0,0),s=Math.floor(s),r=Math.floor(r);!o||!a;)e=l,i=u,s<Math.floor(l*n)?l=Math.floor(l*n):(l=s,o=!0),r<Math.floor(u*n)?u=Math.floor(u*n):(u=r,a=!0),v.drawImage(m,d,f,e,i,g,p,l,u),d=g,f=p,p+=u;return v.getImageData(d,f,s,r)}lanczosResize(t,e,i,s,r){let h=t.imageData.data,n=t.ctx.createImageData(s,r),o=n.data,a=this.lanczosCreate(this.lanczosLobes),l=this.rcpScaleX,u=this.rcpScaleY,c=2/this.rcpScaleX,d=2/this.rcpScaleY,f=Math.ceil(l*this.lanczosLobes/2),g=Math.ceil(u*this.lanczosLobes/2),p={},m={x:0,y:0},v={x:0,y:0};return function t(y){let x,w,b,C,S,_,T,M,k,F,D;for(m.x=(y+.5)*l,v.x=Math.floor(m.x),x=0;x<r;x++){for(m.y=(x+.5)*u,v.y=Math.floor(m.y),S=0,_=0,T=0,M=0,k=0,w=v.x-f;w<=v.x+f;w++)if(!(w<0||w>=e)){F=Math.floor(1e3*Math.abs(w-m.x)),p[F]||(p[F]={});for(let t=v.y-g;t<=v.y+g;t++)t<0||t>=i||(D=Math.floor(1e3*Math.abs(t-m.y)),p[F][D]||(p[F][D]=a(Math.sqrt((F*c)**2+(D*d)**2)/1e3)),b=p[F][D],b>0&&(C=4*(t*e+w),S+=b,_+=b*h[C],T+=b*h[C+1],M+=b*h[C+2],k+=b*h[C+3]))}C=4*(x*s+y),o[C]=_/S,o[C+1]=T/S,o[C+2]=M/S,o[C+3]=k/S}return++y<s?t(y):n}(0)}bilinearFiltering(t,e,i,s,r){let h,n,o,a,l,u,c,d,f,g,p,m,v,y=0,x=this.rcpScaleX,w=this.rcpScaleY,b=4*(e-1),C=t.imageData.data,S=t.ctx.createImageData(s,r),_=S.data;for(c=0;c<r;c++)for(d=0;d<s;d++)for(l=Math.floor(x*d),u=Math.floor(w*c),f=x*d-l,g=w*c-u,v=4*(u*e+l),p=0;p<4;p++)h=C[v+p],n=C[v+4+p],o=C[v+b+p],a=C[v+b+4+p],m=h*(1-f)*(1-g)+n*f*(1-g)+o*g*(1-f)+a*f*g,_[y++]=m;return S}hermiteFastResize(t,e,i,s,r){let h=this.rcpScaleX,n=this.rcpScaleY,o=Math.ceil(h/2),a=Math.ceil(n/2),l=t.imageData.data,u=t.ctx.createImageData(s,r),c=u.data;for(let t=0;t<r;t++)for(let i=0;i<s;i++){let r,u=4*(i+t*s),d=0,f=0,g=0,p=0,m=0,v=0,y=(t+.5)*n;for(let s=Math.floor(t*n);s<(t+1)*n;s++){let t=Math.abs(y-(s+.5))/a,n=(i+.5)*h,u=t*t;for(let t=Math.floor(i*h);t<(i+1)*h;t++){let i=Math.abs(n-(t+.5))/o,h=Math.sqrt(u+i*i);h>1&&h<-1||(r=2*h*h*h-3*h*h+1,r>0&&(i=4*(t+s*e),v+=r*l[i+3],f+=r,l[i+3]<255&&(r=r*l[i+3]/250),g+=r*l[i],p+=r*l[i+1],m+=r*l[i+2],d+=r))}}c[u]=g/d,c[u+1]=p/d,c[u+2]=m/d,c[u+3]=v/f}return u}};i(tn,"type","Resize"),i(tn,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),i(tn,"uniformLocations",["uDelta","uTaps"]),U.setClass(tn);var en=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uSaturation;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float rgMax = max(color.r, color.g);\n float rgbMax = max(rgMax, color.b);\n color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\n color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\n color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\n gl_FragColor = color;\n }\n"}applyTo2d({imageData:{data:t}}){let e=-this.saturation;for(let i=0;i<t.length;i+=4){let s=t[i],r=t[i+1],h=t[i+2],n=Math.max(s,r,h);t[i]+=n===s?0:(n-s)*e,t[i+1]+=n===r?0:(n-r)*e,t[i+2]+=n===h?0:(n-h)*e}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return 0===this.saturation}};i(en,"type","Saturation"),i(en,"defaults",{saturation:0}),i(en,"uniformLocations",["uSaturation"]),U.setClass(en);var sn=class extends Oh{getFragmentSource(){return"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uVibrance;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float max = max(color.r, max(color.g, color.b));\n float avg = (color.r + color.g + color.b) / 3.0;\n float amt = (abs(max - avg) * 2.0) * uVibrance;\n color.r += max != color.r ? (max - color.r) * amt : 0.00;\n color.g += max != color.g ? (max - color.g) * amt : 0.00;\n color.b += max != color.b ? (max - color.b) * amt : 0.00;\n gl_FragColor = color;\n }\n"}applyTo2d({imageData:{data:t}}){let e=-this.vibrance;for(let i=0;i<t.length;i+=4){let s=t[i],r=t[i+1],h=t[i+2],n=Math.max(s,r,h),o=2*Math.abs(n-(s+r+h)/3)/255*e;t[i]+=n===s?0:(n-s)*o,t[i+1]+=n===r?0:(n-r)*o,t[i+2]+=n===h?0:(n-h)*o}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return 0===this.vibrance}};function rn(){return crypto.randomUUID()}async function hn(t,e,i="contain"){const s=await async function(t){if(t.startsWith("data:")||t.startsWith("blob:"))return Th.fromURL(t);try{return await Th.fromURL(t,{crossOrigin:"anonymous"})}catch{}try{const e=`http://localhost:3001/?url=${encodeURIComponent(t)}`;return await Th.fromURL(e,{crossOrigin:"anonymous"})}catch{}return Th.fromURL(t)}(e),r=t.getWidth(),h=t.getHeight();let n,o;if("fill"===i)n=r/(s.width??r),o=h/(s.height??h);else{const e=s.width??r,a=s.height??h,l="contain"===i?Math.min(r/e,h/a):Math.max(r/e,h/a);n=l,o=l,"contain"===i&&t.setDimensions({width:e*l,height:a*l})}const a=t.getWidth(),l=t.getHeight();s.set({scaleX:n,scaleY:o,originX:"center",originY:"center",left:a/2,top:l/2,selectable:!1,evented:!1,excludeFromExport:!0});const u=t.getObjects().find((t=>!0===t._isBackground));void 0!==u&&t.remove(u),s._isBackground=!0,t.insertAt(0,s),t.renderAll()}function nn(t,e,i){return[{x:t.topLeft.x*e,y:t.topLeft.y*i},{x:t.topRight.x*e,y:t.topRight.y*i},{x:t.bottomRight.x*e,y:t.bottomRight.y*i},{x:t.bottomLeft.x*e,y:t.bottomLeft.y*i}]}function on(t,e,i,s=0){return{topLeft:{x:t[0].x/e,y:t[0].y/i},topRight:{x:t[1].x/e,y:t[1].y/i},bottomRight:{x:t[2].x/e,y:t[2].y/i},bottomLeft:{x:t[3].x/e,y:t[3].y/i},...0!==s?{bulge:s}:{}}}function an(){return{topLeft:{x:.35,y:.325},topRight:{x:.65,y:.325},bottomRight:{x:.65,y:.675},bottomLeft:{x:.35,y:.675}}}function ln(t,e,i,s,r){const[h,n,o,a]=nn(i,s,r),l=(h.x+n.x+o.x+a.x)/4,u=(h.y+n.y+o.y+a.y)/4,c=(Math.hypot(n.x-h.x,n.y-h.y)+Math.hypot(o.x-a.x,o.y-a.y))/2,d=(Math.hypot(a.x-h.x,a.y-h.y)+Math.hypot(o.x-n.x,o.y-n.y))/2,f=180*Math.atan2(o.y-a.y,o.x-a.x)/Math.PI,g=Math.min(c/t,d/e);return{x:l,y:u,scaleX:g,scaleY:g,angle:f}}function un(t,e,i,s){const r=t.width,h=t.height,n=Math.ceil(Math.abs(.5*e*i/s))+1,o=document.createElement("canvas");o.width=r,o.height=h+2*n;const a=o.getContext("2d");for(let o=0;o<r;o++){const l=r>1?o/(r-1):.5;a.drawImage(t,o,0,1,h,o,n+-2*l*(1-l)*e*i/s,1,h)}return o}function cn(t){if(!t.startsWith("data:image/svg+xml"))return null;const e=t.indexOf(";base64,");if(-1!==e)return atob(t.slice(e+8));const i=t.indexOf(",");return-1===i?null:decodeURIComponent(t.slice(i+1))}function dn(t){const e=cn(t);if(null===e)return null;const i=e.match(/\bwidth=["']([.\d]+)/),s=e.match(/\bheight=["']([.\d]+)/);if(null!==i&&null!==s)return{width:Math.round(parseFloat(i[1])),height:Math.round(parseFloat(s[1]))};const r=e.match(/viewBox=["']\s*[\d.]+\s+[\d.]+\s+([\d.]+)\s+([\d.]+)/);return null!==r?{width:Math.round(parseFloat(r[1])),height:Math.round(parseFloat(r[2]))}:null}function fn(t,e=4e3){const i=cn(t);if(null===i)return{dataUrl:t,scaleApplied:1};const s=(new DOMParser).parseFromString(i,"image/svg+xml"),r=s.documentElement;if("svg"!==r.tagName)return{dataUrl:t,scaleApplied:1};const h=r.getAttribute("viewBox");let n,o;if(null!==h){const t=h.trim().split(/[\s,]+/);n=parseFloat(t[2])||0,o=parseFloat(t[3])||0}else n=parseFloat(r.getAttribute("width")||"")||0,o=parseFloat(r.getAttribute("height")||"")||0;if(n<=0||o<=0)return{dataUrl:t,scaleApplied:1};const a=Math.max(n,o);if(a>=e)return{dataUrl:t,scaleApplied:1};const l=e/a,u=Math.round(n*l),c=Math.round(o*l);r.setAttribute("width",String(u)),r.setAttribute("height",String(c)),null===h&&r.setAttribute("viewBox",`0 0 ${n} ${o}`);const d=(new XMLSerializer).serializeToString(s),f=(new TextEncoder).encode(d);let g="";for(let t=0;t<f.length;t++)g+=String.fromCharCode(f[t]);return{dataUrl:"data:image/svg+xml;base64,"+btoa(g),scaleApplied:l}}async function gn(t,e=1){const i=cn(t);if(null===i)return t;const s=(new DOMParser).parseFromString(i,"image/svg+xml"),r=s.documentElement;if("svg"!==r.tagName)return t;const h=document.createElement("div");let n;h.style.cssText="visibility:hidden;position:absolute;left:-9999px;top:-9999px;width:0;height:0;overflow:hidden",h.appendChild(r),document.body.appendChild(h);try{n=r.getBBox()}catch{return h.remove(),t}if(h.remove(),n.width<=0||n.height<=0)return t;const o=r.getAttribute("viewBox");if(null!==o){const e=o.trim().split(/[\s,]+/).map(Number);if(4===e.length&&Math.abs(e[0]-n.x)<1&&Math.abs(e[1]-n.y)<1&&Math.abs(e[2]-n.width)<1&&Math.abs(e[3]-n.height)<1)return t}r.setAttribute("viewBox",`${n.x-e} ${n.y-e} ${n.width+2*e} ${n.height+2*e}`);const a=n.height+2*e;r.setAttribute("width",String(n.width+2*e)),r.setAttribute("height",String(a)),r.parentNode!==s&&s.appendChild(r);const l=(new XMLSerializer).serializeToString(s),u=(new TextEncoder).encode(l);let c="";for(let t=0;t<u.length;t++)c+=String.fromCharCode(u[t]);return"data:image/svg+xml;base64,"+btoa(c)}i(sn,"type","Vibrance"),i(sn,"defaults",{vibrance:0}),i(sn,"uniformLocations",["uVibrance"]),U.setClass(sn);export{es as J,tt as N,dn as a,un as b,an as c,gh as d,on as e,ln as f,rn as g,Cr as h,nn as p,Ai as q,hn as s,gn as t,fn as u,Th as w}