@bitovi/vybit 0.13.3 → 0.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import{r as F,j as P,c as vo,s as Ie,o as yo,a as xo}from"./index--Jf_7IdL.js";function p(o,t,e){return(t=function(s){var r=function(i,n){if(typeof i!="object"||!i)return i;var a=i[Symbol.toPrimitive];if(a!==void 0){var h=a.call(i,n);if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(i)}(s,"string");return typeof r=="symbol"?r:r+""}(t))in o?Object.defineProperty(o,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):o[t]=e,o}function ii(o,t){var e=Object.keys(o);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(o);t&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(o,r).enumerable})),e.push.apply(e,s)}return e}function m(o){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?ii(Object(e),!0).forEach(function(s){p(o,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(e)):ii(Object(e)).forEach(function(s){Object.defineProperty(o,s,Object.getOwnPropertyDescriptor(e,s))})}return o}function $(o,t){if(o==null)return{};var e,s,r=function(n,a){if(n==null)return{};var h={};for(var c in n)if({}.hasOwnProperty.call(n,c)){if(a.indexOf(c)>=0)continue;h[c]=n[c]}return h}(o,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(o);for(s=0;s<i.length;s++)e=i[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(o,e)&&(r[e]=o[e])}return r}function Nt(o,t){return t||(t=o.slice(0)),Object.freeze(Object.defineProperties(o,{raw:{value:Object.freeze(t)}}))}class ni{constructor(){p(this,"browserShadowBlurConstant",1),p(this,"DPI",96),p(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),p(this,"perfLimitSizeTotal",2097152),p(this,"maxCacheSideLimit",4096),p(this,"minCacheSideLimit",256),p(this,"disableStyleCopyPaste",!1),p(this,"enableGLFiltering",!0),p(this,"textureSize",4096),p(this,"forceGLPutImageData",!1),p(this,"cachesBoundsOfCurve",!1),p(this,"fontPaths",{}),p(this,"NUM_FRACTION_DIGITS",4)}}const Y=new class extends ni{constructor(o){super(),this.configure(o)}configure(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,o)}addFonts(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths=m(m({},this.fontPaths),o)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(o=>{delete this.fontPaths[o]})}clearFonts(){this.fontPaths={}}restoreDefaults(o){const t=new ni,e=(o==null?void 0:o.reduce((s,r)=>(s[r]=t[r],s),{}))||t;this.configure(e)}},ce=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return console[o]("fabric",...e)};class Ht extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class _o extends Ht{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class bo{}class wo extends bo{testPrecision(t,e){const s="precision ".concat(e,` float;
2
- void main(){}`),r=t.createShader(t.FRAGMENT_SHADER);return!!r&&(t.shaderSource(r,s),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find(s=>this.testPrecision(e,s)),e.getExtension("WEBGL_lose_context").loseContext(),ce("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const So={};let oi;const Gt=()=>oi||(oi={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new wo,dispose(){},copyPasteData:So}),Pe=()=>Gt().document,Ns=()=>Gt().window,tn=()=>{var o;return Math.max((o=Y.devicePixelRatio)!==null&&o!==void 0?o:Ns().devicePixelRatio,1)},Ve=new class{constructor(){p(this,"boundsOfCurveCache",{}),this.charWidthsCache=new Map}getFontCache(o){let{fontFamily:t,fontStyle:e,fontWeight:s}=o;t=t.toLowerCase();const r=this.charWidthsCache;r.has(t)||r.set(t,new Map);const i=r.get(t),n="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return i.has(n)||i.set(n,new Map),i.get(n)}clearFontCache(o){o?this.charWidthsCache.delete((o||"").toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(o){const{perfLimitSizeTotal:t}=Y,e=Math.sqrt(t*o);return[Math.floor(e),Math.floor(t/e)]}},xr="6.9.1";function Os(){}const Ze=Math.PI/2,Ps=2*Math.PI,jr=Math.PI/180,ft=Object.freeze([1,0,0,1,0,0]),Fr=16,ne=.4477152502,R="center",N="left",mt="top",_r="bottom",Q="right",vt="none",Lr=/\r?\n/,en="moving",Us="scaling",sn="rotating",Rr="rotate",rn="skewing",Ne="resizing",Co="modifyPoly",To="modifyPath",As="changed",qs="scale",_t="scaleX",Mt="scaleY",Ae="skewX",je="skewY",ot="fill",yt="stroke",js="modified",xe="json",nr="svg",M=new class{constructor(){this[xe]=new Map,this[nr]=new Map}has(o){return this[xe].has(o)}getClass(o){const t=this[xe].get(o);if(!t)throw new Ht("No class registered for ".concat(o));return t}setClass(o,t){t?this[xe].set(t,o):(this[xe].set(o.type,o),this[xe].set(o.type.toLowerCase(),o))}getSVGClass(o){return this[nr].get(o)}setSVGClass(o,t){this[nr].set(t??o.type.toLowerCase(),o)}},Fs=new class extends Array{remove(o){const t=this.indexOf(o);t>-1&&this.splice(t,1)}cancelAll(){const o=this.splice(0);return o.forEach(t=>t.abort()),o}cancelByCanvas(o){if(!o)return[];const t=this.filter(e=>{var s;return e.target===o||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===o});return t.forEach(e=>e.abort()),t}cancelByTarget(o){if(!o)return[];const t=this.filter(e=>e.target===o);return t.forEach(e=>e.abort()),t}};class Oo{constructor(){p(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach(s=>{let[r,i]=s;this.on(r,i)}),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach(r=>{let[i,n]=r;s.push(this.once(i,n))}),()=>s.forEach(r=>r())}if(e){const s=this.on(t,function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];e.call(this,...i),s()});return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],r=s.indexOf(e);r>-1&&s.splice(r,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach(s=>{let[r,i]=s;this._removeEventListener(r,i)}):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const r=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(r)for(let i=0;i<r.length;i++)r[i].call(this,e||{})}}const Se=(o,t)=>{const e=o.indexOf(t);return e!==-1&&o.splice(e,1),o},Qt=o=>{if(o===0)return 1;switch(Math.abs(o)/Ze){case 1:case 3:return 0;case 2:return-1}return Math.cos(o)},te=o=>{if(o===0)return 0;const t=o/Ze,e=Math.sign(o);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(o)};class x{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;typeof t=="object"?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new x(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new x(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new x(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new x(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new x(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new x(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new x(this.x/t.x,this.y/t.y)}scalarDivide(t){return new x(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.x<t.x&&this.y<t.y}lte(t){return this.x<=t.x&&this.y<=t.y}gt(t){return this.x>t.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new x(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}midPointFrom(t){return this.lerp(t)}min(t){return new x(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new x(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new x(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Br;const s=te(t),r=Qt(t),i=this.subtract(e);return new x(i.x*r-i.y*s,i.x*s+i.y*r).add(e)}transform(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new x(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}const Br=new x(0,0),ks=o=>!!o&&Array.isArray(o._objects);function nn(o){class t extends o{constructor(){super(...arguments),p(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,r=new Array(s),i=0;i<s;i++)r[i]=arguments[i];const n=this._objects.push(...r);return r.forEach(a=>this._onObjectAdded(a)),n}insertAt(s){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return this._objects.splice(s,0,...i),i.forEach(a=>this._onObjectAdded(a)),this._objects.length}remove(){const s=this._objects,r=[];for(var i=arguments.length,n=new Array(i),a=0;a<i;a++)n[a]=arguments[a];return n.forEach(h=>{const c=s.indexOf(h);c!==-1&&(s.splice(c,1),r.push(h),this._onObjectRemoved(h))}),r}forEachObject(s){this.getObjects().forEach((r,i,n)=>s(r,i,n))}getObjects(){for(var s=arguments.length,r=new Array(s),i=0;i<s;i++)r[i]=arguments[i];return r.length===0?[...this._objects]:this._objects.filter(n=>n.isType(...r))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,r){return!!this._objects.includes(s)||!!r&&this._objects.some(i=>i instanceof t&&i.contains(s,!0))}complexity(){return this._objects.reduce((s,r)=>s+=r.complexity?r.complexity():0,0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(Se(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Se(this._objects,s),this._objects.push(s),this._onStackOrderChanged(s),!0)}sendObjectBackwards(s,r){if(!s)return!1;const i=this._objects.indexOf(s);if(i!==0){const n=this.findNewLowerIndex(s,i,r);return Se(this._objects,s),this._objects.splice(n,0,s),this._onStackOrderChanged(s),!0}return!1}bringObjectForward(s,r){if(!s)return!1;const i=this._objects.indexOf(s);if(i!==this._objects.length-1){const n=this.findNewUpperIndex(s,i,r);return Se(this._objects,s),this._objects.splice(n,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,r){return s!==this._objects[r]&&(Se(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,r,i){let n;if(i){n=r;for(let a=r-1;a>=0;--a)if(s.isOverlapping(this._objects[a])){n=a;break}}else n=r-1;return n}findNewUpperIndex(s,r,i){let n;if(i){n=r;for(let a=r+1;a<this._objects.length;++a)if(s.isOverlapping(this._objects[a])){n=a;break}}else n=r+1;return n}collectObjects(s){let{left:r,top:i,width:n,height:a}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const c=[],l=new x(r,i),u=l.add(new x(n,a));for(let d=this._objects.length-1;d>=0;d--){const g=this._objects[d];g.selectable&&g.visible&&(h&&g.intersectsWithRect(l,u)||g.isContainedWithinRect(l,u)||h&&g.containsPoint(l)||h&&g.containsPoint(u))&&c.push(g)}return c}}return t}class on extends Oo{_setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};for(const e in t)this.set(e,t[e])}_setObject(t){for(const e in t)this._set(e,t[e])}set(t,e){return typeof t=="object"?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return typeof e=="boolean"&&this.set(t,!e),this}get(t){return this[t]}}function Ds(o){return Ns().requestAnimationFrame(o)}function ko(o){return Ns().cancelAnimationFrame(o)}let Do=0;const le=()=>Do++,ee=()=>{const o=Pe().createElement("canvas");if(!o||o.getContext===void 0)throw new Ht("Failed to create `canvas` element");return o},Mo=()=>Pe().createElement("img"),Et=o=>{const t=ee();return t.width=o.width,t.height=o.height,t},an=(o,t,e)=>o.toDataURL("image/".concat(t),e),hn=(o,t,e)=>new Promise((s,r)=>{o.toBlob(s,"image/".concat(t),e)}),tt=o=>o*jr,se=o=>o/jr,Eo=o=>o.every((t,e)=>t===ft[e]),pt=(o,t,e)=>new x(o).transform(t,e),Rt=o=>{const t=1/(o[0]*o[3]-o[1]*o[2]),e=[t*o[3],-t*o[1],-t*o[2],t*o[0],0,0],{x:s,y:r}=new x(o[4],o[5]).transform(e,!0);return e[4]=-s,e[5]=-r,e},ct=(o,t,e)=>[o[0]*t[0]+o[2]*t[1],o[1]*t[0]+o[3]*t[1],o[0]*t[2]+o[2]*t[3],o[1]*t[2]+o[3]*t[3],e?0:o[0]*t[4]+o[2]*t[5]+o[4],e?0:o[1]*t[4]+o[3]*t[5]+o[5]],Ir=(o,t)=>o.reduceRight((e,s)=>s&&e?ct(s,e,t):s||e,void 0)||ft.concat(),cn=o=>{let[t,e]=o;return Math.atan2(e,t)},Ls=o=>{const t=cn(o),e=Math.pow(o[0],2)+Math.pow(o[1],2),s=Math.sqrt(e),r=(o[0]*o[3]-o[2]*o[1])/s,i=Math.atan2(o[0]*o[2]+o[1]*o[3],e);return{angle:se(t),scaleX:s,scaleY:r,skewX:se(i),skewY:0,translateX:o[4]||0,translateY:o[5]||0}},Qe=function(o){return[1,0,0,1,o,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function Fe(){let{angle:o=0}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{x:t=0,y:e=0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=tt(o),r=Qt(s),i=te(s);return[r,i,-i,r,t?t-(r*t-i*e):0,e?e-(i*t+r*e):0]}const Wr=function(o){return[o,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:o,0,0]},ln=o=>Math.tan(tt(o)),un=o=>[1,0,ln(o),1,0,0],dn=o=>[1,ln(o),0,1,0,0],Ks=o=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:r=!1,skewX:i=0,skewY:n=0}=o,a=Wr(s?-t:t,r?-e:e);return i&&(a=ct(a,un(i),!0)),n&&(a=ct(a,dn(n),!0)),a},Po=o=>{const{translateX:t=0,translateY:e=0,angle:s=0}=o;let r=Qe(t,e);s&&(r=ct(r,Fe({angle:s})));const i=Ks(o);return Eo(i)||(r=ct(r,i)),r},Ms=function(o){let{signal:t,crossOrigin:e=null}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(s,r){if(t&&t.aborted)return r(new _o("loadImage"));const i=Mo();let n;t&&(n=function(h){i.src="",r(h)},t.addEventListener("abort",n,{once:!0}));const a=function(){i.onload=i.onerror=null,n&&(t==null||t.removeEventListener("abort",n)),s(i)};o?(i.onload=a,i.onerror=function(){n&&(t==null||t.removeEventListener("abort",n)),r(new Ht("Error loading ".concat(i.src)))},e&&(i.crossOrigin=e),i.src=o):a()})},Ue=function(o){let{signal:t,reviver:e=Os}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((s,r)=>{const i=[];t&&t.addEventListener("abort",r,{once:!0}),Promise.all(o.map(n=>M.getClass(n.type).fromObject(n,{signal:t}).then(a=>(e(n,a),i.push(a),a)))).then(s).catch(n=>{i.forEach(a=>{a.dispose&&a.dispose()}),r(n)}).finally(()=>{t&&t.removeEventListener("abort",r)})})},$s=function(o){let{signal:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((e,s)=>{const r=[];t&&t.addEventListener("abort",s,{once:!0});const i=Object.values(o).map(a=>a&&a.type&&M.has(a.type)?Ue([a],{signal:t}).then(h=>{let[c]=h;return r.push(c),c}):a),n=Object.keys(o);Promise.all(i).then(a=>a.reduce((h,c,l)=>(h[n[l]]=c,h),{})).then(e).catch(a=>{r.forEach(h=>{h.dispose&&h.dispose()}),s(a)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},Le=function(o){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in o&&(t[e]=o[e]),t),{})},Xr=(o,t)=>Object.keys(o).reduce((e,s)=>(t(o[s],s,o)&&(e[s]=o[s]),e),{}),K=(o,t)=>parseFloat(Number(o).toFixed(t)),qe=o=>"matrix("+o.map(t=>K(t,Y.NUM_FRACTION_DIGITS)).join(" ")+")",Dt=o=>!!o&&o.toLive!==void 0,ai=o=>!!o&&typeof o.toObject=="function",hi=o=>!!o&&o.offsetX!==void 0&&"source"in o,de=o=>!!o&&"multiSelectionStacking"in o;function gn(o){const t=o&&Lt(o);let e=0,s=0;if(!o||!t)return{left:e,top:s};let r=o;const i=t.documentElement,n=t.body||{scrollLeft:0,scrollTop:0};for(;r&&(r.parentNode||r.host)&&(r=r.parentNode||r.host,r===t?(e=n.scrollLeft||i.scrollLeft||0,s=n.scrollTop||i.scrollTop||0):(e+=r.scrollLeft||0,s+=r.scrollTop||0),r.nodeType!==1||r.style.position!=="fixed"););return{left:e,top:s}}const Lt=o=>o.ownerDocument||null,fn=o=>{var t;return((t=o.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},pn=function(o,t,e){let{width:s,height:r}=e,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;o.width=s,o.height=r,i>1&&(o.setAttribute("width",(s*i).toString()),o.setAttribute("height",(r*i).toString()),t.scale(i,i))},br=(o,t)=>{let{width:e,height:s}=t;e&&(o.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(o.style.height=typeof s=="number"?"".concat(s,"px"):s)};function ci(o){return o.onselectstart!==void 0&&(o.onselectstart=()=>!1),o.style.userSelect=vt,o}class mn{constructor(t){p(this,"_originalCanvasStyle",void 0),p(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&Pe().getElementById(t)||ee();var s;if(e.hasAttribute("data-fabric"))throw new Ht("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:r}=this.lower;r.classList.remove("lower-canvas"),r.removeAttribute("data-fabric"),r.setAttribute("width","".concat(e)),r.setAttribute("height","".concat(s)),r.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:r}=this.lower;pn(s,r,t,e)}setCSSDimensions(t){br(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&Lt(t),r={left:0,top:0};if(!s)return r;const i=((e=fn(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};r.left+=parseInt(i.borderLeftWidth,10)||0,r.top+=parseInt(i.borderTopWidth,10)||0,r.left+=parseInt(i.paddingLeft,10)||0,r.top+=parseInt(i.paddingTop,10)||0;let n={left:0,top:0};const a=s.documentElement;t.getBoundingClientRect!==void 0&&(n=t.getBoundingClientRect());const h=gn(t);return{left:n.left+h.left-(a.clientLeft||0)+r.left,top:n.top+h.top-(a.clientTop||0)+r.top}}(this.lower.el)}dispose(){Gt().dispose(this.lower.el),delete this.lower}}const Ao={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...ft]},jo=["objects"];class ts extends nn(on){get lowerCanvasEl(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.el}get contextContainer(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.ctx}static getDefaults(){return ts.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new mn(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;r<e;r++)s[r-1]=arguments[r];const i=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),i}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(ce("warn",`Canvas is trying to add an object that belongs to a different canvas.
3
- Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?tn():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const r=m({width:this.width,height:this.height},t);this.elements.setDimensions(r,this.getRetinaScaling()),this.hasLostContext=!0,this.width=r.width,this.height=r.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,r=[...this.viewportTransform],i=pt(t,Rt(r));r[0]=e,r[3]=e;const n=pt(i,r);r[4]+=s.x-n.x,r[5]+=s.y-n.y,this.setViewportTransform(r)}setZoom(t){this.zoomToPoint(new x(0,0),t)}absolutePan(t){const e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new x(-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=Ds(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Rt(this.viewportTransform),r=pt({x:0,y:0},s),i=pt({x:t,y:e},s),n=r.min(i),a=r.max(i);return this.vptCoords={tl:n,tr:new x(a.x,n.y),bl:new x(n.x,a.y),br:a}}cancelRequestedRender(){this.nextRenderHandle&&(ko(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const s=this.viewportTransform,r=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),r&&(r._set("canvas",this),r.shouldCache(),r._transformDone=!0,r.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,r)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const s=this.viewportTransform;t.save(),t.transform(...s),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let s=0,r=e.length;s<r;++s)e[s]&&e[s].render(t)}_renderBackgroundOrOverlay(t,e){const s=this["".concat(e,"Color")],r=this["".concat(e,"Image")],i=this.viewportTransform,n=this["".concat(e,"Vpt")];if(!s&&!r)return;const a=Dt(s);if(s){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=a?s.toLive(t):s,n&&t.transform(...i),a){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const h=s.gradientTransform||s.patternTransform;h&&t.transform(...h)}t.fill(),t.restore()}if(r){t.save();const{skipOffscreen:h}=this;this.skipOffscreen=n,n&&t.transform(...i),r.render(t),this.skipOffscreen=h,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenter(){return{top:this.height/2,left:this.width/2}}getCenterPoint(){return new x(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new x(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new x(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 x(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new x(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return pt(this.getCenterPoint(),Rt(this.viewportTransform))}_centerObject(t,e){t.setXY(e,R,R),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(t){return this.toDatalessObject(t)}toObject(t){return this._toObjectMethod("toObject",t)}toJSON(){return this.toObject()}toDatalessObject(t){return this._toObjectMethod("toDatalessObject",t)}_toObjectMethod(t,e){const s=this.clipPath,r=s&&!s.excludeFromExport?this._toObject(s,t,e):null;return m(m(m({version:xr},Le(this,e)),{},{objects:this._objects.filter(i=>!i.excludeFromExport).map(i=>this._toObject(i,t,e))},this.__serializeBgOverlay(t,e)),r?{clipPath:r}:null)}_toObject(t,e,s){let r;this.includeDefaultValues||(r=t.includeDefaultValues,t.includeDefaultValues=!1);const i=t[e](s);return this.includeDefaultValues||(t.includeDefaultValues=!!r),i}__serializeBgOverlay(t,e){const s={},r=this.backgroundImage,i=this.overlayImage,n=this.backgroundColor,a=this.overlayColor;return Dt(n)?n.excludeFromExport||(s.background=n.toObject(e)):n&&(s.background=n),Dt(a)?a.excludeFromExport||(s.overlay=a.toObject(e)):a&&(s.overlay=a),r&&!r.excludeFromExport&&(s.backgroundImage=this._toObject(r,t,e)),i&&!i.excludeFromExport&&(s.overlayImage=this._toObject(i,t,e)),s}toSVG(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const s=[];return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push('<g clip-path="url(#'.concat(this.clipPath.clipPathId,`)" >
1
+ import{G as yo,r as tn,a as F,j as P,S as xo,c as _o,s as Ie,o as bo,b as wo}from"./index-bk-Onymy.js";function p(o,t,e){return(t=function(s){var r=function(i,n){if(typeof i!="object"||!i)return i;var a=i[Symbol.toPrimitive];if(a!==void 0){var h=a.call(i,n);if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(n==="string"?String:Number)(i)}(s,"string");return typeof r=="symbol"?r:r+""}(t))in o?Object.defineProperty(o,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):o[t]=e,o}function ii(o,t){var e=Object.keys(o);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(o);t&&(s=s.filter(function(r){return Object.getOwnPropertyDescriptor(o,r).enumerable})),e.push.apply(e,s)}return e}function m(o){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?ii(Object(e),!0).forEach(function(s){p(o,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(e)):ii(Object(e)).forEach(function(s){Object.defineProperty(o,s,Object.getOwnPropertyDescriptor(e,s))})}return o}function $(o,t){if(o==null)return{};var e,s,r=function(n,a){if(n==null)return{};var h={};for(var c in n)if({}.hasOwnProperty.call(n,c)){if(a.indexOf(c)>=0)continue;h[c]=n[c]}return h}(o,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(o);for(s=0;s<i.length;s++)e=i[s],t.indexOf(e)>=0||{}.propertyIsEnumerable.call(o,e)&&(r[e]=o[e])}return r}function Nt(o,t){return t||(t=o.slice(0)),Object.freeze(Object.defineProperties(o,{raw:{value:Object.freeze(t)}}))}class ni{constructor(){p(this,"browserShadowBlurConstant",1),p(this,"DPI",96),p(this,"devicePixelRatio",typeof window<"u"?window.devicePixelRatio:1),p(this,"perfLimitSizeTotal",2097152),p(this,"maxCacheSideLimit",4096),p(this,"minCacheSideLimit",256),p(this,"disableStyleCopyPaste",!1),p(this,"enableGLFiltering",!0),p(this,"textureSize",4096),p(this,"forceGLPutImageData",!1),p(this,"cachesBoundsOfCurve",!1),p(this,"fontPaths",{}),p(this,"NUM_FRACTION_DIGITS",4)}}const Y=new class extends ni{constructor(o){super(),this.configure(o)}configure(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,o)}addFonts(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths=m(m({},this.fontPaths),o)}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(o=>{delete this.fontPaths[o]})}clearFonts(){this.fontPaths={}}restoreDefaults(o){const t=new ni,e=(o==null?void 0:o.reduce((s,r)=>(s[r]=t[r],s),{}))||t;this.configure(e)}},ce=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return console[o]("fabric",...e)};class Ht extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class So extends Ht{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class Co{}class To extends Co{testPrecision(t,e){const s="precision ".concat(e,` float;
2
+ void main(){}`),r=t.createShader(t.FRAGMENT_SHADER);return!!r&&(t.shaderSource(r,s),t.compileShader(r),!!t.getShaderParameter(r,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find(s=>this.testPrecision(e,s)),e.getExtension("WEBGL_lose_context").loseContext(),ce("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Oo={};let oi;const Gt=()=>oi||(oi={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new To,dispose(){},copyPasteData:Oo}),Pe=()=>Gt().document,Ns=()=>Gt().window,en=()=>{var o;return Math.max((o=Y.devicePixelRatio)!==null&&o!==void 0?o:Ns().devicePixelRatio,1)},Ve=new class{constructor(){p(this,"boundsOfCurveCache",{}),this.charWidthsCache=new Map}getFontCache(o){let{fontFamily:t,fontStyle:e,fontWeight:s}=o;t=t.toLowerCase();const r=this.charWidthsCache;r.has(t)||r.set(t,new Map);const i=r.get(t),n="".concat(e.toLowerCase(),"_").concat((s+"").toLowerCase());return i.has(n)||i.set(n,new Map),i.get(n)}clearFontCache(o){o?this.charWidthsCache.delete((o||"").toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(o){const{perfLimitSizeTotal:t}=Y,e=Math.sqrt(t*o);return[Math.floor(e),Math.floor(t/e)]}},xr="6.9.1";function Os(){}const Ze=Math.PI/2,Ps=2*Math.PI,jr=Math.PI/180,ft=Object.freeze([1,0,0,1,0,0]),Fr=16,ne=.4477152502,R="center",N="left",mt="top",_r="bottom",Q="right",vt="none",Lr=/\r?\n/,sn="moving",Us="scaling",rn="rotating",Rr="rotate",nn="skewing",Ne="resizing",ko="modifyPoly",Do="modifyPath",As="changed",qs="scale",_t="scaleX",Mt="scaleY",Ae="skewX",je="skewY",ot="fill",yt="stroke",js="modified",xe="json",nr="svg",M=new class{constructor(){this[xe]=new Map,this[nr]=new Map}has(o){return this[xe].has(o)}getClass(o){const t=this[xe].get(o);if(!t)throw new Ht("No class registered for ".concat(o));return t}setClass(o,t){t?this[xe].set(t,o):(this[xe].set(o.type,o),this[xe].set(o.type.toLowerCase(),o))}getSVGClass(o){return this[nr].get(o)}setSVGClass(o,t){this[nr].set(t??o.type.toLowerCase(),o)}},Fs=new class extends Array{remove(o){const t=this.indexOf(o);t>-1&&this.splice(t,1)}cancelAll(){const o=this.splice(0);return o.forEach(t=>t.abort()),o}cancelByCanvas(o){if(!o)return[];const t=this.filter(e=>{var s;return e.target===o||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===o});return t.forEach(e=>e.abort()),t}cancelByTarget(o){if(!o)return[];const t=this.filter(e=>e.target===o);return t.forEach(e=>e.abort()),t}};class Mo{constructor(){p(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),typeof t=="object")return Object.entries(t).forEach(s=>{let[r,i]=s;this.on(r,i)}),()=>this.off(t);if(e){const s=t;return this.__eventListeners[s]||(this.__eventListeners[s]=[]),this.__eventListeners[s].push(e),()=>this.off(s,e)}return()=>!1}once(t,e){if(typeof t=="object"){const s=[];return Object.entries(t).forEach(r=>{let[i,n]=r;s.push(this.once(i,n))}),()=>s.forEach(r=>r())}if(e){const s=this.on(t,function(){for(var r=arguments.length,i=new Array(r),n=0;n<r;n++)i[n]=arguments[n];e.call(this,...i),s()});return s}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const s=this.__eventListeners[t],r=s.indexOf(e);r>-1&&s.splice(r,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(t===void 0)for(const s in this.__eventListeners)this._removeEventListener(s);else typeof t=="object"?Object.entries(t).forEach(s=>{let[r,i]=s;this._removeEventListener(r,i)}):this._removeEventListener(t,e)}fire(t,e){var s;if(!this.__eventListeners)return;const r=(s=this.__eventListeners[t])===null||s===void 0?void 0:s.concat();if(r)for(let i=0;i<r.length;i++)r[i].call(this,e||{})}}const Se=(o,t)=>{const e=o.indexOf(t);return e!==-1&&o.splice(e,1),o},Qt=o=>{if(o===0)return 1;switch(Math.abs(o)/Ze){case 1:case 3:return 0;case 2:return-1}return Math.cos(o)},te=o=>{if(o===0)return 0;const t=o/Ze,e=Math.sign(o);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(o)};class x{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;typeof t=="object"?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new x(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new x(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new x(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new x(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new x(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new x(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new x(this.x/t.x,this.y/t.y)}scalarDivide(t){return new x(this.x/t,this.y/t)}scalarDivideEquals(t){return this.x/=t,this.y/=t,this}eq(t){return this.x===t.x&&this.y===t.y}lt(t){return this.x<t.x&&this.y<t.y}lte(t){return this.x<=t.x&&this.y<=t.y}gt(t){return this.x>t.x&&this.y>t.y}gte(t){return this.x>=t.x&&this.y>=t.y}lerp(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new x(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,s=this.y-t.y;return Math.sqrt(e*e+s*s)}midPointFrom(t){return this.lerp(t)}min(t){return new x(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new x(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return"".concat(this.x,",").concat(this.y)}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new x(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Br;const s=te(t),r=Qt(t),i=this.subtract(e);return new x(i.x*r-i.y*s,i.x*s+i.y*r).add(e)}transform(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return new x(t[0]*this.x+t[2]*this.y+(e?0:t[4]),t[1]*this.x+t[3]*this.y+(e?0:t[5]))}}const Br=new x(0,0),ks=o=>!!o&&Array.isArray(o._objects);function on(o){class t extends o{constructor(){super(...arguments),p(this,"_objects",[])}_onObjectAdded(s){}_onObjectRemoved(s){}_onStackOrderChanged(s){}add(){for(var s=arguments.length,r=new Array(s),i=0;i<s;i++)r[i]=arguments[i];const n=this._objects.push(...r);return r.forEach(a=>this._onObjectAdded(a)),n}insertAt(s){for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n<r;n++)i[n-1]=arguments[n];return this._objects.splice(s,0,...i),i.forEach(a=>this._onObjectAdded(a)),this._objects.length}remove(){const s=this._objects,r=[];for(var i=arguments.length,n=new Array(i),a=0;a<i;a++)n[a]=arguments[a];return n.forEach(h=>{const c=s.indexOf(h);c!==-1&&(s.splice(c,1),r.push(h),this._onObjectRemoved(h))}),r}forEachObject(s){this.getObjects().forEach((r,i,n)=>s(r,i,n))}getObjects(){for(var s=arguments.length,r=new Array(s),i=0;i<s;i++)r[i]=arguments[i];return r.length===0?[...this._objects]:this._objects.filter(n=>n.isType(...r))}item(s){return this._objects[s]}isEmpty(){return this._objects.length===0}size(){return this._objects.length}contains(s,r){return!!this._objects.includes(s)||!!r&&this._objects.some(i=>i instanceof t&&i.contains(s,!0))}complexity(){return this._objects.reduce((s,r)=>s+=r.complexity?r.complexity():0,0)}sendObjectToBack(s){return!(!s||s===this._objects[0])&&(Se(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(Se(this._objects,s),this._objects.push(s),this._onStackOrderChanged(s),!0)}sendObjectBackwards(s,r){if(!s)return!1;const i=this._objects.indexOf(s);if(i!==0){const n=this.findNewLowerIndex(s,i,r);return Se(this._objects,s),this._objects.splice(n,0,s),this._onStackOrderChanged(s),!0}return!1}bringObjectForward(s,r){if(!s)return!1;const i=this._objects.indexOf(s);if(i!==this._objects.length-1){const n=this.findNewUpperIndex(s,i,r);return Se(this._objects,s),this._objects.splice(n,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,r){return s!==this._objects[r]&&(Se(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,r,i){let n;if(i){n=r;for(let a=r-1;a>=0;--a)if(s.isOverlapping(this._objects[a])){n=a;break}}else n=r-1;return n}findNewUpperIndex(s,r,i){let n;if(i){n=r;for(let a=r+1;a<this._objects.length;++a)if(s.isOverlapping(this._objects[a])){n=a;break}}else n=r+1;return n}collectObjects(s){let{left:r,top:i,width:n,height:a}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const c=[],l=new x(r,i),u=l.add(new x(n,a));for(let d=this._objects.length-1;d>=0;d--){const g=this._objects[d];g.selectable&&g.visible&&(h&&g.intersectsWithRect(l,u)||g.isContainedWithinRect(l,u)||h&&g.containsPoint(l)||h&&g.containsPoint(u))&&c.push(g)}return c}}return t}class an extends Mo{_setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};for(const e in t)this.set(e,t[e])}_setObject(t){for(const e in t)this._set(e,t[e])}set(t,e){return typeof t=="object"?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return typeof e=="boolean"&&this.set(t,!e),this}get(t){return this[t]}}function Ds(o){return Ns().requestAnimationFrame(o)}function Eo(o){return Ns().cancelAnimationFrame(o)}let Po=0;const le=()=>Po++,ee=()=>{const o=Pe().createElement("canvas");if(!o||o.getContext===void 0)throw new Ht("Failed to create `canvas` element");return o},Ao=()=>Pe().createElement("img"),Et=o=>{const t=ee();return t.width=o.width,t.height=o.height,t},hn=(o,t,e)=>o.toDataURL("image/".concat(t),e),cn=(o,t,e)=>new Promise((s,r)=>{o.toBlob(s,"image/".concat(t),e)}),tt=o=>o*jr,se=o=>o/jr,jo=o=>o.every((t,e)=>t===ft[e]),pt=(o,t,e)=>new x(o).transform(t,e),Rt=o=>{const t=1/(o[0]*o[3]-o[1]*o[2]),e=[t*o[3],-t*o[1],-t*o[2],t*o[0],0,0],{x:s,y:r}=new x(o[4],o[5]).transform(e,!0);return e[4]=-s,e[5]=-r,e},ct=(o,t,e)=>[o[0]*t[0]+o[2]*t[1],o[1]*t[0]+o[3]*t[1],o[0]*t[2]+o[2]*t[3],o[1]*t[2]+o[3]*t[3],e?0:o[0]*t[4]+o[2]*t[5]+o[4],e?0:o[1]*t[4]+o[3]*t[5]+o[5]],Ir=(o,t)=>o.reduceRight((e,s)=>s&&e?ct(s,e,t):s||e,void 0)||ft.concat(),ln=o=>{let[t,e]=o;return Math.atan2(e,t)},Ls=o=>{const t=ln(o),e=Math.pow(o[0],2)+Math.pow(o[1],2),s=Math.sqrt(e),r=(o[0]*o[3]-o[2]*o[1])/s,i=Math.atan2(o[0]*o[2]+o[1]*o[3],e);return{angle:se(t),scaleX:s,scaleY:r,skewX:se(i),skewY:0,translateX:o[4]||0,translateY:o[5]||0}},Qe=function(o){return[1,0,0,1,o,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function Fe(){let{angle:o=0}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},{x:t=0,y:e=0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=tt(o),r=Qt(s),i=te(s);return[r,i,-i,r,t?t-(r*t-i*e):0,e?e-(i*t+r*e):0]}const Wr=function(o){return[o,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:o,0,0]},un=o=>Math.tan(tt(o)),dn=o=>[1,0,un(o),1,0,0],gn=o=>[1,un(o),0,1,0,0],Ks=o=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:r=!1,skewX:i=0,skewY:n=0}=o,a=Wr(s?-t:t,r?-e:e);return i&&(a=ct(a,dn(i),!0)),n&&(a=ct(a,gn(n),!0)),a},Fo=o=>{const{translateX:t=0,translateY:e=0,angle:s=0}=o;let r=Qe(t,e);s&&(r=ct(r,Fe({angle:s})));const i=Ks(o);return jo(i)||(r=ct(r,i)),r},Ms=function(o){let{signal:t,crossOrigin:e=null}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(s,r){if(t&&t.aborted)return r(new So("loadImage"));const i=Ao();let n;t&&(n=function(h){i.src="",r(h)},t.addEventListener("abort",n,{once:!0}));const a=function(){i.onload=i.onerror=null,n&&(t==null||t.removeEventListener("abort",n)),s(i)};o?(i.onload=a,i.onerror=function(){n&&(t==null||t.removeEventListener("abort",n)),r(new Ht("Error loading ".concat(i.src)))},e&&(i.crossOrigin=e),i.src=o):a()})},Ue=function(o){let{signal:t,reviver:e=Os}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((s,r)=>{const i=[];t&&t.addEventListener("abort",r,{once:!0}),Promise.all(o.map(n=>M.getClass(n.type).fromObject(n,{signal:t}).then(a=>(e(n,a),i.push(a),a)))).then(s).catch(n=>{i.forEach(a=>{a.dispose&&a.dispose()}),r(n)}).finally(()=>{t&&t.removeEventListener("abort",r)})})},$s=function(o){let{signal:t}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((e,s)=>{const r=[];t&&t.addEventListener("abort",s,{once:!0});const i=Object.values(o).map(a=>a&&a.type&&M.has(a.type)?Ue([a],{signal:t}).then(h=>{let[c]=h;return r.push(c),c}):a),n=Object.keys(o);Promise.all(i).then(a=>a.reduce((h,c,l)=>(h[n[l]]=c,h),{})).then(e).catch(a=>{r.forEach(h=>{h.dispose&&h.dispose()}),s(a)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},Le=function(o){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in o&&(t[e]=o[e]),t),{})},Xr=(o,t)=>Object.keys(o).reduce((e,s)=>(t(o[s],s,o)&&(e[s]=o[s]),e),{}),K=(o,t)=>parseFloat(Number(o).toFixed(t)),qe=o=>"matrix("+o.map(t=>K(t,Y.NUM_FRACTION_DIGITS)).join(" ")+")",Dt=o=>!!o&&o.toLive!==void 0,ai=o=>!!o&&typeof o.toObject=="function",hi=o=>!!o&&o.offsetX!==void 0&&"source"in o,de=o=>!!o&&"multiSelectionStacking"in o;function fn(o){const t=o&&Lt(o);let e=0,s=0;if(!o||!t)return{left:e,top:s};let r=o;const i=t.documentElement,n=t.body||{scrollLeft:0,scrollTop:0};for(;r&&(r.parentNode||r.host)&&(r=r.parentNode||r.host,r===t?(e=n.scrollLeft||i.scrollLeft||0,s=n.scrollTop||i.scrollTop||0):(e+=r.scrollLeft||0,s+=r.scrollTop||0),r.nodeType!==1||r.style.position!=="fixed"););return{left:e,top:s}}const Lt=o=>o.ownerDocument||null,pn=o=>{var t;return((t=o.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},mn=function(o,t,e){let{width:s,height:r}=e,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;o.width=s,o.height=r,i>1&&(o.setAttribute("width",(s*i).toString()),o.setAttribute("height",(r*i).toString()),t.scale(i,i))},br=(o,t)=>{let{width:e,height:s}=t;e&&(o.style.width=typeof e=="number"?"".concat(e,"px"):e),s&&(o.style.height=typeof s=="number"?"".concat(s,"px"):s)};function ci(o){return o.onselectstart!==void 0&&(o.onselectstart=()=>!1),o.style.userSelect=vt,o}class vn{constructor(t){p(this,"_originalCanvasStyle",void 0),p(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=(s=t)&&s.getContext!==void 0?t:t&&Pe().getElementById(t)||ee();var s;if(e.hasAttribute("data-fabric"))throw new Ht("Trying to initialize a canvas that has already been initialized. Did you forget to dispose the canvas?");return this._originalCanvasStyle=e.style.cssText,e.setAttribute("data-fabric","main"),e.classList.add("lower-canvas"),e}cleanupDOM(t){let{width:e,height:s}=t;const{el:r}=this.lower;r.classList.remove("lower-canvas"),r.removeAttribute("data-fabric"),r.setAttribute("width","".concat(e)),r.setAttribute("height","".concat(s)),r.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:r}=this.lower;mn(s,r,t,e)}setCSSDimensions(t){br(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&Lt(t),r={left:0,top:0};if(!s)return r;const i=((e=pn(t))===null||e===void 0?void 0:e.getComputedStyle(t,null))||{};r.left+=parseInt(i.borderLeftWidth,10)||0,r.top+=parseInt(i.borderTopWidth,10)||0,r.left+=parseInt(i.paddingLeft,10)||0,r.top+=parseInt(i.paddingTop,10)||0;let n={left:0,top:0};const a=s.documentElement;t.getBoundingClientRect!==void 0&&(n=t.getBoundingClientRect());const h=fn(t);return{left:n.left+h.left-(a.clientLeft||0)+r.left,top:n.top+h.top-(a.clientTop||0)+r.top}}(this.lower.el)}dispose(){Gt().dispose(this.lower.el),delete this.lower}}const Lo={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...ft]},Ro=["objects"];class ts extends on(an){get lowerCanvasEl(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.el}get contextContainer(){var t;return(t=this.elements.lower)===null||t===void 0?void 0:t.ctx}static getDefaults(){return ts.ownDefaults}constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,this.constructor.getDefaults()),this.set(e),this.initElements(t),this._setDimensionsImpl({width:this.width||this.elements.lower.el.width||0,height:this.height||this.elements.lower.el.height||0}),this.skipControlsDrawing=!1,this.viewportTransform=[...this.viewportTransform],this.calcViewportBoundaries()}initElements(t){this.elements=new vn(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;r<e;r++)s[r-1]=arguments[r];const i=super.insertAt(t,...s);return s.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),i}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(ce("warn",`Canvas is trying to add an object that belongs to a different canvas.
3
+ Resulting to default behavior: removing object from previous canvas and adding to new canvas`),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?en():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}setWidth(t,e){return this.setDimensions({width:t},e)}setHeight(t,e){return this.setDimensions({height:t},e)}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const r=m({width:this.width,height:this.height},t);this.elements.setDimensions(r,this.getRetinaScaling()),this.hasLostContext=!0,this.width=r.width,this.height=r.height}s||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const s=t,r=[...this.viewportTransform],i=pt(t,Rt(r));r[0]=e,r[3]=e;const n=pt(i,r);r[4]+=s.x-n.x,r[5]+=s.y-n.y,this.setViewportTransform(r)}setZoom(t){this.zoomToPoint(new x(0,0),t)}absolutePan(t){const e=[...this.viewportTransform];return e[4]=-t.x,e[5]=-t.y,this.setViewportTransform(e)}relativePan(t){return this.absolutePan(new x(-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=Ds(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=Rt(this.viewportTransform),r=pt({x:0,y:0},s),i=pt({x:t,y:e},s),n=r.min(i),a=r.max(i);return this.vptCoords={tl:n,tr:new x(a.x,n.y),bl:new x(n.x,a.y),br:a}}cancelRequestedRender(){this.nextRenderHandle&&(Eo(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const s=this.viewportTransform,r=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),r&&(r._set("canvas",this),r.shouldCache(),r._transformDone=!0,r.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,r)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const s=this.viewportTransform;t.save(),t.transform(...s),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let s=0,r=e.length;s<r;++s)e[s]&&e[s].render(t)}_renderBackgroundOrOverlay(t,e){const s=this["".concat(e,"Color")],r=this["".concat(e,"Image")],i=this.viewportTransform,n=this["".concat(e,"Vpt")];if(!s&&!r)return;const a=Dt(s);if(s){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=a?s.toLive(t):s,n&&t.transform(...i),a){t.transform(1,0,0,1,s.offsetX||0,s.offsetY||0);const h=s.gradientTransform||s.patternTransform;h&&t.transform(...h)}t.fill(),t.restore()}if(r){t.save();const{skipOffscreen:h}=this;this.skipOffscreen=n,n&&t.transform(...i),r.render(t),this.skipOffscreen=h,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenter(){return{top:this.height/2,left:this.width/2}}getCenterPoint(){return new x(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new x(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new x(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 x(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new x(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return pt(this.getCenterPoint(),Rt(this.viewportTransform))}_centerObject(t,e){t.setXY(e,R,R),t.setCoords(),this.renderOnAddRemove&&this.requestRenderAll()}toDatalessJSON(t){return this.toDatalessObject(t)}toObject(t){return this._toObjectMethod("toObject",t)}toJSON(){return this.toObject()}toDatalessObject(t){return this._toObjectMethod("toDatalessObject",t)}_toObjectMethod(t,e){const s=this.clipPath,r=s&&!s.excludeFromExport?this._toObject(s,t,e):null;return m(m(m({version:xr},Le(this,e)),{},{objects:this._objects.filter(i=>!i.excludeFromExport).map(i=>this._toObject(i,t,e))},this.__serializeBgOverlay(t,e)),r?{clipPath:r}:null)}_toObject(t,e,s){let r;this.includeDefaultValues||(r=t.includeDefaultValues,t.includeDefaultValues=!1);const i=t[e](s);return this.includeDefaultValues||(t.includeDefaultValues=!!r),i}__serializeBgOverlay(t,e){const s={},r=this.backgroundImage,i=this.overlayImage,n=this.backgroundColor,a=this.overlayColor;return Dt(n)?n.excludeFromExport||(s.background=n.toObject(e)):n&&(s.background=n),Dt(a)?a.excludeFromExport||(s.overlay=a.toObject(e)):a&&(s.overlay=a),r&&!r.excludeFromExport&&(s.backgroundImage=this._toObject(r,t,e)),i&&!i.excludeFromExport&&(s.overlayImage=this._toObject(i,t,e)),s}toSVG(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const s=[];return this._setSVGPreamble(s,t),this._setSVGHeader(s,t),this.clipPath&&s.push('<g clip-path="url(#'.concat(this.clipPath.clipPathId,`)" >
4
4
  `)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
5
5
  `),this._setSVGBgOverlayColor(s,"overlay"),this._setSVGBgOverlayImage(s,"overlayImage",e),s.push("</svg>"),s.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",`" standalone="no" ?>
6
6
  `,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
@@ -18,13 +18,13 @@ Resulting to default behavior: removing object from previous canvas and adding t
18
18
  `.concat(r,`]]></style>
19
19
  `):""}_setSVGObjects(t,e){this.forEachObject(s=>{s.excludeFromExport||this._setSVGObject(t,s,e)})}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const r=this[e];r&&!r.excludeFromExport&&r.toSVG&&t.push(r.toSVG(s))}_setSVGBgOverlayColor(t,e){const s=this["".concat(e,"Color")];if(s)if(Dt(s)){const r=s.repeat||"",i=this.width,n=this.height,a=this["".concat(e,"Vpt")]?qe(Rt(this.viewportTransform)):"";t.push('<rect transform="'.concat(a," translate(").concat(i/2,",").concat(n/2,')" x="').concat(s.offsetX-i/2,'" y="').concat(s.offsetY-n/2,'" width="').concat(r!=="repeat-y"&&r!=="no-repeat"||!hi(s)?i:s.source.width,'" height="').concat(r!=="repeat-x"&&r!=="no-repeat"||!hi(s)?n:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
20
20
  `))}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',s,'"',`></rect>
21
- `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new Ht("`json` is undefined"));const r=typeof t=="string"?JSON.parse(t):t,{objects:i=[]}=r,n=$(r,jo),{backgroundImage:a,background:h,overlayImage:c,overlay:l,clipPath:u}=n,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Ue(i,{reviver:e,signal:s}),$s({backgroundImage:a,backgroundColor:h,overlayImage:c,overlayColor:l,clipPath:u},{signal:s})]).then(g=>{let[f,v]=g;return this.clear(),this.add(...f),this.set(n),this.set(v),this.renderOnAddRemove=d,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=Et(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:r=1,enableRetinaScaling:i=!1}=t,n=r*(i?this.getRetinaScaling():1);return an(this.toCanvasElement(n,t),e,s)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:r=1,enableRetinaScaling:i=!1}=t,n=r*(i?this.getRetinaScaling():1);return hn(this.toCanvasElement(n,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:r,top:i,filter:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const a=(e||this.width)*t,h=(s||this.height)*t,c=this.getZoom(),l=this.width,u=this.height,d=this.skipControlsDrawing,g=c*t,f=this.viewportTransform,v=[g,0,0,g,(f[4]-(r||0))*t,(f[5]-(i||0))*t],_=this.enableRetinaScaling,b=Et({width:a,height:h}),w=n?this._objects.filter(C=>n(C)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=v,this.width=a,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(b.getContext("2d"),w),this.viewportTransform=f,this.width=l,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=_,this.skipControlsDrawing=d,b}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Fs.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}p(ts,"ownDefaults",Ao);const Fo=["touchstart","touchmove","touchend"],Lo=o=>{const t=gn(o.target),e=function(s){const r=s.changedTouches;return r&&r[0]?r[0]:s}(o);return new x(e.clientX+t.left,e.clientY+t.top)},wr=o=>Fo.includes(o.type)||o.pointerType==="touch",li=o=>{o.preventDefault(),o.stopPropagation()},Zt=o=>{let t=0,e=0,s=0,r=0;for(let i=0,n=o.length;i<n;i++){const{x:a,y:h}=o[i];(a>s||!i)&&(s=a),(a<t||!i)&&(t=a),(h>r||!i)&&(r=h),(h<e||!i)&&(e=h)}return{left:t,top:e,width:s-t,height:r-e}},Ro=["translateX","translateY","scaleX","scaleY"],Bo=(o,t)=>Rs(o,ct(t,o.calcOwnMatrix())),Rs=(o,t)=>{const e=Ls(t),{translateX:s,translateY:r,scaleX:i,scaleY:n}=e,a=$(e,Ro),h=new x(s,r);o.flipX=!1,o.flipY=!1,Object.assign(o,a),o.set({scaleX:i,scaleY:n}),o.setPositionByOrigin(h,R,R)},Io=o=>{o.scaleX=1,o.scaleY=1,o.skewX=0,o.skewY=0,o.flipX=!1,o.flipY=!1,o.rotate(0)},vn=o=>({scaleX:o.scaleX,scaleY:o.scaleY,skewX:o.skewX,skewY:o.skewY,angle:o.angle,left:o.left,flipX:o.flipX,flipY:o.flipY,top:o.top}),Yr=(o,t,e)=>{const s=o/2,r=t/2,i=[new x(-s,-r),new x(s,-r),new x(-s,r),new x(s,r)].map(a=>a.transform(e)),n=Zt(i);return new x(n.width,n.height)},Js=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ft;return ct(Rt(arguments.length>1&&arguments[1]!==void 0?arguments[1]:ft),o)},ke=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ft,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ft;return o.transform(Js(t,e))},Wo=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ft,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ft;return o.transform(Js(t,e),!0)},Xo=(o,t,e)=>{const s=Js(t,e);return Rs(o,ct(s,o.calcOwnMatrix())),s},yn=(o,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(o),m(m({},t),{},{target:s})),s.fire(o,t)},Yo={left:-.5,top:-.5,center:0,bottom:.5,right:.5},it=o=>typeof o=="string"?Yo[o]:o-.5,Bs="not-allowed";function xn(o){return it(o.originX)===it(R)&&it(o.originY)===it(R)}function ui(o){return .5-it(o)}const It=(o,t)=>o[t],_n=(o,t,e,s)=>({e:o,transform:t,pointer:new x(e,s)});function bn(o,t){const e=o.getTotalAngle()+se(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Vr(o,t,e,s,r){var i;let{target:n,corner:a}=o;const h=n.controls[a],c=((i=n.canvas)===null||i===void 0?void 0:i.getZoom())||1,l=n.padding/c,u=function(d,g,f,v){const _=d.getRelativeCenterPoint(),b=f!==void 0&&v!==void 0?d.translateToGivenOrigin(_,R,R,f,v):new x(d.left,d.top);return(d.angle?g.rotate(-tt(d.angle),_):g).subtract(b)}(n,new x(s,r),t,e);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-=h.offsetX,u.y-=h.offsetY,u}const Vo=(o,t,e,s)=>{const{target:r,offsetX:i,offsetY:n}=t,a=e-i,h=s-n,c=!It(r,"lockMovementX")&&r.left!==a,l=!It(r,"lockMovementY")&&r.top!==h;return c&&r.set(N,a),l&&r.set(mt,h),(c||l)&&yn(en,_n(o,t,e,s)),c||l},Is=o=>o.replace(/\s+/g," "),di={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"},or=(o,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+6*(t-o)*e:e<.5?t:e<2/3?o+(t-o)*(2/3-e)*6:o),gi=(o,t,e,s)=>{o/=255,t/=255,e/=255;const r=Math.max(o,t,e),i=Math.min(o,t,e);let n,a;const h=(r+i)/2;if(r===i)n=a=0;else{const c=r-i;switch(a=h>.5?c/(2-r-i):c/(r+i),r){case o:n=(t-e)/c+(t<e?6:0);break;case t:n=(e-o)/c+2;break;case e:n=(o-t)/c+4}n/=6}return[Math.round(360*n),Math.round(100*a),Math.round(100*h),s]},fi=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(o)/(o.endsWith("%")?100:1)},es=o=>Math.min(Math.round(o),255).toString(16).toUpperCase().padStart(2,"0"),pi=o=>{let[t,e,s,r=1]=o;const i=Math.round(.3*t+.59*e+.11*s);return[i,i,i,r]};class G{constructor(t){if(p(this,"isUnrecognised",!1),t)if(t instanceof G)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,s,r,i=1]=t;this.setSource([e,s,r,i])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in di&&(t=di[t]),t==="transparent"?[255,255,255,0]:G.sourceFromHex(t)||G.sourceFromRgb(t)||G.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=gi(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,r]=gi(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(r,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,r]=this.getSource();return"".concat(es(t)).concat(es(e)).concat(es(s)).concat(es(Math.round(255*r)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(pi(this.getSource())),this}toBlackWhite(t){const[e,,,s]=pi(this.getSource()),r=e<(t||127)?0:255;return this.setSource([r,r,r,s]),this}overlayWith(t){t instanceof G||(t=new G(t));const e=this.getSource(),s=t.getSource(),[r,i,n]=e.map((a,h)=>Math.round(.5*a+.5*s[h]));return this.setSource([r,i,n,e[3]]),this}static fromRgb(t){return G.fromRgba(t)}static fromRgba(t){return new G(G.sourceFromRgb(t))}static sourceFromRgb(t){const e=Is(t).match(/^rgba?\(\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d{0,3}(?:\.\d+)?%?)\s?)?\)$/i);if(e){const[s,r,i]=e.slice(1,4).map(n=>{const a=parseFloat(n);return n.endsWith("%")?Math.round(2.55*a):a});return[s,r,i,fi(e[4])]}}static fromHsl(t){return G.fromHsla(t)}static fromHsla(t){return new G(G.sourceFromHsl(t))}static sourceFromHsl(t){const e=Is(t).match(/^hsla?\(\s?([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d*(?:\.\d+)?%?)\s?)?\)$/i);if(!e)return;const s=(G.parseAngletoDegrees(e[1])%360+360)%360/360,r=parseFloat(e[2])/100,i=parseFloat(e[3])/100;let n,a,h;if(r===0)n=a=h=i;else{const c=i<=.5?i*(r+1):i+r-i*r,l=2*i-c;n=or(l,c,s+1/3),a=or(l,c,s),h=or(l,c,s-1/3)}return[Math.round(255*n),Math.round(255*a),Math.round(255*h),fi(e[4])]}static fromHex(t){return new G(G.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map(h=>h+h):e.match(/.{2}/g);const[r,i,n,a=255]=s.map(h=>parseInt(h,16));return[r,i,n,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?se(s):e.includes("turn")?360*s:s}}const De=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Fr;const e=/\D{0,2}$/.exec(o),s=parseFloat(o),r=Y.DPI;switch(e==null?void 0:e[0]){case"mm":return s*r/25.4;case"cm":return s*r/2.54;case"in":return s*r;case"pt":return s*r/72;case"pc":return s*r/72*12;case"em":return s*t;default:return s}},Ho=o=>{const[t,e]=o.trim().split(" "),[s,r]=(i=t)&&i!==vt?[i.slice(1,4),i.slice(5,8)]:i===vt?[i,i]:["Mid","Mid"];var i;return{meetOrSlice:e||"meet",alignX:s,alignY:r}},Ke=function(o,t){let e,s,r=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const i=new G(t),n=i.getAlpha();e=i.toRgb(),n!==1&&(s=n.toString())}else e="none";return r?"".concat(o,": ").concat(e,"; ").concat(s?"".concat(o,"-opacity: ").concat(s,"; "):""):"".concat(o,'="').concat(e,'" ').concat(s?"".concat(o,'-opacity="').concat(s,'" '):"")};class wn{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",r=this.strokeDashArray?this.strokeDashArray.join(" "):vt,i=this.strokeDashOffset?this.strokeDashOffset:"0",n=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",c=this.opacity!==void 0?this.opacity:"1",l=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),d=Ke(ot,this.fill);return[Ke(yt,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",r,"; ","stroke-linecap: ",n,"; ","stroke-dashoffset: ",i,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",h,"; ",d,"fill-rule: ",e,"; ","opacity: ",c,";",u,l].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),r='transform="'.concat(qe(s));return"".concat(r).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),i=t.indexOf("COMMON_PARTS");return t[i]=r,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:r,additionalTransform:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=e?"":'style="'.concat(this.getSvgStyles(),'" '),a=r?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,c=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",l=h&&h.absolutePositioned,u=this.stroke,d=this.fill,g=this.shadow,f=[],v=t.indexOf("COMMON_PARTS");let _;h&&(h.clipPathId="CLIPPATH_".concat(le()),_='<clipPath id="'.concat(h.clipPathId,`" >
21
+ `)}loadFromJSON(t,e){let{signal:s}=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};if(!t)return Promise.reject(new Ht("`json` is undefined"));const r=typeof t=="string"?JSON.parse(t):t,{objects:i=[]}=r,n=$(r,Ro),{backgroundImage:a,background:h,overlayImage:c,overlay:l,clipPath:u}=n,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Ue(i,{reviver:e,signal:s}),$s({backgroundImage:a,backgroundColor:h,overlayImage:c,overlayColor:l,clipPath:u},{signal:s})]).then(g=>{let[f,v]=g;return this.clear(),this.add(...f),this.set(n),this.set(v),this.renderOnAddRemove=d,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=Et(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:r=1,enableRetinaScaling:i=!1}=t,n=r*(i?this.getRetinaScaling():1);return hn(this.toCanvasElement(n,t),e,s)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:r=1,enableRetinaScaling:i=!1}=t,n=r*(i?this.getRetinaScaling():1);return cn(this.toCanvasElement(n,t),e,s)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,{width:e,height:s,left:r,top:i,filter:n}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const a=(e||this.width)*t,h=(s||this.height)*t,c=this.getZoom(),l=this.width,u=this.height,d=this.skipControlsDrawing,g=c*t,f=this.viewportTransform,v=[g,0,0,g,(f[4]-(r||0))*t,(f[5]-(i||0))*t],_=this.enableRetinaScaling,b=Et({width:a,height:h}),w=n?this._objects.filter(C=>n(C)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=v,this.width=a,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(b.getContext("2d"),w),this.viewportTransform=f,this.width=l,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=_,this.skipControlsDrawing=d,b}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),Fs.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const s=()=>{this.destroy(),t(!0)};s.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=s:s()})}destroy(){this.destroyed=!0,this.cancelRequestedRender(),this.forEachObject(t=>t.dispose()),this._objects=[],this.backgroundImage&&this.backgroundImage.dispose(),this.backgroundImage=void 0,this.overlayImage&&this.overlayImage.dispose(),this.overlayImage=void 0,this.elements.dispose()}toString(){return"#<Canvas (".concat(this.complexity(),"): { objects: ").concat(this._objects.length," }>")}}p(ts,"ownDefaults",Lo);const Bo=["touchstart","touchmove","touchend"],Io=o=>{const t=fn(o.target),e=function(s){const r=s.changedTouches;return r&&r[0]?r[0]:s}(o);return new x(e.clientX+t.left,e.clientY+t.top)},wr=o=>Bo.includes(o.type)||o.pointerType==="touch",li=o=>{o.preventDefault(),o.stopPropagation()},Zt=o=>{let t=0,e=0,s=0,r=0;for(let i=0,n=o.length;i<n;i++){const{x:a,y:h}=o[i];(a>s||!i)&&(s=a),(a<t||!i)&&(t=a),(h>r||!i)&&(r=h),(h<e||!i)&&(e=h)}return{left:t,top:e,width:s-t,height:r-e}},Wo=["translateX","translateY","scaleX","scaleY"],Xo=(o,t)=>Rs(o,ct(t,o.calcOwnMatrix())),Rs=(o,t)=>{const e=Ls(t),{translateX:s,translateY:r,scaleX:i,scaleY:n}=e,a=$(e,Wo),h=new x(s,r);o.flipX=!1,o.flipY=!1,Object.assign(o,a),o.set({scaleX:i,scaleY:n}),o.setPositionByOrigin(h,R,R)},Yo=o=>{o.scaleX=1,o.scaleY=1,o.skewX=0,o.skewY=0,o.flipX=!1,o.flipY=!1,o.rotate(0)},yn=o=>({scaleX:o.scaleX,scaleY:o.scaleY,skewX:o.skewX,skewY:o.skewY,angle:o.angle,left:o.left,flipX:o.flipX,flipY:o.flipY,top:o.top}),Yr=(o,t,e)=>{const s=o/2,r=t/2,i=[new x(-s,-r),new x(s,-r),new x(-s,r),new x(s,r)].map(a=>a.transform(e)),n=Zt(i);return new x(n.width,n.height)},Js=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ft;return ct(Rt(arguments.length>1&&arguments[1]!==void 0?arguments[1]:ft),o)},ke=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ft,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ft;return o.transform(Js(t,e))},Vo=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:ft,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:ft;return o.transform(Js(t,e),!0)},Ho=(o,t,e)=>{const s=Js(t,e);return Rs(o,ct(s,o.calcOwnMatrix())),s},xn=(o,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire("object:".concat(o),m(m({},t),{},{target:s})),s.fire(o,t)},zo={left:-.5,top:-.5,center:0,bottom:.5,right:.5},it=o=>typeof o=="string"?zo[o]:o-.5,Bs="not-allowed";function _n(o){return it(o.originX)===it(R)&&it(o.originY)===it(R)}function ui(o){return .5-it(o)}const It=(o,t)=>o[t],bn=(o,t,e,s)=>({e:o,transform:t,pointer:new x(e,s)});function wn(o,t){const e=o.getTotalAngle()+se(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Vr(o,t,e,s,r){var i;let{target:n,corner:a}=o;const h=n.controls[a],c=((i=n.canvas)===null||i===void 0?void 0:i.getZoom())||1,l=n.padding/c,u=function(d,g,f,v){const _=d.getRelativeCenterPoint(),b=f!==void 0&&v!==void 0?d.translateToGivenOrigin(_,R,R,f,v):new x(d.left,d.top);return(d.angle?g.rotate(-tt(d.angle),_):g).subtract(b)}(n,new x(s,r),t,e);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-=h.offsetX,u.y-=h.offsetY,u}const Go=(o,t,e,s)=>{const{target:r,offsetX:i,offsetY:n}=t,a=e-i,h=s-n,c=!It(r,"lockMovementX")&&r.left!==a,l=!It(r,"lockMovementY")&&r.top!==h;return c&&r.set(N,a),l&&r.set(mt,h),(c||l)&&xn(sn,bn(o,t,e,s)),c||l},Is=o=>o.replace(/\s+/g," "),di={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"},or=(o,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+6*(t-o)*e:e<.5?t:e<2/3?o+(t-o)*(2/3-e)*6:o),gi=(o,t,e,s)=>{o/=255,t/=255,e/=255;const r=Math.max(o,t,e),i=Math.min(o,t,e);let n,a;const h=(r+i)/2;if(r===i)n=a=0;else{const c=r-i;switch(a=h>.5?c/(2-r-i):c/(r+i),r){case o:n=(t-e)/c+(t<e?6:0);break;case t:n=(e-o)/c+2;break;case e:n=(o-t)/c+4}n/=6}return[Math.round(360*n),Math.round(100*a),Math.round(100*h),s]},fi=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(o)/(o.endsWith("%")?100:1)},es=o=>Math.min(Math.round(o),255).toString(16).toUpperCase().padStart(2,"0"),pi=o=>{let[t,e,s,r=1]=o;const i=Math.round(.3*t+.59*e+.11*s);return[i,i,i,r]};class G{constructor(t){if(p(this,"isUnrecognised",!1),t)if(t instanceof G)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,s,r,i=1]=t;this.setSource([e,s,r,i])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in di&&(t=di[t]),t==="transparent"?[255,255,255,0]:G.sourceFromHex(t)||G.sourceFromRgb(t)||G.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,s]=this.getSource();return"rgb(".concat(t,",").concat(e,",").concat(s,")")}toRgba(){return"rgba(".concat(this.getSource().join(","),")")}toHsl(){const[t,e,s]=gi(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,r]=gi(...this.getSource());return"hsla(".concat(t,",").concat(e,"%,").concat(s,"%,").concat(r,")")}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,r]=this.getSource();return"".concat(es(t)).concat(es(e)).concat(es(s)).concat(es(Math.round(255*r)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(pi(this.getSource())),this}toBlackWhite(t){const[e,,,s]=pi(this.getSource()),r=e<(t||127)?0:255;return this.setSource([r,r,r,s]),this}overlayWith(t){t instanceof G||(t=new G(t));const e=this.getSource(),s=t.getSource(),[r,i,n]=e.map((a,h)=>Math.round(.5*a+.5*s[h]));return this.setSource([r,i,n,e[3]]),this}static fromRgb(t){return G.fromRgba(t)}static fromRgba(t){return new G(G.sourceFromRgb(t))}static sourceFromRgb(t){const e=Is(t).match(/^rgba?\(\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d{0,3}(?:\.\d+)?%?)\s?)?\)$/i);if(e){const[s,r,i]=e.slice(1,4).map(n=>{const a=parseFloat(n);return n.endsWith("%")?Math.round(2.55*a):a});return[s,r,i,fi(e[4])]}}static fromHsl(t){return G.fromHsla(t)}static fromHsla(t){return new G(G.sourceFromHsl(t))}static sourceFromHsl(t){const e=Is(t).match(/^hsla?\(\s?([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?[\s|,]\s?(\d{0,3}(?:\.\d+)?%?)\s?(?:\s?[,/]\s?(\d*(?:\.\d+)?%?)\s?)?\)$/i);if(!e)return;const s=(G.parseAngletoDegrees(e[1])%360+360)%360/360,r=parseFloat(e[2])/100,i=parseFloat(e[3])/100;let n,a,h;if(r===0)n=a=h=i;else{const c=i<=.5?i*(r+1):i+r-i*r,l=2*i-c;n=or(l,c,s+1/3),a=or(l,c,s),h=or(l,c,s-1/3)}return[Math.round(255*n),Math.round(255*a),Math.round(255*h),fi(e[4])]}static fromHex(t){return new G(G.sourceFromHex(t))}static sourceFromHex(t){if(t.match(/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i)){const e=t.slice(t.indexOf("#")+1);let s;s=e.length<=4?e.split("").map(h=>h+h):e.match(/.{2}/g);const[r,i,n,a=255]=s.map(h=>parseInt(h,16));return[r,i,n,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?se(s):e.includes("turn")?360*s:s}}const De=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Fr;const e=/\D{0,2}$/.exec(o),s=parseFloat(o),r=Y.DPI;switch(e==null?void 0:e[0]){case"mm":return s*r/25.4;case"cm":return s*r/2.54;case"in":return s*r;case"pt":return s*r/72;case"pc":return s*r/72*12;case"em":return s*t;default:return s}},No=o=>{const[t,e]=o.trim().split(" "),[s,r]=(i=t)&&i!==vt?[i.slice(1,4),i.slice(5,8)]:i===vt?[i,i]:["Mid","Mid"];var i;return{meetOrSlice:e||"meet",alignX:s,alignY:r}},Ke=function(o,t){let e,s,r=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e="url(#SVGID_".concat(t.id,")");else{const i=new G(t),n=i.getAlpha();e=i.toRgb(),n!==1&&(s=n.toString())}else e="none";return r?"".concat(o,": ").concat(e,"; ").concat(s?"".concat(o,"-opacity: ").concat(s,"; "):""):"".concat(o,'="').concat(e,'" ').concat(s?"".concat(o,'-opacity="').concat(s,'" '):"")};class Sn{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",r=this.strokeDashArray?this.strokeDashArray.join(" "):vt,i=this.strokeDashOffset?this.strokeDashOffset:"0",n=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",c=this.opacity!==void 0?this.opacity:"1",l=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),d=Ke(ot,this.fill);return[Ke(yt,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",r,"; ","stroke-linecap: ",n,"; ","stroke-dashoffset: ",i,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",h,"; ",d,"fill-rule: ",e,"; ","opacity: ",c,";",u,l].join("")}getSvgFilter(){return this.shadow?"filter: url(#SVGID_".concat(this.shadow.id,");"):""}getSvgCommons(){return[this.id?'id="'.concat(this.id,'" '):"",this.clipPath?'clip-path="url(#'.concat(this.clipPath.clipPathId,')" '):""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix(),r='transform="'.concat(qe(s));return"".concat(r).concat(e,'" ')}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return" "+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const r=[this.getSvgTransform(!0,s),this.getSvgCommons()].join(""),i=t.indexOf("COMMON_PARTS");return t[i]=r,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:s,withShadow:r,additionalTransform:i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const n=e?"":'style="'.concat(this.getSvgStyles(),'" '),a=r?'style="'.concat(this.getSvgFilter(),'" '):"",h=this.clipPath,c=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",l=h&&h.absolutePositioned,u=this.stroke,d=this.fill,g=this.shadow,f=[],v=t.indexOf("COMMON_PARTS");let _;h&&(h.clipPathId="CLIPPATH_".concat(le()),_='<clipPath id="'.concat(h.clipPathId,`" >
22
22
  `).concat(h.toClipPathSVG(s),`</clipPath>
23
23
  `)),l&&f.push("<g ",a,this.getSvgCommons(),` >
24
24
  `),f.push("<g ",this.getSvgTransform(!1),l?"":a+this.getSvgCommons(),` >
25
25
  `);const b=[n,c,e?"":this.addPaintOrder()," ",i?'transform="'.concat(i,'" '):""].join("");return t[v]=b,Dt(d)&&f.push(d.toSVG(this)),Dt(u)&&f.push(u.toSVG(this)),g&&f.push(g.toSVG(this)),h&&f.push(_),f.push(t.join("")),f.push(`</g>
26
26
  `),l&&f.push(`</g>
27
- `),s?s(f.join("")):f.join("")}addPaintOrder(){return this.paintFirst!==ot?' paint-order="'.concat(this.paintFirst,'" '):""}}function Zs(o){return new RegExp("^("+o.join("|")+")\\b","i")}const me="textDecorationThickness",Sn=["fontSize","fontWeight","fontFamily","fontStyle"],Cn=["underline","overline","linethrough"],Tn=[...Sn,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],On=[...Tn,...Cn,"textBackgroundColor","direction",me],zo=[...Sn,...Cn,yt,"strokeWidth",ot,"deltaY","textBackgroundColor",me],Go={_reNewline:Lr,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:N,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:N,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,[me]:66.667},Yt="justify",Ws="justify-left",He="justify-right",ze="justify-center";var mi,vi,yi;const Bt=String.raw(mi||(mi=Nt(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),ar=String.raw(vi||(vi=Nt(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),No=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Bt+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Bt+"))?\\s+(.*)"),Uo={cx:N,x:N,r:"radius",cy:mt,y:mt,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":me},hr="font-size",cr="clip-path";Zs(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]);Zs(["symbol","image","marker","pattern","view","svg"]);const xi=Zs(["symbol","g","a","svg","clipPath","defs"]);new RegExp(String.raw(yi||(yi=Nt(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),Bt,ar,Bt,ar,Bt,ar,Bt));const qo=new x(1,0),kn=new x,Dn=(o,t)=>o.rotate(t),Sr=(o,t)=>new x(t).subtract(o),Cr=o=>o.distanceFrom(kn),Tr=(o,t)=>Math.atan2(Ge(o,t),$o(o,t)),Ko=o=>Tr(qo,o),Hr=o=>o.eq(kn)?o:o.scalarDivide(Cr(o)),Mn=function(o){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return Hr(new x(-o.y,o.x).scalarMultiply(t?1:-1))},Ge=(o,t)=>o.x*t.y-o.y*t.x,$o=(o,t)=>o.x*t.x+o.y*t.y,_i=(o,t,e)=>{if(o.eq(t)||o.eq(e))return!0;const s=Ge(t,e),r=Ge(t,o),i=Ge(e,o);return s>=0?r>=0&&i<=0:!(r<=0&&i>=0)},bi="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",wi=new RegExp("(?:\\s|^)"+bi+bi+"("+Bt+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class zt{constructor(t){const e=typeof t=="string"?zt.parseShadow(t):t;Object.assign(this,zt.ownDefaults,e),this.id=le()}static parseShadow(t){const e=t.trim(),[,s=0,r=0,i=0]=(wi.exec(e)||[]).map(n=>parseFloat(n)||0);return{color:(e.replace(wi,"")||"rgb(0,0,0)").trim(),offsetX:s,offsetY:r,blur:i}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const e=Dn(new x(this.offsetX,this.offsetY),tt(-t.angle)),s=new G(this.color);let r=40,i=40;return t.width&&t.height&&(r=100*K((Math.abs(e.x)+this.blur)/t.width,Y.NUM_FRACTION_DIGITS)+20,i=100*K((Math.abs(e.y)+this.blur)/t.height,Y.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(i,'%" height="').concat(100+2*i,'%" x="-').concat(r,'%" width="').concat(100+2*r,`%" >
27
+ `),s?s(f.join("")):f.join("")}addPaintOrder(){return this.paintFirst!==ot?' paint-order="'.concat(this.paintFirst,'" '):""}}function Zs(o){return new RegExp("^("+o.join("|")+")\\b","i")}const me="textDecorationThickness",Cn=["fontSize","fontWeight","fontFamily","fontStyle"],Tn=["underline","overline","linethrough"],On=[...Cn,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],kn=[...On,...Tn,"textBackgroundColor","direction",me],Uo=[...Cn,...Tn,yt,"strokeWidth",ot,"deltaY","textBackgroundColor",me],qo={_reNewline:Lr,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:N,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:N,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,[me]:66.667},Yt="justify",Ws="justify-left",He="justify-right",ze="justify-center";var mi,vi,yi;const Bt=String.raw(mi||(mi=Nt(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),ar=String.raw(vi||(vi=Nt(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),Ko=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Bt+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Bt+"))?\\s+(.*)"),$o={cx:N,x:N,r:"radius",cy:mt,y:mt,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":me},hr="font-size",cr="clip-path";Zs(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]);Zs(["symbol","image","marker","pattern","view","svg"]);const xi=Zs(["symbol","g","a","svg","clipPath","defs"]);new RegExp(String.raw(yi||(yi=Nt(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),Bt,ar,Bt,ar,Bt,ar,Bt));const Jo=new x(1,0),Dn=new x,Mn=(o,t)=>o.rotate(t),Sr=(o,t)=>new x(t).subtract(o),Cr=o=>o.distanceFrom(Dn),Tr=(o,t)=>Math.atan2(Ge(o,t),Qo(o,t)),Zo=o=>Tr(Jo,o),Hr=o=>o.eq(Dn)?o:o.scalarDivide(Cr(o)),En=function(o){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return Hr(new x(-o.y,o.x).scalarMultiply(t?1:-1))},Ge=(o,t)=>o.x*t.y-o.y*t.x,Qo=(o,t)=>o.x*t.x+o.y*t.y,_i=(o,t,e)=>{if(o.eq(t)||o.eq(e))return!0;const s=Ge(t,e),r=Ge(t,o),i=Ge(e,o);return s>=0?r>=0&&i<=0:!(r<=0&&i>=0)},bi="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",wi=new RegExp("(?:\\s|^)"+bi+bi+"("+Bt+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class zt{constructor(t){const e=typeof t=="string"?zt.parseShadow(t):t;Object.assign(this,zt.ownDefaults,e),this.id=le()}static parseShadow(t){const e=t.trim(),[,s=0,r=0,i=0]=(wi.exec(e)||[]).map(n=>parseFloat(n)||0);return{color:(e.replace(wi,"")||"rgb(0,0,0)").trim(),offsetX:s,offsetY:r,blur:i}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const e=Mn(new x(this.offsetX,this.offsetY),tt(-t.angle)),s=new G(this.color);let r=40,i=40;return t.width&&t.height&&(r=100*K((Math.abs(e.x)+this.blur)/t.width,Y.NUM_FRACTION_DIGITS)+20,i=100*K((Math.abs(e.y)+this.blur)/t.height,Y.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),'<filter id="SVGID_'.concat(this.id,'" y="-').concat(i,'%" height="').concat(100+2*i,'%" x="-').concat(r,'%" width="').concat(100+2*r,`%" >
28
28
  <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(K(this.blur?this.blur/2:0,Y.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
29
29
  <feOffset dx="`).concat(K(e.x,Y.NUM_FRACTION_DIGITS),'" dy="').concat(K(e.y,Y.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
30
30
  <feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
@@ -34,44 +34,44 @@ Resulting to default behavior: removing object from previous canvas and adding t
34
34
  <feMergeNode in="SourceGraphic"></feMergeNode>
35
35
  </feMerge>
36
36
  </filter>
37
- `)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=zt.ownDefaults;return this.includeDefaultValues?t:Xr(t,(s,r)=>s!==e[r])}static async fromObject(t){return new this(t)}}p(zt,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),p(zt,"type","shadow"),M.setClass(zt,"shadow");const Ee=(o,t,e)=>Math.max(o,Math.min(t,e)),Jo=[mt,N,_t,Mt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Ae,je],re=[ot,yt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Zo={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:N,originY:mt,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:ot,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},Qo=(o,t,e,s)=>-e*Math.cos(o/s*Ze)+e+t,ta=()=>!1;class zr{constructor(t){let{startValue:e,byValue:s,duration:r=500,delay:i=0,easing:n=Qo,onStart:a=Os,onChange:h=Os,onComplete:c=Os,abort:l=ta,target:u}=t;p(this,"_state","pending"),p(this,"durationProgress",0),p(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=r,this.delay=i,this.easing=n,this._onStart=a,this._onChange=h,this._onComplete=c,this._abort=l,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>Ds(t),this.delay):Ds(t)}tick(t){const e=(t||+new Date)-this.startTime,s=Math.min(e,this.duration);this.durationProgress=s/this.duration;const{value:r,valueProgress:i}=this.calculate(s);this.value=Object.freeze(r),this.valueProgress=i,this._state!=="aborted"&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),Ds(this.tick)))}register(){Fs.push(this)}unregister(){Fs.remove(this)}abort(){this._state="aborted",this.unregister()}}const ea=["startValue","endValue"];class sa extends zr{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(m(m({},$(t,ea)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const ra=["startValue","endValue"];class ia extends zr{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(m(m({},$(t,ra)),{},{startValue:e,byValue:s.map((r,i)=>r-e[i])}))}calculate(t){const e=this.startValue.map((s,r)=>this.easing(t,s,this.byValue[r],this.duration,r));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const na=["startValue","endValue","easing","onChange","onComplete","abort"],oa=(o,t,e,s)=>t+e*(1-Math.cos(o/s*Ze)),lr=o=>o&&((t,e,s)=>o(new G(t).toRgba(),e,s));class aa extends zr{constructor(t){let{startValue:e,endValue:s,easing:r=oa,onChange:i,onComplete:n,abort:a}=t,h=$(t,na);const c=new G(e).getSource(),l=new G(s).getSource();super(m(m({},h),{},{startValue:c,byValue:l.map((u,d)=>u-c[d]),easing:r,onChange:lr(i),onComplete:lr(n),abort:lr(a)}))}calculate(t){const[e,s,r,i]=this.startValue.map((a,h)=>this.easing(t,a,this.byValue[h],this.duration,h)),n=[...[e,s,r].map(Math.round),Ee(0,i,1)];return{value:n,valueProgress:n.map((a,h)=>this.byValue[h]!==0?Math.abs((a-this.startValue[h])/this.byValue[h]):0).find(a=>a!==0)||0}}}function En(o){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(o)?new ia(o):new sa(o);return t.start(),t}function ha(o){const t=new aa(o);return t.start(),t}class J{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter(r=>!this.includes(r))),this}static isPointContained(t,e,s){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(r||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(r||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const i=Sr(e,s),n=Sr(e,t).divide(i);return r?Math.abs(n.x)===Math.abs(n.y):n.x===n.y&&n.x>=0&&n.x<=1}}static isPointInPolygon(t,e){const s=new x(t).setX(Math.min(t.x-1,...e.map(i=>i.x)));let r=0;for(let i=0;i<e.length;i++){const n=this.intersectSegmentSegment(e[i],e[(i+1)%e.length],t,s);if(n.includes(t))return!0;r+=+(n.status==="Intersection")}return r%2==1}static intersectLineLine(t,e,s,r){let i=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],n=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const a=e.x-t.x,h=e.y-t.y,c=r.x-s.x,l=r.y-s.y,u=t.x-s.x,d=t.y-s.y,g=c*d-l*u,f=a*d-h*u,v=l*a-c*h;if(v!==0){const _=g/v,b=f/v;return(i||0<=_&&_<=1)&&(n||0<=b&&b<=1)?new J("Intersection").append(new x(t.x+_*a,t.y+_*h)):new J}if(g===0||f===0){const _=i||n||J.isPointContained(t,s,r)||J.isPointContained(e,s,r)||J.isPointContained(s,t,e)||J.isPointContained(r,t,e);return new J(_?"Coincident":void 0)}return new J("Parallel")}static intersectSegmentLine(t,e,s,r){return J.intersectLineLine(t,e,s,r,!1,!0)}static intersectSegmentSegment(t,e,s,r){return J.intersectLineLine(t,e,s,r,!1,!1)}static intersectLinePolygon(t,e,s){let r=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const i=new J,n=s.length;for(let a,h,c,l=0;l<n;l++){if(a=s[l],h=s[(l+1)%n],c=J.intersectLineLine(t,e,a,h,r,!1),c.status==="Coincident")return c;i.append(...c.points)}return i.points.length>0&&(i.status="Intersection"),i}static intersectSegmentPolygon(t,e,s){return J.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new J,r=t.length,i=[];for(let n=0;n<r;n++){const a=t[n],h=t[(n+1)%r],c=J.intersectSegmentPolygon(a,h,e);c.status==="Coincident"?(i.push(c),s.append(a,h)):s.append(...c.points)}return i.length>0&&i.length===t.length?new J("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const r=e.min(s),i=e.max(s),n=new x(i.x,r.y),a=new x(r.x,i.y);return J.intersectPolygonPolygon(t,[r,n,i,a])}}class ca extends on{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?pt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=pt(t,Rt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new x(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:r}=this.aCoords||(this.aCoords=this.calcACoords()),i=[t,e,s,r];if(this.group){const n=this.group.calcTransformMatrix();return i.map(a=>pt(a,n))}return i}intersectsWithRect(t,e){return J.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=J.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:s,top:r,width:i,height:n}=this.getBoundingRect();return s>=t.x&&s+i<=e.x&&r>=t.y&&r+n<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return J.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every(s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Zt(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(_t,t),this._set(Mt,t),this.setCoords()}scaleToWidth(t){const e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){const e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?se(cn(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||ft.concat()}calcACoords(){const t=Fe({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),r=Qe(e,s),i=ct(r,t),n=this._getTransformedDimensions(),a=n.x/2,h=n.y/2;return{tl:pt({x:-a,y:-h},i),tr:pt({x:a,y:-h},i),bl:pt({x:-a,y:h},i),br:pt({x:a,y:h},i)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,it(this.originX),it(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),r=this.matrixCache;return r&&r.key.every((i,n)=>i===s[n])?r.value:(this.group&&(e=ct(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),r={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},i=Po(r);return this.ownMatrixCache={key:t,value:i},i}_getNonTransformedDimensions(){return new x(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=m({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let r=s,i=0;this.strokeUniform&&(r=0,i=s);const n=e.width+r,a=e.height+r;let h;return h=e.skewX===0&&e.skewY===0?new x(n*e.scaleX,a*e.scaleY):Yr(n,a,Ks(e)),h.scalarAdd(i)}translateToGivenOrigin(t,e,s,r,i){let n=t.x,a=t.y;const h=it(r)-it(e),c=it(i)-it(s);if(h||c){const l=this._getTransformedDimensions();n+=h*l.x,a+=c*l.y}return new x(n,a)}translateToCenterPoint(t,e,s){if(e===R&&s===R)return t;const r=this.translateToGivenOrigin(t,e,s,R,R);return this.angle?r.rotate(tt(this.angle),t):r}translateToOriginPoint(t,e,s){const r=this.translateToGivenOrigin(t,R,R,e,s);return this.angle?r.rotate(tt(this.angle),t):r}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?pt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new x(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const r=this.translateToCenterPoint(t,e,s),i=this.translateToOriginPoint(r,this.originX,this.originY);this.set({left:i.x,top:i.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),N,mt)}}const la=["type"],ua=["extraParam"];let Ut=class Es extends ca{static getDefaults(){return Es.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){ce("warn","Setting type has no effect",t)}constructor(t){super(),p(this,"_cacheContext",null),Object.assign(this,Es.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=ee(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,r=Y.maxCacheSideLimit,i=Y.minCacheSideLimit;if(e<=r&&s<=r&&e*s<=Y.perfLimitSizeTotal)return e<i&&(t.width=i),s<i&&(t.height=i),t;const n=e/s,[a,h]=Ve.limitDimsByArea(n),c=Ee(i,a,r),l=Ee(i,h,r);return e>c&&(t.zoomX/=e/c,t.width=c,t.capped=!0),s>l&&(t.zoomY/=s/l,t.height=l,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,r=e.y*t.y/this.scaleY;return{width:Math.ceil(s+2),height:Math.ceil(r+2),zoomX:t.x,zoomY:t.y,x:s,y:r}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:r,zoomX:i,zoomY:n,x:a,y:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),c=s!==t.width||r!==t.height,l=this.zoomX!==i||this.zoomY!==n;if(!t||!e)return!1;if(c||l){s!==t.width||r!==t.height?(t.width=s,t.height=r):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const u=a/2,d=h/2;return this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-d)+d,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(i,n),this.zoomX=i,this.zoomY=n,!0}return!1}setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,s=this.calcTransformMatrix(!e);t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}getObjectScaling(){if(!this.group)return new x(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Ls(this.calcTransformMatrix());return new x(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),s=this.getCanvasRetinaScaling();return t.scalarMultiply(e*s)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t===0?1e-4:t}_set(t,e){t!==_t&&t!==Mt||(e=this._constrainScale(e)),t===_t&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof zt||(e=new zt(e));const s=this[t]!==e;return this[t]=e,s&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||s&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:r,cacheTranslationY:i}=this,{width:n,height:a}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:r,cacheTranslationY:i,width:n,height:a,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return this.stroke&&this.stroke!=="transparent"&&this.strokeWidth!==0}hasFill(){return this.fill&&this.fill!=="transparent"}needsItsOwnCache(){return!!(this.paintFirst===yt&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const r=this.fill,i=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=r,this.stroke=i}createClipPathLayer(t,e){const s=Et(e),r=s.getContext("2d");if(r.translate(e.cacheTranslationX,e.cacheTranslationY),r.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach(i=>{i.transform(r)}),e.parentClipPaths.push(t),t.absolutePositioned){const i=Rt(this.calcTransformMatrix());r.transform(i[0],i[1],i[2],i[3],i[4],i[5])}return t.transform(r),t.drawObject(r,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const r=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,r)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,s=this._cacheContext;return!(!e||!s||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&s&&!t&&(s.save(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),s.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;const e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){const s=e.stroke;s&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,Dt(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?this._applyPatternForTransformedGradient(t,s):(t.strokeStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:s}=e;s&&(Dt(s)?(t.fillStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.fillStyle=s)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&e.length!==0&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,r=this.getCanvasRetinaScaling(),[i,,,n]=(s==null?void 0:s.viewportTransform)||ft,a=i*r,h=n*r,c=e.nonScaling?new x(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*Y.browserShadowBlurConstant*(a+h)*(c.x+c.y)/4,t.shadowOffsetX=e.offsetX*a*c.x,t.shadowOffsetY=e.offsetY*h*c.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!Dt(e))return{offsetX:0,offsetY:0};const s=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,i=-this.height/2+e.offsetY||0;return e.gradientUnits==="percentage"?t.transform(this.width,0,0,this.height,r,i):t.transform(1,0,0,1,r,i),s&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),{offsetX:r,offsetY:i}}_renderPaintInOrder(t){this.paintFirst===yt?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const r=this._limitCacheSize(this._getCacheCanvasDimensions()),i=this.getCanvasRetinaScaling(),n=r.x/this.scaleX/i,a=r.y/this.scaleY/i,h=Et({width:Math.ceil(n),height:Math.ceil(a)}),c=h.getContext("2d");c&&(c.beginPath(),c.moveTo(0,0),c.lineTo(n,0),c.lineTo(n,a),c.lineTo(0,a),c.closePath(),c.translate(n/2,a/2),c.scale(r.zoomX/this.scaleX/i,r.zoomY/this.scaleY/i),this._applyPatternGradientTransform(c,e),c.fillStyle=e.toLive(t),c.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(i*this.scaleX/r.zoomX,i*this.scaleY/r.zoomY),t.strokeStyle=(s=c.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new x(this.left+this.width/2,this.top+this.height/2)}clone(t){const e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){const e=this.toCanvasElement(t);return new(M.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=vn(this),s=this.group,r=this.shadow,i=Math.abs,n=t.enableRetinaScaling?tn():1,a=(t.multiplier||1)*n,h=t.canvasProvider||(w=>new ts(w,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Io(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Xo(this,this.getViewportTransform()),this.setCoords();const c=ee(),l=this.getBoundingRect(),u=this.shadow,d=new x;if(u){const w=u.blur,C=u.nonScaling?new x(1,1):this.getObjectScaling();d.x=2*Math.round(i(u.offsetX)+w)*i(C.x),d.y=2*Math.round(i(u.offsetY)+w)*i(C.y)}const g=l.width+d.x,f=l.height+d.y;c.width=Math.ceil(g),c.height=Math.ceil(f);const v=h(c);t.format==="jpeg"&&(v.backgroundColor="#fff"),this.setPositionByOrigin(new x(v.width/2,v.height/2),R,R);const _=this.canvas;v._objects=[this],this.set("canvas",v),this.setCoords();const b=v.toCanvasElement(a||1,t);return this.set("canvas",_),this.shadow=r,s&&(this.group=s),this.set(e),this.setCoords(),v._objects=[],v.destroy(),b}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return an(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return hn(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:s,originY:r}=this;if(e){const{x:i,y:n}=this.getRelativeCenterPoint();this.originX=R,this.originY=R,this.left=i,this.top=n}if(this.set("angle",t),e){const{x:i,y:n}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,r);this.left=i,this.top=n,this.originX=s,this.originY=r}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Fs.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Gt().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,r)=>{let[i,n]=r;return s[i]=this._animate(i,n,e),s},{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const r=t.split("."),i=this.constructor.colorProperties.includes(r[r.length-1]),{abort:n,startValue:a,onChange:h,onComplete:c}=s,l=m(m({},s),{},{target:this,startValue:a??r.reduce((u,d)=>u[d],this),endValue:e,abort:n==null?void 0:n.bind(this),onChange:(u,d,g)=>{r.reduce((f,v,_)=>(_===r.length-1&&(f[v]=u),f[v]),this),h&&h(u,d,g)},onComplete:(u,d,g)=>{this.setCoords(),c&&c(u,d,g)}});return i?ha(l):En(l)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let r,i=0;i<e.length;i++){if(r=e[i],r===t)return{fork:[this,...e.slice(0,i)],otherFork:[],common:e.slice(i)};for(let n=0;n<s.length;n++){if(this===s[n])return{fork:[],otherFork:[t,...s.slice(0,n)],common:[this,...e]};if(r===s[n])return{fork:[this,...e.slice(0,i)],otherFork:[t,...s.slice(0,n)],common:e.slice(i)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const r=e.fork.pop(),i=e.otherFork.pop(),n=s._objects.indexOf(r),a=s._objects.indexOf(i);return n>-1&&n>a}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Es.customProperties,this.constructor.customProperties||[]);let e;const s=Y.NUM_FRACTION_DIGITS,{clipPath:r,fill:i,stroke:n,shadow:a,strokeDashArray:h,left:c,top:l,originX:u,originY:d,width:g,height:f,strokeWidth:v,strokeLineCap:_,strokeDashOffset:b,strokeLineJoin:w,strokeUniform:C,strokeMiterLimit:T,scaleX:D,scaleY:A,angle:I,flipX:E,flipY:W,opacity:q,visible:Z,backgroundColor:L,fillRule:V,paintFirst:X,globalCompositeOperation:nt,skewX:et,skewY:st}=this;r&&!r.excludeFromExport&&(e=r.toObject(t.concat("inverted","absolutePositioned")));const U=y=>K(y,s),bt=m(m({},Le(this,t)),{},{type:this.constructor.type,version:xr,originX:u,originY:d,left:U(c),top:U(l),width:U(g),height:U(f),fill:ai(i)?i.toObject():i,stroke:ai(n)?n.toObject():n,strokeWidth:U(v),strokeDashArray:h&&h.concat(),strokeLineCap:_,strokeDashOffset:b,strokeLineJoin:w,strokeUniform:C,strokeMiterLimit:U(T),scaleX:U(D),scaleY:U(A),angle:U(I),flipX:E,flipY:W,opacity:U(q),shadow:a&&a.toObject(),visible:Z,backgroundColor:L,fillRule:V,paintFirst:X,globalCompositeOperation:nt,skewX:U(et),skewY:U(st)},e?{clipPath:e}:null);return this.includeDefaultValues?bt:this._removeDefaultValues(bt)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Xr(t,(r,i)=>{if(i===N||i===mt||i==="type")return!0;const n=s[i];return r!==n&&!(Array.isArray(r)&&Array.isArray(n)&&r.length===0&&n.length===0)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=$(t,la),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:r}=s,i=$(s,ua);return $s(e,i).then(n=>r?(delete n[r],new this(e[r],n)):new this(n))}static fromObject(t,e){return this._fromObject(t,e)}};p(Ut,"stateProperties",Jo),p(Ut,"cacheProperties",re),p(Ut,"ownDefaults",Zo),p(Ut,"type","FabricObject"),p(Ut,"colorProperties",[ot,yt,"backgroundColor"]),p(Ut,"customProperties",[]),M.setClass(Ut),M.setClass(Ut,"object");const Re=(o,t,e)=>(s,r,i,n)=>{const a=t(s,r,i,n);return a&&yn(o,m(m({},_n(s,r,i,n)),e)),a};function Be(o){return(t,e,s,r)=>{const{target:i,originX:n,originY:a}=e,h=i.getRelativeCenterPoint(),c=i.translateToOriginPoint(h,n,a),l=o(t,e,s,r);return i.setPositionByOrigin(c,e.originX,e.originY),l}}const Si=Re(Ne,Be((o,t,e,s)=>{const r=Vr(t,t.originX,t.originY,e,s);if(it(t.originX)===it(R)||it(t.originX)===it(Q)&&r.x<0||it(t.originX)===it(N)&&r.x>0){const{target:i}=t,n=i.strokeWidth/(i.strokeUniform?i.scaleX:1),a=xn(t)?2:1,h=i.width,c=Math.abs(r.x*a/i.scaleX)-n;return i.set("width",Math.max(c,1)),h!==i.width}return!1}));function da(o,t,e,s,r){s=s||{};const i=this.sizeX||s.cornerSize||r.cornerSize,n=this.sizeY||s.cornerSize||r.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:r.transparentCorners,h=a?yt:ot,c=!a&&(s.cornerStrokeColor||r.cornerStrokeColor);let l,u=t,d=e;o.save(),o.fillStyle=s.cornerColor||r.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||r.cornerStrokeColor||"",i>n?(l=i,o.scale(1,n/i),d=e*i/n):n>i?(l=n,o.scale(i/n,1),u=t*n/i):l=i,o.beginPath(),o.arc(u,d,l/2,0,Ps,!1),o[h](),c&&o.stroke(),o.restore()}function ga(o,t,e,s,r){s=s||{};const i=this.sizeX||s.cornerSize||r.cornerSize,n=this.sizeY||s.cornerSize||r.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:r.transparentCorners,h=a?yt:ot,c=!a&&(s.cornerStrokeColor||r.cornerStrokeColor),l=i/2,u=n/2;o.save(),o.fillStyle=s.cornerColor||r.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||r.cornerStrokeColor||"",o.translate(t,e);const d=r.getTotalAngle();o.rotate(tt(d)),o["".concat(h,"Rect")](-l,-u,i,n),c&&o.strokeRect(-l,-u,i,n),o.restore()}class jt{constructor(t){p(this,"visible",!0),p(this,"actionName",qs),p(this,"angle",0),p(this,"x",0),p(this,"y",0),p(this,"offsetX",0),p(this,"offsetY",0),p(this,"sizeX",0),p(this,"sizeY",0),p(this,"touchSizeX",0),p(this,"touchSizeY",0),p(this,"cursorStyle","crosshair"),p(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,r){var i;let{tl:n,tr:a,br:h,bl:c}=r;return((i=e.canvas)===null||i===void 0?void 0:i.getActiveObject())===e&&e.isControlVisible(t)&&J.isPointInPolygon(s,[n,a,h,c])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,r;return(s=(r=t._controlsVisibility)===null||r===void 0?void 0:r[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,r){return new x(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,r,i,n){const a=Ir([Qe(s,r),Fe({angle:t}),Wr((i?this.touchSizeX:this.sizeX)||e,(i?this.touchSizeY:this.sizeY)||e)]);return{tl:new x(-.5,-.5).transform(a),tr:new x(.5,-.5).transform(a),br:new x(.5,.5).transform(a),bl:new x(-.5,.5).transform(a)}}render(t,e,s,r,i){((r=r||{}).cornerStyle||i.cornerStyle)==="circle"?da.call(this,t,e,s,r,i):ga.call(this,t,e,s,r,i)}}const fa=(o,t,e)=>e.lockRotation?Bs:t.cursorStyle,pa=Re(sn,Be((o,t,e,s)=>{let{target:r,ex:i,ey:n,theta:a,originX:h,originY:c}=t;const l=r.translateToOriginPoint(r.getRelativeCenterPoint(),h,c);if(It(r,"lockRotation"))return!1;const u=Math.atan2(n-l.y,i-l.x),d=Math.atan2(s-l.y,e-l.x);let g=se(d-u+a);if(r.snapAngle&&r.snapAngle>0){const v=r.snapAngle,_=r.snapThreshold||v,b=Math.ceil(g/v)*v,w=Math.floor(g/v)*v;Math.abs(g-w)<_?g=w:Math.abs(g-b)<_&&(g=b)}g<0&&(g=360+g),g%=360;const f=r.angle!==g;return r.angle=g,f}));function Pn(o,t){const e=t.canvas,s=o[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function An(o,t,e){const s=It(o,"lockScalingX"),r=It(o,"lockScalingY");if(s&&r||!t&&(s||r)&&e||s&&t==="x"||r&&t==="y")return!0;const{width:i,height:n,strokeWidth:a}=o;return i===0&&a===0&&t!=="y"||n===0&&a===0&&t!=="x"}const ma=["e","se","s","sw","w","nw","n","ne","e"],Ye=(o,t,e)=>{const s=Pn(o,e);if(An(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return Bs;const r=bn(e,t);return"".concat(ma[r],"-resize")};function Gr(o,t,e,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const i=t.target,n=r.by,a=Pn(o,i);let h,c,l,u,d,g;if(An(i,n,a))return!1;if(t.gestureScale)c=t.scaleX*t.gestureScale,l=t.scaleY*t.gestureScale;else{if(h=Vr(t,t.originX,t.originY,e,s),d=n!=="y"?Math.sign(h.x||t.signX||1):1,g=n!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=d),t.signY||(t.signY=g),It(i,"lockScalingFlip")&&(t.signX!==d||t.signY!==g))return!1;if(u=i._getTransformedDimensions(),a&&!n){const _=Math.abs(h.x)+Math.abs(h.y),{original:b}=t,w=_/(Math.abs(u.x*b.scaleX/i.scaleX)+Math.abs(u.y*b.scaleY/i.scaleY));c=b.scaleX*w,l=b.scaleY*w}else c=Math.abs(h.x*i.scaleX/u.x),l=Math.abs(h.y*i.scaleY/u.y);xn(t)&&(c*=2,l*=2),t.signX!==d&&n!=="y"&&(t.originX=ui(t.originX),c*=-1,t.signX=d),t.signY!==g&&n!=="x"&&(t.originY=ui(t.originY),l*=-1,t.signY=g)}const f=i.scaleX,v=i.scaleY;return n?(n==="x"&&i.set(_t,c),n==="y"&&i.set(Mt,l)):(!It(i,"lockScalingX")&&i.set(_t,c),!It(i,"lockScalingY")&&i.set(Mt,l)),f!==i.scaleX||v!==i.scaleY}const ss=Re(Us,Be((o,t,e,s)=>Gr(o,t,e,s))),va=Re(Us,Be((o,t,e,s)=>Gr(o,t,e,s,{by:"x"}))),ya=Re(Us,Be((o,t,e,s)=>Gr(o,t,e,s,{by:"y"}))),xa=["target","ex","ey","skewingSide"],ur={x:{counterAxis:"y",scale:_t,skew:Ae,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Mt,skew:je,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},_a=["ns","nesw","ew","nwse"],ba=(o,t,e)=>{if(t.x!==0&&It(e,"lockSkewingY")||t.y!==0&&It(e,"lockSkewingX"))return Bs;const s=bn(e,t)%4;return"".concat(_a[s],"-resize")};function jn(o,t,e,s,r){const{target:i}=e,{counterAxis:n,origin:a,lockSkewing:h,skew:c,flip:l}=ur[o];if(It(i,h))return!1;const{origin:u,flip:d}=ur[n],g=it(e[u])*(i[d]?-1:1),f=-Math.sign(g)*(i[l]?-1:1),v=.5*-((i[c]===0&&Vr(e,R,R,s,r)[o]>0||i[c]>0?1:-1)*f)+.5;return Re(rn,Be((b,w,C,T)=>function(D,A,I){let{target:E,ex:W,ey:q,skewingSide:Z}=A,L=$(A,xa);const{skew:V}=ur[D],X=I.subtract(new x(W,q)).divide(new x(E.scaleX,E.scaleY))[D],nt=E[V],et=L[V],st=Math.tan(tt(et)),U=D==="y"?E._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:E._getTransformedDimensions({scaleX:1,scaleY:1}).y,bt=2*X*Z/Math.max(U,1)+st,y=se(Math.atan(bt));E.set(V,y);const S=nt!==E[V];if(S&&D==="y"){const{skewX:k,scaleX:O}=E,j=E._getTransformedDimensions({skewY:nt}),H=E._getTransformedDimensions(),B=k!==0?j.x/H.x:1;B!==1&&E.set(_t,B*O)}return S}(o,w,new x(C,T))))(t,m(m({},e),{},{[a]:v,skewingSide:f}),s,r)}const wa=(o,t,e,s)=>jn("x",o,t,e,s),Sa=(o,t,e,s)=>jn("y",o,t,e,s);function Qs(o,t){return o[t.canvas.altActionKey]}const rs=(o,t,e)=>{const s=Qs(o,e);return t.x===0?s?Ae:Mt:t.y===0?s?je:_t:""},Ce=(o,t,e)=>Qs(o,e)?ba(0,t,e):Ye(o,t,e),Ci=(o,t,e,s)=>Qs(o,t.target)?Sa(o,t,e,s):va(o,t,e,s),Ti=(o,t,e,s)=>Qs(o,t.target)?wa(o,t,e,s):ya(o,t,e,s),Fn=()=>({ml:new jt({x:-.5,y:0,cursorStyleHandler:Ce,actionHandler:Ci,getActionName:rs}),mr:new jt({x:.5,y:0,cursorStyleHandler:Ce,actionHandler:Ci,getActionName:rs}),mb:new jt({x:0,y:.5,cursorStyleHandler:Ce,actionHandler:Ti,getActionName:rs}),mt:new jt({x:0,y:-.5,cursorStyleHandler:Ce,actionHandler:Ti,getActionName:rs}),tl:new jt({x:-.5,y:-.5,cursorStyleHandler:Ye,actionHandler:ss}),tr:new jt({x:.5,y:-.5,cursorStyleHandler:Ye,actionHandler:ss}),bl:new jt({x:-.5,y:.5,cursorStyleHandler:Ye,actionHandler:ss}),br:new jt({x:.5,y:.5,cursorStyleHandler:Ye,actionHandler:ss}),mtr:new jt({x:0,y:-.5,actionHandler:pa,cursorStyleHandler:fa,offsetY:-40,withConnection:!0,actionName:Rr})}),Ca=()=>({mr:new jt({x:.5,y:0,actionHandler:Si,cursorStyleHandler:Ce,actionName:Ne}),ml:new jt({x:-.5,y:0,actionHandler:Si,cursorStyleHandler:Ce,actionName:Ne})}),Ta=()=>m(m({},Fn()),Ca());class $e extends Ut{static getDefaults(){return m(m({},super.getDefaults()),$e.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),$e.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Fn()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,s=e.target,r=e.action;if(this===s&&r&&r.startsWith(qs))return!1}return super._updateCacheCanvas()}getActiveControl(){const t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const s=Object.entries(this.oCoords);for(let r=s.length-1;r>=0;r--){const[i,n]=s[r],a=this.controls[i];if(a.shouldActivate(i,this,t,e?n.touchCorner:n.corner))return this.__corner=i,{key:i,control:a,coord:this.oCoords[i]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=Qe(e.x,e.y),r=Fe({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),i=ct(s,r),n=ct(t,i),a=ct(n,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Ls(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const c=this._calculateCurrentDimensions(h),l={};return this.forEachControl((u,d)=>{const g=u.positionHandler(c,a,this,u);l[d]=Object.assign(g,this._calcCornerCoords(u,g))}),l}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),r=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/r[0],1/r[3]),t.rotate(tt(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const r=m({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=r.borderColor,this._setLineDash(t,r.borderDashArray),this.strokeBorders(t,e),r.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:r}=this,i=m({hasBorders:s,hasControls:r},e),n=this.getViewportTransform(),a=i.hasBorders,h=i.hasControls,c=ct(n,this.calcTransformMatrix()),l=Ls(c);t.save(),t.translate(l.translateX,l.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(l.angle-=180),t.rotate(tt(this.group?l.angle:this.angle)),a&&this.drawBorders(t,l,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let r;if(s&&s.forActiveSelection||this.group){const i=Yr(this.width,this.height,Ks(e)),n=this.isStrokeAccountedForInDimensions()?Br:(this.strokeUniform?new x().scalarAdd(this.canvas?this.canvas.getZoom():1):new x(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);r=i.add(n).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else r=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,r,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl((r,i)=>{r.withConnection&&r.getVisibility(this,i)&&(s=!0,t.moveTo(r.x*e.x,r.y*e.y),t.lineTo(r.x*e.x+r.offsetX,r.y*e.y+r.offsetY))}),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:i,cornerColor:n}=this,a=m({cornerStrokeColor:r,cornerDashArray:i,cornerColor:n},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=a.cornerColor,this.transparentCorners||(t.strokeStyle=a.cornerStrokeColor),this._setLineDash(t,a.cornerDashArray),this.forEachControl((h,c)=>{if(h.getVisibility(this,c)){const l=this.oCoords[c];h.render(t,l.x,l.y,a,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,r]=e;return this.setControlVisible(s,r)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const r=this.width+4,i=this.height+4;return e.clearRect(-r/2,-i/2,r,i),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 Ln(o,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(o.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),o}p($e,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class ut extends $e{}Ln(ut,[wn]),M.setClass(ut),M.setClass(ut,"object");const Oa=(o,t,e,s)=>{const r=2*(s=Math.round(s))+1,{data:i}=o.getImageData(t-s,e-s,r,r);for(let n=3;n<i.length;n+=4)if(i[n]>0)return!1;return!0};class Rn{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new x(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new x(1/this.options.scaleX,1/this.options.scaleY):new x(1,1)}createSideVector(t,e){const s=Sr(t,e);return this.options.strokeUniform?s.multiply(this.scale):s}projectOrthogonally(t,e,s){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,s)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(t){const e=new x(t);return e.y+=e.x*Math.tan(tt(this.options.skewY)),e.x+=e.y*Math.tan(tt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const ka=new x;class Me extends Rn{static getOrthogonalRotationFactor(t,e){const s=e?Tr(t,e):Ko(t);return Math.abs(s)<Ze?-1:1}constructor(t,e,s,r){super(r),p(this,"AB",void 0),p(this,"AC",void 0),p(this,"alpha",void 0),p(this,"bisector",void 0),this.A=new x(t),this.B=new x(e),this.C=new x(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Tr(this.AB,this.AC),this.bisector=Hr(Dn(this.AB.eq(ka)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const r=this.createSideVector(t,e),i=Mn(r),n=Me.getOrthogonalRotationFactor(i,this.bisector);return this.scaleUnitVector(i,s*n)}projectBevel(){const t=[];return(this.alpha%Ps==0?[this.B]:[this.B,this.C]).forEach(e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))}),t}projectMiter(){const t=[],e=Math.abs(this.alpha),s=1/Math.sin(e/2),r=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*s),i=this.options.strokeUniform?Cr(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Cr(r)/this.strokeProjectionMagnitude<=i&&t.push(this.applySkew(this.A.add(r))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],r=new x(Me.getOrthogonalRotationFactor(this.bisector),Me.getOrthogonalRotationFactor(new x(this.bisector.y,this.bisector.x)));return[new x(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r),new x(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r)].forEach(i=>{_i(i,t,e)&&s.push(this.A.add(i))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:r,skewY:i,scaleX:n,scaleY:a,strokeUniform:h}=this.options,c=new x(Math.tan(tt(r)),Math.tan(tt(i))),l=this.strokeProjectionMagnitude,u=h?l/a/Math.sqrt(1/a**2+1/n**2*c.y**2):l/Math.sqrt(1+c.y**2),d=new x(Math.sqrt(Math.max(l**2-u**2,0)),u),g=h?l/Math.sqrt(1+c.x**2*(1/a)**2/(1/n+1/n*c.x*c.y)**2):l/Math.sqrt(1+c.x**2/(1+c.x*c.y)**2),f=new x(g,Math.sqrt(Math.max(l**2-g**2,0)));return[f,f.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(v=>this.applySkew(h?v.multiply(this.strokeUniformScalar):v)).forEach(v=>{_i(v,t,e)&&s.push(this.applySkew(this.A).add(v))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Ps==0,s=this.applySkew(this.A),r=t[e?0:2].subtract(s),i=t[e?1:0].subtract(s),n=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),a=Ge(r,n)>0,h=a?r:i,c=a?i:r;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,c)):t.push(...this.projectRoundNoSkew(h,c)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class Oi extends Rn{constructor(t,e,s){super(s),this.A=new x(t),this.T=new x(e)}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const r=this.createSideVector(t,e);return this.scaleUnitVector(Mn(r),s)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){const t=[];if(!this.isSkewed()&&this.A.eq(this.T)){const e=new x(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 Me(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new x(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{const e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),s=this.scaleUnitVector(Hr(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),r=this.A.add(s);t.push(r.add(e),r.subtract(e))}return t.map(e=>this.applySkew(e))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}const Da=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(o.length===0)return s;const r=o.reduce((i,n)=>(i[i.length-1].eq(n)||i.push(new x(n)),i),[new x(o[0])]);if(r.length===1)e=!0;else if(!e){const i=r[0],n=((a,h)=>{for(let c=a.length-1;c>=0;c--)if(h(a[c],c,a))return c;return-1})(r,a=>!a.eq(i));r.splice(n+1)}return r.forEach((i,n,a)=>{let h,c;n===0?(c=a[1],h=e?i:a[a.length-1]):n===a.length-1?(h=a[n-1],c=e?i:a[0]):(h=a[n-1],c=a[n+1]),e&&a.length===1?s.push(...new Oi(i,i,t).project()):!e||n!==0&&n!==a.length-1?s.push(...new Me(i,h,c,t).project()):s.push(...new Oi(i,n===0?c:h,t).project())}),s},Nr=o=>{const t={};return Object.keys(o).forEach(e=>{t[e]={},Object.keys(o[e]).forEach(s=>{t[e][s]=m({},o[e][s])})}),t},Ma=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let We;const Ur=o=>{if(We||We||(We="Intl"in Ns()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),We){const t=We.segment(o);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return Ea(o)},Ea=o=>{const t=[];for(let e,s=0;s<o.length;s++)(e=Pa(o,s))!==!1&&t.push(e);return t},Pa=(o,t)=>{const e=o.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return o.charAt(t);if(55296<=e&&e<=56319){if(o.length<=t+1)throw"High surrogate without following low surrogate";const r=o.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return o.charAt(t)+o.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=o.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1},qr=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return o.fill!==t.fill||o.stroke!==t.stroke||o.strokeWidth!==t.strokeWidth||o.fontSize!==t.fontSize||o.fontFamily!==t.fontFamily||o.fontWeight!==t.fontWeight||o.fontStyle!==t.fontStyle||o.textDecorationThickness!==t.textDecorationThickness||o.textBackgroundColor!==t.textBackgroundColor||o.deltaY!==t.deltaY||e&&(o.overline!==t.overline||o.underline!==t.underline||o.linethrough!==t.linethrough)},Aa=(o,t)=>{const e=t.split(`
38
- `),s=[];let r=-1,i={};o=Nr(o);for(let n=0;n<e.length;n++){const a=Ur(e[n]);if(o[n])for(let h=0;h<a.length;h++){r++;const c=o[n][h];c&&Object.keys(c).length>0&&(qr(i,c,!0)?s.push({start:r,end:r+1,style:c}):s[s.length-1].end++),i=c||{}}else r+=a.length,i={}}return s},ja=(o,t)=>{if(!Array.isArray(o))return Nr(o);const e=t.split(Lr),s={};let r=-1,i=0;for(let n=0;n<e.length;n++){const a=Ur(e[n]);for(let h=0;h<a.length;h++)r++,o[i]&&o[i].start<=r&&r<o[i].end&&(s[n]=s[n]||{},s[n][h]=m({},o[i].style),r===o[i].end-1&&i++)}return s},ue=["display","transform",ot,"fill-opacity","fill-rule","opacity",yt,"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 ki(o,t){const e=o.nodeName,s=o.getAttribute("class"),r=o.getAttribute("id"),i="(?![a-zA-Z\\-]+)";let n;if(n=new RegExp("^"+e,"i"),t=t.replace(n,""),r&&t.length&&(n=new RegExp("#"+r+i,"i"),t=t.replace(n,"")),s&&t.length){const a=s.split(" ");for(let h=a.length;h--;)n=new RegExp("\\."+a[h]+i,"i"),t=t.replace(n,"")}return t.length===0}function Fa(o,t){let e=!0;const s=ki(o,t.pop());return s&&t.length&&(e=function(r,i){let n,a=!0;for(;r.parentElement&&r.parentElement.nodeType===1&&i.length;)a&&(n=i.pop()),a=ki(r=r.parentElement,n);return i.length===0}(o,t)),s&&e&&t.length===0}const La=o=>{var t;return(t=Uo[o])!==null&&t!==void 0?t:o},Ra=new RegExp("(".concat(Bt,")"),"gi"),Ba=o=>Is(o.replace(Ra," $1 ").replace(/,/gi," "));var Di,Mi,Ei,Pi,Ai,ji,Fi;const gt="(".concat(Bt,")"),Ia=String.raw(Di||(Di=Nt(["(skewX)(",")"],["(skewX)\\(","\\)"])),gt),Wa=String.raw(Mi||(Mi=Nt(["(skewY)(",")"],["(skewY)\\(","\\)"])),gt),Xa=String.raw(Ei||(Ei=Nt(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),gt,gt,gt),Ya=String.raw(Pi||(Pi=Nt(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),gt,gt),Va=String.raw(Ai||(Ai=Nt(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),gt,gt),Ha=String.raw(ji||(ji=Nt(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),gt,gt,gt,gt,gt,gt),Kr="(?:".concat(Ha,"|").concat(Va,"|").concat(Xa,"|").concat(Ya,"|").concat(Ia,"|").concat(Wa,")"),za="(?:".concat(Kr,"*)"),Ga=String.raw(Fi||(Fi=Nt(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),za),Na=new RegExp(Ga),Ua=new RegExp(Kr),qa=new RegExp(Kr,"g");function Or(o){const t=[];if(!(o=Ba(o).replace(/\s*([()])\s*/gi,"$1"))||o&&!Na.test(o))return[...ft];for(const e of o.matchAll(qa)){const s=Ua.exec(e[0]);if(!s)continue;let r=ft;const i=s.filter(f=>!!f),[,n,...a]=i,[h,c,l,u,d,g]=a.map(f=>parseFloat(f));switch(n){case"translate":r=Qe(h,c);break;case Rr:r=Fe({angle:h},{x:c,y:l});break;case qs:r=Wr(h,c);break;case Ae:r=un(h);break;case je:r=dn(h);break;case"matrix":r=[h,c,l,u,d,g]}t.push(r)}return Ir(t)}function Ka(o,t,e,s){const r=Array.isArray(t);let i,n=t;if(o!==ot&&o!==yt||t!==vt){if(o==="strokeUniform")return t==="non-scaling-stroke";if(o==="strokeDashArray")n=t===vt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(o==="transformMatrix")n=e&&e.transformMatrix?ct(e.transformMatrix,Or(t)):Or(t);else if(o==="visible")n=t!==vt&&t!=="hidden",e&&e.visible===!1&&(n=!1);else if(o==="opacity")n=parseFloat(t),e&&e.opacity!==void 0&&(n*=e.opacity);else if(o==="textAnchor")n=t==="start"?N:t==="end"?Q:R;else if(o==="charSpacing"||o===me)i=De(t,s)/s*1e3;else if(o==="paintFirst"){const a=t.indexOf(ot),h=t.indexOf(yt);n=ot,(a>-1&&h>-1&&h<a||a===-1&&h>-1)&&(n=yt)}else{if(o==="href"||o==="xlink:href"||o==="font"||o==="id")return t;if(o==="imageSmoothing")return t==="optimizeQuality";i=r?t.map(De):De(t,s)}}else n="";return!r&&isNaN(i)?n:i}function $a(o,t){const e=o.match(No);if(!e)return;const s=e[1],r=e[3],i=e[4],n=e[5],a=e[6];s&&(t.fontStyle=s),r&&(t.fontWeight=isNaN(parseFloat(r))?r:parseFloat(r)),i&&(t.fontSize=De(i)),a&&(t.fontFamily=a),n&&(t.lineHeight=n==="normal"?1:n)}function Ja(o,t){o.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,r]=e.split(":");t[s.trim().toLowerCase()]=r.trim()})}function Za(o){const t={},e=o.getAttribute("style");return e&&(typeof e=="string"?Ja(e,t):function(s,r){Object.entries(s).forEach(i=>{let[n,a]=i;a!==void 0&&(r[n.toLowerCase()]=a)})}(e,t)),t}const Qa={stroke:"strokeOpacity",fill:"fillOpacity"};function ie(o,t,e){if(!o)return{};let s,r={},i=Fr;o.parentNode&&xi.test(o.parentNode.nodeName)&&(r=ie(o.parentElement,t,e),r.fontSize&&(s=i=De(r.fontSize)));const n=m(m(m({},t.reduce((c,l)=>{const u=o.getAttribute(l);return u&&(c[l]=u),c},{})),function(c){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const d in l)Fa(c,d.split(" "))&&(u=m(m({},u),l[d]));return u}(o,e)),Za(o));n[cr]&&o.setAttribute(cr,n[cr]),n[hr]&&(s=De(n[hr],i),n[hr]="".concat(s));const a={};for(const c in n){const l=La(c),u=Ka(l,n[c],r,s);a[l]=u}a&&a.font&&$a(a.font,a);const h=m(m({},r),a);return xi.test(o.nodeName)?h:function(c){const l=ut.getDefaults();return Object.entries(Qa).forEach(u=>{let[d,g]=u;if(c[g]===void 0||c[d]==="")return;if(c[d]===void 0){if(!l[d])return;c[d]=l[d]}if(c[d].indexOf("url(")===0)return;const f=new G(c[d]);c[d]=f.setAlpha(K(f.getAlpha()*c[g],2)).toRgba()}),c}(h)}const th=["left","top","width","height","visible"],Bn=["rx","ry"];class kt extends ut{static getDefaults(){return m(m({},super.getDefaults()),kt.ownDefaults)}constructor(t){super(),Object.assign(this,kt.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){const{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){const{width:e,height:s}=this,r=-e/2,i=-s/2,n=this.rx?Math.min(this.rx,e/2):0,a=this.ry?Math.min(this.ry,s/2):0,h=n!==0||a!==0;t.beginPath(),t.moveTo(r+n,i),t.lineTo(r+e-n,i),h&&t.bezierCurveTo(r+e-ne*n,i,r+e,i+ne*a,r+e,i+a),t.lineTo(r+e,i+s-a),h&&t.bezierCurveTo(r+e,i+s-ne*a,r+e-ne*n,i+s,r+e-n,i+s),t.lineTo(r+n,i+s),h&&t.bezierCurveTo(r+ne*n,i+s,r,i+s-ne*a,r,i+s-a),t.lineTo(r,i+a),h&&t.bezierCurveTo(r,i+ne*a,r+ne*n,i,r+n,i),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Bn,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:r}=this;return["<rect ","COMMON_PARTS",'x="'.concat(-t/2,'" y="').concat(-e/2,'" rx="').concat(s,'" ry="').concat(r,'" width="').concat(t,'" height="').concat(e,`" />
39
- `)]}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{left:i=0,top:n=0,width:a=0,height:h=0,visible:c=!0}=r,l=$(r,th);return new this(m(m(m({},e),l),{},{left:i,top:n,width:a,height:h,visible:!!(c&&a&&h)}))}}p(kt,"type","Rect"),p(kt,"cacheProperties",[...re,...Bn]),p(kt,"ownDefaults",{rx:0,ry:0}),p(kt,"ATTRIBUTE_NAMES",[...ue,"x","y","rx","ry","width","height"]),M.setClass(kt),M.setSVGClass(kt);const Kt="initialization",Xs="added",$r="removed",Ys="imperative",In=(o,t)=>{const{strokeUniform:e,strokeWidth:s,width:r,height:i,group:n}=t,a=n&&n!==o?Js(n.calcTransformMatrix(),o.calcTransformMatrix()):null,h=a?t.getRelativeCenterPoint().transform(a):t.getRelativeCenterPoint(),c=!t.isStrokeAccountedForInDimensions(),l=e&&c?Wo(new x(s,s),void 0,o.calcTransformMatrix()):Br,u=!e&&c?s:0,d=Yr(r+u,i+u,Ir([a,t.calcOwnMatrix()],!0)).add(l).scalarDivide(2);return[h.subtract(d),h.add(d)]};class tr{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:r}=t;return e===Kt||e===Ys||!!s&&r!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Kt&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:r}=e;if(s===Ys&&e.overrides)return e.overrides;if(t.length===0)return;const{left:i,top:n,width:a,height:h}=Zt(t.map(u=>In(r,u)).reduce((u,d)=>u.concat(d),[])),c=new x(a,h),l=new x(i,n).add(c.scalarDivide(2));if(s===Kt){const u=this.getInitialSize(e,{size:c,center:l});return{center:l,relativeCorrection:new x(0,0),size:u}}return{center:l.transform(r.calcOwnMatrix()),size:c}}}p(tr,"type","strategy");class kr extends tr{shouldPerformLayout(t){return!0}}p(kr,"type","fit-content"),M.setClass(kr);const eh=["strategy"],sh=["target","strategy","bubbles","prevStrategy"],Wn="layoutManager";class Je{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new kr;p(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=m(m({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[js,en,Ne,sn,Us,rn,As,Co,To].map(r=>t.on(r,i=>this.performLayout(r===js?{type:"object_modified",trigger:r,e:i,target:s}:{type:"object_modifying",trigger:r,e:i,target:s})))}subscribe(t,e){this.unsubscribe(t,e);const s=this.attachHandlers(t,e);this._subscriptions.set(t,s)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(s=>s()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){const{target:e,type:s}=t,{canvas:r}=e;if(s===Kt||s===Xs?this.subscribeTargets(t):s===$r&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),r&&r.fire("object:layout:before",{target:e,context:t}),s===Ys&&t.deep){const i=$(t,eh);e.forEachObject(n=>n.layoutManager&&n.layoutManager.performLayout(m(m({},i),{},{bubbles:!1,target:n})))}}getLayoutResult(t){const{target:e,strategy:s,type:r}=t,i=s.calcLayoutResult(t,e.getObjects());if(!i)return;const n=r===Kt?new x:e.getRelativeCenterPoint(),{center:a,correction:h=new x,relativeCorrection:c=new x}=i,l=n.subtract(a).add(h).transform(r===Kt?ft:Rt(e.calcOwnMatrix()),!0).add(c);return{result:i,prevCenter:n,nextCenter:a,offset:l}}commitLayout(t,e){const{target:s}=t,{result:{size:r},nextCenter:i}=e;var n,a;s.set({width:r.x,height:r.y}),this.layoutObjects(t,e),t.type===Kt?s.set({left:(n=t.x)!==null&&n!==void 0?n:i.x+r.x*it(s.originX),top:(a=t.y)!==null&&a!==void 0?a:i.y+r.y*it(s.originY)}):(s.setPositionByOrigin(i,R,R),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject(r=>{r.group===s&&this.layoutObject(t,e,r)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:r}=e;s.set({left:s.left+r.x,top:s.top+r.y})}onAfterLayout(t,e){const{target:s,strategy:r,bubbles:i,prevStrategy:n}=t,a=$(t,sh),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const c=s.parent;i&&c!=null&&c.layoutManager&&((a.path||(a.path=[])).push(s),c.layoutManager.performLayout(m(m({},a),{},{target:c}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Wn,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}M.setClass(Je,Wn);const rh=["type","objects","layoutManager"];class ih extends Je{performLayout(){}}class pe extends nn(ut){static getDefaults(){return m(m({},super.getDefaults()),pe.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),p(this,"_activeObjects",[]),p(this,"__objectSelectionTracker",void 0),p(this,"__objectSelectionDisposer",void 0),Object.assign(this,pe.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var s;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(r=>{this.enterGroup(r,!1)}),this.layoutManager=(s=e.layoutManager)!==null&&s!==void 0?s:new Je,this.layoutManager.performLayout({type:Kt,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(ce("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(ce("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((e,s,r)=>this.canEnterGroup(e)&&r.indexOf(e)===s)}add(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];const r=this._filterObjectsBeforeEnteringGroup(e),i=super.add(...r);return this._onAfterObjectsChange(Xs,r),i}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;r<e;r++)s[r-1]=arguments[r];const i=this._filterObjectsBeforeEnteringGroup(s),n=super.insertAt(t,...i);return this._onAfterObjectsChange(Xs,i),n}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange($r,t),t}_onObjectAdded(t){this.enterGroup(t,!0),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t,e){this.exitGroup(t,e),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onAfterObjectsChange(t,e){this.layoutManager.performLayout({type:t,targets:e,target:this})}_onStackOrderChanged(){this._set("dirty",!0)}_set(t,e){const s=this[t];return super._set(t,e),t==="canvas"&&s!==e&&(this._objects||[]).forEach(r=>{r._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:s}=e;const r=this._activeObjects;if(t)r.push(s),this._set("dirty",!0);else if(r.length>0){const i=r.indexOf(s);i>-1&&(r.splice(i,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&&Rs(t,ct(Rt(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const s=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();s&&(s===t||t.isDescendantOf(s))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(Rs(t,ct(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=ut.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let i=0;i<this._objects.length;i++){var r;const n=this._objects[i];(r=this.canvas)!==null&&r!==void 0&&r.preserveObjectStacking&&n.group!==this?(t.save(),t.transform(...Rt(this.calcTransformMatrix())),n.render(t),t.restore()):n.group===this&&n.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(m({target:this,type:Ys},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter(function(r){return!r.excludeFromExport}).map(function(r){const i=r.includeDefaultValues;r.includeDefaultValues=s;const n=r[t||"toObject"](e);return r.includeDefaultValues=i,n})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return m(m(m({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=kt.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const r=e.join("");return t?t(r):r}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
37
+ `)}toObject(){const t={color:this.color,blur:this.blur,offsetX:this.offsetX,offsetY:this.offsetY,affectStroke:this.affectStroke,nonScaling:this.nonScaling,type:this.constructor.type},e=zt.ownDefaults;return this.includeDefaultValues?t:Xr(t,(s,r)=>s!==e[r])}static async fromObject(t){return new this(t)}}p(zt,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),p(zt,"type","shadow"),M.setClass(zt,"shadow");const Ee=(o,t,e)=>Math.max(o,Math.min(t,e)),ta=[mt,N,_t,Mt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Ae,je],re=[ot,yt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],ea={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:N,originY:mt,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:ot,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},sa=(o,t,e,s)=>-e*Math.cos(o/s*Ze)+e+t,ra=()=>!1;class zr{constructor(t){let{startValue:e,byValue:s,duration:r=500,delay:i=0,easing:n=sa,onStart:a=Os,onChange:h=Os,onComplete:c=Os,abort:l=ra,target:u}=t;p(this,"_state","pending"),p(this,"durationProgress",0),p(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=r,this.delay=i,this.easing=n,this._onStart=a,this._onChange=h,this._onComplete=c,this._abort=l,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>Ds(t),this.delay):Ds(t)}tick(t){const e=(t||+new Date)-this.startTime,s=Math.min(e,this.duration);this.durationProgress=s/this.duration;const{value:r,valueProgress:i}=this.calculate(s);this.value=Object.freeze(r),this.valueProgress=i,this._state!=="aborted"&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),Ds(this.tick)))}register(){Fs.push(this)}unregister(){Fs.remove(this)}abort(){this._state="aborted",this.unregister()}}const ia=["startValue","endValue"];class na extends zr{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(m(m({},$(t,ia)),{},{startValue:e,byValue:s-e}))}calculate(t){const e=this.easing(t,this.startValue,this.byValue,this.duration);return{value:e,valueProgress:Math.abs((e-this.startValue)/this.byValue)}}}const oa=["startValue","endValue"];class aa extends zr{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(m(m({},$(t,oa)),{},{startValue:e,byValue:s.map((r,i)=>r-e[i])}))}calculate(t){const e=this.startValue.map((s,r)=>this.easing(t,s,this.byValue[r],this.duration,r));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const ha=["startValue","endValue","easing","onChange","onComplete","abort"],ca=(o,t,e,s)=>t+e*(1-Math.cos(o/s*Ze)),lr=o=>o&&((t,e,s)=>o(new G(t).toRgba(),e,s));class la extends zr{constructor(t){let{startValue:e,endValue:s,easing:r=ca,onChange:i,onComplete:n,abort:a}=t,h=$(t,ha);const c=new G(e).getSource(),l=new G(s).getSource();super(m(m({},h),{},{startValue:c,byValue:l.map((u,d)=>u-c[d]),easing:r,onChange:lr(i),onComplete:lr(n),abort:lr(a)}))}calculate(t){const[e,s,r,i]=this.startValue.map((a,h)=>this.easing(t,a,this.byValue[h],this.duration,h)),n=[...[e,s,r].map(Math.round),Ee(0,i,1)];return{value:n,valueProgress:n.map((a,h)=>this.byValue[h]!==0?Math.abs((a-this.startValue[h])/this.byValue[h]):0).find(a=>a!==0)||0}}}function Pn(o){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(o)?new aa(o):new na(o);return t.start(),t}function ua(o){const t=new la(o);return t.start(),t}class J{constructor(t){this.status=t,this.points=[]}includes(t){return this.points.some(e=>e.eq(t))}append(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return this.points=this.points.concat(e.filter(r=>!this.includes(r))),this}static isPointContained(t,e,s){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(e.eq(s))return t.eq(e);if(e.x===s.x)return t.x===e.x&&(r||t.y>=Math.min(e.y,s.y)&&t.y<=Math.max(e.y,s.y));if(e.y===s.y)return t.y===e.y&&(r||t.x>=Math.min(e.x,s.x)&&t.x<=Math.max(e.x,s.x));{const i=Sr(e,s),n=Sr(e,t).divide(i);return r?Math.abs(n.x)===Math.abs(n.y):n.x===n.y&&n.x>=0&&n.x<=1}}static isPointInPolygon(t,e){const s=new x(t).setX(Math.min(t.x-1,...e.map(i=>i.x)));let r=0;for(let i=0;i<e.length;i++){const n=this.intersectSegmentSegment(e[i],e[(i+1)%e.length],t,s);if(n.includes(t))return!0;r+=+(n.status==="Intersection")}return r%2==1}static intersectLineLine(t,e,s,r){let i=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],n=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const a=e.x-t.x,h=e.y-t.y,c=r.x-s.x,l=r.y-s.y,u=t.x-s.x,d=t.y-s.y,g=c*d-l*u,f=a*d-h*u,v=l*a-c*h;if(v!==0){const _=g/v,b=f/v;return(i||0<=_&&_<=1)&&(n||0<=b&&b<=1)?new J("Intersection").append(new x(t.x+_*a,t.y+_*h)):new J}if(g===0||f===0){const _=i||n||J.isPointContained(t,s,r)||J.isPointContained(e,s,r)||J.isPointContained(s,t,e)||J.isPointContained(r,t,e);return new J(_?"Coincident":void 0)}return new J("Parallel")}static intersectSegmentLine(t,e,s,r){return J.intersectLineLine(t,e,s,r,!1,!0)}static intersectSegmentSegment(t,e,s,r){return J.intersectLineLine(t,e,s,r,!1,!1)}static intersectLinePolygon(t,e,s){let r=!(arguments.length>3&&arguments[3]!==void 0)||arguments[3];const i=new J,n=s.length;for(let a,h,c,l=0;l<n;l++){if(a=s[l],h=s[(l+1)%n],c=J.intersectLineLine(t,e,a,h,r,!1),c.status==="Coincident")return c;i.append(...c.points)}return i.points.length>0&&(i.status="Intersection"),i}static intersectSegmentPolygon(t,e,s){return J.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new J,r=t.length,i=[];for(let n=0;n<r;n++){const a=t[n],h=t[(n+1)%r],c=J.intersectSegmentPolygon(a,h,e);c.status==="Coincident"?(i.push(c),s.append(a,h)):s.append(...c.points)}return i.length>0&&i.length===t.length?new J("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const r=e.min(s),i=e.max(s),n=new x(i.x,r.y),a=new x(r.x,i.y);return J.intersectPolygonPolygon(t,[r,n,i,a])}}class da extends an{getX(){return this.getXY().x}setX(t){this.setXY(this.getXY().setX(t))}getY(){return this.getXY().y}setY(t){this.setXY(this.getXY().setY(t))}getRelativeX(){return this.left}setRelativeX(t){this.left=t}getRelativeY(){return this.top}setRelativeY(t){this.top=t}getXY(){const t=this.getRelativeXY();return this.group?pt(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=pt(t,Rt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new x(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.originX,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.originY;this.setPositionByOrigin(t,e,s)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:s,bl:r}=this.aCoords||(this.aCoords=this.calcACoords()),i=[t,e,s,r];if(this.group){const n=this.group.calcTransformMatrix();return i.map(a=>pt(a,n))}return i}intersectsWithRect(t,e){return J.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=J.intersectPolygonPolygon(this.getCoords(),t.getCoords());return e.status==="Intersection"||e.status==="Coincident"||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:s,top:r,width:i,height:n}=this.getBoundingRect();return s>=t.x&&s+i<=e.x&&r>=t.y&&r+n<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return J.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return!!this.getCoords().some(s=>s.x<=e.x&&s.x>=t.x&&s.y<=e.y&&s.y>=t.y)||!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;return this.intersectsWithRect(t,e)?!0:this.getCoords().every(s=>(s.x>=e.x||s.x<=t.x)&&(s.y>=e.y||s.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return Zt(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(_t,t),this._set(Mt,t),this.setCoords()}scaleToWidth(t){const e=this.getBoundingRect().width/this.getScaledWidth();return this.scale(t/this.width/e)}scaleToHeight(t){const e=this.getBoundingRect().height/this.getScaledHeight();return this.scale(t/this.height/e)}getCanvasRetinaScaling(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?se(ln(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||ft.concat()}calcACoords(){const t=Fe({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),r=Qe(e,s),i=ct(r,t),n=this._getTransformedDimensions(),a=n.x/2,h=n.y/2;return{tl:pt({x:-a,y:-h},i),tr:pt({x:a,y:-h},i),bl:pt({x:-a,y:h},i),br:pt({x:a,y:h},i)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=[];return!t&&this.group&&(e=this.group.transformMatrixKey(t)),e.push(this.top,this.left,this.width,this.height,this.scaleX,this.scaleY,this.angle,this.strokeWidth,this.skewX,this.skewY,+this.flipX,+this.flipY,it(this.originX),it(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const s=this.transformMatrixKey(t),r=this.matrixCache;return r&&r.key.every((i,n)=>i===s[n])?r.value:(this.group&&(e=ct(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:s,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const s=this.getRelativeCenterPoint(),r={angle:this.angle,translateX:s.x,translateY:s.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},i=Fo(r);return this.ownMatrixCache={key:t,value:i},i}_getNonTransformedDimensions(){return new x(this.width,this.height).scalarAdd(this.strokeWidth)}_calculateCurrentDimensions(t){return this._getTransformedDimensions(t).transform(this.getViewportTransform(),!0).scalarAdd(2*this.padding)}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=m({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,width:this.width,height:this.height,strokeWidth:this.strokeWidth},t),s=e.strokeWidth;let r=s,i=0;this.strokeUniform&&(r=0,i=s);const n=e.width+r,a=e.height+r;let h;return h=e.skewX===0&&e.skewY===0?new x(n*e.scaleX,a*e.scaleY):Yr(n,a,Ks(e)),h.scalarAdd(i)}translateToGivenOrigin(t,e,s,r,i){let n=t.x,a=t.y;const h=it(r)-it(e),c=it(i)-it(s);if(h||c){const l=this._getTransformedDimensions();n+=h*l.x,a+=c*l.y}return new x(n,a)}translateToCenterPoint(t,e,s){if(e===R&&s===R)return t;const r=this.translateToGivenOrigin(t,e,s,R,R);return this.angle?r.rotate(tt(this.angle),t):r}translateToOriginPoint(t,e,s){const r=this.translateToGivenOrigin(t,R,R,e,s);return this.angle?r.rotate(tt(this.angle),t):r}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?pt(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new x(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,s){const r=this.translateToCenterPoint(t,e,s),i=this.translateToOriginPoint(r,this.originX,this.originY);this.set({left:i.x,top:i.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),N,mt)}}const ga=["type"],fa=["extraParam"];let Ut=class Es extends da{static getDefaults(){return Es.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){ce("warn","Setting type has no effect",t)}constructor(t){super(),p(this,"_cacheContext",null),Object.assign(this,Es.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=ee(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,r=Y.maxCacheSideLimit,i=Y.minCacheSideLimit;if(e<=r&&s<=r&&e*s<=Y.perfLimitSizeTotal)return e<i&&(t.width=i),s<i&&(t.height=i),t;const n=e/s,[a,h]=Ve.limitDimsByArea(n),c=Ee(i,a,r),l=Ee(i,h,r);return e>c&&(t.zoomX/=e/c,t.width=c,t.capped=!0),s>l&&(t.zoomY/=s/l,t.height=l,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,r=e.y*t.y/this.scaleY;return{width:Math.ceil(s+2),height:Math.ceil(r+2),zoomX:t.x,zoomY:t.y,x:s,y:r}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:s,height:r,zoomX:i,zoomY:n,x:a,y:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),c=s!==t.width||r!==t.height,l=this.zoomX!==i||this.zoomY!==n;if(!t||!e)return!1;if(c||l){s!==t.width||r!==t.height?(t.width=s,t.height=r):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const u=a/2,d=h/2;return this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-d)+d,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(i,n),this.zoomX=i,this.zoomY=n,!0}return!1}setOptions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,s=this.calcTransformMatrix(!e);t.transform(s[0],s[1],s[2],s[3],s[4],s[5])}getObjectScaling(){if(!this.group)return new x(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Ls(this.calcTransformMatrix());return new x(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),s=this.getCanvasRetinaScaling();return t.scalarMultiply(e*s)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:t===0?1e-4:t}_set(t,e){t!==_t&&t!==Mt||(e=this._constrainScale(e)),t===_t&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof zt||(e=new zt(e));const s=this[t]!==e;return this[t]=e,s&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||s&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return this.opacity===0||!this.width&&!this.height&&this.strokeWidth===0||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:s,cacheTranslationX:r,cacheTranslationY:i}=this,{width:n,height:a}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:r,cacheTranslationY:i,width:n,height:a,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return this.stroke&&this.stroke!=="transparent"&&this.strokeWidth!==0}hasFill(){return this.fill&&this.fill!=="transparent"}needsItsOwnCache(){return!!(this.paintFirst===yt&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(this.shadow.offsetX!==0||this.shadow.offsetY!==0)}drawClipPathOnCache(t,e,s){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(s,0,0),t.restore()}drawObject(t,e,s){const r=this.fill,i=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,s),this.fill=r,this.stroke=i}createClipPathLayer(t,e){const s=Et(e),r=s.getContext("2d");if(r.translate(e.cacheTranslationX,e.cacheTranslationY),r.scale(e.zoomX,e.zoomY),t._cacheCanvas=s,e.parentClipPaths.forEach(i=>{i.transform(r)}),e.parentClipPaths.push(t),t.absolutePositioned){const i=Rt(this.calcTransformMatrix());r.transform(i[0],i[1],i[2],i[3],i[4],i[5])}return t.transform(r),t.drawObject(r,!0,e),s}_drawClipPath(t,e,s){if(!e)return;e._transformDone=!0;const r=this.createClipPathLayer(e,s);this.drawClipPathOnCache(t,e,r)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,s=this._cacheContext;return!(!e||!s||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&s&&!t&&(s.save(),s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,e.width,e.height),s.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;const e=this._getNonTransformedDimensions();t.fillStyle=this.backgroundColor,t.fillRect(-e.x/2,-e.y/2,e.x,e.y),this._removeShadow(t)}_setOpacity(t){this.group&&!this.group._transformDone?t.globalAlpha=this.getObjectOpacity():t.globalAlpha*=this.opacity}_setStrokeStyles(t,e){const s=e.stroke;s&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,Dt(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?this._applyPatternForTransformedGradient(t,s):(t.strokeStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:s}=e;s&&(Dt(s)?(t.fillStyle=s.toLive(t),this._applyPatternGradientTransform(t,s)):t.fillStyle=s)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&e.length!==0&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const e=this.shadow,s=this.canvas,r=this.getCanvasRetinaScaling(),[i,,,n]=(s==null?void 0:s.viewportTransform)||ft,a=i*r,h=n*r,c=e.nonScaling?new x(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*Y.browserShadowBlurConstant*(a+h)*(c.x+c.y)/4,t.shadowOffsetX=e.offsetX*a*c.x,t.shadowOffsetY=e.offsetY*h*c.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!Dt(e))return{offsetX:0,offsetY:0};const s=e.gradientTransform||e.patternTransform,r=-this.width/2+e.offsetX||0,i=-this.height/2+e.offsetY||0;return e.gradientUnits==="percentage"?t.transform(this.width,0,0,this.height,r,i):t.transform(1,0,0,1,r,i),s&&t.transform(s[0],s[1],s[2],s[3],s[4],s[5]),{offsetX:r,offsetY:i}}_renderPaintInOrder(t){this.paintFirst===yt?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),this.fillRule==="evenodd"?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&this.strokeWidth!==0){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){const e=this.getObjectScaling();t.scale(1/e.x,1/e.y)}this._setLineDash(t,this.strokeDashArray),this._setStrokeStyles(t,this),t.stroke(),t.restore()}}_applyPatternForTransformedGradient(t,e){var s;const r=this._limitCacheSize(this._getCacheCanvasDimensions()),i=this.getCanvasRetinaScaling(),n=r.x/this.scaleX/i,a=r.y/this.scaleY/i,h=Et({width:Math.ceil(n),height:Math.ceil(a)}),c=h.getContext("2d");c&&(c.beginPath(),c.moveTo(0,0),c.lineTo(n,0),c.lineTo(n,a),c.lineTo(0,a),c.closePath(),c.translate(n/2,a/2),c.scale(r.zoomX/this.scaleX/i,r.zoomY/this.scaleY/i),this._applyPatternGradientTransform(c,e),c.fillStyle=e.toLive(t),c.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(i*this.scaleX/r.zoomX,i*this.scaleY/r.zoomY),t.strokeStyle=(s=c.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new x(this.left+this.width/2,this.top+this.height/2)}clone(t){const e=this.toObject(t);return this.constructor.fromObject(e)}cloneAsImage(t){const e=this.toCanvasElement(t);return new(M.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=yn(this),s=this.group,r=this.shadow,i=Math.abs,n=t.enableRetinaScaling?en():1,a=(t.multiplier||1)*n,h=t.canvasProvider||(w=>new ts(w,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Yo(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Ho(this,this.getViewportTransform()),this.setCoords();const c=ee(),l=this.getBoundingRect(),u=this.shadow,d=new x;if(u){const w=u.blur,C=u.nonScaling?new x(1,1):this.getObjectScaling();d.x=2*Math.round(i(u.offsetX)+w)*i(C.x),d.y=2*Math.round(i(u.offsetY)+w)*i(C.y)}const g=l.width+d.x,f=l.height+d.y;c.width=Math.ceil(g),c.height=Math.ceil(f);const v=h(c);t.format==="jpeg"&&(v.backgroundColor="#fff"),this.setPositionByOrigin(new x(v.width/2,v.height/2),R,R);const _=this.canvas;v._objects=[this],this.set("canvas",v),this.setCoords();const b=v.toCanvasElement(a||1,t);return this.set("canvas",_),this.shadow=r,s&&(this.group=s),this.set(e),this.setCoords(),v._objects=[],v.destroy(),b}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return hn(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return cn(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:s,originY:r}=this;if(e){const{x:i,y:n}=this.getRelativeCenterPoint();this.originX=R,this.originY=R,this.left=i,this.top=n}if(this.set("angle",t),e){const{x:i,y:n}=this.translateToOriginPoint(this.getRelativeCenterPoint(),s,r);this.left=i,this.top=n,this.originX=s,this.originY=r}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){Fs.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Gt().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,r)=>{let[i,n]=r;return s[i]=this._animate(i,n,e),s},{})}_animate(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const r=t.split("."),i=this.constructor.colorProperties.includes(r[r.length-1]),{abort:n,startValue:a,onChange:h,onComplete:c}=s,l=m(m({},s),{},{target:this,startValue:a??r.reduce((u,d)=>u[d],this),endValue:e,abort:n==null?void 0:n.bind(this),onChange:(u,d,g)=>{r.reduce((f,v,_)=>(_===r.length-1&&(f[v]=u),f[v]),this),h&&h(u,d,g)},onComplete:(u,d,g)=>{this.setCoords(),c&&c(u,d,g)}});return i?ua(l):Pn(l)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let r,i=0;i<e.length;i++){if(r=e[i],r===t)return{fork:[this,...e.slice(0,i)],otherFork:[],common:e.slice(i)};for(let n=0;n<s.length;n++){if(this===s[n])return{fork:[],otherFork:[t,...s.slice(0,n)],common:[this,...e]};if(r===s[n])return{fork:[this,...e.slice(0,i)],otherFork:[t,...s.slice(0,n)],common:e.slice(i)}}}return{fork:[this,...e],otherFork:[t,...s],common:[]}}hasCommonAncestors(t){const e=this.findCommonAncestors(t);return e&&!!e.common.length}isInFrontOf(t){if(this===t)return;const e=this.findCommonAncestors(t);if(e.fork.includes(t))return!0;if(e.otherFork.includes(this))return!1;const s=e.common[0]||this.canvas;if(!s)return;const r=e.fork.pop(),i=e.otherFork.pop(),n=s._objects.indexOf(r),a=s._objects.indexOf(i);return n>-1&&n>a}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(Es.customProperties,this.constructor.customProperties||[]);let e;const s=Y.NUM_FRACTION_DIGITS,{clipPath:r,fill:i,stroke:n,shadow:a,strokeDashArray:h,left:c,top:l,originX:u,originY:d,width:g,height:f,strokeWidth:v,strokeLineCap:_,strokeDashOffset:b,strokeLineJoin:w,strokeUniform:C,strokeMiterLimit:T,scaleX:D,scaleY:A,angle:I,flipX:E,flipY:W,opacity:q,visible:Z,backgroundColor:L,fillRule:V,paintFirst:X,globalCompositeOperation:nt,skewX:et,skewY:st}=this;r&&!r.excludeFromExport&&(e=r.toObject(t.concat("inverted","absolutePositioned")));const U=y=>K(y,s),bt=m(m({},Le(this,t)),{},{type:this.constructor.type,version:xr,originX:u,originY:d,left:U(c),top:U(l),width:U(g),height:U(f),fill:ai(i)?i.toObject():i,stroke:ai(n)?n.toObject():n,strokeWidth:U(v),strokeDashArray:h&&h.concat(),strokeLineCap:_,strokeDashOffset:b,strokeLineJoin:w,strokeUniform:C,strokeMiterLimit:U(T),scaleX:U(D),scaleY:U(A),angle:U(I),flipX:E,flipY:W,opacity:U(q),shadow:a&&a.toObject(),visible:Z,backgroundColor:L,fillRule:V,paintFirst:X,globalCompositeOperation:nt,skewX:U(et),skewY:U(st)},e?{clipPath:e}:null);return this.includeDefaultValues?bt:this._removeDefaultValues(bt)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Xr(t,(r,i)=>{if(i===N||i===mt||i==="type")return!0;const n=s[i];return r!==n&&!(Array.isArray(r)&&Array.isArray(n)&&r.length===0&&n.length===0)})}toString(){return"#<".concat(this.constructor.type,">")}static _fromObject(t){let e=$(t,ga),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:r}=s,i=$(s,fa);return $s(e,i).then(n=>r?(delete n[r],new this(e[r],n)):new this(n))}static fromObject(t,e){return this._fromObject(t,e)}};p(Ut,"stateProperties",ta),p(Ut,"cacheProperties",re),p(Ut,"ownDefaults",ea),p(Ut,"type","FabricObject"),p(Ut,"colorProperties",[ot,yt,"backgroundColor"]),p(Ut,"customProperties",[]),M.setClass(Ut),M.setClass(Ut,"object");const Re=(o,t,e)=>(s,r,i,n)=>{const a=t(s,r,i,n);return a&&xn(o,m(m({},bn(s,r,i,n)),e)),a};function Be(o){return(t,e,s,r)=>{const{target:i,originX:n,originY:a}=e,h=i.getRelativeCenterPoint(),c=i.translateToOriginPoint(h,n,a),l=o(t,e,s,r);return i.setPositionByOrigin(c,e.originX,e.originY),l}}const Si=Re(Ne,Be((o,t,e,s)=>{const r=Vr(t,t.originX,t.originY,e,s);if(it(t.originX)===it(R)||it(t.originX)===it(Q)&&r.x<0||it(t.originX)===it(N)&&r.x>0){const{target:i}=t,n=i.strokeWidth/(i.strokeUniform?i.scaleX:1),a=_n(t)?2:1,h=i.width,c=Math.abs(r.x*a/i.scaleX)-n;return i.set("width",Math.max(c,1)),h!==i.width}return!1}));function pa(o,t,e,s,r){s=s||{};const i=this.sizeX||s.cornerSize||r.cornerSize,n=this.sizeY||s.cornerSize||r.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:r.transparentCorners,h=a?yt:ot,c=!a&&(s.cornerStrokeColor||r.cornerStrokeColor);let l,u=t,d=e;o.save(),o.fillStyle=s.cornerColor||r.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||r.cornerStrokeColor||"",i>n?(l=i,o.scale(1,n/i),d=e*i/n):n>i?(l=n,o.scale(i/n,1),u=t*n/i):l=i,o.beginPath(),o.arc(u,d,l/2,0,Ps,!1),o[h](),c&&o.stroke(),o.restore()}function ma(o,t,e,s,r){s=s||{};const i=this.sizeX||s.cornerSize||r.cornerSize,n=this.sizeY||s.cornerSize||r.cornerSize,a=s.transparentCorners!==void 0?s.transparentCorners:r.transparentCorners,h=a?yt:ot,c=!a&&(s.cornerStrokeColor||r.cornerStrokeColor),l=i/2,u=n/2;o.save(),o.fillStyle=s.cornerColor||r.cornerColor||"",o.strokeStyle=s.cornerStrokeColor||r.cornerStrokeColor||"",o.translate(t,e);const d=r.getTotalAngle();o.rotate(tt(d)),o["".concat(h,"Rect")](-l,-u,i,n),c&&o.strokeRect(-l,-u,i,n),o.restore()}class jt{constructor(t){p(this,"visible",!0),p(this,"actionName",qs),p(this,"angle",0),p(this,"x",0),p(this,"y",0),p(this,"offsetX",0),p(this,"offsetY",0),p(this,"sizeX",0),p(this,"sizeY",0),p(this,"touchSizeX",0),p(this,"touchSizeY",0),p(this,"cursorStyle","crosshair"),p(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,r){var i;let{tl:n,tr:a,br:h,bl:c}=r;return((i=e.canvas)===null||i===void 0?void 0:i.getActiveObject())===e&&e.isControlVisible(t)&&J.isPointInPolygon(s,[n,a,h,c])}getActionHandler(t,e,s){return this.actionHandler}getMouseDownHandler(t,e,s){return this.mouseDownHandler}getMouseUpHandler(t,e,s){return this.mouseUpHandler}cursorStyleHandler(t,e,s){return e.cursorStyle}getActionName(t,e,s){return e.actionName}getVisibility(t,e){var s,r;return(s=(r=t._controlsVisibility)===null||r===void 0?void 0:r[e])!==null&&s!==void 0?s:this.visible}setVisibility(t,e,s){this.visible=t}positionHandler(t,e,s,r){return new x(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,r,i,n){const a=Ir([Qe(s,r),Fe({angle:t}),Wr((i?this.touchSizeX:this.sizeX)||e,(i?this.touchSizeY:this.sizeY)||e)]);return{tl:new x(-.5,-.5).transform(a),tr:new x(.5,-.5).transform(a),br:new x(.5,.5).transform(a),bl:new x(-.5,.5).transform(a)}}render(t,e,s,r,i){((r=r||{}).cornerStyle||i.cornerStyle)==="circle"?pa.call(this,t,e,s,r,i):ma.call(this,t,e,s,r,i)}}const va=(o,t,e)=>e.lockRotation?Bs:t.cursorStyle,ya=Re(rn,Be((o,t,e,s)=>{let{target:r,ex:i,ey:n,theta:a,originX:h,originY:c}=t;const l=r.translateToOriginPoint(r.getRelativeCenterPoint(),h,c);if(It(r,"lockRotation"))return!1;const u=Math.atan2(n-l.y,i-l.x),d=Math.atan2(s-l.y,e-l.x);let g=se(d-u+a);if(r.snapAngle&&r.snapAngle>0){const v=r.snapAngle,_=r.snapThreshold||v,b=Math.ceil(g/v)*v,w=Math.floor(g/v)*v;Math.abs(g-w)<_?g=w:Math.abs(g-b)<_&&(g=b)}g<0&&(g=360+g),g%=360;const f=r.angle!==g;return r.angle=g,f}));function An(o,t){const e=t.canvas,s=o[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function jn(o,t,e){const s=It(o,"lockScalingX"),r=It(o,"lockScalingY");if(s&&r||!t&&(s||r)&&e||s&&t==="x"||r&&t==="y")return!0;const{width:i,height:n,strokeWidth:a}=o;return i===0&&a===0&&t!=="y"||n===0&&a===0&&t!=="x"}const xa=["e","se","s","sw","w","nw","n","ne","e"],Ye=(o,t,e)=>{const s=An(o,e);if(jn(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return Bs;const r=wn(e,t);return"".concat(xa[r],"-resize")};function Gr(o,t,e,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const i=t.target,n=r.by,a=An(o,i);let h,c,l,u,d,g;if(jn(i,n,a))return!1;if(t.gestureScale)c=t.scaleX*t.gestureScale,l=t.scaleY*t.gestureScale;else{if(h=Vr(t,t.originX,t.originY,e,s),d=n!=="y"?Math.sign(h.x||t.signX||1):1,g=n!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=d),t.signY||(t.signY=g),It(i,"lockScalingFlip")&&(t.signX!==d||t.signY!==g))return!1;if(u=i._getTransformedDimensions(),a&&!n){const _=Math.abs(h.x)+Math.abs(h.y),{original:b}=t,w=_/(Math.abs(u.x*b.scaleX/i.scaleX)+Math.abs(u.y*b.scaleY/i.scaleY));c=b.scaleX*w,l=b.scaleY*w}else c=Math.abs(h.x*i.scaleX/u.x),l=Math.abs(h.y*i.scaleY/u.y);_n(t)&&(c*=2,l*=2),t.signX!==d&&n!=="y"&&(t.originX=ui(t.originX),c*=-1,t.signX=d),t.signY!==g&&n!=="x"&&(t.originY=ui(t.originY),l*=-1,t.signY=g)}const f=i.scaleX,v=i.scaleY;return n?(n==="x"&&i.set(_t,c),n==="y"&&i.set(Mt,l)):(!It(i,"lockScalingX")&&i.set(_t,c),!It(i,"lockScalingY")&&i.set(Mt,l)),f!==i.scaleX||v!==i.scaleY}const ss=Re(Us,Be((o,t,e,s)=>Gr(o,t,e,s))),_a=Re(Us,Be((o,t,e,s)=>Gr(o,t,e,s,{by:"x"}))),ba=Re(Us,Be((o,t,e,s)=>Gr(o,t,e,s,{by:"y"}))),wa=["target","ex","ey","skewingSide"],ur={x:{counterAxis:"y",scale:_t,skew:Ae,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Mt,skew:je,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Sa=["ns","nesw","ew","nwse"],Ca=(o,t,e)=>{if(t.x!==0&&It(e,"lockSkewingY")||t.y!==0&&It(e,"lockSkewingX"))return Bs;const s=wn(e,t)%4;return"".concat(Sa[s],"-resize")};function Fn(o,t,e,s,r){const{target:i}=e,{counterAxis:n,origin:a,lockSkewing:h,skew:c,flip:l}=ur[o];if(It(i,h))return!1;const{origin:u,flip:d}=ur[n],g=it(e[u])*(i[d]?-1:1),f=-Math.sign(g)*(i[l]?-1:1),v=.5*-((i[c]===0&&Vr(e,R,R,s,r)[o]>0||i[c]>0?1:-1)*f)+.5;return Re(nn,Be((b,w,C,T)=>function(D,A,I){let{target:E,ex:W,ey:q,skewingSide:Z}=A,L=$(A,wa);const{skew:V}=ur[D],X=I.subtract(new x(W,q)).divide(new x(E.scaleX,E.scaleY))[D],nt=E[V],et=L[V],st=Math.tan(tt(et)),U=D==="y"?E._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:E._getTransformedDimensions({scaleX:1,scaleY:1}).y,bt=2*X*Z/Math.max(U,1)+st,y=se(Math.atan(bt));E.set(V,y);const S=nt!==E[V];if(S&&D==="y"){const{skewX:k,scaleX:O}=E,j=E._getTransformedDimensions({skewY:nt}),H=E._getTransformedDimensions(),B=k!==0?j.x/H.x:1;B!==1&&E.set(_t,B*O)}return S}(o,w,new x(C,T))))(t,m(m({},e),{},{[a]:v,skewingSide:f}),s,r)}const Ta=(o,t,e,s)=>Fn("x",o,t,e,s),Oa=(o,t,e,s)=>Fn("y",o,t,e,s);function Qs(o,t){return o[t.canvas.altActionKey]}const rs=(o,t,e)=>{const s=Qs(o,e);return t.x===0?s?Ae:Mt:t.y===0?s?je:_t:""},Ce=(o,t,e)=>Qs(o,e)?Ca(0,t,e):Ye(o,t,e),Ci=(o,t,e,s)=>Qs(o,t.target)?Oa(o,t,e,s):_a(o,t,e,s),Ti=(o,t,e,s)=>Qs(o,t.target)?Ta(o,t,e,s):ba(o,t,e,s),Ln=()=>({ml:new jt({x:-.5,y:0,cursorStyleHandler:Ce,actionHandler:Ci,getActionName:rs}),mr:new jt({x:.5,y:0,cursorStyleHandler:Ce,actionHandler:Ci,getActionName:rs}),mb:new jt({x:0,y:.5,cursorStyleHandler:Ce,actionHandler:Ti,getActionName:rs}),mt:new jt({x:0,y:-.5,cursorStyleHandler:Ce,actionHandler:Ti,getActionName:rs}),tl:new jt({x:-.5,y:-.5,cursorStyleHandler:Ye,actionHandler:ss}),tr:new jt({x:.5,y:-.5,cursorStyleHandler:Ye,actionHandler:ss}),bl:new jt({x:-.5,y:.5,cursorStyleHandler:Ye,actionHandler:ss}),br:new jt({x:.5,y:.5,cursorStyleHandler:Ye,actionHandler:ss}),mtr:new jt({x:0,y:-.5,actionHandler:ya,cursorStyleHandler:va,offsetY:-40,withConnection:!0,actionName:Rr})}),ka=()=>({mr:new jt({x:.5,y:0,actionHandler:Si,cursorStyleHandler:Ce,actionName:Ne}),ml:new jt({x:-.5,y:0,actionHandler:Si,cursorStyleHandler:Ce,actionName:Ne})}),Da=()=>m(m({},Ln()),ka());class $e extends Ut{static getDefaults(){return m(m({},super.getDefaults()),$e.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),$e.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Ln()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,s=e.target,r=e.action;if(this===s&&r&&r.startsWith(qs))return!1}return super._updateCacheCanvas()}getActiveControl(){const t=this.__corner;return t?{key:t,control:this.controls[t],coord:this.oCoords[t]}:void 0}findControl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const s=Object.entries(this.oCoords);for(let r=s.length-1;r>=0;r--){const[i,n]=s[r],a=this.controls[i];if(a.shouldActivate(i,this,t,e?n.touchCorner:n.corner))return this.__corner=i,{key:i,control:a,coord:this.oCoords[i]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=Qe(e.x,e.y),r=Fe({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),i=ct(s,r),n=ct(t,i),a=ct(n,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Ls(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const c=this._calculateCurrentDimensions(h),l={};return this.forEachControl((u,d)=>{const g=u.positionHandler(c,a,this,u);l[d]=Object.assign(g,this._calcCornerCoords(u,g))}),l}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),r=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/r[0],1/r[3]),t.rotate(tt(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-s.x/2,-s.y/2,s.x,s.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};const r=m({hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray},s);t.save(),t.strokeStyle=r.borderColor,this._setLineDash(t,r.borderDashArray),this.strokeBorders(t,e),r.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const{hasBorders:s,hasControls:r}=this,i=m({hasBorders:s,hasControls:r},e),n=this.getViewportTransform(),a=i.hasBorders,h=i.hasControls,c=ct(n,this.calcTransformMatrix()),l=Ls(c);t.save(),t.translate(l.translateX,l.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(l.angle-=180),t.rotate(tt(this.group?l.angle:this.angle)),a&&this.drawBorders(t,l,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let r;if(s&&s.forActiveSelection||this.group){const i=Yr(this.width,this.height,Ks(e)),n=this.isStrokeAccountedForInDimensions()?Br:(this.strokeUniform?new x().scalarAdd(this.canvas?this.canvas.getZoom():1):new x(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);r=i.add(n).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else r=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this._drawBorders(t,r,s)}drawControlsConnectingLines(t,e){let s=!1;t.beginPath(),this.forEachControl((r,i)=>{r.withConnection&&r.getVisibility(this,i)&&(s=!0,t.moveTo(r.x*e.x,r.y*e.y),t.lineTo(r.x*e.x+r.offsetX,r.y*e.y+r.offsetY))}),s&&t.stroke()}drawControls(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:i,cornerColor:n}=this,a=m({cornerStrokeColor:r,cornerDashArray:i,cornerColor:n},e);t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=a.cornerColor,this.transparentCorners||(t.strokeStyle=a.cornerStrokeColor),this._setLineDash(t,a.cornerDashArray),this.forEachControl((h,c)=>{if(h.getVisibility(this,c)){const l=this.oCoords[c];h.render(t,l.x,l.y,a,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,r]=e;return this.setControlVisible(s,r)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const s=this.canvas.viewportTransform;e.save(),e.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this.transform(e);const r=this.width+4,i=this.height+4;return e.clearRect(-r/2,-i/2,r,i),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 Rn(o,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(o.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),o}p($e,"ownDefaults",{noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:13,touchCornerSize:24,transparentCorners:!0,cornerColor:"rgb(178,204,255)",cornerStrokeColor:"",cornerStyle:"rect",cornerDashArray:null,hasControls:!0,borderColor:"rgb(178,204,255)",borderDashArray:null,borderOpacityWhenMoving:.4,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null});class ut extends $e{}Rn(ut,[Sn]),M.setClass(ut),M.setClass(ut,"object");const Ma=(o,t,e,s)=>{const r=2*(s=Math.round(s))+1,{data:i}=o.getImageData(t-s,e-s,r,r);for(let n=3;n<i.length;n+=4)if(i[n]>0)return!1;return!0};class Bn{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new x(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new x(1/this.options.scaleX,1/this.options.scaleY):new x(1,1)}createSideVector(t,e){const s=Sr(t,e);return this.options.strokeUniform?s.multiply(this.scale):s}projectOrthogonally(t,e,s){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,s)))}isSkewed(){return this.options.skewX!==0||this.options.skewY!==0}applySkew(t){const e=new x(t);return e.y+=e.x*Math.tan(tt(this.options.skewY)),e.x+=e.y*Math.tan(tt(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const Ea=new x;class Me extends Bn{static getOrthogonalRotationFactor(t,e){const s=e?Tr(t,e):Zo(t);return Math.abs(s)<Ze?-1:1}constructor(t,e,s,r){super(r),p(this,"AB",void 0),p(this,"AC",void 0),p(this,"alpha",void 0),p(this,"bisector",void 0),this.A=new x(t),this.B=new x(e),this.C=new x(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Tr(this.AB,this.AC),this.bisector=Hr(Mn(this.AB.eq(Ea)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const r=this.createSideVector(t,e),i=En(r),n=Me.getOrthogonalRotationFactor(i,this.bisector);return this.scaleUnitVector(i,s*n)}projectBevel(){const t=[];return(this.alpha%Ps==0?[this.B]:[this.B,this.C]).forEach(e=>{t.push(this.projectOrthogonally(this.A,e)),t.push(this.projectOrthogonally(this.A,e,-this.strokeProjectionMagnitude))}),t}projectMiter(){const t=[],e=Math.abs(this.alpha),s=1/Math.sin(e/2),r=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*s),i=this.options.strokeUniform?Cr(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return Cr(r)/this.strokeProjectionMagnitude<=i&&t.push(this.applySkew(this.A.add(r))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],r=new x(Me.getOrthogonalRotationFactor(this.bisector),Me.getOrthogonalRotationFactor(new x(this.bisector.y,this.bisector.x)));return[new x(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r),new x(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r)].forEach(i=>{_i(i,t,e)&&s.push(this.A.add(i))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:r,skewY:i,scaleX:n,scaleY:a,strokeUniform:h}=this.options,c=new x(Math.tan(tt(r)),Math.tan(tt(i))),l=this.strokeProjectionMagnitude,u=h?l/a/Math.sqrt(1/a**2+1/n**2*c.y**2):l/Math.sqrt(1+c.y**2),d=new x(Math.sqrt(Math.max(l**2-u**2,0)),u),g=h?l/Math.sqrt(1+c.x**2*(1/a)**2/(1/n+1/n*c.x*c.y)**2):l/Math.sqrt(1+c.x**2/(1+c.x*c.y)**2),f=new x(g,Math.sqrt(Math.max(l**2-g**2,0)));return[f,f.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(v=>this.applySkew(h?v.multiply(this.strokeUniformScalar):v)).forEach(v=>{_i(v,t,e)&&s.push(this.applySkew(this.A).add(v))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Ps==0,s=this.applySkew(this.A),r=t[e?0:2].subtract(s),i=t[e?1:0].subtract(s),n=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),a=Ge(r,n)>0,h=a?r:i,c=a?i:r;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,c)):t.push(...this.projectRoundNoSkew(h,c)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class Oi extends Bn{constructor(t,e,s){super(s),this.A=new x(t),this.T=new x(e)}calcOrthogonalProjection(t,e){let s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.strokeProjectionMagnitude;const r=this.createSideVector(t,e);return this.scaleUnitVector(En(r),s)}projectButt(){return[this.projectOrthogonally(this.A,this.T,this.strokeProjectionMagnitude),this.projectOrthogonally(this.A,this.T,-this.strokeProjectionMagnitude)]}projectRound(){const t=[];if(!this.isSkewed()&&this.A.eq(this.T)){const e=new x(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 Me(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new x(1,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar);t.push(this.A.add(e),this.A.subtract(e))}else{const e=this.calcOrthogonalProjection(this.A,this.T,this.strokeProjectionMagnitude),s=this.scaleUnitVector(Hr(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),r=this.A.add(s);t.push(r.add(e),r.subtract(e))}return t.map(e=>this.applySkew(e))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}const Pa=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(o.length===0)return s;const r=o.reduce((i,n)=>(i[i.length-1].eq(n)||i.push(new x(n)),i),[new x(o[0])]);if(r.length===1)e=!0;else if(!e){const i=r[0],n=((a,h)=>{for(let c=a.length-1;c>=0;c--)if(h(a[c],c,a))return c;return-1})(r,a=>!a.eq(i));r.splice(n+1)}return r.forEach((i,n,a)=>{let h,c;n===0?(c=a[1],h=e?i:a[a.length-1]):n===a.length-1?(h=a[n-1],c=e?i:a[0]):(h=a[n-1],c=a[n+1]),e&&a.length===1?s.push(...new Oi(i,i,t).project()):!e||n!==0&&n!==a.length-1?s.push(...new Me(i,h,c,t).project()):s.push(...new Oi(i,n===0?c:h,t).project())}),s},Nr=o=>{const t={};return Object.keys(o).forEach(e=>{t[e]={},Object.keys(o[e]).forEach(s=>{t[e][s]=m({},o[e][s])})}),t},Aa=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let We;const Ur=o=>{if(We||We||(We="Intl"in Ns()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),We){const t=We.segment(o);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return ja(o)},ja=o=>{const t=[];for(let e,s=0;s<o.length;s++)(e=Fa(o,s))!==!1&&t.push(e);return t},Fa=(o,t)=>{const e=o.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return o.charAt(t);if(55296<=e&&e<=56319){if(o.length<=t+1)throw"High surrogate without following low surrogate";const r=o.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return o.charAt(t)+o.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=o.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1},qr=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return o.fill!==t.fill||o.stroke!==t.stroke||o.strokeWidth!==t.strokeWidth||o.fontSize!==t.fontSize||o.fontFamily!==t.fontFamily||o.fontWeight!==t.fontWeight||o.fontStyle!==t.fontStyle||o.textDecorationThickness!==t.textDecorationThickness||o.textBackgroundColor!==t.textBackgroundColor||o.deltaY!==t.deltaY||e&&(o.overline!==t.overline||o.underline!==t.underline||o.linethrough!==t.linethrough)},La=(o,t)=>{const e=t.split(`
38
+ `),s=[];let r=-1,i={};o=Nr(o);for(let n=0;n<e.length;n++){const a=Ur(e[n]);if(o[n])for(let h=0;h<a.length;h++){r++;const c=o[n][h];c&&Object.keys(c).length>0&&(qr(i,c,!0)?s.push({start:r,end:r+1,style:c}):s[s.length-1].end++),i=c||{}}else r+=a.length,i={}}return s},Ra=(o,t)=>{if(!Array.isArray(o))return Nr(o);const e=t.split(Lr),s={};let r=-1,i=0;for(let n=0;n<e.length;n++){const a=Ur(e[n]);for(let h=0;h<a.length;h++)r++,o[i]&&o[i].start<=r&&r<o[i].end&&(s[n]=s[n]||{},s[n][h]=m({},o[i].style),r===o[i].end-1&&i++)}return s},ue=["display","transform",ot,"fill-opacity","fill-rule","opacity",yt,"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 ki(o,t){const e=o.nodeName,s=o.getAttribute("class"),r=o.getAttribute("id"),i="(?![a-zA-Z\\-]+)";let n;if(n=new RegExp("^"+e,"i"),t=t.replace(n,""),r&&t.length&&(n=new RegExp("#"+r+i,"i"),t=t.replace(n,"")),s&&t.length){const a=s.split(" ");for(let h=a.length;h--;)n=new RegExp("\\."+a[h]+i,"i"),t=t.replace(n,"")}return t.length===0}function Ba(o,t){let e=!0;const s=ki(o,t.pop());return s&&t.length&&(e=function(r,i){let n,a=!0;for(;r.parentElement&&r.parentElement.nodeType===1&&i.length;)a&&(n=i.pop()),a=ki(r=r.parentElement,n);return i.length===0}(o,t)),s&&e&&t.length===0}const Ia=o=>{var t;return(t=$o[o])!==null&&t!==void 0?t:o},Wa=new RegExp("(".concat(Bt,")"),"gi"),Xa=o=>Is(o.replace(Wa," $1 ").replace(/,/gi," "));var Di,Mi,Ei,Pi,Ai,ji,Fi;const gt="(".concat(Bt,")"),Ya=String.raw(Di||(Di=Nt(["(skewX)(",")"],["(skewX)\\(","\\)"])),gt),Va=String.raw(Mi||(Mi=Nt(["(skewY)(",")"],["(skewY)\\(","\\)"])),gt),Ha=String.raw(Ei||(Ei=Nt(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),gt,gt,gt),za=String.raw(Pi||(Pi=Nt(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),gt,gt),Ga=String.raw(Ai||(Ai=Nt(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),gt,gt),Na=String.raw(ji||(ji=Nt(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),gt,gt,gt,gt,gt,gt),Kr="(?:".concat(Na,"|").concat(Ga,"|").concat(Ha,"|").concat(za,"|").concat(Ya,"|").concat(Va,")"),Ua="(?:".concat(Kr,"*)"),qa=String.raw(Fi||(Fi=Nt(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),Ua),Ka=new RegExp(qa),$a=new RegExp(Kr),Ja=new RegExp(Kr,"g");function Or(o){const t=[];if(!(o=Xa(o).replace(/\s*([()])\s*/gi,"$1"))||o&&!Ka.test(o))return[...ft];for(const e of o.matchAll(Ja)){const s=$a.exec(e[0]);if(!s)continue;let r=ft;const i=s.filter(f=>!!f),[,n,...a]=i,[h,c,l,u,d,g]=a.map(f=>parseFloat(f));switch(n){case"translate":r=Qe(h,c);break;case Rr:r=Fe({angle:h},{x:c,y:l});break;case qs:r=Wr(h,c);break;case Ae:r=dn(h);break;case je:r=gn(h);break;case"matrix":r=[h,c,l,u,d,g]}t.push(r)}return Ir(t)}function Za(o,t,e,s){const r=Array.isArray(t);let i,n=t;if(o!==ot&&o!==yt||t!==vt){if(o==="strokeUniform")return t==="non-scaling-stroke";if(o==="strokeDashArray")n=t===vt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(o==="transformMatrix")n=e&&e.transformMatrix?ct(e.transformMatrix,Or(t)):Or(t);else if(o==="visible")n=t!==vt&&t!=="hidden",e&&e.visible===!1&&(n=!1);else if(o==="opacity")n=parseFloat(t),e&&e.opacity!==void 0&&(n*=e.opacity);else if(o==="textAnchor")n=t==="start"?N:t==="end"?Q:R;else if(o==="charSpacing"||o===me)i=De(t,s)/s*1e3;else if(o==="paintFirst"){const a=t.indexOf(ot),h=t.indexOf(yt);n=ot,(a>-1&&h>-1&&h<a||a===-1&&h>-1)&&(n=yt)}else{if(o==="href"||o==="xlink:href"||o==="font"||o==="id")return t;if(o==="imageSmoothing")return t==="optimizeQuality";i=r?t.map(De):De(t,s)}}else n="";return!r&&isNaN(i)?n:i}function Qa(o,t){const e=o.match(Ko);if(!e)return;const s=e[1],r=e[3],i=e[4],n=e[5],a=e[6];s&&(t.fontStyle=s),r&&(t.fontWeight=isNaN(parseFloat(r))?r:parseFloat(r)),i&&(t.fontSize=De(i)),a&&(t.fontFamily=a),n&&(t.lineHeight=n==="normal"?1:n)}function th(o,t){o.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,r]=e.split(":");t[s.trim().toLowerCase()]=r.trim()})}function eh(o){const t={},e=o.getAttribute("style");return e&&(typeof e=="string"?th(e,t):function(s,r){Object.entries(s).forEach(i=>{let[n,a]=i;a!==void 0&&(r[n.toLowerCase()]=a)})}(e,t)),t}const sh={stroke:"strokeOpacity",fill:"fillOpacity"};function ie(o,t,e){if(!o)return{};let s,r={},i=Fr;o.parentNode&&xi.test(o.parentNode.nodeName)&&(r=ie(o.parentElement,t,e),r.fontSize&&(s=i=De(r.fontSize)));const n=m(m(m({},t.reduce((c,l)=>{const u=o.getAttribute(l);return u&&(c[l]=u),c},{})),function(c){let l=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},u={};for(const d in l)Ba(c,d.split(" "))&&(u=m(m({},u),l[d]));return u}(o,e)),eh(o));n[cr]&&o.setAttribute(cr,n[cr]),n[hr]&&(s=De(n[hr],i),n[hr]="".concat(s));const a={};for(const c in n){const l=Ia(c),u=Za(l,n[c],r,s);a[l]=u}a&&a.font&&Qa(a.font,a);const h=m(m({},r),a);return xi.test(o.nodeName)?h:function(c){const l=ut.getDefaults();return Object.entries(sh).forEach(u=>{let[d,g]=u;if(c[g]===void 0||c[d]==="")return;if(c[d]===void 0){if(!l[d])return;c[d]=l[d]}if(c[d].indexOf("url(")===0)return;const f=new G(c[d]);c[d]=f.setAlpha(K(f.getAlpha()*c[g],2)).toRgba()}),c}(h)}const rh=["left","top","width","height","visible"],In=["rx","ry"];class kt extends ut{static getDefaults(){return m(m({},super.getDefaults()),kt.ownDefaults)}constructor(t){super(),Object.assign(this,kt.ownDefaults),this.setOptions(t),this._initRxRy()}_initRxRy(){const{rx:t,ry:e}=this;t&&!e?this.ry=t:e&&!t&&(this.rx=e)}_render(t){const{width:e,height:s}=this,r=-e/2,i=-s/2,n=this.rx?Math.min(this.rx,e/2):0,a=this.ry?Math.min(this.ry,s/2):0,h=n!==0||a!==0;t.beginPath(),t.moveTo(r+n,i),t.lineTo(r+e-n,i),h&&t.bezierCurveTo(r+e-ne*n,i,r+e,i+ne*a,r+e,i+a),t.lineTo(r+e,i+s-a),h&&t.bezierCurveTo(r+e,i+s-ne*a,r+e-ne*n,i+s,r+e-n,i+s),t.lineTo(r+n,i+s),h&&t.bezierCurveTo(r+ne*n,i+s,r,i+s-ne*a,r,i+s-a),t.lineTo(r,i+a),h&&t.bezierCurveTo(r,i+ne*a,r+ne*n,i,r+n,i),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...In,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:r}=this;return["<rect ","COMMON_PARTS",'x="'.concat(-t/2,'" y="').concat(-e/2,'" rx="').concat(s,'" ry="').concat(r,'" width="').concat(t,'" height="').concat(e,`" />
39
+ `)]}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{left:i=0,top:n=0,width:a=0,height:h=0,visible:c=!0}=r,l=$(r,rh);return new this(m(m(m({},e),l),{},{left:i,top:n,width:a,height:h,visible:!!(c&&a&&h)}))}}p(kt,"type","Rect"),p(kt,"cacheProperties",[...re,...In]),p(kt,"ownDefaults",{rx:0,ry:0}),p(kt,"ATTRIBUTE_NAMES",[...ue,"x","y","rx","ry","width","height"]),M.setClass(kt),M.setSVGClass(kt);const Kt="initialization",Xs="added",$r="removed",Ys="imperative",Wn=(o,t)=>{const{strokeUniform:e,strokeWidth:s,width:r,height:i,group:n}=t,a=n&&n!==o?Js(n.calcTransformMatrix(),o.calcTransformMatrix()):null,h=a?t.getRelativeCenterPoint().transform(a):t.getRelativeCenterPoint(),c=!t.isStrokeAccountedForInDimensions(),l=e&&c?Vo(new x(s,s),void 0,o.calcTransformMatrix()):Br,u=!e&&c?s:0,d=Yr(r+u,i+u,Ir([a,t.calcOwnMatrix()],!0)).add(l).scalarDivide(2);return[h.subtract(d),h.add(d)]};class tr{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:r}=t;return e===Kt||e===Ys||!!s&&r!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Kt&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:r}=e;if(s===Ys&&e.overrides)return e.overrides;if(t.length===0)return;const{left:i,top:n,width:a,height:h}=Zt(t.map(u=>Wn(r,u)).reduce((u,d)=>u.concat(d),[])),c=new x(a,h),l=new x(i,n).add(c.scalarDivide(2));if(s===Kt){const u=this.getInitialSize(e,{size:c,center:l});return{center:l,relativeCorrection:new x(0,0),size:u}}return{center:l.transform(r.calcOwnMatrix()),size:c}}}p(tr,"type","strategy");class kr extends tr{shouldPerformLayout(t){return!0}}p(kr,"type","fit-content"),M.setClass(kr);const ih=["strategy"],nh=["target","strategy","bubbles","prevStrategy"],Xn="layoutManager";class Je{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new kr;p(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e=m(m({bubbles:!0,strategy:this.strategy},t),{},{prevStrategy:this._prevLayoutStrategy,stopPropagation(){this.bubbles=!1}});this.onBeforeLayout(e);const s=this.getLayoutResult(e);s&&this.commitLayout(e,s),this.onAfterLayout(e,s),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:s}=e;return[js,sn,Ne,rn,Us,nn,As,ko,Do].map(r=>t.on(r,i=>this.performLayout(r===js?{type:"object_modified",trigger:r,e:i,target:s}:{type:"object_modifying",trigger:r,e:i,target:s})))}subscribe(t,e){this.unsubscribe(t,e);const s=this.attachHandlers(t,e);this._subscriptions.set(t,s)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(s=>s()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){const{target:e,type:s}=t,{canvas:r}=e;if(s===Kt||s===Xs?this.subscribeTargets(t):s===$r&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),r&&r.fire("object:layout:before",{target:e,context:t}),s===Ys&&t.deep){const i=$(t,ih);e.forEachObject(n=>n.layoutManager&&n.layoutManager.performLayout(m(m({},i),{},{bubbles:!1,target:n})))}}getLayoutResult(t){const{target:e,strategy:s,type:r}=t,i=s.calcLayoutResult(t,e.getObjects());if(!i)return;const n=r===Kt?new x:e.getRelativeCenterPoint(),{center:a,correction:h=new x,relativeCorrection:c=new x}=i,l=n.subtract(a).add(h).transform(r===Kt?ft:Rt(e.calcOwnMatrix()),!0).add(c);return{result:i,prevCenter:n,nextCenter:a,offset:l}}commitLayout(t,e){const{target:s}=t,{result:{size:r},nextCenter:i}=e;var n,a;s.set({width:r.x,height:r.y}),this.layoutObjects(t,e),t.type===Kt?s.set({left:(n=t.x)!==null&&n!==void 0?n:i.x+r.x*it(s.originX),top:(a=t.y)!==null&&a!==void 0?a:i.y+r.y*it(s.originY)}):(s.setPositionByOrigin(i,R,R),s.setCoords(),s.set("dirty",!0))}layoutObjects(t,e){const{target:s}=t;s.forEachObject(r=>{r.group===s&&this.layoutObject(t,e,r)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,s.clipPath)}layoutObject(t,e,s){let{offset:r}=e;s.set({left:s.left+r.x,top:s.top+r.y})}onAfterLayout(t,e){const{target:s,strategy:r,bubbles:i,prevStrategy:n}=t,a=$(t,nh),{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const c=s.parent;i&&c!=null&&c.layoutManager&&((a.path||(a.path=[])).push(s),c.layoutManager.performLayout(m(m({},a),{},{target:c}))),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Xn,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}M.setClass(Je,Xn);const oh=["type","objects","layoutManager"];class ah extends Je{performLayout(){}}class pe extends on(ut){static getDefaults(){return m(m({},super.getDefaults()),pe.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),p(this,"_activeObjects",[]),p(this,"__objectSelectionTracker",void 0),p(this,"__objectSelectionDisposer",void 0),Object.assign(this,pe.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var s;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(r=>{this.enterGroup(r,!1)}),this.layoutManager=(s=e.layoutManager)!==null&&s!==void 0?s:new Je,this.layoutManager.performLayout({type:Kt,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(ce("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(ce("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((e,s,r)=>this.canEnterGroup(e)&&r.indexOf(e)===s)}add(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];const r=this._filterObjectsBeforeEnteringGroup(e),i=super.add(...r);return this._onAfterObjectsChange(Xs,r),i}insertAt(t){for(var e=arguments.length,s=new Array(e>1?e-1:0),r=1;r<e;r++)s[r-1]=arguments[r];const i=this._filterObjectsBeforeEnteringGroup(s),n=super.insertAt(t,...i);return this._onAfterObjectsChange(Xs,i),n}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange($r,t),t}_onObjectAdded(t){this.enterGroup(t,!0),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t,e){this.exitGroup(t,e),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onAfterObjectsChange(t,e){this.layoutManager.performLayout({type:t,targets:e,target:this})}_onStackOrderChanged(){this._set("dirty",!0)}_set(t,e){const s=this[t];return super._set(t,e),t==="canvas"&&s!==e&&(this._objects||[]).forEach(r=>{r._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:s}=e;const r=this._activeObjects;if(t)r.push(s),this._set("dirty",!0);else if(r.length>0){const i=r.indexOf(s);i>-1&&(r.splice(i,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&&Rs(t,ct(Rt(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const s=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();s&&(s===t||t.isDescendantOf(s))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(Rs(t,ct(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const s=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;s>-1&&this._activeObjects.splice(s,1)}shouldCache(){const t=ut.prototype.shouldCache.call(this);if(t){for(let e=0;e<this._objects.length;e++)if(this._objects[e].willDrawShadow())return this.ownCaching=!1,!1}return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,s){this._renderBackground(t);for(let i=0;i<this._objects.length;i++){var r;const n=this._objects[i];(r=this.canvas)!==null&&r!==void 0&&r.preserveObjectStacking&&n.group!==this?(t.save(),t.transform(...Rt(this.calcTransformMatrix())),n.render(t),t.restore()):n.group===this&&n.render(t)}this._drawClipPath(t,this.clipPath,s)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.layoutManager.performLayout(m({target:this,type:Ys},t))}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const s=this.includeDefaultValues;return this._objects.filter(function(r){return!r.excludeFromExport}).map(function(r){const i=r.includeDefaultValues;r.includeDefaultValues=s;const n=r[t||"toObject"](e);return r.includeDefaultValues=i,n})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return m(m(m({},super.toObject(["subTargetCheck","interactive",...t])),e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{}),{},{objects:this.__serializeObjects("toObject",t)})}toString(){return"#<Group: (".concat(this.complexity(),")>")}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=kt.prototype._toSVG.call(this),s=e.indexOf("COMMON_PARTS");e[s]='for="group" ';const r=e.join("");return t?t(r):r}_toSVG(t){const e=["<g ","COMMON_PARTS",` >
40
40
  `],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let r=0;r<this._objects.length;r++)e.push(" ",this._objects[r].toSVG(t));return e.push(`</g>
41
- `),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let r=0;r<this._objects.length;r++)e.push(" ",this._objects[r].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:r=[],layoutManager:i}=t,n=$(t,rh);return Promise.all([Ue(r,e),$s(n,e)]).then(a=>{let[h,c]=a;const l=new this(h,m(m(m({},n),c),{},{layoutManager:new ih}));if(i){const u=M.getClass(i.type),d=M.getClass(i.strategy);l.layoutManager=new u(new d)}else l.layoutManager=new Je;return l.layoutManager.subscribeTargets({type:Kt,target:l,targets:l.getObjects()}),l.setCoords(),l})}}p(pe,"type","Group"),p(pe,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),M.setClass(pe);const nh=(o,t)=>Math.min(t.width/o.width,t.height/o.height),oh=(o,t)=>Math.max(t.width/o.width,t.height/o.height),Dr="\\s*,?\\s*",Xe="".concat(Dr,"(").concat(Bt,")"),ah="".concat(Xe).concat(Xe).concat(Xe).concat(Dr,"([01])").concat(Dr,"([01])").concat(Xe).concat(Xe),hh={m:"l",M:"L"},ch=(o,t,e,s,r,i,n,a,h,c,l)=>{const u=Qt(o),d=te(o),g=Qt(t),f=te(t),v=e*r*g-s*i*f+n,_=s*r*g+e*i*f+a;return["C",c+h*(-e*r*d-s*i*u),l+h*(-s*r*d+e*i*u),v+h*(e*r*f+s*i*g),_+h*(s*r*f-e*i*g),v,_]},Li=(o,t,e,s)=>{const r=Math.atan2(t,o),i=Math.atan2(s,e);return i>=r?i-r:2*Math.PI-(r-i)};function Ri(o,t,e,s,r,i,n,a){let h;if(Y.cachesBoundsOfCurve&&(h=[...arguments].join(),Ve.boundsOfCurveCache[h]))return Ve.boundsOfCurveCache[h];const c=Math.sqrt,l=Math.abs,u=[],d=[[0,0],[0,0]];let g=6*o-12*e+6*r,f=-3*o+9*e-9*r+3*n,v=3*e-3*o;for(let T=0;T<2;++T){if(T>0&&(g=6*t-12*s+6*i,f=-3*t+9*s-9*i+3*a,v=3*s-3*t),l(f)<1e-12){if(l(g)<1e-12)continue;const W=-v/g;0<W&&W<1&&u.push(W);continue}const D=g*g-4*v*f;if(D<0)continue;const A=c(D),I=(-g+A)/(2*f);0<I&&I<1&&u.push(I);const E=(-g-A)/(2*f);0<E&&E<1&&u.push(E)}let _=u.length;const b=_,w=Xn(o,t,e,s,r,i,n,a);for(;_--;){const{x:T,y:D}=w(u[_]);d[0][_]=T,d[1][_]=D}d[0][b]=o,d[1][b]=t,d[0][b+1]=n,d[1][b+1]=a;const C=[new x(Math.min(...d[0]),Math.min(...d[1])),new x(Math.max(...d[0]),Math.max(...d[1]))];return Y.cachesBoundsOfCurve&&(Ve.boundsOfCurveCache[h]=C),C}const lh=(o,t,e)=>{let[s,r,i,n,a,h,c,l]=e;const u=((d,g,f,v,_,b,w)=>{if(f===0||v===0)return[];let C=0,T=0,D=0;const A=Math.PI,I=w*jr,E=te(I),W=Qt(I),q=.5*(-W*d-E*g),Z=.5*(-W*g+E*d),L=f**2,V=v**2,X=Z**2,nt=q**2,et=L*V-L*X-V*nt;let st=Math.abs(f),U=Math.abs(v);if(et<0){const z=Math.sqrt(1-et/(L*V));st*=z,U*=z}else D=(_===b?-1:1)*Math.sqrt(et/(L*X+V*nt));const bt=D*st*Z/U,y=-D*U*q/st,S=W*bt-E*y+.5*d,k=E*bt+W*y+.5*g;let O=Li(1,0,(q-bt)/st,(Z-y)/U),j=Li((q-bt)/st,(Z-y)/U,(-q-bt)/st,(-Z-y)/U);b===0&&j>0?j-=2*A:b===1&&j<0&&(j+=2*A);const H=Math.ceil(Math.abs(j/A*2)),B=[],ht=j/H,Pt=8/3*Math.sin(ht/4)*Math.sin(ht/4)/Math.sin(ht/2);let rt=O+ht;for(let z=0;z<H;z++)B[z]=ch(O,rt,W,E,st,U,S,k,Pt,C,T),C=B[z][5],T=B[z][6],O=rt,rt+=ht;return B})(c-o,l-t,r,i,a,h,n);for(let d=0,g=u.length;d<g;d++)u[d][1]+=o,u[d][2]+=t,u[d][3]+=o,u[d][4]+=t,u[d][5]+=o,u[d][6]+=t;return u},uh=o=>{let t=0,e=0,s=0,r=0;const i=[];let n,a=0,h=0;for(const c of o){const l=[...c];let u;switch(l[0]){case"l":l[1]+=t,l[2]+=e;case"L":t=l[1],e=l[2],u=["L",t,e];break;case"h":l[1]+=t;case"H":t=l[1],u=["L",t,e];break;case"v":l[1]+=e;case"V":e=l[1],u=["L",t,e];break;case"m":l[1]+=t,l[2]+=e;case"M":t=l[1],e=l[2],s=l[1],r=l[2],u=["M",t,e];break;case"c":l[1]+=t,l[2]+=e,l[3]+=t,l[4]+=e,l[5]+=t,l[6]+=e;case"C":a=l[3],h=l[4],t=l[5],e=l[6],u=["C",l[1],l[2],a,h,t,e];break;case"s":l[1]+=t,l[2]+=e,l[3]+=t,l[4]+=e;case"S":n==="C"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=l[3],e=l[4],u=["C",a,h,l[1],l[2],t,e],a=u[3],h=u[4];break;case"q":l[1]+=t,l[2]+=e,l[3]+=t,l[4]+=e;case"Q":a=l[1],h=l[2],t=l[3],e=l[4],u=["Q",a,h,t,e];break;case"t":l[1]+=t,l[2]+=e;case"T":n==="Q"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=l[1],e=l[2],u=["Q",a,h,t,e];break;case"a":l[6]+=t,l[7]+=e;case"A":lh(t,e,l).forEach(d=>i.push(d)),t=l[6],e=l[7];break;case"z":case"Z":t=s,e=r,u=["Z"]}u?(i.push(u),n=u[0]):n=""}return i},Vs=(o,t,e,s)=>Math.sqrt((e-o)**2+(s-t)**2),Xn=(o,t,e,s,r,i,n,a)=>h=>{const c=h**3,l=(g=>3*g**2*(1-g))(h),u=(g=>3*g*(1-g)**2)(h),d=(g=>(1-g)**3)(h);return new x(n*c+r*l+e*u+o*d,a*c+i*l+s*u+t*d)},Yn=o=>o**2,Vn=o=>2*o*(1-o),Hn=o=>(1-o)**2,dh=(o,t,e,s,r,i,n,a)=>h=>{const c=Yn(h),l=Vn(h),u=Hn(h),d=3*(u*(e-o)+l*(r-e)+c*(n-r)),g=3*(u*(s-t)+l*(i-s)+c*(a-i));return Math.atan2(g,d)},gh=(o,t,e,s,r,i)=>n=>{const a=Yn(n),h=Vn(n),c=Hn(n);return new x(r*a+e*h+o*c,i*a+s*h+t*c)},fh=(o,t,e,s,r,i)=>n=>{const a=1-n,h=2*(a*(e-o)+n*(r-e)),c=2*(a*(s-t)+n*(i-s));return Math.atan2(c,h)},Bi=(o,t,e)=>{let s=new x(t,e),r=0;for(let i=1;i<=100;i+=1){const n=o(i/100);r+=Vs(s.x,s.y,n.x,n.y),s=n}return r},ph=(o,t)=>{let e,s=0,r=0,i={x:o.x,y:o.y},n=m({},i),a=.01,h=0;const c=o.iterator,l=o.angleFinder;for(;r<t&&a>1e-4;)n=c(s),h=s,e=Vs(i.x,i.y,n.x,n.y),e+r>t?(s-=a,a/=2):(i=n,s+=a,r+=e);return m(m({},n),{},{angle:l(h)})},zn=o=>{let t,e,s=0,r=0,i=0,n=0,a=0;const h=[];for(const c of o){const l={x:r,y:i,command:c[0],length:0};switch(c[0]){case"M":e=l,e.x=n=r=c[1],e.y=a=i=c[2];break;case"L":e=l,e.length=Vs(r,i,c[1],c[2]),r=c[1],i=c[2];break;case"C":t=Xn(r,i,c[1],c[2],c[3],c[4],c[5],c[6]),e=l,e.iterator=t,e.angleFinder=dh(r,i,c[1],c[2],c[3],c[4],c[5],c[6]),e.length=Bi(t,r,i),r=c[5],i=c[6];break;case"Q":t=gh(r,i,c[1],c[2],c[3],c[4]),e=l,e.iterator=t,e.angleFinder=fh(r,i,c[1],c[2],c[3],c[4]),e.length=Bi(t,r,i),r=c[3],i=c[4];break;case"Z":e=l,e.destX=n,e.destY=a,e.length=Vs(r,i,n,a),r=n,i=a}s+=e.length,h.push(e)}return h.push({length:s,x:r,y:i}),h},mh=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:zn(o),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const r=e[s],i=t/r.length,n=o[s];switch(r.command){case"M":return{x:r.x,y:r.y,angle:0};case"Z":return m(m({},new x(r.x,r.y).lerp(new x(r.destX,r.destY),i)),{},{angle:Math.atan2(r.destY-r.y,r.destX-r.x)});case"L":return m(m({},new x(r.x,r.y).lerp(new x(n[1],n[2]),i)),{},{angle:Math.atan2(n[2]-r.y,n[1]-r.x)});case"C":case"Q":return ph(r,t)}},vh=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Ii=new RegExp(ah,"g"),yh=new RegExp(Bt,"gi"),xh={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},_h=o=>{var t;const e=[],s=(t=o.match(vh))!==null&&t!==void 0?t:[];for(const r of s){const i=r[0];if(i==="z"||i==="Z"){e.push([i]);continue}const n=xh[i.toLowerCase()];let a=[];if(i==="a"||i==="A"){Ii.lastIndex=0;for(let h=null;h=Ii.exec(r);)a.push(...h.slice(1))}else a=r.match(yh)||[];for(let h=0;h<a.length;h+=n){const c=new Array(n),l=hh[i];c[0]=h>0&&l?l:i;for(let u=0;u<n;u++)c[u+1]=parseFloat(a[h+u]);e.push(c)}}return e},bh=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new x(o[0]),s=new x(o[1]),r=1,i=0;const n=[],a=o.length,h=a>2;let c;for(h&&(r=o[2].x<s.x?-1:o[2].x===s.x?0:1,i=o[2].y<s.y?-1:o[2].y===s.y?0:1),n.push(["M",e.x-r*t,e.y-i*t]),c=1;c<a;c++){if(!e.eq(s)){const l=e.midPointFrom(s);n.push(["Q",e.x,e.y,l.x,l.y])}e=o[c],c+1<o.length&&(s=o[c+1])}return h&&(r=e.x>o[c-2].x?1:e.x===o[c-2].x?0:-1,i=e.y>o[c-2].y?1:e.y===o[c-2].y?0:-1),n.push(["L",e.x+r*t,e.y+i*t]),n},Gn=(o,t)=>o.map(e=>e.map((s,r)=>r===0||t===void 0?s:K(s,t)).join(" ")).join(" ");function Mr(o,t){const e=o.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[r,i]=s;return e.setProperty(r,i)}))}class wh extends mn{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),p(this,"upper",void 0),p(this,"container",void 0);const{el:r}=this.lower,i=this.createUpperCanvas();this.upper={el:i,ctx:i.getContext("2d")},this.applyCanvasStyle(r,{allowTouchScrolling:e}),this.applyCanvasStyle(i,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const n=this.createContainerElement();n.classList.add(s),r.parentNode&&r.parentNode.replaceChild(n,r),n.append(r,i),this.container=n}createUpperCanvas(){const{el:t}=this.lower,e=ee();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){const t=Pe().createElement("div");return t.setAttribute("data-fabric","wrapper"),Mr(t,{position:"relative"}),ci(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:r}=e;Mr(t,m(m({},s),{},{"touch-action":r?"manipulation":vt})),ci(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:r}=this.upper;pn(s,r,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),br(this.upper.el,t),br(this.container,t)}cleanupDOM(t){const e=this.container,{el:s}=this.lower,{el:r}=this.upper;super.cleanupDOM(t),e.removeChild(r),e.removeChild(s),e.parentNode&&e.parentNode.replaceChild(s,e)}dispose(){super.dispose(),Gt().dispose(this.upper.el),delete this.upper,delete this.container}}class er extends ts{constructor(){super(...arguments),p(this,"targets",[]),p(this,"_hoveredTargets",[]),p(this,"_currentTransform",null),p(this,"_groupSelector",null),p(this,"contextTopDirty",!1)}static getDefaults(){return m(m({},super.getDefaults()),er.ownDefaults)}get upperCanvasEl(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.el}get contextTop(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new wh(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){const t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter(e=>!e.group&&e!==t).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()}renderTop(){const t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;const e=this.getRetinaScaling(),s=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=s,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,s){const r=this.targetFindTolerance,i=this.pixelFindContext;this.clearContext(i),i.save(),i.translate(-e+r,-s+r),i.transform(...this.viewportTransform);const n=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(i),t.selectionBackgroundColor=n,i.restore();const a=Math.round(r*this.getRetinaScaling());return Oa(i,a,a,a)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(s=>!!s&&t[s]===!0):t[e])}_shouldClearSelection(t,e){const s=this.getActiveObjects(),r=this._activeObject;return!!(!e||e&&r&&s.length>1&&s.indexOf(e)===-1&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e)}_shouldCenterTransform(t,e,s){if(!t)return;let r;return e===qs||e===_t||e===Mt||e===Ne?r=this.centeredScaling||t.centeredScaling:e===Rr&&(r=this.centeredRotation||t.centeredRotation),r?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=Q:["mr","tr","br"].includes(e)&&(s.x=N),["tl","mt","tr"].includes(e)?s.y=_r:["bl","mb","br"].includes(e)&&(s.y=mt)),s}_setupCurrentTransform(t,e,s){var r;const i=e.group?ke(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:n="",control:a}=e.getActiveControl()||{},h=s&&a?(r=a.getActionHandler(t,e,a))===null||r===void 0?void 0:r.bind(a):Vo,c=((g,f,v,_)=>{if(!f||!g)return"drag";const b=_.controls[f];return b.getActionName(v,b,_)})(s,n,t,e),l=t[this.centeredKey],u=this._shouldCenterTransform(e,c,l)?{x:R,y:R}:this._getOriginFromCorner(e,n),d={target:e,action:c,actionHandler:h,actionPerformed:!1,corner:n,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:i.x-e.left,offsetY:i.y-e.top,originX:u.x,originY:u.y,ex:i.x,ey:i.y,lastX:i.x,lastY:i.y,theta:tt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:l,original:m(m({},vn(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:r,deltaY:i}=this._groupSelector,n=new x(e,s).transform(this.viewportTransform),a=new x(e+r,s+i).transform(this.viewportTransform),h=this.selectionLineWidth/2;let c=Math.min(n.x,a.x),l=Math.min(n.y,a.y),u=Math.max(n.x,a.x),d=Math.max(n.y,a.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(c,l,u-c,d-l)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,c+=h,l+=h,u-=h,d-=h,ut.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(c,l,u-c,d-l))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,r=this.getActiveObjects();if(this.targets=[],s&&r.length>=1){if(s.findControl(e,wr(t))||r.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const i=this.targets;this.targets=[];const n=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&n&&n!==s?(this.targets=i,s):n}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const r=this.getZoom(),i=t.padding/r;if(i){const[n,a,h,c]=s,l=Math.atan2(a.y-n.y,a.x-n.x),u=Qt(l)*i,d=te(l)*i,g=u+d,f=u-d;s=[new x(n.x-f,n.y-g),new x(a.x+g,a.y-f),new x(h.x+f,h.y+g),new x(c.x-g,c.y+f)]}return J.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,ke(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const r=t[s];if(this._checkTarget(r,e)){if(ks(r)&&r.subTargetCheck){const i=this._searchPossibleTargets(r._objects,e);i&&this.targets.push(i)}return r}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&ks(s)&&s.interactive&&this.targets[0]){const r=this.targets;for(let i=r.length-1;i>0;i--){const n=r[i];if(!ks(n)||!n.interactive)return n}return r[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,r=s.getBoundingClientRect();let i=Lo(t),n=r.width||0,a=r.height||0;n&&a||(mt in r&&_r in r&&(a=Math.abs(r.top-r.bottom)),Q in r&&N in r&&(n=Math.abs(r.right-r.left))),this.calcOffset(),i.x=i.x-this._offset.left,i.y=i.y-this._offset.top,e||(i=ke(i,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(i.x/=h,i.y/=h);const c=n===0||a===0?new x(1,1):new x(s.width/n,s.height/a);return i.multiply(c)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=ee(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){const t=this._activeObject;return de(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,r=!1;const i=this.getActiveObjects(),n=[],a=[];t.forEach(h=>{i.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),a.push(h))}),i.forEach(h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),n.push(h))}),t.length>0&&i.length>0?(r=!0,s&&this.fire("selection:updated",{e,selected:n,deselected:a})):i.length>0?(r=!0,this.fire("selection:created",{e,selected:n})):t.length>0&&(r=!0,this.fire("selection:cleared",{e,deselected:a})),r&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),r=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),r}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,de(t)&&s!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){const s=this._activeObject;return!!s&&!s.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===s&&this.endCurrentTransform(t),de(s)&&s===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){const e=this.getActiveObjects(),s=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[s]});const r=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),r}endCurrentTransform(t){const e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){const e=this._currentTransform,s=e.target,r={e:t,target:s,transform:e,action:e.action};s._scaling&&(s._scaling=!1),s.setCoords(),e.actionPerformed&&(this.fire("object:modified",r),s.fire(js,r))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;de(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){const e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,s){const r=this._realizeGroupTransformOnObject(t),i=super._toObject(t,e,s);return t.set(r),i}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&de(e)&&this._activeObject===e){const s=Le(t,["angle","flipX","flipY",N,_t,Mt,Ae,je,mt]);return Bo(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const r=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(r)}}p(er,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class Sh{constructor(t){p(this,"targets",[]),p(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:r}=t.getActiveObject()||{};r&&r.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),Se(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;!((e=this.target)===null||e===void 0)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}const Ch=["target","oldTarget","fireCanvas","e"],St={passive:!1},_e=(o,t)=>{const e=o.getViewportPoint(t),s=o.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},oe=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.addEventListener(...e)},Ot=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.removeEventListener(...e)},Th={mouse:{in:"over",out:"out",targetIn:"mouseover",targetOut:"mouseout",canvasIn:"mouse:over",canvasOut:"mouse:out"},drag:{in:"enter",out:"leave",targetIn:"dragenter",targetOut:"dragleave",canvasIn:"drag:enter",canvasOut:"drag:leave"}};class Er extends er{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),p(this,"_isClick",void 0),p(this,"textEditingManager",new Sh(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(oe,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,r=this._getEventPrefix();t(fn(s),"resize",this._onResize),t(s,r+"down",this._onMouseDown),t(s,"".concat(r,"move"),this._onMouseMove,St),t(s,"".concat(r,"out"),this._onMouseOut),t(s,"".concat(r,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,St)}removeListeners(){this.addOrRemove(Ot,"remove");const t=this._getEventPrefix(),e=Lt(this.upperCanvasEl);Ot(e,"".concat(t,"up"),this._onMouseUp),Ot(e,"touchend",this._onTouchEnd,St),Ot(e,"".concat(t,"move"),this._onMouseMove,St),Ot(e,"touchmove",this._onMouseMove,St),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=m({e:t},_e(this,t));this.fire("mouse:out",m(m({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",m({},s)),this._hoveredTargets.forEach(r=>{this.fire("mouse:out",m(m({},s),{},{target:r})),r&&r.fire("mouseout",m({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",m({e:t},_e(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;const e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;const s={e:t,target:e};return this.fire("dragstart",s),e.fire("dragstart",s),void oe(this.upperCanvasEl,"drag",this._onDragProgress)}li(t)}_renderDragEffects(t,e,s){let r=!1;const i=this._dropTarget;i&&i!==e&&i!==s&&(i.clearContextTop(),r=!0),e==null||e.clearContextTop(),s!==e&&(s==null||s.clearContextTop());const n=this.contextTop;n.save(),n.transform(...this.viewportTransform),e&&(n.save(),e.transform(n),e.renderDragSourceEffect(t),n.restore(),r=!0),s&&(n.save(),s.transform(n),s.renderDropTargetEffect(t),n.restore(),r=!0),n.restore(),r&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==vt,s=e?this._activeObject:void 0,r={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};Ot(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",r),this._dragSource&&this._dragSource.fire("dragend",r),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:r}=this.findDragTargets(t),i=this._dragSource,n={e:t,target:s,subTargets:r,dragSource:i,canDrop:!1,dropTarget:void 0};let a;this.fire(e,n),this._fireEnterLeaveEvents(s,n),s&&(s.canDrop(t)&&(a=s),s.fire(e,n));for(let h=0;h<r.length;h++){const c=r[h];c.canDrop(t)&&(a=c),c.fire(e,n)}this._renderDragEffects(t,i,a),this._dropTarget=a}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),r={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",r),this._fireEnterLeaveEvents(e,r)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),r=this._basicEventHandler("drop:before",m({e:t,target:e,subTargets:s,dragSource:this._dragSource},_e(this,t)));r.didDrop=!1,r.dropTarget=void 0,this._basicEventHandler("drop",r),this.fire("drop:after",r)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],r=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&li(t),this._basicEventHandler("contextmenu",r),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const r=this.upperCanvasEl,i=this._getEventPrefix(),n=Lt(r);oe(n,"touchend",this._onTouchEnd,St),e&&oe(n,"touchmove",this._onMouseMove,St),Ot(r,"".concat(i,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();Ot(e,"".concat(s,"move"),this._onMouseMove,St);const r=Lt(e);oe(r,"".concat(s,"up"),this._onMouseUp),oe(r,"".concat(s,"move"),this._onMouseMove,St)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=Lt(this.upperCanvasEl);Ot(s,"touchend",this._onTouchEnd,St),Ot(s,"touchmove",this._onMouseMove,St),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{oe(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const r=Lt(this.upperCanvasEl);Ot(r,"".concat(s,"up"),this._onMouseUp),Ot(r,"".concat(s,"move"),this._onMouseMove,St),oe(e,"".concat(s,"move"),this._onMouseMove,St)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,r=this._isClick,i=this._target,{button:n}=t;if(n)return(this.fireMiddleClick&&n===1||this.fireRightClick&&n===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let a,h,c=!1;if(s&&(this._finalizeCurrentTransform(t),c=s.actionPerformed),!r){const l=i===this._activeObject;this.handleSelection(t),c||(c=this._shouldRender(i)||!l&&i===this._activeObject)}if(i){const l=i.findControl(this.getViewportPoint(t),wr(t)),{key:u,control:d}=l||{};if(h=u,i.selectable&&i!==this._activeObject&&i.activeOn==="up")this.setActiveObject(i,t),c=!0;else if(d){const g=d.getMouseUpHandler(t,i,d);g&&(a=this.getScenePoint(t),g.call(d,t,s,a.x,a.y))}i.isMoving=!1}if(s&&(s.target!==i||s.corner!==h)){const l=s.target&&s.target.controls[s.corner],u=l&&l.getMouseUpHandler(t,s.target,l);a=a||this.getScenePoint(t),u&&u.call(l,t,s,a.x,a.y)}this._setCursorFromEvent(t,i),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,i&&(i.__corner=void 0),c?this.requestRenderAll():r||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:r=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let i=0;i<r.length;i++)r[i]!==s&&r[i].fire(t,e);return e}_handleEvent(t,e,s){const r=this._target,i=this.targets||[],n=m(m(m({e:t,target:r,subTargets:i},_e(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),n),r&&r.fire("mouse".concat(e),n);for(let a=0;a<i.length;a++)i[a]!==r&&i[a].fire("mouse".concat(e),n)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let i=this._shouldRender(e),n=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,n=!0,i=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const a=this.getScenePoint(t);this._groupSelector={x:a.x,y:a.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const a=e.findControl(this.getViewportPoint(t),wr(t));if(e===this._activeObject&&(a||!n)){this._setupCurrentTransform(t,e,s);const h=a?a.control:void 0,c=this.getScenePoint(t),l=h&&h.getMouseDownHandler(t,e,h);l&&l.call(h,t,this._currentTransform,c.x,c.y)}}i&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),i&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=ke(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,r=this._hoveredTargets,i=this.targets,n=Math.max(r.length,i.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let a=0;a<n;a++)i[a]===e||r[a]&&r[a]===s||this.fireSyntheticInOutEvents("mouse",{e:t,target:i[a],oldTarget:r[a]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,r=this._hoveredTargets,i=this.targets,n=Math.max(r.length,i.length);this.fireSyntheticInOutEvents("drag",m(m({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let a=0;a<n;a++)this.fireSyntheticInOutEvents("drag",m(m({},e),{},{target:i[a],oldTarget:r[a]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:r,fireCanvas:i,e:n}=e,a=$(e,Ch);const{targetIn:h,targetOut:c,canvasIn:l,canvasOut:u}=Th[t],d=r!==s;if(r&&d){const g=m(m({},a),{},{e:n,target:r,nextTarget:s},_e(this,n));i&&this.fire(u,g),r.fire(c,g)}if(s&&d){const g=m(m({},a),{},{e:n,target:s,previousTarget:r},_e(this,n));i&&this.fire(l,g),s.fire(h,g)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,r=s.target,i=r.group?ke(e,void 0,r.group.calcTransformMatrix()):e;s.shiftKey=t.shiftKey,s.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,s,i),s.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,s){const{action:r,actionHandler:i,target:n}=e,a=!!i&&i(t,e,s.x,s.y);a&&n.setCoords(),r==="drag"&&a&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||a}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const r=de(this._activeObject)?this._activeObject:null,i=(!r||e.group!==r)&&e.findControl(this.getViewportPoint(t));if(i){const n=i.control;this.setCursor(n.cursorStyleHandler(t,n,e))}else e.subTargetCheck&&this.targets.concat().reverse().map(n=>{s=n.hoverCursor||s}),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,r=de(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||r)&&(r||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(r){const i=s.getObjects();if(e===s){const n=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(i,n)||this.searchPossibleTargets(this._objects,n))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(i,t)}else{s.isEditing&&s.exitEditing();const i=new(M.getClass("ActiveSelection"))([],{canvas:this});i.multiSelectAdd(s,e),this._hoveredTarget=i,this._setActiveObject(i,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:r,deltaY:i}=this._groupSelector,n=new x(e,s),a=n.add(new x(r,i)),h=n.min(a),c=n.max(a).subtract(h),l=this.collectObjects({left:h.x,top:h.y,width:c.x,height:c.y},{includeIntersecting:!this.selectionFullyContained}),u=n.eq(a)?l[0]?[l[0]]:[]:l.length>1?l.filter(d=>!d.onSelect({e:t})).reverse():l;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const d=M.getClass("ActiveSelection");this.setActiveObject(new d(u,{canvas:this}),t)}return this._groupSelector=null,!0}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,e=arguments.length>1?arguments[1]:void 0;const{upper:s}=this.elements;s.ctx=void 0;const r=super.toCanvasElement(t,e);return s.ctx=s.el.getContext("2d"),r}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const Nn={x1:0,y1:0,x2:0,y2:0},Oh=m(m({},Nn),{},{r1:0,r2:0}),Te=(o,t)=>isNaN(o)&&typeof t=="number"?t:o;function Un(o){return o&&/%$/.test(o)&&Number.isFinite(parseFloat(o))}function qn(o,t){const e=typeof o=="number"?o:typeof o=="string"?parseFloat(o)/(Un(o)?100:1):NaN;return Ee(0,Te(e,t),1)}const kh=/\s*;\s*/,Dh=/\s*:\s*/;function Mh(o,t){let e,s;const r=o.getAttribute("style");if(r){const n=r.split(kh);n[n.length-1]===""&&n.pop();for(let a=n.length;a--;){const[h,c]=n[a].split(Dh).map(l=>l.trim());h==="stop-color"?e=c:h==="stop-opacity"&&(s=c)}}const i=new G(e||o.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:qn(o.getAttribute("offset"),0),color:i.toRgb(),opacity:Te(parseFloat(s||o.getAttribute("stop-opacity")||""),1)*i.getAlpha()*t}}function Eh(o,t){const e=[],s=o.getElementsByTagName("stop"),r=qn(t,1);for(let i=s.length;i--;)e.push(Mh(s[i],r));return e}function Kn(o){return o.nodeName==="linearGradient"||o.nodeName==="LINEARGRADIENT"?"linear":"radial"}function $n(o){return o.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function At(o,t){return o.getAttribute(t)}function Ph(o,t){return function(e,s){let r,{width:i,height:n,gradientUnits:a}=s;return Object.entries(e).reduce((h,c)=>{let[l,u]=c;if(u==="Infinity")r=1;else if(u==="-Infinity")r=0;else{const d=typeof u=="string";r=d?parseFloat(u):u,d&&Un(u)&&(r*=.01,a==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(r*=i),l!=="y1"&&l!=="y2"||(r*=n)))}return h[l]=r,h},{})}(Kn(o)==="linear"?function(e){return{x1:At(e,"x1")||0,y1:At(e,"y1")||0,x2:At(e,"x2")||"100%",y2:At(e,"y2")||0}}(o):function(e){return{x1:At(e,"fx")||At(e,"cx")||"50%",y1:At(e,"fy")||At(e,"cy")||"50%",r1:0,x2:At(e,"cx")||"50%",y2:At(e,"cy")||"50%",r2:At(e,"r")||"50%"}}(o),m(m({},t),{},{gradientUnits:$n(o)}))}class is{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:r={},colorStops:i=[],offsetX:n=0,offsetY:a=0,gradientTransform:h,id:c}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:m(m({},e==="radial"?Oh:Nn),r),colorStops:i,offsetX:n,offsetY:a,gradientTransform:h,id:c?"".concat(c,"_").concat(le()):le()})}addColorStop(t){for(const e in t){const s=new G(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return m(m({},Le(this,t)),{},{type:this.type,coords:m({},this.coords),colorStops:this.colorStops.map(e=>m({},e)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],r=this.gradientTransform?this.gradientTransform.concat():ft.concat(),i=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",n=this.colorStops.map(u=>m({},u)).sort((u,d)=>u.offset-d.offset);let a=-this.offsetX,h=-this.offsetY;var c;i==="objectBoundingBox"?(a/=t.width,h/=t.height):(a+=t.width/2,h+=t.height/2),(c=t)&&typeof c._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(a-=t.pathOffset.x,h-=t.pathOffset.y),r[4]-=a,r[5]-=h;const l=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(i,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(qe(r),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:d,x2:g,y2:f}=this.coords;s.push("<linearGradient ",l,' x1="',u,'" y1="',d,'" x2="',g,'" y2="',f,`">
41
+ `),e}getSvgStyles(){const t=this.opacity!==void 0&&this.opacity!==1?"opacity: ".concat(this.opacity,";"):"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],s=this._createSVGBgRect(t);s&&e.push(" ",s);for(let r=0;r<this._objects.length;r++)e.push(" ",this._objects[r].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:s,objects:r=[],layoutManager:i}=t,n=$(t,oh);return Promise.all([Ue(r,e),$s(n,e)]).then(a=>{let[h,c]=a;const l=new this(h,m(m(m({},n),c),{},{layoutManager:new ah}));if(i){const u=M.getClass(i.type),d=M.getClass(i.strategy);l.layoutManager=new u(new d)}else l.layoutManager=new Je;return l.layoutManager.subscribeTargets({type:Kt,target:l,targets:l.getObjects()}),l.setCoords(),l})}}p(pe,"type","Group"),p(pe,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),M.setClass(pe);const hh=(o,t)=>Math.min(t.width/o.width,t.height/o.height),ch=(o,t)=>Math.max(t.width/o.width,t.height/o.height),Dr="\\s*,?\\s*",Xe="".concat(Dr,"(").concat(Bt,")"),lh="".concat(Xe).concat(Xe).concat(Xe).concat(Dr,"([01])").concat(Dr,"([01])").concat(Xe).concat(Xe),uh={m:"l",M:"L"},dh=(o,t,e,s,r,i,n,a,h,c,l)=>{const u=Qt(o),d=te(o),g=Qt(t),f=te(t),v=e*r*g-s*i*f+n,_=s*r*g+e*i*f+a;return["C",c+h*(-e*r*d-s*i*u),l+h*(-s*r*d+e*i*u),v+h*(e*r*f+s*i*g),_+h*(s*r*f-e*i*g),v,_]},Li=(o,t,e,s)=>{const r=Math.atan2(t,o),i=Math.atan2(s,e);return i>=r?i-r:2*Math.PI-(r-i)};function Ri(o,t,e,s,r,i,n,a){let h;if(Y.cachesBoundsOfCurve&&(h=[...arguments].join(),Ve.boundsOfCurveCache[h]))return Ve.boundsOfCurveCache[h];const c=Math.sqrt,l=Math.abs,u=[],d=[[0,0],[0,0]];let g=6*o-12*e+6*r,f=-3*o+9*e-9*r+3*n,v=3*e-3*o;for(let T=0;T<2;++T){if(T>0&&(g=6*t-12*s+6*i,f=-3*t+9*s-9*i+3*a,v=3*s-3*t),l(f)<1e-12){if(l(g)<1e-12)continue;const W=-v/g;0<W&&W<1&&u.push(W);continue}const D=g*g-4*v*f;if(D<0)continue;const A=c(D),I=(-g+A)/(2*f);0<I&&I<1&&u.push(I);const E=(-g-A)/(2*f);0<E&&E<1&&u.push(E)}let _=u.length;const b=_,w=Yn(o,t,e,s,r,i,n,a);for(;_--;){const{x:T,y:D}=w(u[_]);d[0][_]=T,d[1][_]=D}d[0][b]=o,d[1][b]=t,d[0][b+1]=n,d[1][b+1]=a;const C=[new x(Math.min(...d[0]),Math.min(...d[1])),new x(Math.max(...d[0]),Math.max(...d[1]))];return Y.cachesBoundsOfCurve&&(Ve.boundsOfCurveCache[h]=C),C}const gh=(o,t,e)=>{let[s,r,i,n,a,h,c,l]=e;const u=((d,g,f,v,_,b,w)=>{if(f===0||v===0)return[];let C=0,T=0,D=0;const A=Math.PI,I=w*jr,E=te(I),W=Qt(I),q=.5*(-W*d-E*g),Z=.5*(-W*g+E*d),L=f**2,V=v**2,X=Z**2,nt=q**2,et=L*V-L*X-V*nt;let st=Math.abs(f),U=Math.abs(v);if(et<0){const z=Math.sqrt(1-et/(L*V));st*=z,U*=z}else D=(_===b?-1:1)*Math.sqrt(et/(L*X+V*nt));const bt=D*st*Z/U,y=-D*U*q/st,S=W*bt-E*y+.5*d,k=E*bt+W*y+.5*g;let O=Li(1,0,(q-bt)/st,(Z-y)/U),j=Li((q-bt)/st,(Z-y)/U,(-q-bt)/st,(-Z-y)/U);b===0&&j>0?j-=2*A:b===1&&j<0&&(j+=2*A);const H=Math.ceil(Math.abs(j/A*2)),B=[],ht=j/H,Pt=8/3*Math.sin(ht/4)*Math.sin(ht/4)/Math.sin(ht/2);let rt=O+ht;for(let z=0;z<H;z++)B[z]=dh(O,rt,W,E,st,U,S,k,Pt,C,T),C=B[z][5],T=B[z][6],O=rt,rt+=ht;return B})(c-o,l-t,r,i,a,h,n);for(let d=0,g=u.length;d<g;d++)u[d][1]+=o,u[d][2]+=t,u[d][3]+=o,u[d][4]+=t,u[d][5]+=o,u[d][6]+=t;return u},fh=o=>{let t=0,e=0,s=0,r=0;const i=[];let n,a=0,h=0;for(const c of o){const l=[...c];let u;switch(l[0]){case"l":l[1]+=t,l[2]+=e;case"L":t=l[1],e=l[2],u=["L",t,e];break;case"h":l[1]+=t;case"H":t=l[1],u=["L",t,e];break;case"v":l[1]+=e;case"V":e=l[1],u=["L",t,e];break;case"m":l[1]+=t,l[2]+=e;case"M":t=l[1],e=l[2],s=l[1],r=l[2],u=["M",t,e];break;case"c":l[1]+=t,l[2]+=e,l[3]+=t,l[4]+=e,l[5]+=t,l[6]+=e;case"C":a=l[3],h=l[4],t=l[5],e=l[6],u=["C",l[1],l[2],a,h,t,e];break;case"s":l[1]+=t,l[2]+=e,l[3]+=t,l[4]+=e;case"S":n==="C"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=l[3],e=l[4],u=["C",a,h,l[1],l[2],t,e],a=u[3],h=u[4];break;case"q":l[1]+=t,l[2]+=e,l[3]+=t,l[4]+=e;case"Q":a=l[1],h=l[2],t=l[3],e=l[4],u=["Q",a,h,t,e];break;case"t":l[1]+=t,l[2]+=e;case"T":n==="Q"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=l[1],e=l[2],u=["Q",a,h,t,e];break;case"a":l[6]+=t,l[7]+=e;case"A":gh(t,e,l).forEach(d=>i.push(d)),t=l[6],e=l[7];break;case"z":case"Z":t=s,e=r,u=["Z"]}u?(i.push(u),n=u[0]):n=""}return i},Vs=(o,t,e,s)=>Math.sqrt((e-o)**2+(s-t)**2),Yn=(o,t,e,s,r,i,n,a)=>h=>{const c=h**3,l=(g=>3*g**2*(1-g))(h),u=(g=>3*g*(1-g)**2)(h),d=(g=>(1-g)**3)(h);return new x(n*c+r*l+e*u+o*d,a*c+i*l+s*u+t*d)},Vn=o=>o**2,Hn=o=>2*o*(1-o),zn=o=>(1-o)**2,ph=(o,t,e,s,r,i,n,a)=>h=>{const c=Vn(h),l=Hn(h),u=zn(h),d=3*(u*(e-o)+l*(r-e)+c*(n-r)),g=3*(u*(s-t)+l*(i-s)+c*(a-i));return Math.atan2(g,d)},mh=(o,t,e,s,r,i)=>n=>{const a=Vn(n),h=Hn(n),c=zn(n);return new x(r*a+e*h+o*c,i*a+s*h+t*c)},vh=(o,t,e,s,r,i)=>n=>{const a=1-n,h=2*(a*(e-o)+n*(r-e)),c=2*(a*(s-t)+n*(i-s));return Math.atan2(c,h)},Bi=(o,t,e)=>{let s=new x(t,e),r=0;for(let i=1;i<=100;i+=1){const n=o(i/100);r+=Vs(s.x,s.y,n.x,n.y),s=n}return r},yh=(o,t)=>{let e,s=0,r=0,i={x:o.x,y:o.y},n=m({},i),a=.01,h=0;const c=o.iterator,l=o.angleFinder;for(;r<t&&a>1e-4;)n=c(s),h=s,e=Vs(i.x,i.y,n.x,n.y),e+r>t?(s-=a,a/=2):(i=n,s+=a,r+=e);return m(m({},n),{},{angle:l(h)})},Gn=o=>{let t,e,s=0,r=0,i=0,n=0,a=0;const h=[];for(const c of o){const l={x:r,y:i,command:c[0],length:0};switch(c[0]){case"M":e=l,e.x=n=r=c[1],e.y=a=i=c[2];break;case"L":e=l,e.length=Vs(r,i,c[1],c[2]),r=c[1],i=c[2];break;case"C":t=Yn(r,i,c[1],c[2],c[3],c[4],c[5],c[6]),e=l,e.iterator=t,e.angleFinder=ph(r,i,c[1],c[2],c[3],c[4],c[5],c[6]),e.length=Bi(t,r,i),r=c[5],i=c[6];break;case"Q":t=mh(r,i,c[1],c[2],c[3],c[4]),e=l,e.iterator=t,e.angleFinder=vh(r,i,c[1],c[2],c[3],c[4]),e.length=Bi(t,r,i),r=c[3],i=c[4];break;case"Z":e=l,e.destX=n,e.destY=a,e.length=Vs(r,i,n,a),r=n,i=a}s+=e.length,h.push(e)}return h.push({length:s,x:r,y:i}),h},xh=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Gn(o),s=0;for(;t-e[s].length>0&&s<e.length-2;)t-=e[s].length,s++;const r=e[s],i=t/r.length,n=o[s];switch(r.command){case"M":return{x:r.x,y:r.y,angle:0};case"Z":return m(m({},new x(r.x,r.y).lerp(new x(r.destX,r.destY),i)),{},{angle:Math.atan2(r.destY-r.y,r.destX-r.x)});case"L":return m(m({},new x(r.x,r.y).lerp(new x(n[1],n[2]),i)),{},{angle:Math.atan2(n[2]-r.y,n[1]-r.x)});case"C":case"Q":return yh(r,t)}},_h=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Ii=new RegExp(lh,"g"),bh=new RegExp(Bt,"gi"),wh={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},Sh=o=>{var t;const e=[],s=(t=o.match(_h))!==null&&t!==void 0?t:[];for(const r of s){const i=r[0];if(i==="z"||i==="Z"){e.push([i]);continue}const n=wh[i.toLowerCase()];let a=[];if(i==="a"||i==="A"){Ii.lastIndex=0;for(let h=null;h=Ii.exec(r);)a.push(...h.slice(1))}else a=r.match(bh)||[];for(let h=0;h<a.length;h+=n){const c=new Array(n),l=uh[i];c[0]=h>0&&l?l:i;for(let u=0;u<n;u++)c[u+1]=parseFloat(a[h+u]);e.push(c)}}return e},Ch=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new x(o[0]),s=new x(o[1]),r=1,i=0;const n=[],a=o.length,h=a>2;let c;for(h&&(r=o[2].x<s.x?-1:o[2].x===s.x?0:1,i=o[2].y<s.y?-1:o[2].y===s.y?0:1),n.push(["M",e.x-r*t,e.y-i*t]),c=1;c<a;c++){if(!e.eq(s)){const l=e.midPointFrom(s);n.push(["Q",e.x,e.y,l.x,l.y])}e=o[c],c+1<o.length&&(s=o[c+1])}return h&&(r=e.x>o[c-2].x?1:e.x===o[c-2].x?0:-1,i=e.y>o[c-2].y?1:e.y===o[c-2].y?0:-1),n.push(["L",e.x+r*t,e.y+i*t]),n},Nn=(o,t)=>o.map(e=>e.map((s,r)=>r===0||t===void 0?s:K(s,t)).join(" ")).join(" ");function Mr(o,t){const e=o.style;e&&t&&(typeof t=="string"?e.cssText+=";"+t:Object.entries(t).forEach(s=>{let[r,i]=s;return e.setProperty(r,i)}))}class Th extends vn{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),p(this,"upper",void 0),p(this,"container",void 0);const{el:r}=this.lower,i=this.createUpperCanvas();this.upper={el:i,ctx:i.getContext("2d")},this.applyCanvasStyle(r,{allowTouchScrolling:e}),this.applyCanvasStyle(i,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const n=this.createContainerElement();n.classList.add(s),r.parentNode&&r.parentNode.replaceChild(n,r),n.append(r,i),this.container=n}createUpperCanvas(){const{el:t}=this.lower,e=ee();return e.className=t.className,e.classList.remove("lower-canvas"),e.classList.add("upper-canvas"),e.setAttribute("data-fabric","top"),e.style.cssText=t.style.cssText,e.setAttribute("draggable","true"),e}createContainerElement(){const t=Pe().createElement("div");return t.setAttribute("data-fabric","wrapper"),Mr(t,{position:"relative"}),ci(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:r}=e;Mr(t,m(m({},s),{},{"touch-action":r?"manipulation":vt})),ci(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:r}=this.upper;mn(s,r,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),br(this.upper.el,t),br(this.container,t)}cleanupDOM(t){const e=this.container,{el:s}=this.lower,{el:r}=this.upper;super.cleanupDOM(t),e.removeChild(r),e.removeChild(s),e.parentNode&&e.parentNode.replaceChild(s,e)}dispose(){super.dispose(),Gt().dispose(this.upper.el),delete this.upper,delete this.container}}class er extends ts{constructor(){super(...arguments),p(this,"targets",[]),p(this,"_hoveredTargets",[]),p(this,"_currentTransform",null),p(this,"_groupSelector",null),p(this,"contextTopDirty",!1)}static getDefaults(){return m(m({},super.getDefaults()),er.ownDefaults)}get upperCanvasEl(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.el}get contextTop(){var t;return(t=this.elements.upper)===null||t===void 0?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new Th(t,{allowTouchScrolling:this.allowTouchScrolling,containerClass:this.containerClass}),this._createCacheCanvas()}_onObjectAdded(t){this._objectsToRender=void 0,super._onObjectAdded(t)}_onObjectRemoved(t){this._objectsToRender=void 0,t===this._activeObject&&(this.fire("before:selection:cleared",{deselected:[t]}),this._discardActiveObject(),this.fire("selection:cleared",{deselected:[t]}),t.fire("deselected",{target:t})),t===this._hoveredTarget&&(this._hoveredTarget=void 0,this._hoveredTargets=[]),super._onObjectRemoved(t)}_onStackOrderChanged(){this._objectsToRender=void 0,super._onStackOrderChanged()}_chooseObjectsToRender(){const t=this._activeObject;return!this.preserveObjectStacking&&t?this._objects.filter(e=>!e.group&&e!==t).concat(t):this._objects}renderAll(){this.cancelRequestedRender(),this.destroyed||(!this.contextTopDirty||this._groupSelector||this.isDrawingMode||(this.clearContext(this.contextTop),this.contextTopDirty=!1),this.hasLostContext&&(this.renderTopLayer(this.contextTop),this.hasLostContext=!1),!this._objectsToRender&&(this._objectsToRender=this._chooseObjectsToRender()),this.renderCanvas(this.getContext(),this._objectsToRender))}renderTopLayer(t){t.save(),this.isDrawingMode&&this._isCurrentlyDrawing&&(this.freeDrawingBrush&&this.freeDrawingBrush._render(),this.contextTopDirty=!0),this.selection&&this._groupSelector&&(this._drawSelection(t),this.contextTopDirty=!0),t.restore()}renderTop(){const t=this.contextTop;this.clearContext(t),this.renderTopLayer(t),this.fire("after:render",{ctx:t})}setTargetFindTolerance(t){t=Math.round(t),this.targetFindTolerance=t;const e=this.getRetinaScaling(),s=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=s,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,s){const r=this.targetFindTolerance,i=this.pixelFindContext;this.clearContext(i),i.save(),i.translate(-e+r,-s+r),i.transform(...this.viewportTransform);const n=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(i),t.selectionBackgroundColor=n,i.restore();const a=Math.round(r*this.getRetinaScaling());return Ma(i,a,a,a)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(s=>!!s&&t[s]===!0):t[e])}_shouldClearSelection(t,e){const s=this.getActiveObjects(),r=this._activeObject;return!!(!e||e&&r&&s.length>1&&s.indexOf(e)===-1&&r!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&r&&r!==e)}_shouldCenterTransform(t,e,s){if(!t)return;let r;return e===qs||e===_t||e===Mt||e===Ne?r=this.centeredScaling||t.centeredScaling:e===Rr&&(r=this.centeredRotation||t.centeredRotation),r?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=Q:["mr","tr","br"].includes(e)&&(s.x=N),["tl","mt","tr"].includes(e)?s.y=_r:["bl","mb","br"].includes(e)&&(s.y=mt)),s}_setupCurrentTransform(t,e,s){var r;const i=e.group?ke(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:n="",control:a}=e.getActiveControl()||{},h=s&&a?(r=a.getActionHandler(t,e,a))===null||r===void 0?void 0:r.bind(a):Go,c=((g,f,v,_)=>{if(!f||!g)return"drag";const b=_.controls[f];return b.getActionName(v,b,_)})(s,n,t,e),l=t[this.centeredKey],u=this._shouldCenterTransform(e,c,l)?{x:R,y:R}:this._getOriginFromCorner(e,n),d={target:e,action:c,actionHandler:h,actionPerformed:!1,corner:n,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:i.x-e.left,offsetY:i.y-e.top,originX:u.x,originY:u.y,ex:i.x,ey:i.y,lastX:i.x,lastY:i.y,theta:tt(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:l,original:m(m({},yn(e)),{},{originX:u.x,originY:u.y})};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:r,deltaY:i}=this._groupSelector,n=new x(e,s).transform(this.viewportTransform),a=new x(e+r,s+i).transform(this.viewportTransform),h=this.selectionLineWidth/2;let c=Math.min(n.x,a.x),l=Math.min(n.y,a.y),u=Math.max(n.x,a.x),d=Math.max(n.y,a.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(c,l,u-c,d-l)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,c+=h,l+=h,u-=h,d-=h,ut.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(c,l,u-c,d-l))}findTarget(t){if(this.skipTargetFind)return;const e=this.getViewportPoint(t),s=this._activeObject,r=this.getActiveObjects();if(this.targets=[],s&&r.length>=1){if(s.findControl(e,wr(t))||r.length>1&&this.searchPossibleTargets([s],e))return s;if(s===this.searchPossibleTargets([s],e)){if(this.preserveObjectStacking){const i=this.targets;this.targets=[];const n=this.searchPossibleTargets(this._objects,e);return t[this.altSelectionKey]&&n&&n!==s?(this.targets=i,s):n}return s}}return this.searchPossibleTargets(this._objects,e)}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const r=this.getZoom(),i=t.padding/r;if(i){const[n,a,h,c]=s,l=Math.atan2(a.y-n.y,a.x-n.x),u=Qt(l)*i,d=te(l)*i,g=u+d,f=u-d;s=[new x(n.x-f,n.y-g),new x(a.x+g,a.y-f),new x(h.x+f,h.y+g),new x(c.x-g,c.y+f)]}return J.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,ke(e,void 0,this.viewportTransform))&&(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing||!this.isTargetTransparent(t,e.x,e.y)))}_searchPossibleTargets(t,e){let s=t.length;for(;s--;){const r=t[s];if(this._checkTarget(r,e)){if(ks(r)&&r.subTargetCheck){const i=this._searchPossibleTargets(r._objects,e);i&&this.targets.push(i)}return r}}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e);if(s&&ks(s)&&s.interactive&&this.targets[0]){const r=this.targets;for(let i=r.length-1;i>0;i--){const n=r[i];if(!ks(n)||!n.interactive)return n}return r[0]}return s}getViewportPoint(t){return this._pointer?this._pointer:this.getPointer(t,!0)}getScenePoint(t){return this._absolutePointer?this._absolutePointer:this.getPointer(t)}getPointer(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,r=s.getBoundingClientRect();let i=Io(t),n=r.width||0,a=r.height||0;n&&a||(mt in r&&_r in r&&(a=Math.abs(r.top-r.bottom)),Q in r&&N in r&&(n=Math.abs(r.right-r.left))),this.calcOffset(),i.x=i.x-this._offset.left,i.y=i.y-this._offset.top,e||(i=ke(i,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(i.x/=h,i.y/=h);const c=n===0||a===0?new x(1,1):new x(s.width/n,s.height/a);return i.multiply(c)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=ee(),this.pixelFindContext=this.pixelFindCanvasEl.getContext("2d",{willReadFrequently:!0}),this.setTargetFindTolerance(this.targetFindTolerance)}getTopContext(){return this.elements.upper.ctx}getSelectionContext(){return this.elements.upper.ctx}getSelectionElement(){return this.elements.upper.el}getActiveObject(){return this._activeObject}getActiveObjects(){const t=this._activeObject;return de(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,r=!1;const i=this.getActiveObjects(),n=[],a=[];t.forEach(h=>{i.includes(h)||(s=!0,h.fire("deselected",{e,target:h}),a.push(h))}),i.forEach(h=>{t.includes(h)||(s=!0,h.fire("selected",{e,target:h}),n.push(h))}),t.length>0&&i.length>0?(r=!0,s&&this.fire("selection:updated",{e,selected:n,deselected:a})):i.length>0?(r=!0,this.fire("selection:created",{e,selected:n})):t.length>0&&(r=!0,this.fire("selection:cleared",{e,deselected:a})),r&&(this._objectsToRender=void 0)}setActiveObject(t,e){const s=this.getActiveObjects(),r=this._setActiveObject(t,e);return this._fireSelectionEvents(s,e),r}_setActiveObject(t,e){const s=this._activeObject;return s!==t&&!(!this._discardActiveObject(e,t)&&this._activeObject)&&!t.onSelect({e})&&(this._activeObject=t,de(t)&&s!==t&&t.set("canvas",this),t.setCoords(),!0)}_discardActiveObject(t,e){const s=this._activeObject;return!!s&&!s.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===s&&this.endCurrentTransform(t),de(s)&&s===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0)}discardActiveObject(t){const e=this.getActiveObjects(),s=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[s]});const r=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),r}endCurrentTransform(t){const e=this._currentTransform;this._finalizeCurrentTransform(t),e&&e.target&&(e.target.isMoving=!1),this._currentTransform=null}_finalizeCurrentTransform(t){const e=this._currentTransform,s=e.target,r={e:t,target:s,transform:e,action:e.action};s._scaling&&(s._scaling=!1),s.setCoords(),e.actionPerformed&&(this.fire("object:modified",r),s.fire(js,r))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;de(t)&&(t.removeAll(),t.dispose()),delete this._activeObject,super.destroy(),this.pixelFindContext=null,this.pixelFindCanvasEl=void 0}clear(){this.discardActiveObject(),this._activeObject=void 0,this.clearContext(this.contextTop),super.clear()}drawControls(t){const e=this._activeObject;e&&e._renderControls(t)}_toObject(t,e,s){const r=this._realizeGroupTransformOnObject(t),i=super._toObject(t,e,s);return t.set(r),i}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&de(e)&&this._activeObject===e){const s=Le(t,["angle","flipX","flipY",N,_t,Mt,Ae,je,mt]);return Xo(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const r=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(r)}}p(er,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!1});class Oh{constructor(t){p(this,"targets",[]),p(this,"__disposer",void 0);const e=()=>{const{hiddenTextarea:r}=t.getActiveObject()||{};r&&r.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),Se(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;!((e=this.target)===null||e===void 0)&&e.isEditing&&this.target.updateSelectionOnMouseMove(t)}clear(){this.targets=[],this.target=void 0}dispose(){this.clear(),this.__disposer(),delete this.__disposer}}const kh=["target","oldTarget","fireCanvas","e"],St={passive:!1},_e=(o,t)=>{const e=o.getViewportPoint(t),s=o.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},oe=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.addEventListener(...e)},Ot=function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return o.removeEventListener(...e)},Dh={mouse:{in:"over",out:"out",targetIn:"mouseover",targetOut:"mouseout",canvasIn:"mouse:over",canvasOut:"mouse:out"},drag:{in:"enter",out:"leave",targetIn:"dragenter",targetOut:"dragleave",canvasIn:"drag:enter",canvasOut:"drag:leave"}};class Er extends er{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),p(this,"_isClick",void 0),p(this,"textEditingManager",new Oh(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(e=>{this[e]=this[e].bind(this)}),this.addOrRemove(oe,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,r=this._getEventPrefix();t(pn(s),"resize",this._onResize),t(s,r+"down",this._onMouseDown),t(s,"".concat(r,"move"),this._onMouseMove,St),t(s,"".concat(r,"out"),this._onMouseOut),t(s,"".concat(r,"enter"),this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),t(s,"click",this._onClick),t(s,"dblclick",this._onClick),t(s,"dragstart",this._onDragStart),t(s,"dragend",this._onDragEnd),t(s,"dragover",this._onDragOver),t(s,"dragenter",this._onDragEnter),t(s,"dragleave",this._onDragLeave),t(s,"drop",this._onDrop),this.enablePointerEvents||t(s,"touchstart",this._onTouchStart,St)}removeListeners(){this.addOrRemove(Ot,"remove");const t=this._getEventPrefix(),e=Lt(this.upperCanvasEl);Ot(e,"".concat(t,"up"),this._onMouseUp),Ot(e,"touchend",this._onTouchEnd,St),Ot(e,"".concat(t,"move"),this._onMouseMove,St),Ot(e,"touchmove",this._onMouseMove,St),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=m({e:t},_e(this,t));this.fire("mouse:out",m(m({},s),{},{target:e})),this._hoveredTarget=void 0,e&&e.fire("mouseout",m({},s)),this._hoveredTargets.forEach(r=>{this.fire("mouse:out",m(m({},s),{},{target:r})),r&&r.fire("mouseout",m({},s))}),this._hoveredTargets=[]}_onMouseEnter(t){this._currentTransform||this.findTarget(t)||(this.fire("mouse:over",m({e:t},_e(this,t))),this._hoveredTarget=void 0,this._hoveredTargets=[])}_onDragStart(t){this._isClick=!1;const e=this.getActiveObject();if(e&&e.onDragStart(t)){this._dragSource=e;const s={e:t,target:e};return this.fire("dragstart",s),e.fire("dragstart",s),void oe(this.upperCanvasEl,"drag",this._onDragProgress)}li(t)}_renderDragEffects(t,e,s){let r=!1;const i=this._dropTarget;i&&i!==e&&i!==s&&(i.clearContextTop(),r=!0),e==null||e.clearContextTop(),s!==e&&(s==null||s.clearContextTop());const n=this.contextTop;n.save(),n.transform(...this.viewportTransform),e&&(n.save(),e.transform(n),e.renderDragSourceEffect(t),n.restore(),r=!0),s&&(n.save(),s.transform(n),s.renderDropTargetEffect(t),n.restore(),r=!0),n.restore(),r&&(this.contextTopDirty=!0)}_onDragEnd(t){const e=!!t.dataTransfer&&t.dataTransfer.dropEffect!==vt,s=e?this._activeObject:void 0,r={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};Ot(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",r),this._dragSource&&this._dragSource.fire("dragend",r),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}findDragTargets(t){return this.targets=[],{target:this._searchPossibleTargets(this._objects,this.getViewportPoint(t)),targets:[...this.targets]}}_onDragOver(t){const e="dragover",{target:s,targets:r}=this.findDragTargets(t),i=this._dragSource,n={e:t,target:s,subTargets:r,dragSource:i,canDrop:!1,dropTarget:void 0};let a;this.fire(e,n),this._fireEnterLeaveEvents(s,n),s&&(s.canDrop(t)&&(a=s),s.fire(e,n));for(let h=0;h<r.length;h++){const c=r[h];c.canDrop(t)&&(a=c),c.fire(e,n)}this._renderDragEffects(t,i,a),this._dropTarget=a}_onDragEnter(t){const{target:e,targets:s}=this.findDragTargets(t),r={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",r),this._fireEnterLeaveEvents(e,r)}_onDragLeave(t){const e={e:t,target:this._draggedoverTarget,subTargets:this.targets,dragSource:this._dragSource};this.fire("dragleave",e),this._fireEnterLeaveEvents(void 0,e),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this.targets=[],this._hoveredTargets=[]}_onDrop(t){const{target:e,targets:s}=this.findDragTargets(t),r=this._basicEventHandler("drop:before",m({e:t,target:e,subTargets:s,dragSource:this._dragSource},_e(this,t)));r.didDrop=!1,r.dropTarget=void 0,this._basicEventHandler("drop",r),this.fire("drop:after",r)}_onContextMenu(t){const e=this.findTarget(t),s=this.targets||[],r=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&li(t),this._basicEventHandler("contextmenu",r),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),e==2&&t.type==="dblclick"&&this._handleEvent(t,"dblclick"),e==3&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return t.isPrimary===!0||t.isPrimary!==!1&&(t.type==="touchend"&&t.touches.length===0||!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId)}_onTouchStart(t){let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t),(this.isDrawingMode||s&&this._target===s)&&(e=!0),e&&t.preventDefault(),this._resetTransformEventData();const r=this.upperCanvasEl,i=this._getEventPrefix(),n=Lt(r);oe(n,"touchend",this._onTouchEnd,St),e&&oe(n,"touchmove",this._onMouseMove,St),Ot(r,"".concat(i,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();Ot(e,"".concat(s,"move"),this._onMouseMove,St);const r=Lt(e);oe(r,"".concat(s,"up"),this._onMouseUp),oe(r,"".concat(s,"move"),this._onMouseMove,St)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=Lt(this.upperCanvasEl);Ot(s,"touchend",this._onTouchEnd,St),Ot(s,"touchmove",this._onMouseMove,St),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{oe(this.upperCanvasEl,"".concat(e,"down"),this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this.__onMouseUp(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const r=Lt(this.upperCanvasEl);Ot(r,"".concat(s,"up"),this._onMouseUp),Ot(r,"".concat(s,"move"),this._onMouseMove,St),oe(e,"".concat(s,"move"),this._onMouseMove,St)}}_onMouseMove(t){const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t)}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._cacheTransformEventData(t),this._handleEvent(t,"up:before");const s=this._currentTransform,r=this._isClick,i=this._target,{button:n}=t;if(n)return(this.fireMiddleClick&&n===1||this.fireRightClick&&n===2)&&this._handleEvent(t,"up"),void this._resetTransformEventData();if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let a,h,c=!1;if(s&&(this._finalizeCurrentTransform(t),c=s.actionPerformed),!r){const l=i===this._activeObject;this.handleSelection(t),c||(c=this._shouldRender(i)||!l&&i===this._activeObject)}if(i){const l=i.findControl(this.getViewportPoint(t),wr(t)),{key:u,control:d}=l||{};if(h=u,i.selectable&&i!==this._activeObject&&i.activeOn==="up")this.setActiveObject(i,t),c=!0;else if(d){const g=d.getMouseUpHandler(t,i,d);g&&(a=this.getScenePoint(t),g.call(d,t,s,a.x,a.y))}i.isMoving=!1}if(s&&(s.target!==i||s.corner!==h)){const l=s.target&&s.target.controls[s.corner],u=l&&l.getMouseUpHandler(t,s.target,l);a=a||this.getScenePoint(t),u&&u.call(l,t,s,a.x,a.y)}this._setCursorFromEvent(t,i),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,i&&(i.__corner=void 0),c?this.requestRenderAll():r||(e=this._activeObject)!==null&&e!==void 0&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:s,subTargets:r=[]}=e;this.fire(t,e),s&&s.fire(t,e);for(let i=0;i<r.length;i++)r[i]!==s&&r[i].fire(t,e);return e}_handleEvent(t,e,s){const r=this._target,i=this.targets||[],n=m(m(m({e:t,target:r,subTargets:i},_e(this,t)),{},{transform:this._currentTransform},e==="up:before"||e==="up"?{isClick:this._isClick,currentTarget:this.findTarget(t),currentSubTargets:this.targets}:{}),e==="down:before"||e==="down"?s:{});this.fire("mouse:".concat(e),n),r&&r.fire("mouse".concat(e),n);for(let a=0;a<i.length;a++)i[a]!==r&&i[a].fire("mouse".concat(e),n)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._cacheTransformEventData(t),this._handleEvent(t,"down:before");let e=this._target,s=!!e&&e===this._activeObject;const{button:r}=t;if(r)return(this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"down",{alreadySelected:s}),void this._resetTransformEventData();if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let i=this._shouldRender(e),n=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,n=!0,i=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const a=this.getScenePoint(t);this._groupSelector={x:a.x,y:a.y,deltaY:0,deltaX:0}}if(s=!!e&&e===this._activeObject,e){e.selectable&&e.activeOn==="down"&&this.setActiveObject(e,t);const a=e.findControl(this.getViewportPoint(t),wr(t));if(e===this._activeObject&&(a||!n)){this._setupCurrentTransform(t,e,s);const h=a?a.control:void 0,c=this.getScenePoint(t),l=h&&h.getMouseDownHandler(t,e,h);l&&l.call(h,t,this._currentTransform,c.x,c.y)}}i&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),i&&this.requestRenderAll()}_resetTransformEventData(){this._target=this._pointer=this._absolutePointer=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._pointer=this.getViewportPoint(t),this._absolutePointer=ke(this._pointer,void 0,this.viewportTransform),this._target=this._currentTransform?this._currentTransform.target:this.findTarget(t)}__onMouseMove(t){if(this._isClick=!1,this._cacheTransformEventData(t),this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;const e=this._groupSelector;if(e){const s=this.getScenePoint(t);e.deltaX=s.x-e.x,e.deltaY=s.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const s=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move"),this._resetTransformEventData()}_fireOverOutEvents(t,e){const s=this._hoveredTarget,r=this._hoveredTargets,i=this.targets,n=Math.max(r.length,i.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let a=0;a<n;a++)i[a]===e||r[a]&&r[a]===s||this.fireSyntheticInOutEvents("mouse",{e:t,target:i[a],oldTarget:r[a]});this._hoveredTarget=e,this._hoveredTargets=this.targets.concat()}_fireEnterLeaveEvents(t,e){const s=this._draggedoverTarget,r=this._hoveredTargets,i=this.targets,n=Math.max(r.length,i.length);this.fireSyntheticInOutEvents("drag",m(m({},e),{},{target:t,oldTarget:s,fireCanvas:!0}));for(let a=0;a<n;a++)this.fireSyntheticInOutEvents("drag",m(m({},e),{},{target:i[a],oldTarget:r[a]}));this._draggedoverTarget=t}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:r,fireCanvas:i,e:n}=e,a=$(e,kh);const{targetIn:h,targetOut:c,canvasIn:l,canvasOut:u}=Dh[t],d=r!==s;if(r&&d){const g=m(m({},a),{},{e:n,target:r,nextTarget:s},_e(this,n));i&&this.fire(u,g),r.fire(c,g)}if(s&&d){const g=m(m({},a),{},{e:n,target:s,previousTarget:r},_e(this,n));i&&this.fire(l,g),s.fire(h,g)}}__onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,r=s.target,i=r.group?ke(e,void 0,r.group.calcTransformMatrix()):e;s.shiftKey=t.shiftKey,s.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,s,i),s.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,s){const{action:r,actionHandler:i,target:n}=e,a=!!i&&i(t,e,s.x,s.y);a&&n.setCoords(),r==="drag"&&a&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||a}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let s=e.hoverCursor||this.hoverCursor;const r=de(this._activeObject)?this._activeObject:null,i=(!r||e.group!==r)&&e.findControl(this.getViewportPoint(t));if(i){const n=i.control;this.setCursor(n.cursorStyleHandler(t,n,e))}else e.subTargetCheck&&this.targets.concat().reverse().map(n=>{s=n.hoverCursor||s}),this.setCursor(s)}handleMultiSelection(t,e){const s=this._activeObject,r=de(s);if(s&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(s!==e||r)&&(r||!e.isDescendantOf(s)&&!s.isDescendantOf(e))&&!e.onSelect({e:t})&&!s.getActiveControl()){if(r){const i=s.getObjects();if(e===s){const n=this.getViewportPoint(t);if(!(e=this.searchPossibleTargets(i,n)||this.searchPossibleTargets(this._objects,n))||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=[...this.targets],s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=[...this.targets]),this._fireSelectionEvents(i,t)}else{s.isEditing&&s.exitEditing();const i=new(M.getClass("ActiveSelection"))([],{canvas:this});i.multiSelectAdd(s,e),this._hoveredTarget=i,this._setActiveObject(i,t),this._fireSelectionEvents([s],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:s,deltaX:r,deltaY:i}=this._groupSelector,n=new x(e,s),a=n.add(new x(r,i)),h=n.min(a),c=n.max(a).subtract(h),l=this.collectObjects({left:h.x,top:h.y,width:c.x,height:c.y},{includeIntersecting:!this.selectionFullyContained}),u=n.eq(a)?l[0]?[l[0]]:[]:l.length>1?l.filter(d=>!d.onSelect({e:t})).reverse():l;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const d=M.getClass("ActiveSelection");this.setActiveObject(new d(u,{canvas:this}),t)}return this._groupSelector=null,!0}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1,e=arguments.length>1?arguments[1]:void 0;const{upper:s}=this.elements;s.ctx=void 0;const r=super.toCanvasElement(t,e);return s.ctx=s.el.getContext("2d"),r}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const Un={x1:0,y1:0,x2:0,y2:0},Mh=m(m({},Un),{},{r1:0,r2:0}),Te=(o,t)=>isNaN(o)&&typeof t=="number"?t:o;function qn(o){return o&&/%$/.test(o)&&Number.isFinite(parseFloat(o))}function Kn(o,t){const e=typeof o=="number"?o:typeof o=="string"?parseFloat(o)/(qn(o)?100:1):NaN;return Ee(0,Te(e,t),1)}const Eh=/\s*;\s*/,Ph=/\s*:\s*/;function Ah(o,t){let e,s;const r=o.getAttribute("style");if(r){const n=r.split(Eh);n[n.length-1]===""&&n.pop();for(let a=n.length;a--;){const[h,c]=n[a].split(Ph).map(l=>l.trim());h==="stop-color"?e=c:h==="stop-opacity"&&(s=c)}}const i=new G(e||o.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Kn(o.getAttribute("offset"),0),color:i.toRgb(),opacity:Te(parseFloat(s||o.getAttribute("stop-opacity")||""),1)*i.getAlpha()*t}}function jh(o,t){const e=[],s=o.getElementsByTagName("stop"),r=Kn(t,1);for(let i=s.length;i--;)e.push(Ah(s[i],r));return e}function $n(o){return o.nodeName==="linearGradient"||o.nodeName==="LINEARGRADIENT"?"linear":"radial"}function Jn(o){return o.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function At(o,t){return o.getAttribute(t)}function Fh(o,t){return function(e,s){let r,{width:i,height:n,gradientUnits:a}=s;return Object.entries(e).reduce((h,c)=>{let[l,u]=c;if(u==="Infinity")r=1;else if(u==="-Infinity")r=0;else{const d=typeof u=="string";r=d?parseFloat(u):u,d&&qn(u)&&(r*=.01,a==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(r*=i),l!=="y1"&&l!=="y2"||(r*=n)))}return h[l]=r,h},{})}($n(o)==="linear"?function(e){return{x1:At(e,"x1")||0,y1:At(e,"y1")||0,x2:At(e,"x2")||"100%",y2:At(e,"y2")||0}}(o):function(e){return{x1:At(e,"fx")||At(e,"cx")||"50%",y1:At(e,"fy")||At(e,"cy")||"50%",r1:0,x2:At(e,"cx")||"50%",y2:At(e,"cy")||"50%",r2:At(e,"r")||"50%"}}(o),m(m({},t),{},{gradientUnits:Jn(o)}))}class is{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:r={},colorStops:i=[],offsetX:n=0,offsetY:a=0,gradientTransform:h,id:c}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:m(m({},e==="radial"?Mh:Un),r),colorStops:i,offsetX:n,offsetY:a,gradientTransform:h,id:c?"".concat(c,"_").concat(le()):le()})}addColorStop(t){for(const e in t){const s=new G(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return m(m({},Le(this,t)),{},{type:this.type,coords:m({},this.coords),colorStops:this.colorStops.map(e=>m({},e)),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0})}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],r=this.gradientTransform?this.gradientTransform.concat():ft.concat(),i=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",n=this.colorStops.map(u=>m({},u)).sort((u,d)=>u.offset-d.offset);let a=-this.offsetX,h=-this.offsetY;var c;i==="objectBoundingBox"?(a/=t.width,h/=t.height):(a+=t.width/2,h+=t.height/2),(c=t)&&typeof c._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(a-=t.pathOffset.x,h-=t.pathOffset.y),r[4]-=a,r[5]-=h;const l=['id="SVGID_'.concat(this.id,'"'),'gradientUnits="'.concat(i,'"'),'gradientTransform="'.concat(e?e+" ":"").concat(qe(r),'"'),""].join(" ");if(this.type==="linear"){const{x1:u,y1:d,x2:g,y2:f}=this.coords;s.push("<linearGradient ",l,' x1="',u,'" y1="',d,'" x2="',g,'" y2="',f,`">
42
42
  `)}else if(this.type==="radial"){const{x1:u,y1:d,x2:g,y2:f,r1:v,r2:_}=this.coords,b=v>_;s.push("<radialGradient ",l,' cx="',b?u:g,'" cy="',b?d:f,'" r="',b?v:_,'" fx="',b?g:u,'" fy="',b?f:d,`">
43
43
  `),b&&(n.reverse(),n.forEach(C=>{C.offset=1-C.offset}));const w=Math.min(v,_);if(w>0){const C=w/Math.max(v,_);n.forEach(T=>{T.offset+=C*(1-T.offset)})}}return n.forEach(u=>{let{color:d,offset:g,opacity:f}=u;s.push("<stop ",'offset="',100*g+"%",'" style="stop-color:',d,f!==void 0?";stop-opacity: "+f:";",`"/>
44
44
  `)}),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
45
- `),s.join("")}toLive(t){const{x1:e,y1:s,x2:r,y2:i,r1:n,r2:a}=this.coords,h=this.type==="linear"?t.createLinearGradient(e,s,r,i):t.createRadialGradient(e,s,n,r,i,a);return this.colorStops.forEach(c=>{let{color:l,opacity:u,offset:d}=c;h.addColorStop(d,u!==void 0?new G(l).setAlpha(u).toRgba():l)}),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(m(m({},t),{},{colorStops:e?e.map(r=>m({},r)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const r=$n(t),i=e._findCenterFromElement();return new this(m({id:t.getAttribute("id")||void 0,type:Kn(t),coords:Ph(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:Eh(t,s.opacity),gradientUnits:r,gradientTransform:Or(t.getAttribute("gradientTransform")||"")},r==="pixels"?{offsetX:e.width/2-i.x,offsetY:e.height/2-i.y}:{offsetX:0,offsetY:0}))}}p(is,"type","Gradient"),M.setClass(is,"gradient"),M.setClass(is,"linear"),M.setClass(is,"radial");const Ah=["type","source","patternTransform"];class dr{get type(){return"pattern"}set type(t){ce("warn","Setting type has no effect",t)}constructor(t){p(this,"repeat","repeat"),p(this,"offsetX",0),p(this,"offsetY",0),p(this,"crossOrigin",""),this.id=le(),Object.assign(this,t)}isImageSource(){return!!this.source&&typeof this.source.src=="string"}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const{repeat:e,crossOrigin:s}=this;return m(m({},Le(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:K(this.offsetX,Y.NUM_FRACTION_DIGITS),offsetY:K(this.offsetY,Y.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:s}=t;const{source:r,repeat:i,id:n}=this,a=Te(this.offsetX/e,0),h=Te(this.offsetY/s,0),c=i==="repeat-y"||i==="no-repeat"?1+Math.abs(a||0):Te(r.width/e,0),l=i==="repeat-x"||i==="no-repeat"?1+Math.abs(h||0):Te(r.height/s,0);return['<pattern id="SVGID_'.concat(n,'" x="').concat(a,'" y="').concat(h,'" width="').concat(c,'" height="').concat(l,'">'),'<image x="0" y="0" width="'.concat(r.width,'" height="').concat(r.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
46
- `)}static async fromObject(t,e){let{type:s,source:r,patternTransform:i}=t,n=$(t,Ah);const a=await Ms(r,m(m({},e),{},{crossOrigin:n.crossOrigin}));return new this(m(m({},n),{},{patternTransform:i&&i.slice(0),source:a}))}}p(dr,"type","Pattern"),M.setClass(dr),M.setClass(dr,"pattern");class jh{constructor(t){p(this,"color","rgb(0, 0, 0)"),p(this,"width",1),p(this,"shadow",null),p(this,"strokeLineCap","round"),p(this,"strokeLineJoin","round"),p(this,"strokeMiterLimit",10),p(this,"strokeDashArray",null),p(this,"limitedToCanvasSize",!1),this.canvas=t}_setBrushStyles(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])}_saveAndTransform(t){const e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])}needsFullRender(){return new G(this.color).getAlpha()<1||!!this.shadow}_setShadow(){if(!this.shadow||!this.canvas)return;const t=this.canvas,e=this.shadow,s=t.contextTop,r=t.getZoom()*t.getRetinaScaling();s.shadowColor=e.color,s.shadowBlur=e.blur*r,s.shadowOffsetX=e.offsetX*r,s.shadowOffsetY=e.offsetY*r}_resetShadow(){const t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}_isOutSideCanvas(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}const Fh=["path","left","top"],Lh=["d"];class ae extends ut{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:r,top:i}=e,n=$(e,Fh);super(),Object.assign(this,ae.ownDefaults),this.setOptions(n),this._setPath(t||[],!0),typeof r=="number"&&this.set(N,r),typeof i=="number"&&this.set(mt,i)}_setPath(t,e){this.path=uh(Array.isArray(t)?t:_h(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new x(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const r of this.path)switch(r[0]){case"L":t.lineTo(r[1]+e,r[2]+s);break;case"M":t.moveTo(r[1]+e,r[2]+s);break;case"C":t.bezierCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s,r[5]+e,r[6]+s);break;case"Q":t.quadraticCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject(t)),{},{path:this.path.map(e=>e.slice())})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=Gn(this.path,Y.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
- `)]}_getOffsetTransform(){const t=Y.NUM_FRACTION_DIGITS;return" translate(".concat(K(-this.pathOffset.x,t),", ").concat(K(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return" "+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:r}=this._calcDimensions();this.set({width:e,height:s,pathOffset:r}),t&&this.setPositionByOrigin(r,R,R)}_calcBoundsFromPath(){const t=[];let e=0,s=0,r=0,i=0;for(const n of this.path)switch(n[0]){case"L":r=n[1],i=n[2],t.push({x:e,y:s},{x:r,y:i});break;case"M":r=n[1],i=n[2],e=r,s=i;break;case"C":t.push(...Ri(r,i,n[1],n[2],n[3],n[4],n[5],n[6])),r=n[5],i=n[6];break;case"Q":t.push(...Ri(r,i,n[1],n[2],n[1],n[2],n[3],n[4])),r=n[3],i=n[4];break;case"Z":r=e,i=s}return Zt(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return m(m({},t),{},{pathOffset:new x(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{d:i}=r;return new this(i,m(m(m({},$(r,Lh)),e),{},{left:void 0,top:void 0}))}}p(ae,"type","Path"),p(ae,"cacheProperties",[...re,"path","fillRule"]),p(ae,"ATTRIBUTE_NAMES",[...ue,"d"]),M.setClass(ae),M.setSVGClass(ae);class Hs extends jh{constructor(t){super(t),p(this,"decimate",.4),p(this,"drawStraightLine",!1),p(this,"straightLineKey","shiftKey"),this._points=[],this._hasStraightLine=!1}needsFullRender(){return super.needsFullRender()||this._hasStraightLine}static drawSegment(t,e,s){const r=e.midPointFrom(s);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r}onMouseDown(t,e){let{e:s}=e;this.canvas._isMainEvent(s)&&(this.drawStraightLine=!!this.straightLineKey&&s[this.straightLineKey],this._prepareForDrawing(t),this._addPoint(t),this._render())}onMouseMove(t,e){let{e:s}=e;if(this.canvas._isMainEvent(s)&&(this.drawStraightLine=!!this.straightLineKey&&s[this.straightLineKey],(this.limitedToCanvasSize!==!0||!this._isOutSideCanvas(t))&&this._addPoint(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{const r=this._points,i=r.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=Hs.drawSegment(n,r[i-2],r[i-1]),n.stroke(),n.restore()}}onMouseUp(t){let{e}=t;return!this.canvas._isMainEvent(e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)}_prepareForDrawing(t){this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)}_addPoint(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1]))&&(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),!0)}_reset(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1}_render(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.canvas.contextTop,e=this._points[0],s=this._points[1];if(this._saveAndTransform(t),t.beginPath(),this._points.length===2&&e.x===s.x&&e.y===s.y){const r=this.width/1e3;e.x-=r,s.x+=r}t.moveTo(e.x,e.y);for(let r=1;r<this._points.length;r++)Hs.drawSegment(t,e,s),e=this._points[r],s=this._points[r+1];t.lineTo(e.x,e.y),t.stroke(),t.restore()}convertPointsToSVGPath(t){const e=this.width/1e3;return bh(t,e)}createPath(t){const e=new ae(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new zt(this.shadow)),e}decimatePoints(t,e){if(t.length<=2)return t;let s,r=t[0];const i=this.canvas.getZoom(),n=Math.pow(e/i,2),a=t.length-1,h=[r];for(let c=1;c<a-1;c++)s=Math.pow(r.x-t[c].x,2)+Math.pow(r.y-t[c].y,2),s>=n&&(r=t[c],h.push(r));return h.push(t[a]),h}_finalizeAndAddPath(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));const t=this.convertPointsToSVGPath(this._points);if(function(s){return Gn(s)==="M 0 0 Q 0 0 0 0 L 0 0"}(t))return void this.canvas.requestRenderAll();const e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}const Rh=["left","top","radius"],Jn=["radius","startAngle","endAngle","counterClockwise"];class Xt extends ut{static getDefaults(){return m(m({},super.getDefaults()),Xt.ownDefaults)}constructor(t){super(),Object.assign(this,Xt.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),t==="radius"&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,tt(this.startAngle),tt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(_t)}getRadiusY(){return this.get("radius")*this.get(Mt)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Jn,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
45
+ `),s.join("")}toLive(t){const{x1:e,y1:s,x2:r,y2:i,r1:n,r2:a}=this.coords,h=this.type==="linear"?t.createLinearGradient(e,s,r,i):t.createRadialGradient(e,s,n,r,i,a);return this.colorStops.forEach(c=>{let{color:l,opacity:u,offset:d}=c;h.addColorStop(d,u!==void 0?new G(l).setAlpha(u).toRgba():l)}),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this(m(m({},t),{},{colorStops:e?e.map(r=>m({},r)):void 0,gradientTransform:s?[...s]:void 0}))}static fromElement(t,e,s){const r=Jn(t),i=e._findCenterFromElement();return new this(m({id:t.getAttribute("id")||void 0,type:$n(t),coords:Fh(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:jh(t,s.opacity),gradientUnits:r,gradientTransform:Or(t.getAttribute("gradientTransform")||"")},r==="pixels"?{offsetX:e.width/2-i.x,offsetY:e.height/2-i.y}:{offsetX:0,offsetY:0}))}}p(is,"type","Gradient"),M.setClass(is,"gradient"),M.setClass(is,"linear"),M.setClass(is,"radial");const Lh=["type","source","patternTransform"];class dr{get type(){return"pattern"}set type(t){ce("warn","Setting type has no effect",t)}constructor(t){p(this,"repeat","repeat"),p(this,"offsetX",0),p(this,"offsetY",0),p(this,"crossOrigin",""),this.id=le(),Object.assign(this,t)}isImageSource(){return!!this.source&&typeof this.source.src=="string"}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&this.source.naturalWidth!==0&&this.source.naturalHeight!==0)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const{repeat:e,crossOrigin:s}=this;return m(m({},Le(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:K(this.offsetX,Y.NUM_FRACTION_DIGITS),offsetY:K(this.offsetY,Y.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null})}toSVG(t){let{width:e,height:s}=t;const{source:r,repeat:i,id:n}=this,a=Te(this.offsetX/e,0),h=Te(this.offsetY/s,0),c=i==="repeat-y"||i==="no-repeat"?1+Math.abs(a||0):Te(r.width/e,0),l=i==="repeat-x"||i==="no-repeat"?1+Math.abs(h||0):Te(r.height/s,0);return['<pattern id="SVGID_'.concat(n,'" x="').concat(a,'" y="').concat(h,'" width="').concat(c,'" height="').concat(l,'">'),'<image x="0" y="0" width="'.concat(r.width,'" height="').concat(r.height,'" xlink:href="').concat(this.sourceToString(),'"></image>'),"</pattern>",""].join(`
46
+ `)}static async fromObject(t,e){let{type:s,source:r,patternTransform:i}=t,n=$(t,Lh);const a=await Ms(r,m(m({},e),{},{crossOrigin:n.crossOrigin}));return new this(m(m({},n),{},{patternTransform:i&&i.slice(0),source:a}))}}p(dr,"type","Pattern"),M.setClass(dr),M.setClass(dr,"pattern");class Rh{constructor(t){p(this,"color","rgb(0, 0, 0)"),p(this,"width",1),p(this,"shadow",null),p(this,"strokeLineCap","round"),p(this,"strokeLineJoin","round"),p(this,"strokeMiterLimit",10),p(this,"strokeDashArray",null),p(this,"limitedToCanvasSize",!1),this.canvas=t}_setBrushStyles(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])}_saveAndTransform(t){const e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])}needsFullRender(){return new G(this.color).getAlpha()<1||!!this.shadow}_setShadow(){if(!this.shadow||!this.canvas)return;const t=this.canvas,e=this.shadow,s=t.contextTop,r=t.getZoom()*t.getRetinaScaling();s.shadowColor=e.color,s.shadowBlur=e.blur*r,s.shadowOffsetX=e.offsetX*r,s.shadowOffsetY=e.offsetY*r}_resetShadow(){const t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}_isOutSideCanvas(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}const Bh=["path","left","top"],Ih=["d"];class ae extends ut{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:r,top:i}=e,n=$(e,Bh);super(),Object.assign(this,ae.ownDefaults),this.setOptions(n),this._setPath(t||[],!0),typeof r=="number"&&this.set(N,r),typeof i=="number"&&this.set(mt,i)}_setPath(t,e){this.path=fh(Array.isArray(t)?t:Sh(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new x(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,s=-this.pathOffset.y;t.beginPath();for(const r of this.path)switch(r[0]){case"L":t.lineTo(r[1]+e,r[2]+s);break;case"M":t.moveTo(r[1]+e,r[2]+s);break;case"C":t.bezierCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s,r[5]+e,r[6]+s);break;case"Q":t.quadraticCurveTo(r[1]+e,r[2]+s,r[3]+e,r[4]+s);break;case"Z":t.closePath()}}_render(t){this._renderPathCommands(t),this._renderPaintInOrder(t)}toString(){return"#<Path (".concat(this.complexity(),'): { "top": ').concat(this.top,', "left": ').concat(this.left," }>")}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject(t)),{},{path:this.path.map(e=>e.slice())})}toDatalessObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=Nn(this.path,Y.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
+ `)]}_getOffsetTransform(){const t=Y.NUM_FRACTION_DIGITS;return" translate(".concat(K(-this.pathOffset.x,t),", ").concat(K(-this.pathOffset.y,t),")")}toClipPathSVG(t){const e=this._getOffsetTransform();return" "+this._createBaseClipPathSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}toSVG(t){const e=this._getOffsetTransform();return this._createBaseSVGMarkup(this._toSVG(),{reviver:t,additionalTransform:e})}complexity(){return this.path.length}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{width:e,height:s,pathOffset:r}=this._calcDimensions();this.set({width:e,height:s,pathOffset:r}),t&&this.setPositionByOrigin(r,R,R)}_calcBoundsFromPath(){const t=[];let e=0,s=0,r=0,i=0;for(const n of this.path)switch(n[0]){case"L":r=n[1],i=n[2],t.push({x:e,y:s},{x:r,y:i});break;case"M":r=n[1],i=n[2],e=r,s=i;break;case"C":t.push(...Ri(r,i,n[1],n[2],n[3],n[4],n[5],n[6])),r=n[5],i=n[6];break;case"Q":t.push(...Ri(r,i,n[1],n[2],n[1],n[2],n[3],n[4])),r=n[3],i=n[4];break;case"Z":r=e,i=s}return Zt(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return m(m({},t),{},{pathOffset:new x(t.left+t.width/2,t.top+t.height/2)})}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{d:i}=r;return new this(i,m(m(m({},$(r,Ih)),e),{},{left:void 0,top:void 0}))}}p(ae,"type","Path"),p(ae,"cacheProperties",[...re,"path","fillRule"]),p(ae,"ATTRIBUTE_NAMES",[...ue,"d"]),M.setClass(ae),M.setSVGClass(ae);class Hs extends Rh{constructor(t){super(t),p(this,"decimate",.4),p(this,"drawStraightLine",!1),p(this,"straightLineKey","shiftKey"),this._points=[],this._hasStraightLine=!1}needsFullRender(){return super.needsFullRender()||this._hasStraightLine}static drawSegment(t,e,s){const r=e.midPointFrom(s);return t.quadraticCurveTo(e.x,e.y,r.x,r.y),r}onMouseDown(t,e){let{e:s}=e;this.canvas._isMainEvent(s)&&(this.drawStraightLine=!!this.straightLineKey&&s[this.straightLineKey],this._prepareForDrawing(t),this._addPoint(t),this._render())}onMouseMove(t,e){let{e:s}=e;if(this.canvas._isMainEvent(s)&&(this.drawStraightLine=!!this.straightLineKey&&s[this.straightLineKey],(this.limitedToCanvasSize!==!0||!this._isOutSideCanvas(t))&&this._addPoint(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{const r=this._points,i=r.length,n=this.canvas.contextTop;this._saveAndTransform(n),this.oldEnd&&(n.beginPath(),n.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=Hs.drawSegment(n,r[i-2],r[i-1]),n.stroke(),n.restore()}}onMouseUp(t){let{e}=t;return!this.canvas._isMainEvent(e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)}_prepareForDrawing(t){this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)}_addPoint(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1]))&&(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),!0)}_reset(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1}_render(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.canvas.contextTop,e=this._points[0],s=this._points[1];if(this._saveAndTransform(t),t.beginPath(),this._points.length===2&&e.x===s.x&&e.y===s.y){const r=this.width/1e3;e.x-=r,s.x+=r}t.moveTo(e.x,e.y);for(let r=1;r<this._points.length;r++)Hs.drawSegment(t,e,s),e=this._points[r],s=this._points[r+1];t.lineTo(e.x,e.y),t.stroke(),t.restore()}convertPointsToSVGPath(t){const e=this.width/1e3;return Ch(t,e)}createPath(t){const e=new ae(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new zt(this.shadow)),e}decimatePoints(t,e){if(t.length<=2)return t;let s,r=t[0];const i=this.canvas.getZoom(),n=Math.pow(e/i,2),a=t.length-1,h=[r];for(let c=1;c<a-1;c++)s=Math.pow(r.x-t[c].x,2)+Math.pow(r.y-t[c].y,2),s>=n&&(r=t[c],h.push(r));return h.push(t[a]),h}_finalizeAndAddPath(){this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));const t=this.convertPointsToSVGPath(this._points);if(function(s){return Nn(s)==="M 0 0 Q 0 0 0 0 L 0 0"}(t))return void this.canvas.requestRenderAll();const e=this.createPath(t);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:e}),this.canvas.add(e),this.canvas.requestRenderAll(),e.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:e})}}const Wh=["left","top","radius"],Zn=["radius","startAngle","endAngle","counterClockwise"];class Xt extends ut{static getDefaults(){return m(m({},super.getDefaults()),Xt.ownDefaults)}constructor(t){super(),Object.assign(this,Xt.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),t==="radius"&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,tt(this.startAngle),tt(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(_t)}getRadiusY(){return this.get("radius")*this.get(Mt)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Zn,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
48
48
  `];{const{radius:e}=this,s=tt(this.startAngle),r=tt(this.endAngle),i=Qt(s)*e,n=te(s)*e,a=Qt(r)*e,h=te(r)*e,c=t>180?1:0,l=this.counterClockwise?0:1;return['<path d="M '.concat(i," ").concat(n," A ").concat(e," ").concat(e," 0 ").concat(c," ").concat(l," ").concat(a," ").concat(h,'" '),"COMMON_PARTS",` />
49
- `]}}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{left:i=0,top:n=0,radius:a=0}=r;return new this(m(m({},$(r,Rh)),{},{radius:a,left:i-a,top:n-a}))}static fromObject(t){return super._fromObject(t)}}p(Xt,"type","Circle"),p(Xt,"cacheProperties",[...re,...Jn]),p(Xt,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),p(Xt,"ATTRIBUTE_NAMES",["cx","cy","r",...ue]),M.setClass(Xt),M.setSVGClass(Xt);const Bh=["x1","y1","x2","y2"],Ih=["x1","y1","x2","y2"],Pr=["x1","x2","y1","y2"];class Vt extends ut{constructor(){let[t,e,s,r]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,Vt.ownDefaults),this.setOptions(i),this.x1=t,this.x2=s,this.y1=e,this.y2=r,this._setWidthHeight();const{left:n,top:a}=i;typeof n=="number"&&this.set(N,n),typeof a=="number"&&this.set(mt,a)}_setWidthHeight(){const{x1:t,y1:e,x2:s,y2:r}=this;this.width=Math.abs(s-t),this.height=Math.abs(r-e);const{left:i,top:n,width:a,height:h}=Zt([{x:t,y:e},{x:s,y:r}]),c=new x(i+a/2,n+h/2);this.setPositionByOrigin(c,R,R)}_set(t,e){return super._set(t,e),Pr.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const s=t.strokeStyle;var r;Dt(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(r=this.stroke)!==null&&r!==void 0?r:t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=s}_findCenterFromElement(){return new x((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:r,width:i,height:n}=this,a=t<=e?-1:1,h=s<=r?-1:1;return{x1:a*i/2,x2:a*-i/2,y1:h*n/2,y2:h*-n/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:r}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(r,`" />
50
- `)]}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{x1:i=0,y1:n=0,x2:a=0,y2:h=0}=r;return new this([i,n,a,h],$(r,Bh))}static fromObject(t){let{x1:e,y1:s,x2:r,y2:i}=t,n=$(t,Ih);return this._fromObject(m(m({},n),{},{points:[e,s,r,i]}),{extraParam:"points"})}}p(Vt,"type","Line"),p(Vt,"cacheProperties",[...re,...Pr]),p(Vt,"ATTRIBUTE_NAMES",ue.concat(Pr)),M.setClass(Vt),M.setSVGClass(Vt);class ge extends ut{static getDefaults(){return m(m({},super.getDefaults()),ge.ownDefaults)}constructor(t){super(),Object.assign(this,ge.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}p(ge,"type","Triangle"),p(ge,"ownDefaults",{width:100,height:100}),M.setClass(ge),M.setSVGClass(ge);const Zn=["rx","ry"];class qt extends ut{static getDefaults(){return m(m({},super.getDefaults()),qt.ownDefaults)}constructor(t){super(),Object.assign(this,qt.ownDefaults),this.setOptions(t)}_set(t,e){switch(super._set(t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this}getRx(){return this.get("rx")*this.get(_t)}getRy(){return this.get("ry")*this.get(Mt)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Zn,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
51
- `)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Ps,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}}function Wh(o){if(!o)return[];const t=o.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}p(qt,"type","Ellipse"),p(qt,"cacheProperties",[...re,...Zn]),p(qt,"ownDefaults",{rx:0,ry:0}),p(qt,"ATTRIBUTE_NAMES",[...ue,"cx","cy","rx","ry"]),M.setClass(qt),M.setSVGClass(qt);const Xh=["left","top"],Qn={exactBoundingBox:!1};class Ft extends ut{static getDefaults(){return m(m({},super.getDefaults()),Ft.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),p(this,"strokeDiff",void 0),Object.assign(this,Ft.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:r}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(N,s),typeof r=="number"&&this.set(mt,r)}isOpen(){return!0}_projectStrokeOnPoints(t){return Da(this.points,t,this.isOpen())}_calcDimensions(t){t=m({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(c=>c.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new x,strokeOffset:new x,strokeDiff:new x};const s=Zt(e),r=Ks(m(m({},t),{},{scaleX:1,scaleY:1})),i=Zt(this.points.map(c=>pt(c,r,!0))),n=new x(this.scaleX,this.scaleY);let a=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(a-=h*Math.tan(tt(this.skewX)),h-=a*Math.tan(tt(this.skewY))),m(m({},s),{},{pathOffset:new x(a,h),strokeOffset:new x(i.left,i.top).subtract(new x(s.left,s.top)).multiply(n),strokeDiff:new x(s.width,s.height).subtract(new x(i.width,i.height)).multiply(n)})}_findCenterFromElement(){const t=Zt(this.points);return new x(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:s,width:r,height:i,pathOffset:n,strokeOffset:a,strokeDiff:h}=this._calcDimensions();this.set({width:r,height:i,pathOffset:n,strokeOffset:a,strokeDiff:h}),t&&this.setPositionByOrigin(new x(e+r/2,s+i/2),R,R)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new x(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let n;if(Object.keys(t).some(a=>this.strokeUniform||this.constructor.layoutProperties.includes(a))){var e,s;const{width:a,height:h}=this._calcDimensions(t);n=new x((e=t.width)!==null&&e!==void 0?e:a,(s=t.height)!==null&&s!==void 0?s:h)}else{var r,i;n=new x((r=t.width)!==null&&r!==void 0?r:this.width,(i=t.height)!==null&&i!==void 0?i:this.height)}return n.multiply(new x(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const s=this.initialized&&this[t]!==e,r=super._set(t,e);return this.exactBoundingBox&&s&&((t===_t||t===Mt)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),r}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject(t)),{},{points:this.points.map(e=>{let{x:s,y:r}=e;return{x:s,y:r}})})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,r=Y.NUM_FRACTION_DIGITS;for(let i=0,n=this.points.length;i<n;i++)t.push(K(this.points[i].x-e,r),",",K(this.points[i].y-s,r)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
52
- `)]}_render(t){const e=this.points.length,s=this.pathOffset.x,r=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-r);for(let i=0;i<e;i++){const n=this.points[i];t.lineTo(n.x-s,n.y-r)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(Wh(t.getAttribute("points")),m(m({},$(ie(t,this.ATTRIBUTE_NAMES,s),Xh)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}p(Ft,"ownDefaults",Qn),p(Ft,"type","Polyline"),p(Ft,"layoutProperties",[Ae,je,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),p(Ft,"cacheProperties",[...re,"points"]),p(Ft,"ATTRIBUTE_NAMES",[...ue]),M.setClass(Ft),M.setSVGClass(Ft);class ns extends Ft{isOpen(){return!1}}p(ns,"ownDefaults",Qn),p(ns,"type","Polygon"),M.setClass(ns),M.setSVGClass(ns);class to extends ut{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const r in e[s])for(const i in e[s][r])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const r in s)for(const i in s[r])if(s[r][i][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,r,i=0,n=!0,a=0;for(const h in e){s=0;for(const c in e[h]){const l=e[h][c]||{};i++,l[t]!==void 0?(r?l[t]!==r&&(n=!1):r=l[t],l[t]===this[t]&&delete l[t]):n=!1,Object.keys(l).length!==0?s++:delete e[h][c]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)a+=this._textLines[h].length;n&&i===a&&(this[t]=r,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,r,i;for(r in e){for(i in s=e[r],s)delete s[i][t],Object.keys(s[i]).length===0&&delete s[i];Object.keys(s).length===0&&delete e[r]}}_extendStyles(t,e){const{lineIndex:s,charIndex:r}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const i=Xr(m(m({},this._getStyleDeclaration(s,r)),e),n=>n!==void 0);this._setStyleDeclaration(s,r,i)}getSelectionStyles(t,e,s){const r=[];for(let i=t;i<(e||t);i++)r.push(this.getStyleAtPosition(i,s));return r}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:r}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,r):this._getStyleDeclaration(s,r)}setSelectionStyles(t,e,s){for(let r=e;r<(s||e);r++)this._extendStyles(r,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const r=this.styles&&this.styles[t];return r&&(s=r[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return m(m({},Le(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}p(to,"_styleProperties",zo);const Yh=/ +/g,Vh=/"/g;function gr(o,t,e,s,r){return" ".concat(function(i,n){let{left:a,top:h,width:c,height:l}=n,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Y.NUM_FRACTION_DIGITS;const d=Ke(ot,i,!1),[g,f,v,_]=[a,h,c,l].map(b=>K(b,u));return"<rect ".concat(d,' x="').concat(g,'" y="').concat(f,'" width="').concat(v,'" height="').concat(_,'"></rect>')}(o,{left:t,top:e,width:s,height:r}),`
53
- `)}const Hh=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let fr;class dt extends to{static getDefaults(){return m(m({},super.getDefaults()),dt.ownDefaults)}constructor(t,e){super(),p(this,"__charBounds",[]),Object.assign(this,dt.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=zn(t.path))}_splitText(){const t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(Yt)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,r,i,n,a;for(let h=0,c=this._textLines.length;h<c;h++)if((this.textAlign===Yt||h!==c-1&&!this.isEndOfWrapping(h))&&(r=0,i=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(a=this.textLines[h].match(this._reSpacesAndTabs)))){s=a.length,t=(this.width-e)/s;for(let l=0;l<=i.length;l++)n=this.__charBounds[h][l],this._reSpaceAndTab.test(i[l])?(n.width+=t,n.kernedWidth+=t,n.left+=r,r+=t):n.left+=r}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let r;for(r=0;r<s.length;r++){if(t<=s[r].length)return{lineIndex:r,charIndex:t};t-=s[r].length+this.missingNewlineOffset(r,e)}return{lineIndex:r-1,charIndex:s[r-1].length<t?s[r-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===yt?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,s){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case R:t.textBaseline="middle";break;case"ascender":t.textBaseline=mt;break;case"descender":t.textBaseline=_r}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const r=this.getLineWidth(e);r>t&&(t=r)}return t}_renderTextLine(t,e,s,r,i,n){this._renderChars(t,e,s,r,i,n)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let r=this._getTopOffset();for(let i=0,n=this._textLines.length;i<n;i++){const a=this.getHeightOfLine(i);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",i)){r+=a;continue}const h=this._textLines[i].length,c=this._getLineLeftOffset(i);let l,u,d=0,g=0,f=this.getValueOfPropertyAt(i,0,"textBackgroundColor");const v=this.getHeightOfLineImpl(i);for(let _=0;_<h;_++){const b=this.__charBounds[i][_];u=this.getValueOfPropertyAt(i,_,"textBackgroundColor"),this.path?(t.save(),t.translate(b.renderLeft,b.renderTop),t.rotate(b.angle),t.fillStyle=u,u&&t.fillRect(-b.width/2,-v*(1-this._fontSizeFraction),b.width,v),t.restore()):u!==f?(l=s+c+g,this.direction==="rtl"&&(l=this.width-l-d),t.fillStyle=f,f&&t.fillRect(l,r,d,v),g=b.left,d=b.width,f=u):d+=b.kernedWidth}u&&!this.path&&(l=s+c+g,this.direction==="rtl"&&(l=this.width-l-d),t.fillStyle=u,t.fillRect(l,r,d,v)),r+=a}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,r){const i=Ve.getFontCache(e),n=this._getFontDeclaration(e),a=s?s+t:t,h=s&&n===this._getFontDeclaration(r),c=e.fontSize/this.CACHE_FONT_SIZE;let l,u,d,g;if(s&&i.has(s)&&(d=i.get(s)),i.has(t)&&(g=l=i.get(t)),h&&i.has(a)&&(u=i.get(a),g=u-d),l===void 0||d===void 0||u===void 0){const f=function(){return fr||(fr=Et({width:0,height:0}).getContext("2d")),fr}();this._setTextStyles(f,e,!0),l===void 0&&(g=l=f.measureText(t).width,i.set(t,l)),d===void 0&&h&&s&&(d=f.measureText(s).width,i.set(s,d)),h&&u===void 0&&(u=f.measureText(a).width,i.set(a,u),g=u-d)}return{width:l*c,kernedWidth:g*c}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,r=0;const i=this.pathSide===Q,n=this.path,a=this._textLines[t],h=a.length,c=new Array(h);this.__charBounds[t]=c;for(let l=0;l<h;l++){const u=a[l];s=this._getGraphemeBox(u,t,l,e),c[l]=s,r+=s.kernedWidth,e=u}if(c[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},n&&n.segmentsInfo){let l=0;const u=n.segmentsInfo[n.segmentsInfo.length-1].length;switch(this.textAlign){case N:l=i?u-r:0;break;case R:l=(u-r)/2;break;case Q:l=i?0:u-r}l+=this.pathStartOffset*(i?-1:1);for(let d=i?h-1:0;i?d>=0:d<h;i?d--:d++)s=c[d],l>u?l%=u:l<0&&(l+=u),this._setGraphemeOnPath(l,s),l+=s.kernedWidth}return{width:r,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,r=this.path,i=mh(r.path,s,r.segmentsInfo);e.renderLeft=i.x-r.pathOffset.x,e.renderTop=i.y-r.pathOffset.y,e.angle=i.angle+(this.pathSide===Q?Math.PI:0)}_getGraphemeBox(t,e,s,r,i){const n=this.getCompleteStyleDeclaration(e,s),a=r?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,n,r,a);let c,l=h.kernedWidth,u=h.width;this.charSpacing!==0&&(c=this._getWidthOfCharSpacing(),u+=c,l+=c);const d={width:u,left:0,height:n.fontSize,kernedWidth:l,deltaY:n.deltaY};if(s>0&&!i){const g=this.__charBounds[e][s-1];d.left=g.left+g.width+h.kernedWidth-h.width}return d}getHeightOfLineImpl(t){const e=this.__lineHeights;if(e[t])return e[t];let s=this.getHeightOfChar(t,0);for(let r=1,i=this._textLines[t].length;r<i;r++)s=Math.max(this.getHeightOfChar(t,r),s);return e[t]=s*this._fontSizeMult}getHeightOfLine(t){return this.getHeightOfLineImpl(t)*this.lineHeight}calcTextHeight(){let t=0;for(let e=0,s=this._textLines.length;e<s;e++)t+=e===s-1?this.getHeightOfLineImpl(e):this.getHeightOfLine(e);return t}_getLeftOffset(){return this.direction==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const r=this._getLeftOffset(),i=this._getTopOffset();for(let n=0,a=this._textLines.length;n<a;n++)this._renderTextLine(e,t,this._textLines[n],r+this._getLineLeftOffset(n),i+s+this.getHeightOfLineImpl(n),n),s+=this.getHeightOfLine(n);t.restore()}_renderTextFill(t){(this.fill||this.styleHas(ot))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,s,r,i,n){const a=this.textAlign.includes(Yt),h=this.path,c=!a&&this.charSpacing===0&&this.isEmptyStyles(n)&&!h,l=this.direction==="ltr",u=this.direction==="ltr"?1:-1,d=e.direction;let g,f,v,_,b,w="",C=0;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",l?"ltr":"rtl"),e.direction=l?"ltr":"rtl",e.textAlign=l?N:Q),i-=this.getHeightOfLineImpl(n)*this._fontSizeFraction,c)return this._renderChar(t,e,n,0,s.join(""),r,i),void e.restore();for(let T=0,D=s.length-1;T<=D;T++)_=T===D||this.charSpacing||h,w+=s[T],v=this.__charBounds[n][T],C===0?(r+=u*(v.kernedWidth-v.width),C+=v.width):C+=v.kernedWidth,a&&!_&&this._reSpaceAndTab.test(s[T])&&(_=!0),_||(g=g||this.getCompleteStyleDeclaration(n,T),f=this.getCompleteStyleDeclaration(n,T+1),_=qr(g,f,!1)),_&&(h?(e.save(),e.translate(v.renderLeft,v.renderTop),e.rotate(v.angle),this._renderChar(t,e,n,T,w,-C/2,0),e.restore()):(b=r,this._renderChar(t,e,n,T,w,b,i)),w="",g=f,r+=u*C,C=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,r=Et({width:e,height:s}),i=r.getContext("2d");return r.width=e,r.height=s,i.beginPath(),i.moveTo(0,0),i.lineTo(e,0),i.lineTo(e,s),i.lineTo(0,s),i.closePath(),i.translate(e/2,s/2),i.fillStyle=t.toLive(i),this._applyPatternGradientTransform(i,t),i.fill(),i.createPattern(r,"no-repeat")}handleFiller(t,e,s){let r,i;return Dt(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(r=-this.width/2,i=-this.height/2,t.translate(r,i),t[e]=this._applyPatternGradientTransformText(s),{offsetX:r,offsetY:i}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:r}=e;return t.lineWidth=r,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,r,i,n,a){const h=this._getStyleDeclaration(s,r),c=this.getCompleteStyleDeclaration(s,r),l=t==="fillText"&&c.fill,u=t==="strokeText"&&c.stroke&&c.strokeWidth;if(u||l){if(e.save(),e.font=this._getFontDeclaration(c),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(a+=h.deltaY),l){const d=this._setFillStyles(e,c);e.fillText(i,n-d.offsetX,a-d.offsetY)}if(u){const d=this._setStrokeStyles(e,c);e.strokeText(i,n-d.offsetX,a-d.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,s){const r=this.get2DCursorLocation(t,!0),i=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,"fontSize"),n=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,"deltaY"),a={fontSize:i*s.size,deltaY:n+i*s.baseline};this.setSelectionStyles(a,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,r=this.textAlign,i=this.direction,n=this.isEndOfWrapping(t);let a=0;return r===Yt||r===ze&&!n||r===He&&!n||r===Ws&&!n?0:(r===R&&(a=s/2),r===Q&&(a=s),r===ze&&(a=s/2),r===He&&(a=s),i==="rtl"&&(r===Q||r===Yt||r===He?a=0:r===N||r===Ws?a=-s:r!==R&&r!==ze||(a=-s/2)),a)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var r;return(r=this._getStyleDeclaration(t,e)[s])!==null&&r!==void 0?r:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const r=this._getLeftOffset(),i=this.path,n=this._getWidthOfCharSpacing(),a=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let c=0,l=this._textLines.length;c<l;c++){const u=this.getHeightOfLine(c);if(!this[e]&&!this.styleHas(e,c)){s+=u;continue}const d=this._textLines[c],g=u/this.lineHeight,f=this._getLineLeftOffset(c);let v=0,_=0,b=this.getValueOfPropertyAt(c,0,e),w=this.getValueOfPropertyAt(c,0,ot),C=this.getValueOfPropertyAt(c,0,me),T=b,D=w,A=C;const I=s+g*(1-this._fontSizeFraction);let E=this.getHeightOfChar(c,0),W=this.getValueOfPropertyAt(c,0,"deltaY");for(let L=0,V=d.length;L<V;L++){const X=this.__charBounds[c][L];T=this.getValueOfPropertyAt(c,L,e),D=this.getValueOfPropertyAt(c,L,ot),A=this.getValueOfPropertyAt(c,L,me);const nt=this.getHeightOfChar(c,L),et=this.getValueOfPropertyAt(c,L,"deltaY");if(i&&T&&D){const st=this.fontSize*A/1e3;t.save(),t.fillStyle=w,t.translate(X.renderLeft,X.renderTop),t.rotate(X.angle),t.fillRect(-X.kernedWidth/2,h*nt+et-a*st,X.kernedWidth,st),t.restore()}else if((T!==b||D!==w||nt!==E||A!==C||et!==W)&&_>0){const st=this.fontSize*C/1e3;let U=r+f+v;this.direction==="rtl"&&(U=this.width-U-_),b&&w&&C&&(t.fillStyle=w,t.fillRect(U,I+h*E+W-a*st,_,st)),v=X.left,_=X.width,b=T,C=A,w=D,E=nt,W=et}else _+=X.kernedWidth}let q=r+f+v;this.direction==="rtl"&&(q=this.width-q-_),t.fillStyle=D;const Z=this.fontSize*A/1e3;T&&D&&A&&t.fillRect(q,I+h*E+W-a*Z,_-n,Z),s+=u}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:r=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1?arguments[1]:void 0;const n=t.includes("'")||t.includes('"')||t.includes(",")||dt.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(i?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 Ur(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),r=[`
54
- `];let i=[];for(let n=0;n<e.length;n++)s[n]=this.graphemeSplit(e[n]),i=i.concat(s[n],r);return i.pop(),{_unwrappedLines:s,lines:e,graphemeText:i,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject([...On,...t])),{},{styles:Aa(this.styles,this.text)},this.path?{path:this.path.toObject()}:{})}set(t,e){const{textLayoutProperties:s}=this.constructor;super.set(t,e);let r=!1,i=!1;if(typeof t=="object")for(const n in t)n==="path"&&this.setPathInfo(),r=r||s.includes(n),i=i||n==="path";else r=s.includes(t),i=t==="path";return i&&this.setPathInfo(),r&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,s){const r=ie(t,dt.ATTRIBUTE_NAMES,s),i=m(m({},e),r),{textAnchor:n=N,textDecoration:a="",dx:h=0,dy:c=0,top:l=0,left:u=0,fontSize:d=Fr,strokeWidth:g=1}=i,f=$(i,Hh),v=new this(Is(t.textContent||"").trim(),m({left:u+h,top:l+c,underline:a.includes("underline"),overline:a.includes("overline"),linethrough:a.includes("line-through"),strokeWidth:0,fontSize:d},f)),_=v.getScaledHeight()/v.height,b=((v.height+v.strokeWidth)*v.lineHeight-v.height)*_,w=v.getScaledHeight()+b;let C=0;return n===R&&(C=v.getScaledWidth()/2),n===Q&&(C=v.getScaledWidth()),v.set({left:v.left-C,top:v.top-(w-v.fontSize*(.07+v._fontSizeFraction))/v.lineHeight,strokeWidth:g}),v}static fromObject(t){return this._fromObject(m(m({},t),{},{styles:ja(t.styles||{},t.text)}),{extraParam:"text"})}}p(dt,"textLayoutProperties",Tn),p(dt,"cacheProperties",[...re,...On]),p(dt,"ownDefaults",Go),p(dt,"type","Text"),p(dt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),p(dt,"ATTRIBUTE_NAMES",ue.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Ln(dt,[class extends wn{_toSVG(){const o=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(o.textTop,o.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(o){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:o,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:o,withShadow:!0,additionalTransform:qe(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(o){let{textBgRects:t,textSpans:e}=o;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ','font-family="'.concat(this.fontFamily.replace(Vh,"'"),'" '),'font-size="'.concat(this.fontSize,'" '),this.fontStyle?'font-style="'.concat(this.fontStyle,'" '):"",this.fontWeight?'font-weight="'.concat(this.fontWeight,'" '):"",s?'text-decoration="'.concat(s,'" '):"",this.direction==="rtl"?'direction="'.concat(this.direction,'" '):"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
55
- `]}_getSVGTextAndBg(o,t){const e=[],s=[];let r,i=o;this.backgroundColor&&s.push(...gr(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let n=0,a=this._textLines.length;n<a;n++)r=this._getLineLeftOffset(n),this.direction==="rtl"&&(r+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",n))&&this._setSVGTextLineBg(s,n,t+r,i),this._setSVGTextLineText(e,n,t+r,i),i+=this.getHeightOfLine(n);return{textSpans:e,textBgRects:s}}_createTextCharSpan(o,t,e,s,r){const i=Y.NUM_FRACTION_DIGITS,n=this.getSvgSpanStyles(t,o!==o.trim()||!!o.match(Yh)),a=n?'style="'.concat(n,'"'):"",h=t.deltaY,c=h?' dy="'.concat(K(h,i),'" '):"",{angle:l,renderLeft:u,renderTop:d,width:g}=r;let f="";if(u!==void 0){const v=g/2;l&&(f=' rotate="'.concat(K(se(l),i),'"'));const _=Fe({angle:se(l)});_[4]=u,_[5]=d;const b=new x(-v,0).transform(_);e=b.x,s=b.y}return'<tspan x="'.concat(K(e,i),'" y="').concat(K(s,i),'" ').concat(c).concat(f).concat(a,">").concat(Ma(o),"</tspan>")}_setSVGTextLineText(o,t,e,s){const r=this.getHeightOfLine(t),i=this.textAlign.includes(Yt),n=this._textLines[t];let a,h,c,l,u,d="",g=0;s+=r*(1-this._fontSizeFraction)/this.lineHeight;for(let f=0,v=n.length-1;f<=v;f++)u=f===v||this.charSpacing||this.path,d+=n[f],c=this.__charBounds[t][f],g===0?(e+=c.kernedWidth-c.width,g+=c.width):g+=c.kernedWidth,i&&!u&&this._reSpaceAndTab.test(n[f])&&(u=!0),u||(a=a||this.getCompleteStyleDeclaration(t,f),h=this.getCompleteStyleDeclaration(t,f+1),u=qr(a,h,!0)),u&&(l=this._getStyleDeclaration(t,f),o.push(this._createTextCharSpan(d,l,e,s,c)),d="",a=h,this.direction==="rtl"?e-=g:e+=g,g=0)}_setSVGTextLineBg(o,t,e,s){const r=this._textLines[t],i=this.getHeightOfLine(t)/this.lineHeight;let n,a=0,h=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let l=0;l<r.length;l++){const{left:u,width:d,kernedWidth:g}=this.__charBounds[t][l];n=this.getValueOfPropertyAt(t,l,"textBackgroundColor"),n!==c?(c&&o.push(...gr(c,e+h,s,a,i)),h=u,a=d,c=n):a+=g}n&&o.push(...gr(c,e+h,s,a,i))}_getSVGLineTopOffset(o){let t,e=0;for(t=0;t<o;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(o){return"".concat(super.getSvgStyles(o)," text-decoration-thickness: ").concat(K(this.textDecorationThickness*this.getObjectScaling().y/10,Y.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(o,t){const{fontFamily:e,strokeWidth:s,stroke:r,fill:i,fontSize:n,fontStyle:a,fontWeight:h,deltaY:c,textDecorationThickness:l,linethrough:u,overline:d,underline:g}=o,f=this.getSvgTextDecoration({underline:g??this.underline,overline:d??this.overline,linethrough:u??this.linethrough}),v=l||this.textDecorationThickness;return[r?Ke(yt,r):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",n?"font-size: ".concat(n,"px; "):"",a?"font-style: ".concat(a,"; "):"",h?"font-weight: ".concat(h,"; "):"",f?"text-decoration: ".concat(f,"; text-decoration-thickness: ").concat(K(v*this.getObjectScaling().y/10,Y.NUM_FRACTION_DIGITS),"%; "):"",i?Ke(ot,i):"",c?"baseline-shift: ".concat(-c,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(o){return["overline","underline","line-through"].filter(t=>o[t.replace("-","")]).join(" ")}}]),M.setClass(dt),M.setSVGClass(dt);class zh{constructor(t){p(this,"target",void 0),p(this,"__mouseDownInPlace",!1),p(this,"__dragStartFired",!1),p(this,"__isDraggingOver",!1),p(this,"__dragStartSelection",void 0),p(this,"__dragImageDisposer",void 0),p(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(s=>s()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:r,selectionEnd:i}=e;const n=this.target,a=n.canvas,h=new x(n.flipX?-1:1,n.flipY?-1:1),c=n._getCursorBoundaries(r),l=new x(c.left+c.leftOffset,c.top+c.topOffset).multiply(h).transform(n.calcTransformMatrix()),u=a.getScenePoint(t).subtract(l),d=n.getCanvasRetinaScaling(),g=n.getBoundingRect(),f=l.subtract(new x(g.left,g.top)),v=a.viewportTransform,_=f.add(u).transform(v,!0),b=n.backgroundColor,w=Nr(n.styles);n.backgroundColor="";const C={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};n.setSelectionStyles(C,0,r),n.setSelectionStyles(C,i,n.text.length),n.dirty=!0;const T=n.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});n.backgroundColor=b,n.styles=w,n.dirty=!0,Mr(T,{position:"fixed",left:"".concat(-T.width,"px"),border:vt,width:"".concat(T.width/d,"px"),height:"".concat(T.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{T.remove()},Lt(t.target||this.target.hiddenTextarea).body.appendChild(T),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(T,_.x,_.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const r=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},i=e._text.slice(r.selectionStart,r.selectionEnd).join(""),n=m({text:e.text,value:i},r);t.dataTransfer.setData("text/plain",i),t.dataTransfer.setData("application/fabric",JSON.stringify({value:i,styles:e.getSelectionStyles(r.selectionStart,r.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,n)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,r=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let i=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(i&&!r){const n=this.target,a=n.canvas;let h=n.getSelectionStartFromPointer(s);const{styles:c}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},l=i[Math.max(0,i.length-1)],u=0;if(this.__dragStartSelection){const d=this.__dragStartSelection.selectionStart,g=this.__dragStartSelection.selectionEnd;h>d&&h<=g?h=d:h>g&&(h-=g-d),n.removeChars(d,g),delete this.__dragStartSelection}n._reNewline.test(l)&&(n._reNewline.test(n._text[h])||h===n._text.length)&&(i=i.trimEnd()),t.didDrop=!0,t.dropTarget=n,n.insertChars(i,c,h),a.setActiveObject(n),n.enterEditing(s),n.selectionStart=Math.min(h+u,n._text.length),n.selectionEnd=Math.min(n.selectionStart+i.length,n._text.length),n.hiddenTextarea.value=n.text,n._updateTextarea(),n.hiddenTextarea.focus(),n.fire(As,{index:h+u,action:"drop"}),a.fire("text:changed",{target:n}),a.contextTopDirty=!0,a.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const r=this.target,i=this.target.canvas,{selectionStart:n,selectionEnd:a}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||vt;h===vt?(r.selectionStart=n,r.selectionEnd=a,r._updateTextarea(),r.hiddenTextarea.focus()):(r.clearContextTop(),h==="move"&&(r.removeChars(n,a),r.selectionStart=r.selectionEnd=n,r.hiddenTextarea&&(r.hiddenTextarea.value=r.text),r._updateTextarea(),r.fire(As,{index:n,action:"dragend"}),i.fire("text:changed",{target:r}),i.requestRenderAll()),r.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}const Wi=/[ \n\.,;!\?\-]/;class Gh extends dt{constructor(){super(...arguments),p(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:r,onComplete:i}=t;return En({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:r,onComplete:i,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:n=>{this._currentCursorOpacity=n,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;(t=this._currentTickCompleteState)===null||t===void 0||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,s=t-1;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s--;for(;/\S/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findWordBoundaryRight(t){let e=0,s=t;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s++;for(;/\S/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}findLineBoundaryLeft(t){let e=0,s=t-1;for(;!/\n/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findLineBoundaryRight(t){let e=0,s=t;for(;!/\n/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}searchWordBoundary(t,e){const s=this._text;let r=t>0&&this._reSpace.test(s[t])&&(e===-1||!Lr.test(s[t-1]))?t-1:t,i=s[r];for(;r>0&&r<s.length&&!Wi.test(i);)r+=e,i=s[r];return e===-1&&Wi.test(i)&&r++,r}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),r=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),r=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;Lt(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),r=this.selectionStart,i=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&r!==i||r!==s&&i!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===r&&this.selectionEnd===i||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const r=s.slice(0,t),i=this.graphemeSplit(r).length;if(t===e)return{selectionStart:i,selectionEnd:i};const n=s.slice(t,e);return{selectionStart:i,selectionEnd:i+this.graphemeSplit(n).length}}fromGraphemeToStringSelection(t,e,s){const r=s.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),r=s.lineIndex,i=s.charIndex,n=this.getValueOfPropertyAt(r,i,"fontSize")*this.lineHeight,a=e.leftOffset,h=this.getCanvasRetinaScaling(),c=this.canvas.upperCanvasEl,l=c.width/h,u=c.height/h,d=l-n,g=u-n,f=new x(e.left+a,e.top+e.topOffset+n).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new x(c.clientWidth/l,c.clientHeight/u));return f.x<0&&(f.x=0),f.x>d&&(f.x=d),f.y<0&&(f.y=0),f.y>g&&(f.y=g),f.x+=this.canvas._offset.left,f.y+=this.canvas._offset.top,{left:"".concat(f.x,"px"),top:"".concat(f.y,"px"),fontSize:"".concat(n,"px"),charHeight:n}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(js),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:r}=this.get2DCursorLocation(t,!0),{lineIndex:i,charIndex:n}=this.get2DCursorLocation(e,!0);if(s!==i){if(this.styles[s])for(let a=r;a<this._unwrappedTextLines[s].length;a++)delete this.styles[s][a];if(this.styles[i])for(let a=n;a<this._unwrappedTextLines[i].length;a++){const h=this.styles[i][a];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][r+a-n]=h)}for(let a=s+1;a<=i;a++)delete this.styles[a];this.shiftLineStyles(i,s-i)}else if(this.styles[s]){const a=this.styles[s],h=n-r;for(let c=r;c<n;c++)delete a[c];for(const c in this.styles[s]){const l=parseInt(c,10);l>=n&&(a[l-h]=a[c],delete a[c])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const r in this.styles){const i=parseInt(r,10);i>t&&(this.styles[i+e]=s[i],s[i-e]||delete this.styles[i])}}insertNewlineStyleObject(t,e,s,r){const i={},n=this._unwrappedTextLines[t].length,a=n===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const c=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const d=parseInt(u,10);d>=e&&(h=!0,i[d-e]=this.styles[t][u],a&&e===0||delete this.styles[t][u])}let l=!1;for(h&&!a&&(this.styles[t+s]=i,l=!0),(l||n>e)&&s--;s>0;)r&&r[s-1]?this.styles[t+s]={0:m({},r[s-1])}:c?this.styles[t+s]={0:m({},c)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,r){this.styles||(this.styles={});const i=this.styles[t],n=i?m({},i):{};s||(s=1);for(const h in n){const c=parseInt(h,10);c>=e&&(i[c+s]=n[c],n[c-s]||delete i[c])}if(this._forceClearCache=!0,r){for(;s--;)Object.keys(r[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=m({},r[s]));return}if(!i)return;const a=i[e?e-1:1];for(;a&&s--;)this.styles[t][e+s]=m({},a)}insertNewStyleBlock(t,e,s){const r=this.get2DCursorLocation(e,!0),i=[0];let n,a=0;for(let h=0;h<t.length;h++)t[h]===`
56
- `?(a++,i[a]=0):i[a]++;for(i[0]>0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,i[0],s),s=s&&s.slice(i[0]+1)),a&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+i[0],a),n=1;n<a;n++)i[n]>0?this.insertCharStyleObject(r.lineIndex+n,0,i[n],s):s&&this.styles[r.lineIndex+n]&&s[0]&&(this.styles[r.lineIndex+n][0]=s[0]),s=s&&s.slice(i[n]+1);i[n]>0&&this.insertCharStyleObject(r.lineIndex+n,0,i[n],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;r>s&&this.removeStyleFromTo(s,r);const i=this.graphemeSplit(t);this.insertNewStyleBlock(i,s,e),this._text=[...this._text.slice(0,s),...i,...this._text.slice(r)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=N:this._selectionDirection===Q&&(this._selectionDirection=N,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Q?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Q:this._selectionDirection===N&&(this._selectionDirection=Q,this.selectionStart=e),this.selectionEnd=s)}}class Nh extends Gh{initHiddenTextarea(){const t=this.canvas&&Lt(this.canvas.getElement())||Pe(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off",name:"fabricTextarea"}).map(n=>{let[a,h]=n;return e.setAttribute(a,h)});const{top:s,left:r,fontSize:i}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(r,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(i,";"),(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(n=>{let[a,h]=n;return e.addEventListener(a,this[h].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:r,selectionEnd:i}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const n=()=>{this.updateFromTextArea(),this.fire(As),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void n();const a=this._splitTextIntoLines(s).graphemeText,h=this._text.length,c=a.length,l=this.selectionStart,u=this.selectionEnd,d=l!==u;let g,f,v,_,b=c-h;const w=this.fromStringToGraphemeSelection(r,i,s),C=l>w.selectionStart;d?(f=this._text.slice(l,u),b+=u-l):c<h&&(f=C?this._text.slice(u+b,u):this._text.slice(l,l-b));const T=a.slice(w.selectionEnd-b,w.selectionEnd);if(f&&f.length&&(T.length&&(g=this.getSelectionStyles(l,l+1,!1),g=T.map(()=>g[0])),d?(v=l,_=u):C?(v=u-f.length,_=u):(v=u,_=u+f.length),this.removeStyleFromTo(v,_)),T.length){const{copyPasteData:D}=Gt();e&&T.join("")===D.copiedText&&!Y.disableStyleCopyPaste&&(g=D.copiedTextStyle),this.insertNewStyleBlock(T,l,g)}n()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:s,selectionEnd:r}=e;this.compositionStart=s,this.compositionEnd=r,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=Gt();t.copiedText=this.getSelectedText(),Y.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,r=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],r+=s.left+s.width),r}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(s),i=r.lineIndex;if(i===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const n=r.charIndex,a=this._getWidthBeforeCursor(i,n),h=this._getIndexOnLine(i+1,a);return this._textLines[i].slice(n).length+h+1+this.missingNewlineOffset(i)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(s),i=r.lineIndex;if(i===0||t.metaKey||t.keyCode===33)return-s;const n=r.charIndex,a=this._getWidthBeforeCursor(i,n),h=this._getIndexOnLine(i-1,a),c=this._textLines[i].slice(0,n),l=this.missingNewlineOffset(i-1);return-this._textLines[i-1].length+h-c.length+(1-l)}_getIndexOnLine(t,e){const s=this._textLines[t];let r,i,n=this._getLineLeftOffset(t),a=0;for(let h=0,c=s.length;h<c;h++)if(r=this.__charBounds[t][h].width,n+=r,n>e){i=!0;const l=n-r,u=n,d=Math.abs(l-e);a=Math.abs(u-e)<d?h:h-1;break}return i||(a=s.length-1),a}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===Q);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const r=this.text.length;this.selectionStart=Ee(0,this.selectionStart,r),this.selectionEnd=Ee(0,this.selectionEnd,r),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===N?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let r;if(t.altKey)r=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;r=this["findLineBoundary".concat(s)](this[e])}return r!==void 0&&this[e]!==r&&(this[e]=r,!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=N,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Q&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=N,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===N&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Q,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Q,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const Xi=o=>!!o.button;class Uh extends Nh{constructor(){super(...arguments),p(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("mousetripleclick",this.tripleClickHandler),this.draggableTextDelegate=new zh(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!Xi(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}mouseUpHandler(t){let{e,transform:s}=t;const r=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const i=this.canvas._activeObject;if(i&&i!==this)return}!this.editable||this.group&&!this.group.interactive||s&&s.actionPerformed||Xi(e)||r||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),s=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(s,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(Rt(this.calcTransformMatrix())).add(new x(-this._getLeftOffset(),-this._getTopOffset()));let s=0,r=0,i=0;for(let c=0;c<this._textLines.length&&s<=e.y;c++)s+=this.getHeightOfLine(c),i=c,c>0&&(r+=this._textLines[c-1].length+this.missingNewlineOffset(c-1));let n=Math.abs(this._getLineLeftOffset(i));const a=this._textLines[i].length,h=this.__charBounds[i];for(let c=0;c<a;c++){const l=n+h[c].kernedWidth;if(e.x<=l){Math.abs(e.x-l)<=Math.abs(e.x-n)&&r++;break}n=l,r++}return Math.min(this.flipX?a-r:r,this._text.length)}}const os="moveCursorUp",as="moveCursorDown",hs="moveCursorLeft",cs="moveCursorRight",ls="exitEditing",Yi=(o,t)=>{const e=t.getRetinaScaling();o.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;o.transform(s[0],s[1],s[2],s[3],s[4],s[5])},qh=m({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:ls,27:ls,33:os,34:as,35:cs,36:hs,37:hs,38:os,39:cs,40:as},keysMapRtl:{9:ls,27:ls,33:os,34:as,35:hs,36:cs,37:cs,38:os,39:hs,40:as},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class $t extends Uh{static getDefaults(){return m(m({},super.getDefaults()),$t.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,m(m({},$t.ownDefaults),e)),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):(t==="canvas"&&(this.canvas instanceof Er&&this.canvas.textEditingManager.remove(this),e instanceof Er&&e.textEditingManager.add(this)),super._set(t,e))}setSelectionStart(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)}setSelectionEnd(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)}_updateAndFire(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()}_fireSelectionChanged(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart||0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionEnd,s=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,s)}setSelectionStyles(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionStart||0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,s)}get2DCursorLocation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const s=super.toCanvasElement(t);return this.isEditing=e,s}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),r=s.length>0;let i,n=t;if(r){i=Et(t.canvas),n=i.getContext("2d"),Yi(n,this.canvas);const a=this.calcTransformMatrix();n.transform(a[0],a[1],a[2],a[3],a[4],a[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(n,e):this.renderCursor(n,e),r)for(const a of s){const h=a.clipPath,c=Et(t.canvas),l=c.getContext("2d");if(Yi(l,this.canvas),!h.absolutePositioned){const u=a.calcTransformMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5])}h.transform(l),h.drawObject(l,!0,{}),this.drawClipPathOnCache(n,h,c)}r&&(t.setTransform(1,0,0,1,0,0),t.drawImage(i,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),r=this._getTopOffset(),i=this._getCursorBoundariesOffsets(t,e);return{left:s,top:r,leftOffset:i.left,topOffset:i.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:r,lineIndex:i}=this.get2DCursorLocation(t);for(let c=0;c<i;c++)e+=this.getHeightOfLine(c);const n=this._getLineLeftOffset(i),a=this.__charBounds[i][r];a&&(s=a.left),this.charSpacing!==0&&r===this._textLines[i].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:n+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===Q||this.textAlign===Yt||this.textAlign===He?h.left*=-1:this.textAlign===N||this.textAlign===Ws?h.left=n-(s>0?s:0):this.textAlign!==R&&this.textAlign!==ze||(h.left=n-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),r=s.lineIndex,i=s.charIndex>0?s.charIndex-1:0,n=this.getValueOfPropertyAt(r,i,"fontSize"),a=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/a,c=this.getValueOfPropertyAt(r,i,"deltaY"),l=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-n*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(r,i,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:l+e.top+c,width:h,height:n}}_renderCursor(t,e,s){const{color:r,opacity:i,left:n,top:a,width:h,height:c}=this.getCursorRenderingData(s,e);t.fillStyle=r,t.globalAlpha=i,t.fillRect(n,a,h,c)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const r=e.selectionStart,i=e.selectionEnd,n=this.textAlign.includes(Yt),a=this.get2DCursorLocation(r),h=this.get2DCursorLocation(i),c=a.lineIndex,l=h.lineIndex,u=a.charIndex<0?0:a.charIndex,d=h.charIndex<0?0:h.charIndex;for(let g=c;g<=l;g++){const f=this._getLineLeftOffset(g)||0;let v=this.getHeightOfLine(g),_=0,b=0,w=0;if(g===c&&(b=this.__charBounds[c][u].left),g>=c&&g<l)w=n&&!this.isEndOfWrapping(g)?this.width:this.getLineWidth(g)||5;else if(g===l)if(d===0)w=this.__charBounds[l][d].left;else{const I=this._getWidthOfCharSpacing();w=this.__charBounds[l][d-1].left+this.__charBounds[l][d-1].width-I}_=v,(this.lineHeight<1||g===l&&this.lineHeight>1)&&(v/=this.lineHeight);let C=s.left+f+b,T=v,D=0;const A=w-b;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",T=1,D=v):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Q||this.textAlign===Yt||this.textAlign===He?C=this.width-C-A:this.textAlign===N||this.textAlign===Ws?C=s.left+f-w:this.textAlign!==R&&this.textAlign!==ze||(C=s.left+f-w)),t.fillRect(C,s.top+s.topOffset+D,A,T),s.topOffset+=_}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,ot)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}p($t,"ownDefaults",qh),p($t,"type","IText"),M.setClass($t),M.setClass($t,"i-text");class Jt extends $t{static getDefaults(){return m(m({},super.getDefaults()),Jt.ownDefaults)}constructor(t,e){super(t,m(m({},Jt.ownDefaults),e))}static createControls(){return{controls:Ta()}}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(Yt)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,r=0;const i={};for(let n=0;n<t.graphemeLines.length;n++)t.graphemeText[r]===`
57
- `&&n>0?(s=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&n>0&&(s++,r++),i[n]={line:e,offset:s},r+=t.graphemeLines[n].length,s+=t.graphemeLines[n].length;return i}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,r=t+1,i=!1;const n=this._styleMap[t],a=this._styleMap[t+1];n&&(t=n.line,s=n.offset),a&&(r=a.line,i=r===t,e=a.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const c in h)for(const l in h[c]){const u=parseInt(l,10);if(u>=s&&(!i||u<e))for(const d in h[c][l])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const r=this._styleMap[t];super._setStyleDeclaration(r.line,r.offset+e,s)}_deleteStyleDeclaration(t,e){const s=this._styleMap[t];super._deleteStyleDeclaration(s.line,s.offset+e)}_getLineStyle(t){const e=this._styleMap[t];return!!this.styles[e.line]}_setLineStyle(t){const e=this._styleMap[t];super._setLineStyle(e.line)}_wrapText(t,e){this.isWrapping=!0;const s=this.getGraphemeDataForRender(t),r=[];for(let i=0;i<s.wordsData.length;i++)r.push(...this._wrapLine(i,e,s));return this.isWrapping=!1,r}getGraphemeDataForRender(t){const e=this.splitByGrapheme,s=e?"":" ";let r=0;return{wordsData:t.map((i,n)=>{let a=0;const h=e?this.graphemeSplit(i):this.wordSplit(i);return h.length===0?[{word:[],width:0}]:h.map(c=>{const l=e?[c]:this.graphemeSplit(c),u=this._measureWord(l,n,a);return r=Math.max(u,r),a+=l.length+s.length,{word:l,width:u}})}),largestWordWidth:r}}_measureWord(t,e){let s,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=0;for(let n=0,a=t.length;n<a;n++)i+=this._getGraphemeBox(t[n],e,n+r,s,!0).kernedWidth,s=t[n];return i}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:r,wordsData:i}=s,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const a=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,c=[],l=h?"":" ";let u=0,d=[],g=0,f=0,v=!0;e-=n;const _=Math.max(e,r,this.dynamicMinWidth),b=i[t];let w;for(g=0,w=0;w<b.length;w++){const{word:C,width:T}=b[w];g+=C.length,u+=f+T-a,u>_&&!v?(c.push(d),d=[],u=T,v=!0):u+=a,v||h||d.push(l),d=d.concat(C),f=h?0:this._measureWord([l],t,g),g++,v=!1}return w&&c.push(d),r+n>this.dynamicMinWidth&&(this.dynamicMinWidth=r-a+n),c}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),r=new Array(s.length);for(let i=0;i<s.length;i++)r[i]=s[i].join("");return e.lines=r,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const r=this._styleMap[e].line;t.set("".concat(r),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}p(Jt,"type","Textbox"),p(Jt,"textLayoutProperties",[...$t.textLayoutProperties,"width"]),p(Jt,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),M.setClass(Jt);class Vi extends tr{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:s}=t,{clipPath:r,group:i}=s;if(!r||!this.shouldPerformLayout(t))return;const{width:n,height:a}=Zt(In(s,r)),h=new x(n,a);if(r.absolutePositioned)return{center:ke(r.getRelativeCenterPoint(),void 0,i?i.calcTransformMatrix():void 0),size:h};{const c=r.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:l=new x,correction:u=new x}=this.calcBoundingBox(e,t)||{};return{center:l.add(c),correction:u.subtract(c),size:h}}return{center:s.getRelativeCenterPoint().add(c),size:h}}}}p(Vi,"type","clip-path"),M.setClass(Vi);class Hi extends tr{getInitialSize(t,e){let{target:s}=t,{size:r}=e;return new x(s.width||r.x,s.height||r.y)}}p(Hi,"type","fixed"),M.setClass(Hi);class Kh extends Je{subscribeTargets(t){const e=t.target;t.targets.reduce((s,r)=>(r.parent&&s.add(r.parent),s),new Set).forEach(s=>{s.layoutManager.subscribeTargets({target:s,targets:[e]})})}unsubscribeTargets(t){const e=t.target,s=e.getObjects();t.targets.reduce((r,i)=>(i.parent&&r.add(i.parent),r),new Set).forEach(r=>{!s.some(i=>i.parent===r)&&r.layoutManager.unsubscribeTargets({target:r,targets:[e]})})}}class fe extends pe{static getDefaults(){return m(m({},super.getDefaults()),fe.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,fe.ownDefaults),this.setOptions(e);const{left:s,top:r,layoutManager:i}=e;this.groupInit(t,{left:s,top:r,layoutManager:i??new Kh})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];this.multiSelectionStacking==="selection-order"?this.add(...e):e.forEach(r=>{const i=this._objects.findIndex(a=>a.isInFrontOf(r)),n=i===-1?this.size():i;this.insertAt(n,r)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(ce("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);const s=new Set;e.forEach(r=>{const{parent:i}=r;i&&s.add(i)}),t===$r?s.forEach(r=>{r._onAfterObjectsChange(Xs,e)}):s.forEach(r=>{r._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const r=m(m({hasControls:!1},s),{},{forActiveSelection:!0});for(let i=0;i<this._objects.length;i++)this._objects[i]._renderControls(t,r);super._renderControls(t,e),t.restore()}}p(fe,"type","ActiveSelection"),p(fe,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),M.setClass(fe),M.setClass(fe,"activeSelection");class $h{constructor(){p(this,"resources",{})}applyFilters(t,e,s,r,i){const n=i.getContext("2d");if(!n)return;n.drawImage(e,0,0,s,r);const a={sourceWidth:s,sourceHeight:r,imageData:n.getImageData(0,0,s,r),originalEl:e,originalImageData:n.getImageData(0,0,s,r),canvasEl:i,ctx:n,filterBackend:this};t.forEach(c=>{c.applyTo(a)});const{imageData:h}=a;return h.width===s&&h.height===r||(i.width=h.width,i.height=h.height),n.putImageData(h,0,0),a}}class eo{constructor(){let{tileSize:t=Y.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};p(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),p(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=Et({width:t,height:e}),r=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});r&&(r.clearColor(0,0,0,0),this.canvas=s,this.gl=r)}applyFilters(t,e,s,r,i,n){const a=this.gl,h=i.getContext("2d");if(!a||!h)return;let c;n&&(c=this.getCachedTexture(n,e));const l={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:r,destinationWidth:s,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,s,r,c?void 0:e),targetTexture:this.createTexture(a,s,r),originalTexture:c||this.createTexture(a,s,r,c?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:i},u=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,u),t.forEach(d=>{d&&d.applyTo(l)}),function(d){const g=d.targetCanvas,f=g.width,v=g.height,_=d.destinationWidth,b=d.destinationHeight;f===_&&v===b||(g.width=_,g.height=b)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(u),h.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,s,r,i){const{NEAREST:n,TEXTURE_2D:a,RGBA:h,UNSIGNED_BYTE:c,CLAMP_TO_EDGE:l,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:g,TEXTURE_WRAP_T:f}=t,v=t.createTexture();return t.bindTexture(a,v),t.texParameteri(a,u,i||n),t.texParameteri(a,d,i||n),t.texParameteri(a,g,l),t.texParameteri(a,f,l),r?t.texImage2D(a,0,h,h,c,r):t.texImage2D(a,0,h,e,s,0,h,c,null),v}getCachedTexture(t,e,s){const{textureCache:r}=this;if(r[t])return r[t];{const i=this.createTexture(this.gl,e.width,e.height,e,s);return i&&(r[t]=i),i}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const s=t.canvas,r=e.targetCanvas,i=r.getContext("2d");if(!i)return;i.translate(0,r.height),i.scale(1,-1);const n=s.height-r.height;i.drawImage(s,0,n,r.width,r.height,0,0,r.width,r.height)}copyGLTo2DPutImageData(t,e){const s=e.targetCanvas.getContext("2d"),r=e.destinationWidth,i=e.destinationHeight,n=r*i*4;if(!s)return;const a=new Uint8Array(this.imageBuffer,0,n),h=new Uint8ClampedArray(this.imageBuffer,0,n);t.readPixels(0,0,r,i,t.RGBA,t.UNSIGNED_BYTE,a);const c=new ImageData(h,r,i);s.putImageData(c,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const r=t.getParameter(s.UNMASKED_RENDERER_WEBGL),i=t.getParameter(s.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),i&&(e.vendor=i.toLowerCase())}return this.gpuInfo=e,e}}let pr;function Jh(){const{WebGLProbe:o}=Gt();return o.queryWebGL(ee()),Y.enableGLFiltering&&o.isSupported(Y.textureSize)?new eo({tileSize:Y.textureSize}):new $h}function mr(){return!pr&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(pr=Jh()),pr}const Zh=["filters","resizeFilter","src","crossOrigin","type"],so=["cropX","cropY"];class lt extends ut{static getDefaults(){return m(m({},super.getDefaults()),lt.ownDefaults)}constructor(t,e){super(),p(this,"_lastScaleX",1),p(this,"_lastScaleY",1),p(this,"_filterScalingX",1),p(this,"_filterScalingY",1),this.filters=[],Object.assign(this,lt.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(le()),this.setElement(typeof t=="string"?(this.canvas&&Lt(this.canvas.getElement())||Pe()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(lt.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=mr(!1);e instanceof eo&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{const e=this[t];e&&Gt().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach(s=>{s&&e.push(s.toObject())}),m(m({},super.toObject([...so,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,r=-this.height/2;let i=[],n=[],a="",h="";if(!e)return[];if(this.hasCrop()){const c=le();i.push('<clipPath id="imageCrop_'+c+`">
49
+ `]}}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{left:i=0,top:n=0,radius:a=0}=r;return new this(m(m({},$(r,Wh)),{},{radius:a,left:i-a,top:n-a}))}static fromObject(t){return super._fromObject(t)}}p(Xt,"type","Circle"),p(Xt,"cacheProperties",[...re,...Zn]),p(Xt,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),p(Xt,"ATTRIBUTE_NAMES",["cx","cy","r",...ue]),M.setClass(Xt),M.setSVGClass(Xt);const Xh=["x1","y1","x2","y2"],Yh=["x1","y1","x2","y2"],Pr=["x1","x2","y1","y2"];class Vt extends ut{constructor(){let[t,e,s,r]=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[0,0,0,0],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,Vt.ownDefaults),this.setOptions(i),this.x1=t,this.x2=s,this.y1=e,this.y2=r,this._setWidthHeight();const{left:n,top:a}=i;typeof n=="number"&&this.set(N,n),typeof a=="number"&&this.set(mt,a)}_setWidthHeight(){const{x1:t,y1:e,x2:s,y2:r}=this;this.width=Math.abs(s-t),this.height=Math.abs(r-e);const{left:i,top:n,width:a,height:h}=Zt([{x:t,y:e},{x:s,y:r}]),c=new x(i+a/2,n+h/2);this.setPositionByOrigin(c,R,R)}_set(t,e){return super._set(t,e),Pr.includes(t)&&this._setWidthHeight(),this}_render(t){t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const s=t.strokeStyle;var r;Dt(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(r=this.stroke)!==null&&r!==void 0?r:t.fillStyle,this.stroke&&this._renderStroke(t),t.strokeStyle=s}_findCenterFromElement(){return new x((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject(t)),this.calcLinePoints())}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return this.strokeLineCap==="butt"&&(this.width===0&&(t.y-=this.strokeWidth),this.height===0&&(t.x-=this.strokeWidth)),t}calcLinePoints(){const{x1:t,x2:e,y1:s,y2:r,width:i,height:n}=this,a=t<=e?-1:1,h=s<=r?-1:1;return{x1:a*i/2,x2:a*-i/2,y1:h*n/2,y2:h*-n/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:r}=this.calcLinePoints();return["<line ","COMMON_PARTS",'x1="'.concat(t,'" y1="').concat(s,'" x2="').concat(e,'" y2="').concat(r,`" />
50
+ `)]}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s),{x1:i=0,y1:n=0,x2:a=0,y2:h=0}=r;return new this([i,n,a,h],$(r,Xh))}static fromObject(t){let{x1:e,y1:s,x2:r,y2:i}=t,n=$(t,Yh);return this._fromObject(m(m({},n),{},{points:[e,s,r,i]}),{extraParam:"points"})}}p(Vt,"type","Line"),p(Vt,"cacheProperties",[...re,...Pr]),p(Vt,"ATTRIBUTE_NAMES",ue.concat(Pr)),M.setClass(Vt),M.setSVGClass(Vt);class ge extends ut{static getDefaults(){return m(m({},super.getDefaults()),ge.ownDefaults)}constructor(t){super(),Object.assign(this,ge.ownDefaults),this.setOptions(t)}_render(t){const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,s),t.lineTo(0,-s),t.lineTo(e,s),t.closePath(),this._renderPaintInOrder(t)}_toSVG(){const t=this.width/2,e=this.height/2;return["<polygon ","COMMON_PARTS",'points="',"".concat(-t," ").concat(e,",0 ").concat(-e,",").concat(t," ").concat(e),'" />']}}p(ge,"type","Triangle"),p(ge,"ownDefaults",{width:100,height:100}),M.setClass(ge),M.setSVGClass(ge);const Qn=["rx","ry"];class qt extends ut{static getDefaults(){return m(m({},super.getDefaults()),qt.ownDefaults)}constructor(t){super(),Object.assign(this,qt.ownDefaults),this.setOptions(t)}_set(t,e){switch(super._set(t,e),t){case"rx":this.rx=e,this.set("width",2*e);break;case"ry":this.ry=e,this.set("height",2*e)}return this}getRx(){return this.get("rx")*this.get(_t)}getRy(){return this.get("ry")*this.get(Mt)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Qn,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",'cx="0" cy="0" rx="'.concat(this.rx,'" ry="').concat(this.ry,`" />
51
+ `)]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,Ps,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const r=ie(t,this.ATTRIBUTE_NAMES,s);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}}function Vh(o){if(!o)return[];const t=o.replace(/,/g," ").trim().split(/\s+/),e=[];for(let s=0;s<t.length;s+=2)e.push({x:parseFloat(t[s]),y:parseFloat(t[s+1])});return e}p(qt,"type","Ellipse"),p(qt,"cacheProperties",[...re,...Qn]),p(qt,"ownDefaults",{rx:0,ry:0}),p(qt,"ATTRIBUTE_NAMES",[...ue,"cx","cy","rx","ry"]),M.setClass(qt),M.setSVGClass(qt);const Hh=["left","top"],to={exactBoundingBox:!1};class Ft extends ut{static getDefaults(){return m(m({},super.getDefaults()),Ft.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),p(this,"strokeDiff",void 0),Object.assign(this,Ft.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:r}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(N,s),typeof r=="number"&&this.set(mt,r)}isOpen(){return!0}_projectStrokeOnPoints(t){return Pa(this.points,t,this.isOpen())}_calcDimensions(t){t=m({scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth},t||{});const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(c=>c.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new x,strokeOffset:new x,strokeDiff:new x};const s=Zt(e),r=Ks(m(m({},t),{},{scaleX:1,scaleY:1})),i=Zt(this.points.map(c=>pt(c,r,!0))),n=new x(this.scaleX,this.scaleY);let a=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(a-=h*Math.tan(tt(this.skewX)),h-=a*Math.tan(tt(this.skewY))),m(m({},s),{},{pathOffset:new x(a,h),strokeOffset:new x(i.left,i.top).subtract(new x(s.left,s.top)).multiply(n),strokeDiff:new x(s.width,s.height).subtract(new x(i.width,i.height)).multiply(n)})}_findCenterFromElement(){const t=Zt(this.points);return new x(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:s,width:r,height:i,pathOffset:n,strokeOffset:a,strokeDiff:h}=this._calcDimensions();this.set({width:r,height:i,pathOffset:n,strokeOffset:a,strokeDiff:h}),t&&this.setPositionByOrigin(new x(e+r/2,s+i/2),R,R)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new x(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let n;if(Object.keys(t).some(a=>this.strokeUniform||this.constructor.layoutProperties.includes(a))){var e,s;const{width:a,height:h}=this._calcDimensions(t);n=new x((e=t.width)!==null&&e!==void 0?e:a,(s=t.height)!==null&&s!==void 0?s:h)}else{var r,i;n=new x((r=t.width)!==null&&r!==void 0?r:this.width,(i=t.height)!==null&&i!==void 0?i:this.height)}return n.multiply(new x(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const s=this.initialized&&this[t]!==e,r=super._set(t,e);return this.exactBoundingBox&&s&&((t===_t||t===Mt)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),r}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject(t)),{},{points:this.points.map(e=>{let{x:s,y:r}=e;return{x:s,y:r}})})}_toSVG(){const t=[],e=this.pathOffset.x,s=this.pathOffset.y,r=Y.NUM_FRACTION_DIGITS;for(let i=0,n=this.points.length;i<n;i++)t.push(K(this.points[i].x-e,r),",",K(this.points[i].y-s,r)," ");return["<".concat(this.constructor.type.toLowerCase()," "),"COMMON_PARTS",'points="'.concat(t.join(""),`" />
52
+ `)]}_render(t){const e=this.points.length,s=this.pathOffset.x,r=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){t.beginPath(),t.moveTo(this.points[0].x-s,this.points[0].y-r);for(let i=0;i<e;i++){const n=this.points[i];t.lineTo(n.x-s,n.y-r)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){return new this(Vh(t.getAttribute("points")),m(m({},$(ie(t,this.ATTRIBUTE_NAMES,s),Hh)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}p(Ft,"ownDefaults",to),p(Ft,"type","Polyline"),p(Ft,"layoutProperties",[Ae,je,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),p(Ft,"cacheProperties",[...re,"points"]),p(Ft,"ATTRIBUTE_NAMES",[...ue]),M.setClass(Ft),M.setSVGClass(Ft);class ns extends Ft{isOpen(){return!1}}p(ns,"ownDefaults",to),p(ns,"type","Polygon"),M.setClass(ns),M.setSVGClass(ns);class eo extends ut{isEmptyStyles(t){if(!this.styles||t!==void 0&&!this.styles[t])return!0;const e=t===void 0?this.styles:{line:this.styles[t]};for(const s in e)for(const r in e[s])for(const i in e[s][r])return!1;return!0}styleHas(t,e){if(!this.styles||e!==void 0&&!this.styles[e])return!1;const s=e===void 0?this.styles:{0:this.styles[e]};for(const r in s)for(const i in s[r])if(s[r][i][t]!==void 0)return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let s,r,i=0,n=!0,a=0;for(const h in e){s=0;for(const c in e[h]){const l=e[h][c]||{};i++,l[t]!==void 0?(r?l[t]!==r&&(n=!1):r=l[t],l[t]===this[t]&&delete l[t]):n=!1,Object.keys(l).length!==0?s++:delete e[h][c]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)a+=this._textLines[h].length;n&&i===a&&(this[t]=r,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let s,r,i;for(r in e){for(i in s=e[r],s)delete s[i][t],Object.keys(s[i]).length===0&&delete s[i];Object.keys(s).length===0&&delete e[r]}}_extendStyles(t,e){const{lineIndex:s,charIndex:r}=this.get2DCursorLocation(t);this._getLineStyle(s)||this._setLineStyle(s);const i=Xr(m(m({},this._getStyleDeclaration(s,r)),e),n=>n!==void 0);this._setStyleDeclaration(s,r,i)}getSelectionStyles(t,e,s){const r=[];for(let i=t;i<(e||t);i++)r.push(this.getStyleAtPosition(i,s));return r}getStyleAtPosition(t,e){const{lineIndex:s,charIndex:r}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(s,r):this._getStyleDeclaration(s,r)}setSelectionStyles(t,e,s){for(let r=e;r<(s||e);r++)this._extendStyles(r,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var s;const r=this.styles&&this.styles[t];return r&&(s=r[e])!==null&&s!==void 0?s:{}}getCompleteStyleDeclaration(t,e){return m(m({},Le(this,this.constructor._styleProperties)),this._getStyleDeclaration(t,e))}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}p(eo,"_styleProperties",Uo);const zh=/ +/g,Gh=/"/g;function gr(o,t,e,s,r){return" ".concat(function(i,n){let{left:a,top:h,width:c,height:l}=n,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Y.NUM_FRACTION_DIGITS;const d=Ke(ot,i,!1),[g,f,v,_]=[a,h,c,l].map(b=>K(b,u));return"<rect ".concat(d,' x="').concat(g,'" y="').concat(f,'" width="').concat(v,'" height="').concat(_,'"></rect>')}(o,{left:t,top:e,width:s,height:r}),`
53
+ `)}const Nh=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let fr;class dt extends eo{static getDefaults(){return m(m({},super.getDefaults()),dt.ownDefaults)}constructor(t,e){super(),p(this,"__charBounds",[]),Object.assign(this,dt.ownDefaults),this.setOptions(e),this.styles||(this.styles={}),this.text=t,this.initialized=!0,this.path&&this.setPathInfo(),this.initDimensions(),this.setCoords()}setPathInfo(){const t=this.path;t&&(t.segmentsInfo=Gn(t.path))}_splitText(){const t=this._splitTextIntoLines(this.text);return this.textLines=t.lines,this._textLines=t.graphemeLines,this._unwrappedTextLines=t._unwrappedLines,this._text=t.graphemeText,t}initDimensions(){this._splitText(),this._clearCache(),this.dirty=!0,this.path?(this.width=this.path.width,this.height=this.path.height):(this.width=this.calcTextWidth()||this.cursorWidth||this.MIN_TEXT_WIDTH,this.height=this.calcTextHeight()),this.textAlign.includes(Yt)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,r,i,n,a;for(let h=0,c=this._textLines.length;h<c;h++)if((this.textAlign===Yt||h!==c-1&&!this.isEndOfWrapping(h))&&(r=0,i=this._textLines[h],e=this.getLineWidth(h),e<this.width&&(a=this.textLines[h].match(this._reSpacesAndTabs)))){s=a.length,t=(this.width-e)/s;for(let l=0;l<=i.length;l++)n=this.__charBounds[h][l],this._reSpaceAndTab.test(i[l])?(n.width+=t,n.kernedWidth+=t,n.left+=r,r+=t):n.left+=r}}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const s=e?this._unwrappedTextLines:this._textLines;let r;for(r=0;r<s.length;r++){if(t<=s[r].length)return{lineIndex:r,charIndex:t};t-=s[r].length+this.missingNewlineOffset(r,e)}return{lineIndex:r-1,charIndex:s[r-1].length<t?s[r-1].length:t}}toString(){return"#<Text (".concat(this.complexity(),'): { "text": "').concat(this.text,'", "fontFamily": "').concat(this.fontFamily,'" }>')}_getCacheCanvasDimensions(){const t=super._getCacheCanvasDimensions(),e=this.fontSize;return t.width+=e*t.zoomX,t.height+=e*t.zoomY,t}_render(t){const e=this.path;e&&!e.isNotVisible()&&e._render(t),this._setTextStyles(t),this._renderTextLinesBackground(t),this._renderTextDecoration(t,"underline"),this._renderText(t),this._renderTextDecoration(t,"overline"),this._renderTextDecoration(t,"linethrough")}_renderText(t){this.paintFirst===yt?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t))}_setTextStyles(t,e,s){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case R:t.textBaseline="middle";break;case"ascender":t.textBaseline=mt;break;case"descender":t.textBaseline=_r}t.font=this._getFontDeclaration(e,s)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,s=this._textLines.length;e<s;e++){const r=this.getLineWidth(e);r>t&&(t=r)}return t}_renderTextLine(t,e,s,r,i,n){this._renderChars(t,e,s,r,i,n)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let r=this._getTopOffset();for(let i=0,n=this._textLines.length;i<n;i++){const a=this.getHeightOfLine(i);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",i)){r+=a;continue}const h=this._textLines[i].length,c=this._getLineLeftOffset(i);let l,u,d=0,g=0,f=this.getValueOfPropertyAt(i,0,"textBackgroundColor");const v=this.getHeightOfLineImpl(i);for(let _=0;_<h;_++){const b=this.__charBounds[i][_];u=this.getValueOfPropertyAt(i,_,"textBackgroundColor"),this.path?(t.save(),t.translate(b.renderLeft,b.renderTop),t.rotate(b.angle),t.fillStyle=u,u&&t.fillRect(-b.width/2,-v*(1-this._fontSizeFraction),b.width,v),t.restore()):u!==f?(l=s+c+g,this.direction==="rtl"&&(l=this.width-l-d),t.fillStyle=f,f&&t.fillRect(l,r,d,v),g=b.left,d=b.width,f=u):d+=b.kernedWidth}u&&!this.path&&(l=s+c+g,this.direction==="rtl"&&(l=this.width-l-d),t.fillStyle=u,t.fillRect(l,r,d,v)),r+=a}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,r){const i=Ve.getFontCache(e),n=this._getFontDeclaration(e),a=s?s+t:t,h=s&&n===this._getFontDeclaration(r),c=e.fontSize/this.CACHE_FONT_SIZE;let l,u,d,g;if(s&&i.has(s)&&(d=i.get(s)),i.has(t)&&(g=l=i.get(t)),h&&i.has(a)&&(u=i.get(a),g=u-d),l===void 0||d===void 0||u===void 0){const f=function(){return fr||(fr=Et({width:0,height:0}).getContext("2d")),fr}();this._setTextStyles(f,e,!0),l===void 0&&(g=l=f.measureText(t).width,i.set(t,l)),d===void 0&&h&&s&&(d=f.measureText(s).width,i.set(s,d)),h&&u===void 0&&(u=f.measureText(a).width,i.set(a,u),g=u-d)}return{width:l*c,kernedWidth:g*c}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,r=0;const i=this.pathSide===Q,n=this.path,a=this._textLines[t],h=a.length,c=new Array(h);this.__charBounds[t]=c;for(let l=0;l<h;l++){const u=a[l];s=this._getGraphemeBox(u,t,l,e),c[l]=s,r+=s.kernedWidth,e=u}if(c[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},n&&n.segmentsInfo){let l=0;const u=n.segmentsInfo[n.segmentsInfo.length-1].length;switch(this.textAlign){case N:l=i?u-r:0;break;case R:l=(u-r)/2;break;case Q:l=i?0:u-r}l+=this.pathStartOffset*(i?-1:1);for(let d=i?h-1:0;i?d>=0:d<h;i?d--:d++)s=c[d],l>u?l%=u:l<0&&(l+=u),this._setGraphemeOnPath(l,s),l+=s.kernedWidth}return{width:r,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,r=this.path,i=xh(r.path,s,r.segmentsInfo);e.renderLeft=i.x-r.pathOffset.x,e.renderTop=i.y-r.pathOffset.y,e.angle=i.angle+(this.pathSide===Q?Math.PI:0)}_getGraphemeBox(t,e,s,r,i){const n=this.getCompleteStyleDeclaration(e,s),a=r?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,n,r,a);let c,l=h.kernedWidth,u=h.width;this.charSpacing!==0&&(c=this._getWidthOfCharSpacing(),u+=c,l+=c);const d={width:u,left:0,height:n.fontSize,kernedWidth:l,deltaY:n.deltaY};if(s>0&&!i){const g=this.__charBounds[e][s-1];d.left=g.left+g.width+h.kernedWidth-h.width}return d}getHeightOfLineImpl(t){const e=this.__lineHeights;if(e[t])return e[t];let s=this.getHeightOfChar(t,0);for(let r=1,i=this._textLines[t].length;r<i;r++)s=Math.max(this.getHeightOfChar(t,r),s);return e[t]=s*this._fontSizeMult}getHeightOfLine(t){return this.getHeightOfLineImpl(t)*this.lineHeight}calcTextHeight(){let t=0;for(let e=0,s=this._textLines.length;e<s;e++)t+=e===s-1?this.getHeightOfLineImpl(e):this.getHeightOfLine(e);return t}_getLeftOffset(){return this.direction==="ltr"?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){t.save();let s=0;const r=this._getLeftOffset(),i=this._getTopOffset();for(let n=0,a=this._textLines.length;n<a;n++)this._renderTextLine(e,t,this._textLines[n],r+this._getLineLeftOffset(n),i+s+this.getHeightOfLineImpl(n),n),s+=this.getHeightOfLine(n);t.restore()}_renderTextFill(t){(this.fill||this.styleHas(ot))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&this.strokeWidth!==0||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,s,r,i,n){const a=this.textAlign.includes(Yt),h=this.path,c=!a&&this.charSpacing===0&&this.isEmptyStyles(n)&&!h,l=this.direction==="ltr",u=this.direction==="ltr"?1:-1,d=e.direction;let g,f,v,_,b,w="",C=0;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",l?"ltr":"rtl"),e.direction=l?"ltr":"rtl",e.textAlign=l?N:Q),i-=this.getHeightOfLineImpl(n)*this._fontSizeFraction,c)return this._renderChar(t,e,n,0,s.join(""),r,i),void e.restore();for(let T=0,D=s.length-1;T<=D;T++)_=T===D||this.charSpacing||h,w+=s[T],v=this.__charBounds[n][T],C===0?(r+=u*(v.kernedWidth-v.width),C+=v.width):C+=v.kernedWidth,a&&!_&&this._reSpaceAndTab.test(s[T])&&(_=!0),_||(g=g||this.getCompleteStyleDeclaration(n,T),f=this.getCompleteStyleDeclaration(n,T+1),_=qr(g,f,!1)),_&&(h?(e.save(),e.translate(v.renderLeft,v.renderTop),e.rotate(v.angle),this._renderChar(t,e,n,T,w,-C/2,0),e.restore()):(b=r,this._renderChar(t,e,n,T,w,b,i)),w="",g=f,r+=u*C,C=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,r=Et({width:e,height:s}),i=r.getContext("2d");return r.width=e,r.height=s,i.beginPath(),i.moveTo(0,0),i.lineTo(e,0),i.lineTo(e,s),i.lineTo(0,s),i.closePath(),i.translate(e/2,s/2),i.fillStyle=t.toLive(i),this._applyPatternGradientTransform(i,t),i.fill(),i.createPattern(r,"no-repeat")}handleFiller(t,e,s){let r,i;return Dt(s)?s.gradientUnits==="percentage"||s.gradientTransform||s.patternTransform?(r=-this.width/2,i=-this.height/2,t.translate(r,i),t[e]=this._applyPatternGradientTransformText(s),{offsetX:r,offsetY:i}):(t[e]=s.toLive(t),this._applyPatternGradientTransform(t,s)):(t[e]=s,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:s,strokeWidth:r}=e;return t.lineWidth=r,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",s)}_setFillStyles(t,e){let{fill:s}=e;return this.handleFiller(t,"fillStyle",s)}_renderChar(t,e,s,r,i,n,a){const h=this._getStyleDeclaration(s,r),c=this.getCompleteStyleDeclaration(s,r),l=t==="fillText"&&c.fill,u=t==="strokeText"&&c.stroke&&c.strokeWidth;if(u||l){if(e.save(),e.font=this._getFontDeclaration(c),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(a+=h.deltaY),l){const d=this._setFillStyles(e,c);e.fillText(i,n-d.offsetX,a-d.offsetY)}if(u){const d=this._setStrokeStyles(e,c);e.strokeText(i,n-d.offsetX,a-d.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,s){const r=this.get2DCursorLocation(t,!0),i=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,"fontSize"),n=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,"deltaY"),a={fontSize:i*s.size,deltaY:n+i*s.baseline};this.setSelectionStyles(a,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),s=this.width-e,r=this.textAlign,i=this.direction,n=this.isEndOfWrapping(t);let a=0;return r===Yt||r===ze&&!n||r===He&&!n||r===Ws&&!n?0:(r===R&&(a=s/2),r===Q&&(a=s),r===ze&&(a=s/2),r===He&&(a=s),i==="rtl"&&(r===Q||r===Yt||r===He?a=0:r===N||r===Ws?a=-s:r!==R&&r!==ze||(a=-s/2)),a)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[]}getLineWidth(t){if(this.__lineWidths[t]!==void 0)return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return this.charSpacing!==0?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,s){var r;return(r=this._getStyleDeclaration(t,e)[s])!==null&&r!==void 0?r:this[s]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let s=this._getTopOffset();const r=this._getLeftOffset(),i=this.path,n=this._getWidthOfCharSpacing(),a=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let c=0,l=this._textLines.length;c<l;c++){const u=this.getHeightOfLine(c);if(!this[e]&&!this.styleHas(e,c)){s+=u;continue}const d=this._textLines[c],g=u/this.lineHeight,f=this._getLineLeftOffset(c);let v=0,_=0,b=this.getValueOfPropertyAt(c,0,e),w=this.getValueOfPropertyAt(c,0,ot),C=this.getValueOfPropertyAt(c,0,me),T=b,D=w,A=C;const I=s+g*(1-this._fontSizeFraction);let E=this.getHeightOfChar(c,0),W=this.getValueOfPropertyAt(c,0,"deltaY");for(let L=0,V=d.length;L<V;L++){const X=this.__charBounds[c][L];T=this.getValueOfPropertyAt(c,L,e),D=this.getValueOfPropertyAt(c,L,ot),A=this.getValueOfPropertyAt(c,L,me);const nt=this.getHeightOfChar(c,L),et=this.getValueOfPropertyAt(c,L,"deltaY");if(i&&T&&D){const st=this.fontSize*A/1e3;t.save(),t.fillStyle=w,t.translate(X.renderLeft,X.renderTop),t.rotate(X.angle),t.fillRect(-X.kernedWidth/2,h*nt+et-a*st,X.kernedWidth,st),t.restore()}else if((T!==b||D!==w||nt!==E||A!==C||et!==W)&&_>0){const st=this.fontSize*C/1e3;let U=r+f+v;this.direction==="rtl"&&(U=this.width-U-_),b&&w&&C&&(t.fillStyle=w,t.fillRect(U,I+h*E+W-a*st,_,st)),v=X.left,_=X.width,b=T,C=A,w=D,E=nt,W=et}else _+=X.kernedWidth}let q=r+f+v;this.direction==="rtl"&&(q=this.width-q-_),t.fillStyle=D;const Z=this.fontSize*A/1e3;T&&D&&A&&t.fillRect(q,I+h*E+W-a*Z,_-n,Z),s+=u}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:s=this.fontWeight,fontSize:r=this.fontSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},i=arguments.length>1?arguments[1]:void 0;const n=t.includes("'")||t.includes('"')||t.includes(",")||dt.genericFonts.includes(t.toLowerCase())?t:'"'.concat(t,'"');return[e,s,"".concat(i?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 Ur(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),r=[`
54
+ `];let i=[];for(let n=0;n<e.length;n++)s[n]=this.graphemeSplit(e[n]),i=i.concat(s[n],r);return i.pop(),{_unwrappedLines:s,lines:e,graphemeText:i,graphemeLines:s}}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return m(m({},super.toObject([...kn,...t])),{},{styles:La(this.styles,this.text)},this.path?{path:this.path.toObject()}:{})}set(t,e){const{textLayoutProperties:s}=this.constructor;super.set(t,e);let r=!1,i=!1;if(typeof t=="object")for(const n in t)n==="path"&&this.setPathInfo(),r=r||s.includes(n),i=i||n==="path";else r=s.includes(t),i=t==="path";return i&&this.setPathInfo(),r&&this.initialized&&(this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,s){const r=ie(t,dt.ATTRIBUTE_NAMES,s),i=m(m({},e),r),{textAnchor:n=N,textDecoration:a="",dx:h=0,dy:c=0,top:l=0,left:u=0,fontSize:d=Fr,strokeWidth:g=1}=i,f=$(i,Nh),v=new this(Is(t.textContent||"").trim(),m({left:u+h,top:l+c,underline:a.includes("underline"),overline:a.includes("overline"),linethrough:a.includes("line-through"),strokeWidth:0,fontSize:d},f)),_=v.getScaledHeight()/v.height,b=((v.height+v.strokeWidth)*v.lineHeight-v.height)*_,w=v.getScaledHeight()+b;let C=0;return n===R&&(C=v.getScaledWidth()/2),n===Q&&(C=v.getScaledWidth()),v.set({left:v.left-C,top:v.top-(w-v.fontSize*(.07+v._fontSizeFraction))/v.lineHeight,strokeWidth:g}),v}static fromObject(t){return this._fromObject(m(m({},t),{},{styles:Ra(t.styles||{},t.text)}),{extraParam:"text"})}}p(dt,"textLayoutProperties",On),p(dt,"cacheProperties",[...re,...kn]),p(dt,"ownDefaults",qo),p(dt,"type","Text"),p(dt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),p(dt,"ATTRIBUTE_NAMES",ue.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Rn(dt,[class extends Sn{_toSVG(){const o=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(o.textTop,o.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(o){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:o,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:o,withShadow:!0,additionalTransform:qe(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(o){let{textBgRects:t,textSpans:e}=o;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ','font-family="'.concat(this.fontFamily.replace(Gh,"'"),'" '),'font-size="'.concat(this.fontSize,'" '),this.fontStyle?'font-style="'.concat(this.fontStyle,'" '):"",this.fontWeight?'font-weight="'.concat(this.fontWeight,'" '):"",s?'text-decoration="'.concat(s,'" '):"",this.direction==="rtl"?'direction="'.concat(this.direction,'" '):"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
55
+ `]}_getSVGTextAndBg(o,t){const e=[],s=[];let r,i=o;this.backgroundColor&&s.push(...gr(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let n=0,a=this._textLines.length;n<a;n++)r=this._getLineLeftOffset(n),this.direction==="rtl"&&(r+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",n))&&this._setSVGTextLineBg(s,n,t+r,i),this._setSVGTextLineText(e,n,t+r,i),i+=this.getHeightOfLine(n);return{textSpans:e,textBgRects:s}}_createTextCharSpan(o,t,e,s,r){const i=Y.NUM_FRACTION_DIGITS,n=this.getSvgSpanStyles(t,o!==o.trim()||!!o.match(zh)),a=n?'style="'.concat(n,'"'):"",h=t.deltaY,c=h?' dy="'.concat(K(h,i),'" '):"",{angle:l,renderLeft:u,renderTop:d,width:g}=r;let f="";if(u!==void 0){const v=g/2;l&&(f=' rotate="'.concat(K(se(l),i),'"'));const _=Fe({angle:se(l)});_[4]=u,_[5]=d;const b=new x(-v,0).transform(_);e=b.x,s=b.y}return'<tspan x="'.concat(K(e,i),'" y="').concat(K(s,i),'" ').concat(c).concat(f).concat(a,">").concat(Aa(o),"</tspan>")}_setSVGTextLineText(o,t,e,s){const r=this.getHeightOfLine(t),i=this.textAlign.includes(Yt),n=this._textLines[t];let a,h,c,l,u,d="",g=0;s+=r*(1-this._fontSizeFraction)/this.lineHeight;for(let f=0,v=n.length-1;f<=v;f++)u=f===v||this.charSpacing||this.path,d+=n[f],c=this.__charBounds[t][f],g===0?(e+=c.kernedWidth-c.width,g+=c.width):g+=c.kernedWidth,i&&!u&&this._reSpaceAndTab.test(n[f])&&(u=!0),u||(a=a||this.getCompleteStyleDeclaration(t,f),h=this.getCompleteStyleDeclaration(t,f+1),u=qr(a,h,!0)),u&&(l=this._getStyleDeclaration(t,f),o.push(this._createTextCharSpan(d,l,e,s,c)),d="",a=h,this.direction==="rtl"?e-=g:e+=g,g=0)}_setSVGTextLineBg(o,t,e,s){const r=this._textLines[t],i=this.getHeightOfLine(t)/this.lineHeight;let n,a=0,h=0,c=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let l=0;l<r.length;l++){const{left:u,width:d,kernedWidth:g}=this.__charBounds[t][l];n=this.getValueOfPropertyAt(t,l,"textBackgroundColor"),n!==c?(c&&o.push(...gr(c,e+h,s,a,i)),h=u,a=d,c=n):a+=g}n&&o.push(...gr(c,e+h,s,a,i))}_getSVGLineTopOffset(o){let t,e=0;for(t=0;t<o;t++)e+=this.getHeightOfLine(t);const s=this.getHeightOfLine(t);return{lineTop:e,offset:(this._fontSizeMult-this._fontSizeFraction)*s/(this.lineHeight*this._fontSizeMult)}}getSvgStyles(o){return"".concat(super.getSvgStyles(o)," text-decoration-thickness: ").concat(K(this.textDecorationThickness*this.getObjectScaling().y/10,Y.NUM_FRACTION_DIGITS),"%; white-space: pre;")}getSvgSpanStyles(o,t){const{fontFamily:e,strokeWidth:s,stroke:r,fill:i,fontSize:n,fontStyle:a,fontWeight:h,deltaY:c,textDecorationThickness:l,linethrough:u,overline:d,underline:g}=o,f=this.getSvgTextDecoration({underline:g??this.underline,overline:d??this.overline,linethrough:u??this.linethrough}),v=l||this.textDecorationThickness;return[r?Ke(yt,r):"",s?"stroke-width: ".concat(s,"; "):"",e?"font-family: ".concat(e.includes("'")||e.includes('"')?e:"'".concat(e,"'"),"; "):"",n?"font-size: ".concat(n,"px; "):"",a?"font-style: ".concat(a,"; "):"",h?"font-weight: ".concat(h,"; "):"",f?"text-decoration: ".concat(f,"; text-decoration-thickness: ").concat(K(v*this.getObjectScaling().y/10,Y.NUM_FRACTION_DIGITS),"%; "):"",i?Ke(ot,i):"",c?"baseline-shift: ".concat(-c,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(o){return["overline","underline","line-through"].filter(t=>o[t.replace("-","")]).join(" ")}}]),M.setClass(dt),M.setSVGClass(dt);class Uh{constructor(t){p(this,"target",void 0),p(this,"__mouseDownInPlace",!1),p(this,"__dragStartFired",!1),p(this,"__isDraggingOver",!1),p(this,"__dragStartSelection",void 0),p(this,"__dragImageDisposer",void 0),p(this,"_dispose",void 0),this.target=t;const e=[this.target.on("dragenter",this.dragEnterHandler.bind(this)),this.target.on("dragover",this.dragOverHandler.bind(this)),this.target.on("dragleave",this.dragLeaveHandler.bind(this)),this.target.on("dragend",this.dragEndHandler.bind(this)),this.target.on("drop",this.dropHandler.bind(this))];this._dispose=()=>{e.forEach(s=>s()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,s=e.getSelectionStartFromPointer(t);return e.isEditing&&s>=e.selectionStart&&s<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){const e=this.isActive();return e&&!this.__dragStartFired&&(this.target.setCursorByClick(t),this.target.initDelayedCursor(!0)),this.__mouseDownInPlace=!1,this.__dragStartFired=!1,this.__isDraggingOver=!1,e}getDragStartSelection(){return this.__dragStartSelection}setDragImage(t,e){var s;let{selectionStart:r,selectionEnd:i}=e;const n=this.target,a=n.canvas,h=new x(n.flipX?-1:1,n.flipY?-1:1),c=n._getCursorBoundaries(r),l=new x(c.left+c.leftOffset,c.top+c.topOffset).multiply(h).transform(n.calcTransformMatrix()),u=a.getScenePoint(t).subtract(l),d=n.getCanvasRetinaScaling(),g=n.getBoundingRect(),f=l.subtract(new x(g.left,g.top)),v=a.viewportTransform,_=f.add(u).transform(v,!0),b=n.backgroundColor,w=Nr(n.styles);n.backgroundColor="";const C={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};n.setSelectionStyles(C,0,r),n.setSelectionStyles(C,i,n.text.length),n.dirty=!0;const T=n.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});n.backgroundColor=b,n.styles=w,n.dirty=!0,Mr(T,{position:"fixed",left:"".concat(-T.width,"px"),border:vt,width:"".concat(T.width/d,"px"),height:"".concat(T.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{T.remove()},Lt(t.target||this.target.hiddenTextarea).body.appendChild(T),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(T,_.x,_.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,s=this.isActive();if(s&&t.dataTransfer){const r=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},i=e._text.slice(r.selectionStart,r.selectionEnd).join(""),n=m({text:e.text,value:i},r);t.dataTransfer.setData("text/plain",i),t.dataTransfer.setData("application/fabric",JSON.stringify({value:i,styles:e.getSelectionStyles(r.selectionStart,r.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,n)}return e.abortCursorAnimation(),s}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),s=this.__dragStartSelection;return e<s.selectionStart||e>s.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e}=t;const s=this.targetCanDrop(e);!this.__isDraggingOver&&s&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e}=t,s=this.targetCanDrop(e);!this.__isDraggingOver&&s?this.__isDraggingOver=!0:this.__isDraggingOver&&!s&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:s}=t,r=s.defaultPrevented;this.__isDraggingOver=!1,s.preventDefault();let i=(e=s.dataTransfer)===null||e===void 0?void 0:e.getData("text/plain");if(i&&!r){const n=this.target,a=n.canvas;let h=n.getSelectionStartFromPointer(s);const{styles:c}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},l=i[Math.max(0,i.length-1)],u=0;if(this.__dragStartSelection){const d=this.__dragStartSelection.selectionStart,g=this.__dragStartSelection.selectionEnd;h>d&&h<=g?h=d:h>g&&(h-=g-d),n.removeChars(d,g),delete this.__dragStartSelection}n._reNewline.test(l)&&(n._reNewline.test(n._text[h])||h===n._text.length)&&(i=i.trimEnd()),t.didDrop=!0,t.dropTarget=n,n.insertChars(i,c,h),a.setActiveObject(n),n.enterEditing(s),n.selectionStart=Math.min(h+u,n._text.length),n.selectionEnd=Math.min(n.selectionStart+i.length,n._text.length),n.hiddenTextarea.value=n.text,n._updateTextarea(),n.hiddenTextarea.focus(),n.fire(As,{index:h+u,action:"drop"}),a.fire("text:changed",{target:n}),a.contextTopDirty=!0,a.requestRenderAll()}}dragEndHandler(t){let{e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var s;const r=this.target,i=this.target.canvas,{selectionStart:n,selectionEnd:a}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||vt;h===vt?(r.selectionStart=n,r.selectionEnd=a,r._updateTextarea(),r.hiddenTextarea.focus()):(r.clearContextTop(),h==="move"&&(r.removeChars(n,a),r.selectionStart=r.selectionEnd=n,r.hiddenTextarea&&(r.hiddenTextarea.value=r.text),r._updateTextarea(),r.fire(As,{index:n,action:"dragend"}),i.fire("text:changed",{target:r}),i.requestRenderAll()),r.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}const Wi=/[ \n\.,;!\?\-]/;class qh extends dt{constructor(){super(...arguments),p(this,"_currentCursorOpacity",1)}initBehavior(){this._tick=this._tick.bind(this),this._onTickComplete=this._onTickComplete.bind(this),this.updateSelectionOnMouseMove=this.updateSelectionOnMouseMove.bind(this)}onDeselect(t){return this.isEditing&&this.exitEditing(),this.selected=!1,super.onDeselect(t)}_animateCursor(t){let{toValue:e,duration:s,delay:r,onComplete:i}=t;return Pn({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:r,onComplete:i,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:n=>{this._currentCursorOpacity=n,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;(t=this._currentTickCompleteState)===null||t===void 0||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,s=t-1;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s--;for(;/\S/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findWordBoundaryRight(t){let e=0,s=t;if(this._reSpace.test(this._text[s]))for(;this._reSpace.test(this._text[s]);)e++,s++;for(;/\S/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}findLineBoundaryLeft(t){let e=0,s=t-1;for(;!/\n/.test(this._text[s])&&s>-1;)e++,s--;return t-e}findLineBoundaryRight(t){let e=0,s=t;for(;!/\n/.test(this._text[s])&&s<this._text.length;)e++,s++;return t+e}searchWordBoundary(t,e){const s=this._text;let r=t>0&&this._reSpace.test(s[t])&&(e===-1||!Lr.test(s[t-1]))?t-1:t,i=s[r];for(;r>0&&r<s.length&&!Wi.test(i);)r+=e,i=s[r];return e===-1&&Wi.test(i)&&r++,r}selectWord(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.searchWordBoundary(t,-1),r=Math.max(s,this.searchWordBoundary(t,1));this.selectionStart=s,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){var e;t=(e=t)!==null&&e!==void 0?e:this.selectionStart;const s=this.findLineBoundaryLeft(t),r=this.findLineBoundaryRight(t);this.selectionStart=s,this.selectionEnd=r,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;Lt(e).activeElement!==e&&e.focus();const s=this.getSelectionStartFromPointer(t),r=this.selectionStart,i=this.selectionEnd;(s===this.__selectionStartOnMouseDown&&r!==i||r!==s&&i!==s)&&(s>this.__selectionStartOnMouseDown?(this.selectionStart=this.__selectionStartOnMouseDown,this.selectionEnd=s):(this.selectionStart=s,this.selectionEnd=this.__selectionStartOnMouseDown),this.selectionStart===r&&this.selectionEnd===i||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()))}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,s){const r=s.slice(0,t),i=this.graphemeSplit(r).length;if(t===e)return{selectionStart:i,selectionEnd:i};const n=s.slice(t,e);return{selectionStart:i,selectionEnd:i+this.graphemeSplit(n).length}}fromGraphemeToStringSelection(t,e,s){const r=s.slice(0,t).join("").length;return t===e?{selectionStart:r,selectionEnd:r}:{selectionStart:r,selectionEnd:r+s.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},this.hiddenTextarea){if(!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),s=this.get2DCursorLocation(t),r=s.lineIndex,i=s.charIndex,n=this.getValueOfPropertyAt(r,i,"fontSize")*this.lineHeight,a=e.leftOffset,h=this.getCanvasRetinaScaling(),c=this.canvas.upperCanvasEl,l=c.width/h,u=c.height/h,d=l-n,g=u-n,f=new x(e.left+a,e.top+e.topOffset+n).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new x(c.clientWidth/l,c.clientHeight/u));return f.x<0&&(f.x=0),f.x>d&&(f.x=d),f.y<0&&(f.y=0),f.y>g&&(f.y=g),f.x+=this.canvas._offset.left,f.y+=this.canvas._offset.top,{left:"".concat(f.x,"px"),top:"".concat(f.y,"px"),fontSize:"".concat(n,"px"),charHeight:n}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}_exitEditing(){const t=this.hiddenTextarea;this.selected=!1,this.isEditing=!1,t&&(t.blur&&t.blur(),t.parentNode&&t.parentNode.removeChild(t)),this.hiddenTextarea=null,this.abortCursorAnimation(),this.selectionStart!==this.selectionEnd&&this.clearContextTop()}exitEditingImpl(){this._exitEditing(),this.selectionEnd=this.selectionStart,this._restoreEditingProps(),this._forceClearCache&&(this.initDimensions(),this.setCoords())}exitEditing(){const t=this._textBeforeEdit!==this.text;return this.exitEditingImpl(),this.fire("editing:exited"),t&&this.fire(js),this.canvas&&(this.canvas.fire("text:editing:exited",{target:this}),t&&this.canvas.fire("object:modified",{target:this})),this}_removeExtraneousStyles(){for(const t in this.styles)this._textLines[t]||delete this.styles[t]}removeStyleFromTo(t,e){const{lineIndex:s,charIndex:r}=this.get2DCursorLocation(t,!0),{lineIndex:i,charIndex:n}=this.get2DCursorLocation(e,!0);if(s!==i){if(this.styles[s])for(let a=r;a<this._unwrappedTextLines[s].length;a++)delete this.styles[s][a];if(this.styles[i])for(let a=n;a<this._unwrappedTextLines[i].length;a++){const h=this.styles[i][a];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][r+a-n]=h)}for(let a=s+1;a<=i;a++)delete this.styles[a];this.shiftLineStyles(i,s-i)}else if(this.styles[s]){const a=this.styles[s],h=n-r;for(let c=r;c<n;c++)delete a[c];for(const c in this.styles[s]){const l=parseInt(c,10);l>=n&&(a[l-h]=a[c],delete a[c])}}}shiftLineStyles(t,e){const s=Object.assign({},this.styles);for(const r in this.styles){const i=parseInt(r,10);i>t&&(this.styles[i+e]=s[i],s[i-e]||delete this.styles[i])}}insertNewlineStyleObject(t,e,s,r){const i={},n=this._unwrappedTextLines[t].length,a=n===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const c=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const d=parseInt(u,10);d>=e&&(h=!0,i[d-e]=this.styles[t][u],a&&e===0||delete this.styles[t][u])}let l=!1;for(h&&!a&&(this.styles[t+s]=i,l=!0),(l||n>e)&&s--;s>0;)r&&r[s-1]?this.styles[t+s]={0:m({},r[s-1])}:c?this.styles[t+s]={0:m({},c)}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,r){this.styles||(this.styles={});const i=this.styles[t],n=i?m({},i):{};s||(s=1);for(const h in n){const c=parseInt(h,10);c>=e&&(i[c+s]=n[c],n[c-s]||delete i[c])}if(this._forceClearCache=!0,r){for(;s--;)Object.keys(r[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]=m({},r[s]));return}if(!i)return;const a=i[e?e-1:1];for(;a&&s--;)this.styles[t][e+s]=m({},a)}insertNewStyleBlock(t,e,s){const r=this.get2DCursorLocation(e,!0),i=[0];let n,a=0;for(let h=0;h<t.length;h++)t[h]===`
56
+ `?(a++,i[a]=0):i[a]++;for(i[0]>0&&(this.insertCharStyleObject(r.lineIndex,r.charIndex,i[0],s),s=s&&s.slice(i[0]+1)),a&&this.insertNewlineStyleObject(r.lineIndex,r.charIndex+i[0],a),n=1;n<a;n++)i[n]>0?this.insertCharStyleObject(r.lineIndex+n,0,i[n],s):s&&this.styles[r.lineIndex+n]&&s[0]&&(this.styles[r.lineIndex+n][0]=s[0]),s=s&&s.slice(i[n]+1);i[n]>0&&this.insertCharStyleObject(r.lineIndex+n,0,i[n],s)}removeChars(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:t+1;this.removeStyleFromTo(t,e),this._text.splice(t,e-t),this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}insertChars(t,e,s){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:s;r>s&&this.removeStyleFromTo(s,r);const i=this.graphemeSplit(t);this.insertNewStyleBlock(i,s,e),this._text=[...this._text.slice(0,s),...i,...this._text.slice(r)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,s){s<=t?(e===t?this._selectionDirection=N:this._selectionDirection===Q&&(this._selectionDirection=N,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Q?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Q:this._selectionDirection===N&&(this._selectionDirection=Q,this.selectionStart=e),this.selectionEnd=s)}}class Kh extends qh{initHiddenTextarea(){const t=this.canvas&&Lt(this.canvas.getElement())||Pe(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off",name:"fabricTextarea"}).map(n=>{let[a,h]=n;return e.setAttribute(a,h)});const{top:s,left:r,fontSize:i}=this._calcTextareaPosition();e.style.cssText="position: absolute; top: ".concat(s,"; left: ").concat(r,"; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ").concat(i,";"),(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(n=>{let[a,h]=n;return e.addEventListener(a,this[h].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e=this.direction==="rtl"?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const e=this.fromPaste,{value:s,selectionStart:r,selectionEnd:i}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;const n=()=>{this.updateFromTextArea(),this.fire(As),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void n();const a=this._splitTextIntoLines(s).graphemeText,h=this._text.length,c=a.length,l=this.selectionStart,u=this.selectionEnd,d=l!==u;let g,f,v,_,b=c-h;const w=this.fromStringToGraphemeSelection(r,i,s),C=l>w.selectionStart;d?(f=this._text.slice(l,u),b+=u-l):c<h&&(f=C?this._text.slice(u+b,u):this._text.slice(l,l-b));const T=a.slice(w.selectionEnd-b,w.selectionEnd);if(f&&f.length&&(T.length&&(g=this.getSelectionStyles(l,l+1,!1),g=T.map(()=>g[0])),d?(v=l,_=u):C?(v=u-f.length,_=u):(v=u,_=u+f.length),this.removeStyleFromTo(v,_)),T.length){const{copyPasteData:D}=Gt();e&&T.join("")===D.copiedText&&!Y.disableStyleCopyPaste&&(g=D.copiedTextStyle),this.insertNewStyleBlock(T,l,g)}n()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:s,selectionEnd:r}=e;this.compositionStart=s,this.compositionEnd=r,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=Gt();t.copiedText=this.getSelectedText(),Y.disableStyleCopyPaste?t.copiedTextStyle=void 0:t.copiedTextStyle=this.getSelectionStyles(this.selectionStart,this.selectionEnd,!0),this._copyDone=!0}paste(){this.fromPaste=!0}_getWidthBeforeCursor(t,e){let s,r=this._getLineLeftOffset(t);return e>0&&(s=this.__charBounds[t][e-1],r+=s.left+s.width),r}getDownCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(s),i=r.lineIndex;if(i===this._textLines.length-1||t.metaKey||t.keyCode===34)return this._text.length-s;const n=r.charIndex,a=this._getWidthBeforeCursor(i,n),h=this._getIndexOnLine(i+1,a);return this._textLines[i].slice(n).length+h+1+this.missingNewlineOffset(i)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const s=this._getSelectionForOffset(t,e),r=this.get2DCursorLocation(s),i=r.lineIndex;if(i===0||t.metaKey||t.keyCode===33)return-s;const n=r.charIndex,a=this._getWidthBeforeCursor(i,n),h=this._getIndexOnLine(i-1,a),c=this._textLines[i].slice(0,n),l=this.missingNewlineOffset(i-1);return-this._textLines[i-1].length+h-c.length+(1-l)}_getIndexOnLine(t,e){const s=this._textLines[t];let r,i,n=this._getLineLeftOffset(t),a=0;for(let h=0,c=s.length;h<c;h++)if(r=this.__charBounds[t][h].width,n+=r,n>e){i=!0;const l=n-r,u=n,d=Math.abs(l-e);a=Math.abs(u-e)<d?h:h-1;break}return i||(a=s.length-1),a}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const s=this["get".concat(t,"CursorOffset")](e,this._selectionDirection===Q);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const r=this.text.length;this.selectionStart=Ee(0,this.selectionStart,r),this.selectionEnd=Ee(0,this.selectionEnd,r),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===N?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let r;if(t.altKey)r=this["findWordBoundary".concat(s)](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;r=this["findLineBoundary".concat(s)](this[e])}return r!==void 0&&this[e]!==r&&(this[e]=r,!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=N,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Q&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=N,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===N&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Q,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Q,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const Xi=o=>!!o.button;class $h extends Kh{constructor(){super(...arguments),p(this,"draggableTextDelegate",void 0)}initBehavior(){this.on("mousedown",this._mouseDownHandler),this.on("mouseup",this.mouseUpHandler),this.on("mousedblclick",this.doubleClickHandler),this.on("mousetripleclick",this.tripleClickHandler),this.draggableTextDelegate=new Uh(this),super.initBehavior()}shouldStartDragging(){return this.draggableTextDelegate.isActive()}onDragStart(t){return this.draggableTextDelegate.onDragStart(t)}canDrop(t){return this.draggableTextDelegate.canDrop(t)}doubleClickHandler(t){this.isEditing&&(this.selectWord(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}tripleClickHandler(t){this.isEditing&&(this.selectLine(this.getSelectionStartFromPointer(t.e)),this.renderCursorOrSelection())}_mouseDownHandler(t){let{e,alreadySelected:s}=t;this.canvas&&this.editable&&!Xi(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),s&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=s||this.isEditing)))}mouseUpHandler(t){let{e,transform:s}=t;const r=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const i=this.canvas._activeObject;if(i&&i!==this)return}!this.editable||this.group&&!this.group.interactive||s&&s.actionPerformed||Xi(e)||r||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),s=this.selectionStart,r=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(s,r,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(Rt(this.calcTransformMatrix())).add(new x(-this._getLeftOffset(),-this._getTopOffset()));let s=0,r=0,i=0;for(let c=0;c<this._textLines.length&&s<=e.y;c++)s+=this.getHeightOfLine(c),i=c,c>0&&(r+=this._textLines[c-1].length+this.missingNewlineOffset(c-1));let n=Math.abs(this._getLineLeftOffset(i));const a=this._textLines[i].length,h=this.__charBounds[i];for(let c=0;c<a;c++){const l=n+h[c].kernedWidth;if(e.x<=l){Math.abs(e.x-l)<=Math.abs(e.x-n)&&r++;break}n=l,r++}return Math.min(this.flipX?a-r:r,this._text.length)}}const os="moveCursorUp",as="moveCursorDown",hs="moveCursorLeft",cs="moveCursorRight",ls="exitEditing",Yi=(o,t)=>{const e=t.getRetinaScaling();o.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;o.transform(s[0],s[1],s[2],s[3],s[4],s[5])},Jh=m({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:ls,27:ls,33:os,34:as,35:cs,36:hs,37:hs,38:os,39:cs,40:as},keysMapRtl:{9:ls,27:ls,33:os,34:as,35:hs,36:cs,37:cs,38:os,39:hs,40:as},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class $t extends $h{static getDefaults(){return m(m({},super.getDefaults()),$t.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,m(m({},$t.ownDefaults),e)),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):(t==="canvas"&&(this.canvas instanceof Er&&this.canvas.textEditingManager.remove(this),e instanceof Er&&e.textEditingManager.add(this)),super._set(t,e))}setSelectionStart(t){t=Math.max(t,0),this._updateAndFire("selectionStart",t)}setSelectionEnd(t){t=Math.min(t,this.text.length),this._updateAndFire("selectionEnd",t)}_updateAndFire(t,e){this[t]!==e&&(this._fireSelectionChanged(),this[t]=e),this._updateTextarea()}_fireSelectionChanged(){this.fire("selection:changed"),this.canvas&&this.canvas.fire("text:selection:changed",{target:this})}initDimensions(){this.isEditing&&this.initDelayedCursor(),super.initDimensions()}getSelectionStyles(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart||0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionEnd,s=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,s)}setSelectionStyles(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.selectionStart||0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,s)}get2DCursorLocation(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return super.get2DCursorLocation(t,e)}render(t){super.render(t),this.cursorOffsetCache={},this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const s=super.toCanvasElement(t);return this.isEditing=e,s}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;const e=this._getCursorBoundaries(),s=this.findAncestorsWithClipPath(),r=s.length>0;let i,n=t;if(r){i=Et(t.canvas),n=i.getContext("2d"),Yi(n,this.canvas);const a=this.calcTransformMatrix();n.transform(a[0],a[1],a[2],a[3],a[4],a[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(n,e):this.renderCursor(n,e),r)for(const a of s){const h=a.clipPath,c=Et(t.canvas),l=c.getContext("2d");if(Yi(l,this.canvas),!h.absolutePositioned){const u=a.calcTransformMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5])}h.transform(l),h.drawObject(l,!0,{}),this.drawClipPathOnCache(n,h,c)}r&&(t.setTransform(1,0,0,1,0,0),t.drawImage(i,0,0)),this.canvas.contextTopDirty=!0,t.restore()}findAncestorsWithClipPath(){const t=[];let e=this;for(;e;)e.clipPath&&t.push(e),e=e.parent;return t}_getCursorBoundaries(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;const s=this._getLeftOffset(),r=this._getTopOffset(),i=this._getCursorBoundariesOffsets(t,e);return{left:s,top:r,leftOffset:i.left,topOffset:i.top}}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}__getCursorBoundariesOffsets(t){let e=0,s=0;const{charIndex:r,lineIndex:i}=this.get2DCursorLocation(t);for(let c=0;c<i;c++)e+=this.getHeightOfLine(c);const n=this._getLineLeftOffset(i),a=this.__charBounds[i][r];a&&(s=a.left),this.charSpacing!==0&&r===this._textLines[i].length&&(s-=this._getWidthOfCharSpacing());const h={top:e,left:n+(s>0?s:0)};return this.direction==="rtl"&&(this.textAlign===Q||this.textAlign===Yt||this.textAlign===He?h.left*=-1:this.textAlign===N||this.textAlign===Ws?h.left=n-(s>0?s:0):this.textAlign!==R&&this.textAlign!==ze||(h.left=n-(s>0?s:0))),h}renderCursorAt(t){this._renderCursor(this.canvas.contextTop,this._getCursorBoundaries(t,!0),t)}renderCursor(t,e){this._renderCursor(t,e,this.selectionStart)}getCursorRenderingData(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.selectionStart,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this._getCursorBoundaries(t);const s=this.get2DCursorLocation(t),r=s.lineIndex,i=s.charIndex>0?s.charIndex-1:0,n=this.getValueOfPropertyAt(r,i,"fontSize"),a=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/a,c=this.getValueOfPropertyAt(r,i,"deltaY"),l=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-n*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(r,i,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:l+e.top+c,width:h,height:n}}_renderCursor(t,e,s){const{color:r,opacity:i,left:n,top:a,width:h,height:c}=this.getCursorRenderingData(s,e);t.fillStyle=r,t.globalAlpha=i,t.fillRect(n,a,h,c)}renderSelection(t,e){const s={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,s,e)}renderDragSourceEffect(){const t=this.draggableTextDelegate.getDragStartSelection();this._renderSelection(this.canvas.contextTop,t,this._getCursorBoundaries(t.selectionStart,!0))}renderDropTargetEffect(t){const e=this.getSelectionStartFromPointer(t);this.renderCursorAt(e)}_renderSelection(t,e,s){const r=e.selectionStart,i=e.selectionEnd,n=this.textAlign.includes(Yt),a=this.get2DCursorLocation(r),h=this.get2DCursorLocation(i),c=a.lineIndex,l=h.lineIndex,u=a.charIndex<0?0:a.charIndex,d=h.charIndex<0?0:h.charIndex;for(let g=c;g<=l;g++){const f=this._getLineLeftOffset(g)||0;let v=this.getHeightOfLine(g),_=0,b=0,w=0;if(g===c&&(b=this.__charBounds[c][u].left),g>=c&&g<l)w=n&&!this.isEndOfWrapping(g)?this.width:this.getLineWidth(g)||5;else if(g===l)if(d===0)w=this.__charBounds[l][d].left;else{const I=this._getWidthOfCharSpacing();w=this.__charBounds[l][d-1].left+this.__charBounds[l][d-1].width-I}_=v,(this.lineHeight<1||g===l&&this.lineHeight>1)&&(v/=this.lineHeight);let C=s.left+f+b,T=v,D=0;const A=w-b;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",T=1,D=v):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Q||this.textAlign===Yt||this.textAlign===He?C=this.width-C-A:this.textAlign===N||this.textAlign===Ws?C=s.left+f-w:this.textAlign!==R&&this.textAlign!==ze||(C=s.left+f-w)),t.fillRect(C,s.top+s.topOffset+D,A,T),s.topOffset+=_}}getCurrentCharFontSize(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,"fontSize")}getCurrentCharColor(){const t=this._getCurrentCharIndex();return this.getValueOfPropertyAt(t.l,t.c,ot)}_getCurrentCharIndex(){const t=this.get2DCursorLocation(this.selectionStart,!0),e=t.charIndex>0?t.charIndex-1:0;return{l:t.lineIndex,c:e}}dispose(){this.exitEditingImpl(),this.draggableTextDelegate.dispose(),super.dispose()}}p($t,"ownDefaults",Jh),p($t,"type","IText"),M.setClass($t),M.setClass($t,"i-text");class Jt extends $t{static getDefaults(){return m(m({},super.getDefaults()),Jt.ownDefaults)}constructor(t,e){super(t,m(m({},Jt.ownDefaults),e))}static createControls(){return{controls:Da()}}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(Yt)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,r=0;const i={};for(let n=0;n<t.graphemeLines.length;n++)t.graphemeText[r]===`
57
+ `&&n>0?(s=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&n>0&&(s++,r++),i[n]={line:e,offset:s},r+=t.graphemeLines[n].length,s+=t.graphemeLines[n].length;return i}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[e];s&&(e=s.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e,s=0,r=t+1,i=!1;const n=this._styleMap[t],a=this._styleMap[t+1];n&&(t=n.line,s=n.offset),a&&(r=a.line,i=r===t,e=a.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const c in h)for(const l in h[c]){const u=parseInt(l,10);if(u>=s&&(!i||u<e))for(const d in h[c][l])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const r=this._styleMap[t];super._setStyleDeclaration(r.line,r.offset+e,s)}_deleteStyleDeclaration(t,e){const s=this._styleMap[t];super._deleteStyleDeclaration(s.line,s.offset+e)}_getLineStyle(t){const e=this._styleMap[t];return!!this.styles[e.line]}_setLineStyle(t){const e=this._styleMap[t];super._setLineStyle(e.line)}_wrapText(t,e){this.isWrapping=!0;const s=this.getGraphemeDataForRender(t),r=[];for(let i=0;i<s.wordsData.length;i++)r.push(...this._wrapLine(i,e,s));return this.isWrapping=!1,r}getGraphemeDataForRender(t){const e=this.splitByGrapheme,s=e?"":" ";let r=0;return{wordsData:t.map((i,n)=>{let a=0;const h=e?this.graphemeSplit(i):this.wordSplit(i);return h.length===0?[{word:[],width:0}]:h.map(c=>{const l=e?[c]:this.graphemeSplit(c),u=this._measureWord(l,n,a);return r=Math.max(u,r),a+=l.length+s.length,{word:l,width:u}})}),largestWordWidth:r}}_measureWord(t,e){let s,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=0;for(let n=0,a=t.length;n<a;n++)i+=this._getGraphemeBox(t[n],e,n+r,s,!0).kernedWidth,s=t[n];return i}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:r,wordsData:i}=s,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const a=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,c=[],l=h?"":" ";let u=0,d=[],g=0,f=0,v=!0;e-=n;const _=Math.max(e,r,this.dynamicMinWidth),b=i[t];let w;for(g=0,w=0;w<b.length;w++){const{word:C,width:T}=b[w];g+=C.length,u+=f+T-a,u>_&&!v?(c.push(d),d=[],u=T,v=!0):u+=a,v||h||d.push(l),d=d.concat(C),f=h?0:this._measureWord([l],t,g),g++,v=!1}return w&&c.push(d),r+n>this.dynamicMinWidth&&(this.dynamicMinWidth=r-a+n),c}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=super._splitTextIntoLines(t),s=this._wrapText(e.lines,this.width),r=new Array(s.length);for(let i=0;i<s.length;i++)r[i]=s[i].join("");return e.lines=r,e.graphemeLines=s,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const s=parseInt(e,10);if(this._textLines[s]){const r=this._styleMap[e].line;t.set("".concat(r),!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}p(Jt,"type","Textbox"),p(Jt,"textLayoutProperties",[...$t.textLayoutProperties,"width"]),p(Jt,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),M.setClass(Jt);class Vi extends tr{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:s}=t,{clipPath:r,group:i}=s;if(!r||!this.shouldPerformLayout(t))return;const{width:n,height:a}=Zt(Wn(s,r)),h=new x(n,a);if(r.absolutePositioned)return{center:ke(r.getRelativeCenterPoint(),void 0,i?i.calcTransformMatrix():void 0),size:h};{const c=r.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:l=new x,correction:u=new x}=this.calcBoundingBox(e,t)||{};return{center:l.add(c),correction:u.subtract(c),size:h}}return{center:s.getRelativeCenterPoint().add(c),size:h}}}}p(Vi,"type","clip-path"),M.setClass(Vi);class Hi extends tr{getInitialSize(t,e){let{target:s}=t,{size:r}=e;return new x(s.width||r.x,s.height||r.y)}}p(Hi,"type","fixed"),M.setClass(Hi);class Zh extends Je{subscribeTargets(t){const e=t.target;t.targets.reduce((s,r)=>(r.parent&&s.add(r.parent),s),new Set).forEach(s=>{s.layoutManager.subscribeTargets({target:s,targets:[e]})})}unsubscribeTargets(t){const e=t.target,s=e.getObjects();t.targets.reduce((r,i)=>(i.parent&&r.add(i.parent),r),new Set).forEach(r=>{!s.some(i=>i.parent===r)&&r.layoutManager.unsubscribeTargets({target:r,targets:[e]})})}}class fe extends pe{static getDefaults(){return m(m({},super.getDefaults()),fe.ownDefaults)}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,fe.ownDefaults),this.setOptions(e);const{left:s,top:r,layoutManager:i}=e;this.groupInit(t,{left:s,top:r,layoutManager:i??new Zh})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),s=0;s<t;s++)e[s]=arguments[s];this.multiSelectionStacking==="selection-order"?this.add(...e):e.forEach(r=>{const i=this._objects.findIndex(a=>a.isInFrontOf(r)),n=i===-1?this.size():i;this.insertAt(n,r)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(ce("error","ActiveSelection: circular object trees are not supported, this call has no effect"),!1):super.canEnterGroup(t)}enterGroup(t,e){t.parent&&t.parent===t.group?t.parent._exitGroup(t):t.group&&t.parent!==t.group&&t.group.remove(t),this._enterGroup(t,e)}exitGroup(t,e){this._exitGroup(t,e),t.parent&&t.parent._enterGroup(t,!0)}_onAfterObjectsChange(t,e){super._onAfterObjectsChange(t,e);const s=new Set;e.forEach(r=>{const{parent:i}=r;i&&s.add(i)}),t===$r?s.forEach(r=>{r._onAfterObjectsChange(Xs,e)}):s.forEach(r=>{r._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return"#<ActiveSelection: (".concat(this.complexity(),")>")}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const r=m(m({hasControls:!1},s),{},{forActiveSelection:!0});for(let i=0;i<this._objects.length;i++)this._objects[i]._renderControls(t,r);super._renderControls(t,e),t.restore()}}p(fe,"type","ActiveSelection"),p(fe,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),M.setClass(fe),M.setClass(fe,"activeSelection");class Qh{constructor(){p(this,"resources",{})}applyFilters(t,e,s,r,i){const n=i.getContext("2d");if(!n)return;n.drawImage(e,0,0,s,r);const a={sourceWidth:s,sourceHeight:r,imageData:n.getImageData(0,0,s,r),originalEl:e,originalImageData:n.getImageData(0,0,s,r),canvasEl:i,ctx:n,filterBackend:this};t.forEach(c=>{c.applyTo(a)});const{imageData:h}=a;return h.width===s&&h.height===r||(i.width=h.width,i.height=h.height),n.putImageData(h,0,0),a}}class so{constructor(){let{tileSize:t=Y.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};p(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),p(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const s=Et({width:t,height:e}),r=s.getContext("webgl",{alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1});r&&(r.clearColor(0,0,0,0),this.canvas=s,this.gl=r)}applyFilters(t,e,s,r,i,n){const a=this.gl,h=i.getContext("2d");if(!a||!h)return;let c;n&&(c=this.getCachedTexture(n,e));const l={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:s,sourceHeight:r,destinationWidth:s,destinationHeight:r,context:a,sourceTexture:this.createTexture(a,s,r,c?void 0:e),targetTexture:this.createTexture(a,s,r),originalTexture:c||this.createTexture(a,s,r,c?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:i},u=a.createFramebuffer();return a.bindFramebuffer(a.FRAMEBUFFER,u),t.forEach(d=>{d&&d.applyTo(l)}),function(d){const g=d.targetCanvas,f=g.width,v=g.height,_=d.destinationWidth,b=d.destinationHeight;f===_&&v===b||(g.width=_,g.height=b)}(l),this.copyGLTo2D(a,l),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(l.sourceTexture),a.deleteTexture(l.targetTexture),a.deleteFramebuffer(u),h.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,s,r,i){const{NEAREST:n,TEXTURE_2D:a,RGBA:h,UNSIGNED_BYTE:c,CLAMP_TO_EDGE:l,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:g,TEXTURE_WRAP_T:f}=t,v=t.createTexture();return t.bindTexture(a,v),t.texParameteri(a,u,i||n),t.texParameteri(a,d,i||n),t.texParameteri(a,g,l),t.texParameteri(a,f,l),r?t.texImage2D(a,0,h,h,c,r):t.texImage2D(a,0,h,e,s,0,h,c,null),v}getCachedTexture(t,e,s){const{textureCache:r}=this;if(r[t])return r[t];{const i=this.createTexture(this.gl,e.width,e.height,e,s);return i&&(r[t]=i),i}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const s=t.canvas,r=e.targetCanvas,i=r.getContext("2d");if(!i)return;i.translate(0,r.height),i.scale(1,-1);const n=s.height-r.height;i.drawImage(s,0,n,r.width,r.height,0,0,r.width,r.height)}copyGLTo2DPutImageData(t,e){const s=e.targetCanvas.getContext("2d"),r=e.destinationWidth,i=e.destinationHeight,n=r*i*4;if(!s)return;const a=new Uint8Array(this.imageBuffer,0,n),h=new Uint8ClampedArray(this.imageBuffer,0,n);t.readPixels(0,0,r,i,t.RGBA,t.UNSIGNED_BYTE,a);const c=new ImageData(h,r,i);s.putImageData(c,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const s=t.getExtension("WEBGL_debug_renderer_info");if(s){const r=t.getParameter(s.UNMASKED_RENDERER_WEBGL),i=t.getParameter(s.UNMASKED_VENDOR_WEBGL);r&&(e.renderer=r.toLowerCase()),i&&(e.vendor=i.toLowerCase())}return this.gpuInfo=e,e}}let pr;function tc(){const{WebGLProbe:o}=Gt();return o.queryWebGL(ee()),Y.enableGLFiltering&&o.isSupported(Y.textureSize)?new so({tileSize:Y.textureSize}):new Qh}function mr(){return!pr&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(pr=tc()),pr}const ec=["filters","resizeFilter","src","crossOrigin","type"],ro=["cropX","cropY"];class lt extends ut{static getDefaults(){return m(m({},super.getDefaults()),lt.ownDefaults)}constructor(t,e){super(),p(this,"_lastScaleX",1),p(this,"_lastScaleY",1),p(this,"_filterScalingX",1),p(this,"_filterScalingY",1),this.filters=[],Object.assign(this,lt.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(le()),this.setElement(typeof t=="string"?(this.canvas&&Lt(this.canvas.getElement())||Pe()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){var e;let s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._element=t,this._originalElement=t,this._setWidthHeight(s),(e=t.classList)===null||e===void 0||e.add(lt.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=mr(!1);e instanceof so&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture("".concat(this.cacheKey,"_filtered")),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{const e=this[t];e&&Gt().dispose(e),this[t]=void 0})}getCrossOrigin(){return this._originalElement&&(this._originalElement.crossOrigin||null)}getOriginalSize(){const t=this.getElement();return t?{width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}:{width:0,height:0}}_stroke(t){if(!this.stroke||this.strokeWidth===0)return;const e=this.width/2,s=this.height/2;t.beginPath(),t.moveTo(-e,-s),t.lineTo(e,-s),t.lineTo(e,s),t.lineTo(-e,s),t.lineTo(-e,-s),t.closePath()}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=[];return this.filters.forEach(s=>{s&&e.push(s.toObject())}),m(m({},super.toObject([...ro,...t])),{},{src:this.getSrc(),crossOrigin:this.getCrossOrigin(),filters:e},this.resizeFilter?{resizeFilter:this.resizeFilter.toObject()}:{})}hasCrop(){return!!this.cropX||!!this.cropY||this.width<this._element.width||this.height<this._element.height}_toSVG(){const t=[],e=this._element,s=-this.width/2,r=-this.height/2;let i=[],n=[],a="",h="";if(!e)return[];if(this.hasCrop()){const c=le();i.push('<clipPath id="imageCrop_'+c+`">
58
58
  `,' <rect x="'+s+'" y="'+r+'" width="'+this.width+'" height="'+this.height+`" />
59
59
  `,`</clipPath>
60
60
  `),a=' clip-path="url(#imageCrop_'+c+')" '}if(this.imageSmoothing||(h=' image-rendering="optimizeSpeed"'),t.push(" <image ","COMMON_PARTS",'xlink:href="'.concat(this.getSvgSrc(!0),'" x="').concat(s-this.cropX,'" y="').concat(r-this.cropY,'" width="').concat(e.width||e.naturalWidth,'" height="').concat(e.height||e.naturalHeight,'"').concat(h).concat(a,`></image>
61
61
  `)),this.stroke||this.strokeDashArray){const c=this.fill;this.fill=null,n=[' <rect x="'.concat(s,'" y="').concat(r,'" width="').concat(this.width,'" height="').concat(this.height,'" style="').concat(this.getSvgStyles(),`" />
62
- `)],this.fill=c}return i=this.paintFirst!==ot?i.concat(n,t):i.concat(t,n),i}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Ms(t,{crossOrigin:e,signal:s}).then(r=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(r)})}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),r=s.x,i=s.y,n=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&i>e)return this._element=n,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=i);const a=Et(n),{width:h,height:c}=n;this._element=a,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=i,mr().applyFilters([t],n,h,c,this._element),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter(i=>i&&!i.isNeutralState()),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){const i=Et({width:s,height:r});this._element=i,this._filteredEl=i}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,s,r),this._lastScaleX=1,this._lastScaleY=1);mr().applyFilters(t,this._originalElement,s,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,r=this._filterScalingY,i=this.width,n=this.height,a=Math.max(this.cropX,0),h=Math.max(this.cropY,0),c=e.naturalWidth||e.width,l=e.naturalHeight||e.height,u=a*s,d=h*r,g=Math.min(i*s,c-u),f=Math.min(n*r,l-d),v=-i/2,_=-n/2,b=Math.min(i,c/s-a),w=Math.min(n,l/r-h);e&&t.drawImage(e,u,d,g,f,v,_,b,w)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=Ho(this.preserveAspectRatio||""),e=this.width,s=this.height,r={width:e,height:s};let i,n=this._element.width,a=this._element.height,h=1,c=1,l=0,u=0,d=0,g=0;return!t||t.alignX===vt&&t.alignY===vt?(h=e/n,c=s/a):(t.meetOrSlice==="meet"&&(h=c=nh(this._element,r),i=(e-n*h)/2,t.alignX==="Min"&&(l=-i),t.alignX==="Max"&&(l=i),i=(s-a*c)/2,t.alignY==="Min"&&(u=-i),t.alignY==="Max"&&(u=i)),t.meetOrSlice==="slice"&&(h=c=oh(this._element,r),i=n-e/h,t.alignX==="Mid"&&(d=i/2),t.alignX==="Max"&&(d=i),i=a-s/c,t.alignY==="Mid"&&(g=i/2),t.alignY==="Max"&&(g=i),n=e/h,a=s/c)),{width:n,height:a,scaleX:h,scaleY:c,offsetLeft:l,offsetTop:u,cropX:d,cropY:g}}static fromObject(t,e){let{filters:s,resizeFilter:r,src:i,crossOrigin:n,type:a}=t,h=$(t,Zh);return Promise.all([Ms(i,m(m({},e),{},{crossOrigin:n})),s&&Ue(s,e),r&&Ue([r],e),$s(h,e)]).then(c=>{let[l,u=[],[d]=[],g={}]=c;return new this(l,m(m({},h),{},{src:i,filters:u,resizeFilter:d},g))})}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return Ms(t,{crossOrigin:e,signal:s}).then(i=>new this(i,r))}static async fromElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;const r=ie(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(r["xlink:href"]||r.href,e,r).catch(i=>(ce("log","Unable to parse Image",i),null))}}p(lt,"type","Image"),p(lt,"cacheProperties",[...re,...so]),p(lt,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),p(lt,"CSS_CANVAS","canvas-img"),p(lt,"ATTRIBUTE_NAMES",[...ue,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),M.setClass(lt),M.setSVGClass(lt);Zs(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);const sr=o=>o.webgl!==void 0,Jr="precision highp float",Qh=`
62
+ `)],this.fill=c}return i=this.paintFirst!==ot?i.concat(n,t):i.concat(t,n),i}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Ms(t,{crossOrigin:e,signal:s}).then(r=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(r)})}toString(){return'#<Image: { src: "'.concat(this.getSrc(),'" }>')}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),r=s.x,i=s.y,n=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&i>e)return this._element=n,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=i);const a=Et(n),{width:h,height:c}=n;this._element=a,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=i,mr().applyFilters([t],n,h,c,this._element),this._filterScalingX=a.width/this._originalElement.width,this._filterScalingY=a.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.filters||[];if(t=t.filter(i=>i&&!i.isNeutralState()),this.set("dirty",!0),this.removeTexture("".concat(this.cacheKey,"_filtered")),t.length===0)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,s=e.naturalWidth||e.width,r=e.naturalHeight||e.height;if(this._element===this._originalElement){const i=Et({width:s,height:r});this._element=i,this._filteredEl=i}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,s,r),this._lastScaleX=1,this._lastScaleY=1);mr().applyFilters(t,this._originalElement,s,r,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,this.isMoving!==!0&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const s=this._filterScalingX,r=this._filterScalingY,i=this.width,n=this.height,a=Math.max(this.cropX,0),h=Math.max(this.cropY,0),c=e.naturalWidth||e.width,l=e.naturalHeight||e.height,u=a*s,d=h*r,g=Math.min(i*s,c-u),f=Math.min(n*r,l-d),v=-i/2,_=-n/2,b=Math.min(i,c/s-a),w=Math.min(n,l/r-h);e&&t.drawImage(e,u,d,g,f,v,_,b,w)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=No(this.preserveAspectRatio||""),e=this.width,s=this.height,r={width:e,height:s};let i,n=this._element.width,a=this._element.height,h=1,c=1,l=0,u=0,d=0,g=0;return!t||t.alignX===vt&&t.alignY===vt?(h=e/n,c=s/a):(t.meetOrSlice==="meet"&&(h=c=hh(this._element,r),i=(e-n*h)/2,t.alignX==="Min"&&(l=-i),t.alignX==="Max"&&(l=i),i=(s-a*c)/2,t.alignY==="Min"&&(u=-i),t.alignY==="Max"&&(u=i)),t.meetOrSlice==="slice"&&(h=c=ch(this._element,r),i=n-e/h,t.alignX==="Mid"&&(d=i/2),t.alignX==="Max"&&(d=i),i=a-s/c,t.alignY==="Mid"&&(g=i/2),t.alignY==="Max"&&(g=i),n=e/h,a=s/c)),{width:n,height:a,scaleX:h,scaleY:c,offsetLeft:l,offsetTop:u,cropX:d,cropY:g}}static fromObject(t,e){let{filters:s,resizeFilter:r,src:i,crossOrigin:n,type:a}=t,h=$(t,ec);return Promise.all([Ms(i,m(m({},e),{},{crossOrigin:n})),s&&Ue(s,e),r&&Ue([r],e),$s(h,e)]).then(c=>{let[l,u=[],[d]=[],g={}]=c;return new this(l,m(m({},h),{},{src:i,filters:u,resizeFilter:d},g))})}static fromURL(t){let{crossOrigin:e=null,signal:s}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0;return Ms(t,{crossOrigin:e,signal:s}).then(i=>new this(i,r))}static async fromElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;const r=ie(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(r["xlink:href"]||r.href,e,r).catch(i=>(ce("log","Unable to parse Image",i),null))}}p(lt,"type","Image"),p(lt,"cacheProperties",[...re,...ro]),p(lt,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),p(lt,"CSS_CANVAS","canvas-img"),p(lt,"ATTRIBUTE_NAMES",[...ue,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),M.setClass(lt),M.setSVGClass(lt);Zs(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);const sr=o=>o.webgl!==void 0,Jr="precision highp float",sc=`
63
63
  `.concat(Jr,`;
64
64
  varying vec2 vTexCoord;
65
65
  uniform sampler2D uTexture;
66
66
  void main() {
67
67
  gl_FragColor = texture2D(uTexture, vTexCoord);
68
- }`),tc=["type"],ec=["type"],sc=new RegExp(Jr,"g");class at{get type(){return this.constructor.type}constructor(){let t=$(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},tc);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Qh}getVertexSource(){return`
68
+ }`),rc=["type"],ic=["type"],nc=new RegExp(Jr,"g");class at{get type(){return this.constructor.type}constructor(){let t=$(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},rc);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return sc}getVertexSource(){return`
69
69
  attribute vec2 aPosition;
70
70
  varying vec2 vTexCoord;
71
71
  void main() {
72
72
  vTexCoord = aPosition;
73
73
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
74
- }`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:r="highp"}}=Gt();r!=="highp"&&(e=e.replace(sc,Jr.replace("highp",r)));const i=t.createShader(t.VERTEX_SHADER),n=t.createShader(t.FRAGMENT_SHADER),a=t.createProgram();if(!i||!n||!a)throw new Ht("Vertex, fragment shader or program creation error");if(t.shaderSource(i,s),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Ht("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(i)));if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Ht("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.attachShader(a,i),t.attachShader(a,n),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS))throw new Ht('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(a)));const h=this.getUniformLocations(t,a)||{};return h.uStepW=t.getUniformLocation(a,"uStepW"),h.uStepH=t.getUniformLocation(a,"uStepH"),{program:a,attributeLocations:this.getAttributeLocations(t,a),uniformLocations:h}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const s=this.constructor.uniformLocations,r={};for(let i=0;i<s.length;i++)r[s[i]]=t.getUniformLocation(e,s[i]);return r}sendAttributeData(t,e,s){const r=e.aPosition,i=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,i),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const s=t.destinationWidth,r=t.destinationHeight;t.sourceWidth===s&&t.sourceHeight===r||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,s,r)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){sr(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){const e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){const e=t.context,s=this.retrieveShader(t);t.pass===0&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(s.program),this.sendAttributeData(e,s.attributeLocations,t.aPosition),e.uniform1f(s.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(s.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,s.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,s){t.activeTexture(s),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const{sourceWidth:e,sourceHeight:s}=t,r=Et({width:e,height:s});t.helpLayer=r}}toObject(){const t=Object.keys(this.constructor.defaults||{});return m({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this($(t,ec))}}p(at,"type","BaseFilter"),p(at,"uniformLocations",[]);const rc={multiply:`gl_FragColor.rgb *= uColor.rgb;
74
+ }`}createProgram(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.getFragmentSource(),s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:r="highp"}}=Gt();r!=="highp"&&(e=e.replace(nc,Jr.replace("highp",r)));const i=t.createShader(t.VERTEX_SHADER),n=t.createShader(t.FRAGMENT_SHADER),a=t.createProgram();if(!i||!n||!a)throw new Ht("Vertex, fragment shader or program creation error");if(t.shaderSource(i,s),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Ht("Vertex shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(i)));if(t.shaderSource(n,e),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new Ht("Fragment shader compile error for ".concat(this.type,": ").concat(t.getShaderInfoLog(n)));if(t.attachShader(a,i),t.attachShader(a,n),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS))throw new Ht('Shader link error for "'.concat(this.type,'" ').concat(t.getProgramInfoLog(a)));const h=this.getUniformLocations(t,a)||{};return h.uStepW=t.getUniformLocation(a,"uStepW"),h.uStepH=t.getUniformLocation(a,"uStepH"),{program:a,attributeLocations:this.getAttributeLocations(t,a),uniformLocations:h}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const s=this.constructor.uniformLocations,r={};for(let i=0;i<s.length;i++)r[s[i]]=t.getUniformLocation(e,s[i]);return r}sendAttributeData(t,e,s){const r=e.aPosition,i=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,i),t.enableVertexAttribArray(r),t.vertexAttribPointer(r,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,s,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const s=t.destinationWidth,r=t.destinationHeight;t.sourceWidth===s&&t.sourceHeight===r||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,s,r)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){sr(t)?(this._setupFrameBuffer(t),this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){}getCacheKey(){return this.type}retrieveShader(t){const e=this.getCacheKey();return t.programCache[e]||(t.programCache[e]=this.createProgram(t.context)),t.programCache[e]}applyToWebGL(t){const e=t.context,s=this.retrieveShader(t);t.pass===0&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(s.program),this.sendAttributeData(e,s.attributeLocations,t.aPosition),e.uniform1f(s.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(s.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,s.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,s){t.activeTexture(s),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const{sourceWidth:e,sourceHeight:s}=t,r=Et({width:e,height:s});t.helpLayer=r}}toObject(){const t=Object.keys(this.constructor.defaults||{});return m({type:this.type},t.reduce((e,s)=>(e[s]=this[s],e),{}))}toJSON(){return this.toObject()}static async fromObject(t,e){return new this($(t,ic))}}p(at,"type","BaseFilter"),p(at,"uniformLocations",[]);const oc={multiply:`gl_FragColor.rgb *= uColor.rgb;
75
75
  `,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
76
76
  `,add:`gl_FragColor.rgb += uColor.rgb;
77
77
  `,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
@@ -107,10 +107,10 @@ Resulting to default behavior: removing object from previous canvas and adding t
107
107
  vec4 color = texture2D(uTexture, vTexCoord);
108
108
  gl_FragColor = color;
109
109
  if (color.a > 0.0) {
110
- `.concat(rc[this.mode],`
110
+ `.concat(oc[this.mode],`
111
111
  }
112
112
  }
113
- `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new G(this.color).getSource(),r=this.alpha,i=s[0]*r,n=s[1]*r,a=s[2]*r,h=1-r;for(let c=0;c<e.length;c+=4){const l=e[c],u=e[c+1],d=e[c+2];let g,f,v;switch(this.mode){case"multiply":g=l*i/255,f=u*n/255,v=d*a/255;break;case"screen":g=255-(255-l)*(255-i)/255,f=255-(255-u)*(255-n)/255,v=255-(255-d)*(255-a)/255;break;case"add":g=l+i,f=u+n,v=d+a;break;case"difference":g=Math.abs(l-i),f=Math.abs(u-n),v=Math.abs(d-a);break;case"subtract":g=l-i,f=u-n,v=d-a;break;case"darken":g=Math.min(l,i),f=Math.min(u,n),v=Math.min(d,a);break;case"lighten":g=Math.max(l,i),f=Math.max(u,n),v=Math.max(d,a);break;case"overlay":g=i<128?2*l*i/255:255-2*(255-l)*(255-i)/255,f=n<128?2*u*n/255:255-2*(255-u)*(255-n)/255,v=a<128?2*d*a/255:255-2*(255-d)*(255-a)/255;break;case"exclusion":g=i+l-2*i*l/255,f=n+u-2*n*u/255,v=a+d-2*a*d/255;break;case"tint":g=i+l*h,f=n+u*h,v=a+d*h}e[c]=g,e[c+1]=f,e[c+2]=v}}sendUniformData(t,e){const s=new G(this.color).getSource();s[0]=this.alpha*s[0]/255,s[1]=this.alpha*s[1]/255,s[2]=this.alpha*s[2]/255,s[3]=this.alpha,t.uniform4fv(e.uColor,s)}}p(us,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),p(us,"type","BlendColor"),p(us,"uniformLocations",["uColor"]),M.setClass(us);const ic={multiply:`
113
+ `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new G(this.color).getSource(),r=this.alpha,i=s[0]*r,n=s[1]*r,a=s[2]*r,h=1-r;for(let c=0;c<e.length;c+=4){const l=e[c],u=e[c+1],d=e[c+2];let g,f,v;switch(this.mode){case"multiply":g=l*i/255,f=u*n/255,v=d*a/255;break;case"screen":g=255-(255-l)*(255-i)/255,f=255-(255-u)*(255-n)/255,v=255-(255-d)*(255-a)/255;break;case"add":g=l+i,f=u+n,v=d+a;break;case"difference":g=Math.abs(l-i),f=Math.abs(u-n),v=Math.abs(d-a);break;case"subtract":g=l-i,f=u-n,v=d-a;break;case"darken":g=Math.min(l,i),f=Math.min(u,n),v=Math.min(d,a);break;case"lighten":g=Math.max(l,i),f=Math.max(u,n),v=Math.max(d,a);break;case"overlay":g=i<128?2*l*i/255:255-2*(255-l)*(255-i)/255,f=n<128?2*u*n/255:255-2*(255-u)*(255-n)/255,v=a<128?2*d*a/255:255-2*(255-d)*(255-a)/255;break;case"exclusion":g=i+l-2*i*l/255,f=n+u-2*n*u/255,v=a+d-2*a*d/255;break;case"tint":g=i+l*h,f=n+u*h,v=a+d*h}e[c]=g,e[c+1]=f,e[c+2]=v}}sendUniformData(t,e){const s=new G(this.color).getSource();s[0]=this.alpha*s[0]/255,s[1]=this.alpha*s[1]/255,s[2]=this.alpha*s[2]/255,s[3]=this.alpha,t.uniform4fv(e.uColor,s)}}p(us,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),p(us,"type","BlendColor"),p(us,"uniformLocations",["uColor"]),M.setClass(us);const ac={multiply:`
114
114
  precision highp float;
115
115
  uniform sampler2D uTexture;
116
116
  uniform sampler2D uImage;
@@ -136,7 +136,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
136
136
  color.a = color2.a;
137
137
  gl_FragColor = color;
138
138
  }
139
- `},nc=["type","image"];class ds extends at{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return ic[this.mode]}getVertexSource(){return`
139
+ `},hc=["type","image"];class ds extends at{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return ac[this.mode]}getVertexSource(){return`
140
140
  attribute vec2 aPosition;
141
141
  varying vec2 vTexCoord;
142
142
  varying vec2 vTexCoord2;
@@ -146,7 +146,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
146
146
  vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
147
147
  gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
148
148
  }
149
- `}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:r},filterBackend:{resources:i}}=t;const n=this.image;i.blendImage||(i.blendImage=ee());const a=i.blendImage,h=a.getContext("2d");a.width!==s||a.height!==r?(a.width=s,a.height=r):h.clearRect(0,0,s,r),h.setTransform(n.scaleX,0,0,n.scaleY,n.left,n.top),h.drawImage(n.getElement(),0,0,s,r);const c=h.getImageData(0,0,s,r).data;for(let l=0;l<e.length;l+=4){const u=e[l],d=e[l+1],g=e[l+2],f=e[l+3],v=c[l],_=c[l+1],b=c[l+2],w=c[l+3];switch(this.mode){case"multiply":e[l]=u*v/255,e[l+1]=d*_/255,e[l+2]=g*b/255,e[l+3]=f*w/255;break;case"mask":e[l+3]=w}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return m(m({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:r}=t,i=$(t,nc);return lt.fromObject(r,e).then(n=>new this(m(m({},i),{},{image:n})))}}p(ds,"type","BlendImage"),p(ds,"defaults",{mode:"multiply",alpha:1}),p(ds,"uniformLocations",["uTransformMatrix","uImage"]),M.setClass(ds);class gs extends at{getFragmentSource(){return`
149
+ `}applyToWebGL(t){const e=t.context,s=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,s,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:s}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/s,1]}applyTo2d(t){let{imageData:{data:e,width:s,height:r},filterBackend:{resources:i}}=t;const n=this.image;i.blendImage||(i.blendImage=ee());const a=i.blendImage,h=a.getContext("2d");a.width!==s||a.height!==r?(a.width=s,a.height=r):h.clearRect(0,0,s,r),h.setTransform(n.scaleX,0,0,n.scaleY,n.left,n.top),h.drawImage(n.getElement(),0,0,s,r);const c=h.getImageData(0,0,s,r).data;for(let l=0;l<e.length;l+=4){const u=e[l],d=e[l+1],g=e[l+2],f=e[l+3],v=c[l],_=c[l+1],b=c[l+2],w=c[l+3];switch(this.mode){case"multiply":e[l]=u*v/255,e[l+1]=d*_/255,e[l+2]=g*b/255,e[l+3]=f*w/255;break;case"mask":e[l+3]=w}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return m(m({},super.toObject()),{},{image:this.image&&this.image.toObject()})}static async fromObject(t,e){let{type:s,image:r}=t,i=$(t,hc);return lt.fromObject(r,e).then(n=>new this(m(m({},i),{},{image:n})))}}p(ds,"type","BlendImage"),p(ds,"defaults",{mode:"multiply",alpha:1}),p(ds,"uniformLocations",["uTransformMatrix","uImage"]),M.setClass(ds);class gs extends at{getFragmentSource(){return`
150
150
  precision highp float;
151
151
  uniform sampler2D uTexture;
152
152
  uniform vec2 uDelta;
@@ -185,7 +185,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
185
185
  color.rgb += uBrightness;
186
186
  gl_FragColor = color;
187
187
  }
188
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.round(255*this.brightness);for(let r=0;r<e.length;r+=4)e[r]+=s,e[r+1]+=s,e[r+2]+=s}isNeutralState(){return this.brightness===0}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}p(fs,"type","Brightness"),p(fs,"defaults",{brightness:0}),p(fs,"uniformLocations",["uBrightness"]),M.setClass(fs);const ro={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Oe extends at{getFragmentSource(){return`
188
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.round(255*this.brightness);for(let r=0;r<e.length;r+=4)e[r]+=s,e[r+1]+=s,e[r+2]+=s}isNeutralState(){return this.brightness===0}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}p(fs,"type","Brightness"),p(fs,"defaults",{brightness:0}),p(fs,"uniformLocations",["uBrightness"]),M.setClass(fs);const io={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Oe extends at{getFragmentSource(){return`
189
189
  precision highp float;
190
190
  uniform sampler2D uTexture;
191
191
  varying vec2 vTexCoord;
@@ -196,7 +196,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
196
196
  color *= uColorMatrix;
197
197
  color += uConstants;
198
198
  gl_FragColor = color;
199
- }`}applyTo2d(t){const e=t.imageData.data,s=this.matrix,r=this.colorsOnly;for(let i=0;i<e.length;i+=4){const n=e[i],a=e[i+1],h=e[i+2];if(e[i]=n*s[0]+a*s[1]+h*s[2]+255*s[4],e[i+1]=n*s[5]+a*s[6]+h*s[7]+255*s[9],e[i+2]=n*s[10]+a*s[11]+h*s[12]+255*s[14],!r){const c=e[i+3];e[i]+=c*s[3],e[i+1]+=c*s[8],e[i+2]+=c*s[13],e[i+3]=n*s[15]+a*s[16]+h*s[17]+c*s[18]+255*s[19]}}}sendUniformData(t,e){const s=this.matrix,r=[s[0],s[1],s[2],s[3],s[5],s[6],s[7],s[8],s[10],s[11],s[12],s[13],s[15],s[16],s[17],s[18]],i=[s[4],s[9],s[14],s[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,r),t.uniform4fv(e.uConstants,i)}toObject(){return m(m({},super.toObject()),{},{matrix:[...this.matrix]})}}function ve(o,t){var e;const s=(p(e=class extends Oe{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",o),p(e,"defaults",{colorsOnly:!1,matrix:t}),e);return M.setClass(s,o),s}p(Oe,"type","ColorMatrix"),p(Oe,"defaults",ro),p(Oe,"uniformLocations",["uColorMatrix","uConstants"]),M.setClass(Oe);ve("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]);ve("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]);ve("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]);ve("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]);ve("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]);ve("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]);ve("BlackWhite",[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]);class zi extends at{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){sr(t)&&(t.passes+=this.subFilters.length-1),this.subFilters.forEach(e=>{e.applyTo(t)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(t=>t.toObject())}}isNeutralState(){return!this.subFilters.some(t=>!t.isNeutralState())}static fromObject(t,e){return Promise.all((t.subFilters||[]).map(s=>M.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}p(zi,"type","Composed"),M.setClass(zi);class ps extends at{getFragmentSource(){return`
199
+ }`}applyTo2d(t){const e=t.imageData.data,s=this.matrix,r=this.colorsOnly;for(let i=0;i<e.length;i+=4){const n=e[i],a=e[i+1],h=e[i+2];if(e[i]=n*s[0]+a*s[1]+h*s[2]+255*s[4],e[i+1]=n*s[5]+a*s[6]+h*s[7]+255*s[9],e[i+2]=n*s[10]+a*s[11]+h*s[12]+255*s[14],!r){const c=e[i+3];e[i]+=c*s[3],e[i+1]+=c*s[8],e[i+2]+=c*s[13],e[i+3]=n*s[15]+a*s[16]+h*s[17]+c*s[18]+255*s[19]}}}sendUniformData(t,e){const s=this.matrix,r=[s[0],s[1],s[2],s[3],s[5],s[6],s[7],s[8],s[10],s[11],s[12],s[13],s[15],s[16],s[17],s[18]],i=[s[4],s[9],s[14],s[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,r),t.uniform4fv(e.uConstants,i)}toObject(){return m(m({},super.toObject()),{},{matrix:[...this.matrix]})}}function ve(o,t){var e;const s=(p(e=class extends Oe{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",o),p(e,"defaults",{colorsOnly:!1,matrix:t}),e);return M.setClass(s,o),s}p(Oe,"type","ColorMatrix"),p(Oe,"defaults",io),p(Oe,"uniformLocations",["uColorMatrix","uConstants"]),M.setClass(Oe);ve("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]);ve("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]);ve("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]);ve("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]);ve("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]);ve("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]);ve("BlackWhite",[1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,1.5,1.5,1.5,0,-1,0,0,0,1,0]);class zi extends at{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){sr(t)&&(t.passes+=this.subFilters.length-1),this.subFilters.forEach(e=>{e.applyTo(t)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(t=>t.toObject())}}isNeutralState(){return!this.subFilters.some(t=>!t.isNeutralState())}static fromObject(t,e){return Promise.all((t.subFilters||[]).map(s=>M.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}p(zi,"type","Composed"),M.setClass(zi);class ps extends at{getFragmentSource(){return`
200
200
  precision highp float;
201
201
  uniform sampler2D uTexture;
202
202
  uniform float uContrast;
@@ -206,7 +206,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
206
206
  float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
207
207
  color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
208
208
  gl_FragColor = color;
209
- }`}isNeutralState(){return this.contrast===0}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.floor(255*this.contrast),r=259*(s+255)/(255*(259-s));for(let i=0;i<e.length;i+=4)e[i]=r*(e[i]-128)+128,e[i+1]=r*(e[i+1]-128)+128,e[i+2]=r*(e[i+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}p(ps,"type","Contrast"),p(ps,"defaults",{contrast:0}),p(ps,"uniformLocations",["uContrast"]),M.setClass(ps);const oc={Convolute_3_1:`
209
+ }`}isNeutralState(){return this.contrast===0}applyTo2d(t){let{imageData:{data:e}}=t;const s=Math.floor(255*this.contrast),r=259*(s+255)/(255*(259-s));for(let i=0;i<e.length;i+=4)e[i]=r*(e[i]-128)+128,e[i+1]=r*(e[i+1]-128)+128,e[i+2]=r*(e[i+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}p(ps,"type","Contrast"),p(ps,"defaults",{contrast:0}),p(ps,"uniformLocations",["uContrast"]),M.setClass(ps);const cc={Convolute_3_1:`
210
210
  precision highp float;
211
211
  uniform sampler2D uTexture;
212
212
  uniform float uMatrix[9];
@@ -350,7 +350,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
350
350
  gl_FragColor = color;
351
351
  gl_FragColor.a = alpha;
352
352
  }
353
- `};class ms extends at{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return oc[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,s=e.data,r=this.matrix,i=Math.round(Math.sqrt(r.length)),n=Math.floor(i/2),a=e.width,h=e.height,c=t.ctx.createImageData(a,h),l=c.data,u=this.opaque?1:0;let d,g,f,v,_,b,w,C,T,D,A,I,E;for(A=0;A<h;A++)for(D=0;D<a;D++){for(_=4*(A*a+D),d=0,g=0,f=0,v=0,E=0;E<i;E++)for(I=0;I<i;I++)w=A+E-n,b=D+I-n,w<0||w>=h||b<0||b>=a||(C=4*(w*a+b),T=r[E*i+I],d+=s[C]*T,g+=s[C+1]*T,f+=s[C+2]*T,u||(v+=s[C+3]*T));l[_]=d,l[_+1]=g,l[_+2]=f,l[_+3]=u?s[_+3]:v}t.imageData=c}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return m(m({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}p(ms,"type","Convolute"),p(ms,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),p(ms,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),M.setClass(ms);const io="Gamma";class vs extends at{getFragmentSource(){return`
353
+ `};class ms extends at{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return cc[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,s=e.data,r=this.matrix,i=Math.round(Math.sqrt(r.length)),n=Math.floor(i/2),a=e.width,h=e.height,c=t.ctx.createImageData(a,h),l=c.data,u=this.opaque?1:0;let d,g,f,v,_,b,w,C,T,D,A,I,E;for(A=0;A<h;A++)for(D=0;D<a;D++){for(_=4*(A*a+D),d=0,g=0,f=0,v=0,E=0;E<i;E++)for(I=0;I<i;I++)w=A+E-n,b=D+I-n,w<0||w>=h||b<0||b>=a||(C=4*(w*a+b),T=r[E*i+I],d+=s[C]*T,g+=s[C+1]*T,f+=s[C+2]*T,u||(v+=s[C+3]*T));l[_]=d,l[_+1]=g,l[_+2]=f,l[_+3]=u?s[_+3]:v}t.imageData=c}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return m(m({},super.toObject()),{},{opaque:this.opaque,matrix:[...this.matrix]})}}p(ms,"type","Convolute"),p(ms,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),p(ms,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),M.setClass(ms);const no="Gamma";class vs extends at{getFragmentSource(){return`
354
354
  precision highp float;
355
355
  uniform sampler2D uTexture;
356
356
  uniform vec3 uGamma;
@@ -364,7 +364,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
364
364
  gl_FragColor = color;
365
365
  gl_FragColor.rgb *= color.a;
366
366
  }
367
- `}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.gamma,r=1/s[0],i=1/s[1],n=1/s[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const a=this.rgbValues;for(let h=0;h<256;h++)a.r[h]=255*Math.pow(h/255,r),a.g[h]=255*Math.pow(h/255,i),a.b[h]=255*Math.pow(h/255,n);for(let h=0;h<e.length;h+=4)e[h]=a.r[e[h]],e[h+1]=a.g[e[h+1]],e[h+2]=a.b[e[h+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return t[0]===1&&t[1]===1&&t[2]===1}toObject(){return{type:io,gamma:this.gamma.concat()}}}p(vs,"type",io),p(vs,"defaults",{gamma:[1,1,1]}),p(vs,"uniformLocations",["uGamma"]),M.setClass(vs);const ac={average:`
367
+ `}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.gamma,r=1/s[0],i=1/s[1],n=1/s[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const a=this.rgbValues;for(let h=0;h<256;h++)a.r[h]=255*Math.pow(h/255,r),a.g[h]=255*Math.pow(h/255,i),a.b[h]=255*Math.pow(h/255,n);for(let h=0;h<e.length;h+=4)e[h]=a.r[e[h]],e[h+1]=a.g[e[h+1]],e[h+2]=a.b[e[h+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return t[0]===1&&t[1]===1&&t[2]===1}toObject(){return{type:no,gamma:this.gamma.concat()}}}p(vs,"type",no),p(vs,"defaults",{gamma:[1,1,1]}),p(vs,"uniformLocations",["uGamma"]),M.setClass(vs);const lc={average:`
368
368
  precision highp float;
369
369
  uniform sampler2D uTexture;
370
370
  varying vec2 vTexCoord;
@@ -393,7 +393,7 @@ Resulting to default behavior: removing object from previous canvas and adding t
393
393
  float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
394
394
  gl_FragColor = vec4(average, average, average, col.a);
395
395
  }
396
- `};class ys extends at{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,r=0;r<e.length;r+=4){const i=e[r],n=e[r+1],a=e[r+2];switch(this.mode){case"average":s=(i+n+a)/3;break;case"lightness":s=(Math.min(i,n,a)+Math.max(i,n,a))/2;break;case"luminosity":s=.21*i+.72*n+.07*a}e[r+2]=e[r+1]=e[r]=s}}getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return ac[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}p(ys,"type","Grayscale"),p(ys,"defaults",{mode:"average"}),p(ys,"uniformLocations",["uMode"]),M.setClass(ys);const hc=m(m({},ro),{},{rotation:0});class vr extends Oe{calculateMatrix(){const t=this.rotation*Math.PI,e=Qt(t),s=te(t),r=1/3,i=Math.sqrt(r)*s,n=1-e;this.matrix=[e+n/3,r*n-i,r*n+i,0,0,r*n+i,e+r*n,r*n-i,0,0,r*n-i,r*n+i,e+r*n,0,0,0,0,0,1,0]}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}p(vr,"type","HueRotation"),p(vr,"defaults",hc),M.setClass(vr);class xs extends at{applyTo2d(t){let{imageData:{data:e}}=t;for(let s=0;s<e.length;s+=4)e[s]=255-e[s],e[s+1]=255-e[s+1],e[s+2]=255-e[s+2],this.alpha&&(e[s+3]=255-e[s+3])}getFragmentSource(){return`
396
+ `};class ys extends at{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,r=0;r<e.length;r+=4){const i=e[r],n=e[r+1],a=e[r+2];switch(this.mode){case"average":s=(i+n+a)/3;break;case"lightness":s=(Math.min(i,n,a)+Math.max(i,n,a))/2;break;case"luminosity":s=.21*i+.72*n+.07*a}e[r+2]=e[r+1]=e[r]=s}}getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return lc[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}p(ys,"type","Grayscale"),p(ys,"defaults",{mode:"average"}),p(ys,"uniformLocations",["uMode"]),M.setClass(ys);const uc=m(m({},io),{},{rotation:0});class vr extends Oe{calculateMatrix(){const t=this.rotation*Math.PI,e=Qt(t),s=te(t),r=1/3,i=Math.sqrt(r)*s,n=1-e;this.matrix=[e+n/3,r*n-i,r*n+i,0,0,r*n+i,e+r*n,r*n-i,0,0,r*n-i,r*n+i,e+r*n,0,0,0,0,0,1,0]}isNeutralState(){return this.rotation===0}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}p(vr,"type","HueRotation"),p(vr,"defaults",uc),M.setClass(vr);class xs extends at{applyTo2d(t){let{imageData:{data:e}}=t;for(let s=0;s<e.length;s+=4)e[s]=255-e[s],e[s+1]=255-e[s+1],e[s+2]=255-e[s+2],this.alpha&&(e[s+3]=255-e[s+3])}getFragmentSource(){return`
397
397
  precision highp float;
398
398
  uniform sampler2D uTexture;
399
399
  uniform int uInvert;
@@ -501,11 +501,11 @@ void main() {
501
501
  color.b += max != color.b ? (max - color.b) * amt : 0.00;
502
502
  gl_FragColor = color;
503
503
  }
504
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let r=0;r<e.length;r+=4){const i=e[r],n=e[r+1],a=e[r+2],h=Math.max(i,n,a),c=(i+n+a)/3,l=2*Math.abs(h-c)/255*s;e[r]+=h!==i?(h-i)*l:0,e[r+1]+=h!==n?(h-n)*l:0,e[r+2]+=h!==a?(h-a)*l:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}p(Ts,"type","Vibrance"),p(Ts,"defaults",{vibrance:0}),p(Ts,"uniformLocations",["uVibrance"]),M.setClass(Ts);function cc(o,t){if(o.match(/^[a-z]+:\/\//i))return o;if(o.match(/^\/\//))return window.location.protocol+o;if(o.match(/^[a-z]+:/i))return o;const e=document.implementation.createHTMLDocument(),s=e.createElement("base"),r=e.createElement("a");return e.head.appendChild(s),e.body.appendChild(r),t&&(s.href=t),r.href=o,r.href}const lc=(()=>{let o=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(o+=1,`u${t()}${o}`)})();function he(o){const t=[];for(let e=0,s=o.length;e<s;e++)t.push(o[e]);return t}let be=null;function no(o={}){return be||(o.includeStyleProperties?(be=o.includeStyleProperties,be):(be=he(window.getComputedStyle(document.documentElement)),be))}function zs(o,t){const s=(o.ownerDocument.defaultView||window).getComputedStyle(o).getPropertyValue(t);return s?parseFloat(s.replace("px","")):0}function uc(o){const t=zs(o,"border-left-width"),e=zs(o,"border-right-width");return o.clientWidth+t+e}function dc(o){const t=zs(o,"border-top-width"),e=zs(o,"border-bottom-width");return o.clientHeight+t+e}function oo(o,t={}){const e=t.width||uc(o),s=t.height||dc(o);return{width:e,height:s}}function gc(){let o,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(o=parseInt(e,10),Number.isNaN(o)&&(o=1)),o||window.devicePixelRatio||1}const Ct=16384;function fc(o){(o.width>Ct||o.height>Ct)&&(o.width>Ct&&o.height>Ct?o.width>o.height?(o.height*=Ct/o.width,o.width=Ct):(o.width*=Ct/o.height,o.height=Ct):o.width>Ct?(o.height*=Ct/o.width,o.width=Ct):(o.width*=Ct/o.height,o.height=Ct))}function Gs(o){return new Promise((t,e)=>{const s=new Image;s.onload=()=>{s.decode().then(()=>{requestAnimationFrame(()=>t(s))})},s.onerror=e,s.crossOrigin="anonymous",s.decoding="async",s.src=o})}async function pc(o){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(o)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function mc(o,t,e){const s="http://www.w3.org/2000/svg",r=document.createElementNS(s,"svg"),i=document.createElementNS(s,"foreignObject");return r.setAttribute("width",`${t}`),r.setAttribute("height",`${e}`),r.setAttribute("viewBox",`0 0 ${t} ${e}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),r.appendChild(i),i.appendChild(o),pc(r)}const xt=(o,t)=>{if(o instanceof t)return!0;const e=Object.getPrototypeOf(o);return e===null?!1:e.constructor.name===t.name||xt(e,t)};function vc(o){const t=o.getPropertyValue("content");return`${o.cssText} content: '${t.replace(/'|"/g,"")}';`}function yc(o,t){return no(t).map(e=>{const s=o.getPropertyValue(e),r=o.getPropertyPriority(e);return`${e}: ${s}${r?" !important":""};`}).join(" ")}function xc(o,t,e,s){const r=`.${o}:${t}`,i=e.cssText?vc(e):yc(e,s);return document.createTextNode(`${r}{${i}}`)}function Gi(o,t,e,s){const r=window.getComputedStyle(o,e),i=r.getPropertyValue("content");if(i===""||i==="none")return;const n=lc();try{t.className=`${t.className} ${n}`}catch{return}const a=document.createElement("style");a.appendChild(xc(n,e,r,s)),t.appendChild(a)}function _c(o,t,e){Gi(o,t,":before",e),Gi(o,t,":after",e)}const Ni="application/font-woff",Ui="image/jpeg",bc={woff:Ni,woff2:Ni,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Ui,jpeg:Ui,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function wc(o){const t=/\.([^./]*?)$/g.exec(o);return t?t[1]:""}function Zr(o){const t=wc(o).toLowerCase();return bc[t]||""}function Sc(o){return o.split(/,/)[1]}function Ar(o){return o.search(/^(data:)/)!==-1}function Cc(o,t){return`data:${t};base64,${o}`}async function ao(o,t,e){const s=await fetch(o,t);if(s.status===404)throw new Error(`Resource "${s.url}" not found`);const r=await s.blob();return new Promise((i,n)=>{const a=new FileReader;a.onerror=n,a.onloadend=()=>{try{i(e({res:s,result:a.result}))}catch(h){n(h)}},a.readAsDataURL(r)})}const yr={};function Tc(o,t,e){let s=o.replace(/\?.*/,"");return e&&(s=o),/ttf|otf|eot|woff2?/i.test(s)&&(s=s.replace(/.*\//,"")),t?`[${t}]${s}`:s}async function Qr(o,t,e){const s=Tc(o,t,e.includeQueryParams);if(yr[s]!=null)return yr[s];e.cacheBust&&(o+=(/\?/.test(o)?"&":"?")+new Date().getTime());let r;try{const i=await ao(o,e.fetchRequestInit,({res:n,result:a})=>(t||(t=n.headers.get("Content-Type")||""),Sc(a)));r=Cc(i,t)}catch(i){r=e.imagePlaceholder||"";let n=`Failed to fetch resource: ${o}`;i&&(n=typeof i=="string"?i:i.message),n&&console.warn(n)}return yr[s]=r,r}async function Oc(o){const t=o.toDataURL();return t==="data:,"?o.cloneNode(!1):Gs(t)}async function kc(o,t){if(o.currentSrc){const i=document.createElement("canvas"),n=i.getContext("2d");i.width=o.clientWidth,i.height=o.clientHeight,n==null||n.drawImage(o,0,0,i.width,i.height);const a=i.toDataURL();return Gs(a)}const e=o.poster,s=Zr(e),r=await Qr(e,s,t);return Gs(r)}async function Dc(o,t){var e;try{if(!((e=o==null?void 0:o.contentDocument)===null||e===void 0)&&e.body)return await rr(o.contentDocument.body,t,!0)}catch{}return o.cloneNode(!1)}async function Mc(o,t){return xt(o,HTMLCanvasElement)?Oc(o):xt(o,HTMLVideoElement)?kc(o,t):xt(o,HTMLIFrameElement)?Dc(o,t):o.cloneNode(ho(o))}const Ec=o=>o.tagName!=null&&o.tagName.toUpperCase()==="SLOT",ho=o=>o.tagName!=null&&o.tagName.toUpperCase()==="SVG";async function Pc(o,t,e){var s,r;if(ho(t))return t;let i=[];return Ec(o)&&o.assignedNodes?i=he(o.assignedNodes()):xt(o,HTMLIFrameElement)&&(!((s=o.contentDocument)===null||s===void 0)&&s.body)?i=he(o.contentDocument.body.childNodes):i=he(((r=o.shadowRoot)!==null&&r!==void 0?r:o).childNodes),i.length===0||xt(o,HTMLVideoElement)||await i.reduce((n,a)=>n.then(()=>rr(a,e)).then(h=>{h&&t.appendChild(h)}),Promise.resolve()),t}function Ac(o,t,e){const s=t.style;if(!s)return;const r=window.getComputedStyle(o);r.cssText?(s.cssText=r.cssText,s.transformOrigin=r.transformOrigin):no(e).forEach(i=>{let n=r.getPropertyValue(i);i==="font-size"&&n.endsWith("px")&&(n=`${Math.floor(parseFloat(n.substring(0,n.length-2)))-.1}px`),xt(o,HTMLIFrameElement)&&i==="display"&&n==="inline"&&(n="block"),i==="d"&&t.getAttribute("d")&&(n=`path(${t.getAttribute("d")})`),s.setProperty(i,n,r.getPropertyPriority(i))})}function jc(o,t){xt(o,HTMLTextAreaElement)&&(t.innerHTML=o.value),xt(o,HTMLInputElement)&&t.setAttribute("value",o.value)}function Fc(o,t){if(xt(o,HTMLSelectElement)){const e=t,s=Array.from(e.children).find(r=>o.value===r.getAttribute("value"));s&&s.setAttribute("selected","")}}function Lc(o,t,e){return xt(t,Element)&&(Ac(o,t,e),_c(o,t,e),jc(o,t),Fc(o,t)),t}async function Rc(o,t){const e=o.querySelectorAll?o.querySelectorAll("use"):[];if(e.length===0)return o;const s={};for(let i=0;i<e.length;i++){const a=e[i].getAttribute("xlink:href");if(a){const h=o.querySelector(a),c=document.querySelector(a);!h&&c&&!s[a]&&(s[a]=await rr(c,t,!0))}}const r=Object.values(s);if(r.length){const i="http://www.w3.org/1999/xhtml",n=document.createElementNS(i,"svg");n.setAttribute("xmlns",i),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const a=document.createElementNS(i,"defs");n.appendChild(a);for(let h=0;h<r.length;h++)a.appendChild(r[h]);o.appendChild(n)}return o}async function rr(o,t,e){return!e&&t.filter&&!t.filter(o)?null:Promise.resolve(o).then(s=>Mc(s,t)).then(s=>Pc(o,s,t)).then(s=>Lc(o,s,t)).then(s=>Rc(s,t))}const co=/url\((['"]?)([^'"]+?)\1\)/g,Bc=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Ic=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Wc(o){const t=o.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Xc(o){const t=[];return o.replace(co,(e,s,r)=>(t.push(r),e)),t.filter(e=>!Ar(e))}async function Yc(o,t,e,s,r){try{const i=e?cc(t,e):t,n=Zr(t);let a;return r||(a=await Qr(i,n,s)),o.replace(Wc(t),`$1${a}$3`)}catch{}return o}function Vc(o,{preferredFontFormat:t}){return t?o.replace(Ic,e=>{for(;;){const[s,,r]=Bc.exec(e)||[];if(!r)return"";if(r===t)return`src: ${s};`}}):o}function lo(o){return o.search(co)!==-1}async function uo(o,t,e){if(!lo(o))return o;const s=Vc(o,e);return Xc(s).reduce((i,n)=>i.then(a=>Yc(a,n,t,e)),Promise.resolve(s))}async function we(o,t,e){var s;const r=(s=t.style)===null||s===void 0?void 0:s.getPropertyValue(o);if(r){const i=await uo(r,null,e);return t.style.setProperty(o,i,t.style.getPropertyPriority(o)),!0}return!1}async function Hc(o,t){await we("background",o,t)||await we("background-image",o,t),await we("mask",o,t)||await we("-webkit-mask",o,t)||await we("mask-image",o,t)||await we("-webkit-mask-image",o,t)}async function zc(o,t){const e=xt(o,HTMLImageElement);if(!(e&&!Ar(o.src))&&!(xt(o,SVGImageElement)&&!Ar(o.href.baseVal)))return;const s=e?o.src:o.href.baseVal,r=await Qr(s,Zr(s),t);await new Promise((i,n)=>{o.onload=i,o.onerror=t.onImageErrorHandler?(...h)=>{try{i(t.onImageErrorHandler(...h))}catch(c){n(c)}}:n;const a=o;a.decode&&(a.decode=i),a.loading==="lazy"&&(a.loading="eager"),e?(o.srcset="",o.src=r):o.href.baseVal=r})}async function Gc(o,t){const s=he(o.childNodes).map(r=>go(r,t));await Promise.all(s).then(()=>o)}async function go(o,t){xt(o,Element)&&(await Hc(o,t),await zc(o,t),await Gc(o,t))}function Nc(o,t){const{style:e}=o;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const s=t.style;return s!=null&&Object.keys(s).forEach(r=>{e[r]=s[r]}),o}const qi={};async function Ki(o){let t=qi[o];if(t!=null)return t;const s=await(await fetch(o)).text();return t={url:o,cssText:s},qi[o]=t,t}async function $i(o,t){let e=o.cssText;const s=/url\(["']?([^"')]+)["']?\)/g,i=(e.match(/url\([^)]+\)/g)||[]).map(async n=>{let a=n.replace(s,"$1");return a.startsWith("https://")||(a=new URL(a,o.url).href),ao(a,t.fetchRequestInit,({result:h})=>(e=e.replace(n,`url(${h})`),[n,h]))});return Promise.all(i).then(()=>e)}function Ji(o){if(o==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let s=o.replace(e,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const h=r.exec(s);if(h===null)break;t.push(h[0])}s=s.replace(r,"");const i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,n="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(n,"gi");for(;;){let h=i.exec(s);if(h===null){if(h=a.exec(s),h===null)break;i.lastIndex=a.lastIndex}else a.lastIndex=i.lastIndex;t.push(h[0])}return t}async function Uc(o,t){const e=[],s=[];return o.forEach(r=>{if("cssRules"in r)try{he(r.cssRules||[]).forEach((i,n)=>{if(i.type===CSSRule.IMPORT_RULE){let a=n+1;const h=i.href,c=Ki(h).then(l=>$i(l,t)).then(l=>Ji(l).forEach(u=>{try{r.insertRule(u,u.startsWith("@import")?a+=1:r.cssRules.length)}catch(d){console.error("Error inserting rule from remote css",{rule:u,error:d})}})).catch(l=>{console.error("Error loading remote css",l.toString())});s.push(c)}})}catch(i){const n=o.find(a=>a.href==null)||document.styleSheets[0];r.href!=null&&s.push(Ki(r.href).then(a=>$i(a,t)).then(a=>Ji(a).forEach(h=>{n.insertRule(h,n.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",i)}}),Promise.all(s).then(()=>(o.forEach(r=>{if("cssRules"in r)try{he(r.cssRules||[]).forEach(i=>{e.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${r.href}`,i)}}),e))}function qc(o){return o.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>lo(t.style.getPropertyValue("src")))}async function Kc(o,t){if(o.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=he(o.ownerDocument.styleSheets),s=await Uc(e,t);return qc(s)}function fo(o){return o.trim().replace(/["']/g,"")}function $c(o){const t=new Set;function e(s){(s.style.fontFamily||getComputedStyle(s).fontFamily).split(",").forEach(i=>{t.add(fo(i))}),Array.from(s.children).forEach(i=>{i instanceof HTMLElement&&e(i)})}return e(o),t}async function Jc(o,t){const e=await Kc(o,t),s=$c(o);return(await Promise.all(e.filter(i=>s.has(fo(i.style.fontFamily))).map(i=>{const n=i.parentStyleSheet?i.parentStyleSheet.href:null;return uo(i.cssText,n,t)}))).join(`
505
- `)}async function Zc(o,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await Jc(o,t);if(e){const s=document.createElement("style"),r=document.createTextNode(e);s.appendChild(r),o.firstChild?o.insertBefore(s,o.firstChild):o.appendChild(s)}}async function Qc(o,t={}){const{width:e,height:s}=oo(o,t),r=await rr(o,t,!0);return await Zc(r,t),await go(r,t),Nc(r,t),await mc(r,e,s)}async function tl(o,t={}){const{width:e,height:s}=oo(o,t),r=await Qc(o,t),i=await Gs(r),n=document.createElement("canvas"),a=n.getContext("2d"),h=t.pixelRatio||gc(),c=t.canvasWidth||e,l=t.canvasHeight||s;return n.width=c*h,n.height=l*h,t.skipAutoScale||fc(n),n.style.width=`${c}`,n.style.height=`${l}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,n.width,n.height)),a.drawImage(i,0,0,n.width,n.height),n}async function el(o,t={}){return(await tl(o,t)).toDataURL()}async function Zi(o,t,e){const s=document.createElement("div");s.style.cssText="position:fixed;left:0;top:0;z-index:999999;pointer-events:none;visibility:visible;",s.innerHTML=o,document.body.appendChild(s);try{const r=s.offsetWidth||100,i=s.offsetHeight||40,n=t?t/r:1,a=e?e/i:1,h=Math.max(n,a,1);return{dataUrl:await el(s,{skipFonts:!0,width:r,height:i,pixelRatio:h}),width:t??r,height:e??i}}finally{s.remove()}}function sl({onSubmit:o,backgroundImage:t,armedComponent:e,onComponentPlaced:s}){const r=F.useRef(null),i=F.useRef(null),n=F.useRef(null),[a,h]=F.useState("freehand"),[c,l]=F.useState("#3B82F6"),[u,d]=F.useState("#000000"),[g,f]=F.useState([]),[v,_]=F.useState([]),b=F.useRef(null),w=F.useRef(!1),C=F.useRef(!1),T=F.useRef([]),D=F.useRef(0),[A,I]=F.useState(null),[E,W]=F.useState(null),[q,Z]=F.useState(null);F.useEffect(()=>{if(!r.current||i.current)return;const y=new Er(r.current,{backgroundColor:"#ffffff",selection:!0});i.current=y;const S=()=>{if(!n.current)return;const{width:O,height:j}=n.current.getBoundingClientRect();y.setDimensions({width:O,height:j})};S();const k=new ResizeObserver(S);return n.current&&k.observe(n.current),window.addEventListener("resize",S),f([JSON.stringify(y.toJSON())]),()=>{k.disconnect(),window.removeEventListener("resize",S),y.dispose(),i.current=null}},[]),F.useEffect(()=>{const y=i.current;if(!y)return;const S=async k=>{const O=k.target,j=O==null?void 0:O._componentMeta;if(!(j!=null&&j.ghostHtml)||O.type!=="image")return;const H=Math.round((O.width??0)*(O.scaleX??1)),B=Math.round((O.height??0)*(O.scaleY??1));if(!(H<4||B<4))try{const{dataUrl:ht,width:Pt,height:rt}=await Zi(j.ghostHtml,H,B),z=await lt.fromURL(ht);z.set({left:O.left,top:O.top,scaleX:H/(z.width??Pt),scaleY:B/(z.height??rt)}),z._componentMeta=j;const wt=y.getObjects().indexOf(O);y.remove(O),y.insertAt(wt,z),y.setActiveObject(z),y.requestRenderAll()}catch{}};return y.on("object:modified",S),()=>{y.off("object:modified",S)}},[]),F.useEffect(()=>{if(!t)return;const y=i.current;y&&lt.fromURL(t).then(S=>{!S.width||!S.height||(C.current=!0,S.set({selectable:!1,evented:!1,hasBorders:!1,hasControls:!1}),y.backgroundImage=S,y.requestRenderAll())})},[t]),F.useEffect(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();S.length!==0&&(S.forEach(k=>{"fill"in k&&k.fill!==""&&k.fill!==null&&k.set("fill",c)}),y.requestRenderAll())},[c]),F.useEffect(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();S.length!==0&&(S.forEach(k=>{"stroke"in k&&k.set("stroke",u)}),y.requestRenderAll())},[u]);const L=F.useCallback(()=>{const y=i.current;if(!y)return;const S=JSON.stringify(y.toJSON());f(k=>[...k,S]),_([])},[]);F.useEffect(()=>{const y=i.current;if(y){if(y.isDrawingMode=!1,y.selection=!0,y.defaultCursor="default",y.setCursor("default"),y.getObjects().forEach(S=>{S.evented=!0,S.selectable=!0,S.hasControls=!0,S.hasBorders=!0,S.setCoords()}),y.requestRenderAll(),y.off("mouse:down"),y.off("mouse:move"),y.off("mouse:up"),a==="freehand"){y.isDrawingMode=!0;const S=new Hs(y);S.color=u,S.width=2,y.freeDrawingBrush=S,y.on("path:created",k=>{L();const O=k.path;O&&(y.setActiveObject(O),y.requestRenderAll()),h("select")})}else if(a==="eraser"){y.selection=!1;const S='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="%23555" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4 9.5-9.5 5.5 5.5L7 21Z"/><path d="M22 21H7"/><path d="m11.5 12.5 5.5 5.5"/></svg>';y.defaultCursor=`url("data:image/svg+xml,${S}") 4 18, auto`,y.on("mouse:down",k=>{const O=y.findTarget(k.e);O&&(y.remove(O),L())})}else if(a!=="select"){if(a==="text")y.selection=!1,y.defaultCursor="text",y.on("mouse:down",S=>{if(w.current)return;const k=y.getScenePoint(S.e),O=new Jt("Text",{left:k.x,top:k.y,fontSize:16,fill:u,width:120});y.add(O),y.setActiveObject(O),O.enterEditing(),O.selectAll(),L(),y.defaultCursor="default",y.setCursor("default"),h("select"),O.once("editing:exited",()=>{y.defaultCursor="default",y.setCursor("default")})});else if(["rectangle","circle","line","arrow"].includes(a)){y.selection=!1,y.defaultCursor="crosshair",y.getObjects().forEach(k=>{k.evented=!1,k.selectable=!1});let S=null;y.on("mouse:down",k=>{y.getObjects().forEach(j=>{j.evented=!1,j.selectable=!1}),w.current=!0;const O=y.getScenePoint(k.e);b.current={x:O.x,y:O.y},a==="rectangle"?(S=new kt({left:O.x,top:O.y,width:0,height:0,fill:c==="transparent"?"transparent":c,stroke:u,strokeWidth:2,selectable:!1}),y.add(S)):a==="circle"?(S=new Xt({left:O.x,top:O.y,radius:0,fill:c==="transparent"?"transparent":c,stroke:u,strokeWidth:2,selectable:!1}),y.add(S)):(a==="line"||a==="arrow")&&(S=new Vt([O.x,O.y,O.x,O.y],{stroke:u,strokeWidth:2,selectable:!1}),y.add(S))}),y.on("mouse:move",k=>{if(!b.current||!S)return;const O=y.getScenePoint(k.e),j=b.current;if(a==="rectangle"){const H=Math.min(j.x,O.x),B=Math.min(j.y,O.y);S.set({left:H,top:B,width:Math.abs(O.x-j.x),height:Math.abs(O.y-j.y)})}else if(a==="circle"){const H=Math.abs(O.x-j.x)/2,B=Math.abs(O.y-j.y)/2;S.set({left:Math.min(j.x,O.x),top:Math.min(j.y,O.y),radius:Math.max(H,B)})}else(a==="line"||a==="arrow")&&S.set({x2:O.x,y2:O.y});y.requestRenderAll()}),y.on("mouse:up",()=>{if(S){if(a==="arrow"&&b.current){const k=S.x1,O=S.y1,j=S.x2,H=S.y2,B=Math.atan2(H-O,j-k),ht=12,Pt=new Vt([j-ht*Math.cos(B-Math.PI/6),H-ht*Math.sin(B-Math.PI/6),j,H],{stroke:u,strokeWidth:2,selectable:!1}),rt=new Vt([j-ht*Math.cos(B+Math.PI/6),H-ht*Math.sin(B+Math.PI/6),j,H],{stroke:u,strokeWidth:2,selectable:!1});y.add(Pt,rt)}L(),S.set({evented:!0,selectable:!0,hasControls:!0,hasBorders:!0}),S.setCoords(),y.setActiveObject(S),y.requestRenderAll(),h("select")}S=null,b.current=null,w.current=!1})}}}},[a,c,u,L]);const V=F.useCallback(()=>{const y=i.current;if(!y||g.length<=1)return;const S=g[g.length-1],k=g[g.length-2];_(O=>[...O,S]),f(O=>O.slice(0,-1)),y.loadFromJSON(JSON.parse(k)).then(()=>y.requestRenderAll())},[g]),X=F.useCallback(()=>{const y=i.current;if(!y||v.length===0)return;const S=v[v.length-1];_(k=>k.slice(0,-1)),f(k=>[...k,S]),y.loadFromJSON(JSON.parse(S)).then(()=>y.requestRenderAll())},[v]),nt=F.useCallback(()=>{const y=i.current;y&&(y.clear(),t?lt.fromURL(t).then(S=>{!S.width||!S.height||(S.set({selectable:!1,evented:!1,hasBorders:!1,hasControls:!1}),y.backgroundImage=S,y.requestRenderAll())}):(y.backgroundColor="#ffffff",y.requestRenderAll()),L())},[L,t]),et=F.useCallback(()=>{const y=i.current;if(!y)return;const S=y.getObjects();let k;if(S.length>0&&!C.current){let z=1/0,wt=1/0,Wt=-1/0,Tt=-1/0;for(const mo of S){const ye=mo.getBoundingRect();z=Math.min(z,ye.left),wt=Math.min(wt,ye.top),Wt=Math.max(Wt,ye.left+ye.width),Tt=Math.max(Tt,ye.top+ye.height)}const ir=y.getWidth(),po=y.getHeight(),ti=Math.max(0,Math.floor(z-10)),ei=Math.max(0,Math.floor(wt-10)),si=Math.min(ir-ti,Math.ceil(Wt-z+10*2)),ri=Math.min(po-ei,Math.ceil(Tt-wt+10*2));si>0&&ri>0&&(k={left:ti,top:ei,width:si,height:ri})}const O=y.toDataURL({format:"png",multiplier:1,...k}),j=(k==null?void 0:k.width)??y.getWidth(),H=(k==null?void 0:k.height)??y.getHeight(),B=[],ht=(k==null?void 0:k.left)??0,Pt=(k==null?void 0:k.top)??0;for(const rt of S){const z=rt._componentMeta;z&&B.push({componentName:z.componentName,componentPath:z.componentPath,storyId:z.storyId,args:z.args,x:Math.round((rt.left??0)-ht),y:Math.round((rt.top??0)-Pt),width:Math.round((rt.width??0)*(rt.scaleX??1)),height:Math.round((rt.height??0)*(rt.scaleY??1))})}o(O,j,H,B.length>0?B:void 0)},[o]),st=F.useCallback(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();if(S.length>0){for(const k of S)y.remove(k);y.discardActiveObject(),y.requestRenderAll(),L()}},[L]),U=F.useCallback(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();S.length!==0&&Promise.all(S.map(k=>k.clone())).then(k=>{T.current=k,D.current=0})},[]),bt=F.useCallback(()=>{const y=i.current;if(!y||T.current.length===0)return;const S=20;D.current+=S;const k=D.current;Promise.all(T.current.map(O=>O.clone())).then(O=>{if(y.discardActiveObject(),O.forEach(j=>{j.set({left:(j.left??0)+k,top:(j.top??0)+k,evented:!0,selectable:!0}),j.setCoords(),y.add(j)}),O.length===1)y.setActiveObject(O[0]);else{const j=new y.constructor.ActiveSelection(O,{canvas:y});y.setActiveObject(j)}y.requestRenderAll(),L()})},[L]);return F.useEffect(()=>{const y=S=>{if(S.key==="Delete"||S.key==="Backspace"){const k=i.current;if(k){const O=k.getActiveObject();if(O&&O.type==="textbox"&&O.isEditing)return}st()}if((S.metaKey||S.ctrlKey)&&S.key==="z"&&(S.preventDefault(),S.shiftKey?X():V()),(S.metaKey||S.ctrlKey)&&S.key==="c"){const k=i.current;if(k){const O=k.getActiveObject();if(O&&O.type==="textbox"&&O.isEditing)return}U()}if((S.metaKey||S.ctrlKey)&&S.key==="v"){const k=i.current;if(k){const O=k.getActiveObject();if(O&&O.type==="textbox"&&O.isEditing)return}S.preventDefault(),bt()}};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[st,V,X,U,bt]),F.useEffect(()=>{if(!(e!=null&&e.ghostHtml)){Z(null),W(null);return}const y=document.createElement("div");y.style.cssText="position:fixed;left:-99999px;top:-99999px;visibility:hidden;pointer-events:none;",y.innerHTML=e.ghostHtml,document.body.appendChild(y),Z({width:y.offsetWidth||100,height:y.offsetHeight||40}),document.body.removeChild(y)},[e]),F.useEffect(()=>{const y=n.current;if(!y||!e){W(null);return}const S=H=>{const B=y.getBoundingClientRect();W({x:H.clientX-B.left,y:H.clientY-B.top})},k=()=>W(null),O=H=>{const B=y.getBoundingClientRect();W({x:H.clientX-B.left,y:H.clientY-B.top})},j=async H=>{H.preventDefault(),H.stopPropagation();const B=i.current;if(!B||!e.ghostHtml)return;const ht=y.getBoundingClientRect(),Pt=H.clientX-ht.left,rt=H.clientY-ht.top;try{const{dataUrl:z,width:wt,height:Wt}=await Zi(e.ghostHtml),Tt=await lt.fromURL(z);Tt.set({left:Pt-wt/2,top:rt-Wt/2,scaleX:1,scaleY:1}),Tt._componentMeta={componentName:e.componentName,componentPath:e.componentPath,storyId:e.storyId,args:e.args,ghostHtml:e.ghostHtml},B.add(Tt),B.setActiveObject(Tt),B.requestRenderAll(),L(),h("select")}catch(z){console.error("[DesignCanvas] Failed to rasterize component:",z);const wt=(q==null?void 0:q.width)??100,Wt=(q==null?void 0:q.height)??40,Tt=new kt({left:Pt-wt/2,top:rt-Wt/2,width:wt,height:Wt,fill:"rgba(0, 132, 139, 0.08)",stroke:"#00848B",strokeWidth:2,strokeDashArray:[4,4]});Tt._componentMeta={componentName:e.componentName,componentPath:e.componentPath,storyId:e.storyId,args:e.args,ghostHtml:e.ghostHtml};const ir=new Jt(e.componentName,{left:Pt-wt/2+4,top:rt-Wt/2+(Wt-14)/2,fontSize:12,fill:"#00848B",width:wt-8,selectable:!1,evented:!1});B.add(Tt,ir),B.setActiveObject(Tt),B.requestRenderAll(),L(),h("select")}s==null||s()};return y.addEventListener("mousemove",S),y.addEventListener("mouseleave",k),y.addEventListener("mouseenter",O),y.addEventListener("click",j,{capture:!0}),()=>{y.removeEventListener("mousemove",S),y.removeEventListener("mouseleave",k),y.removeEventListener("mouseenter",O),y.removeEventListener("click",j,{capture:!0})}},[e,q,L,s]),{canvasElRef:r,containerRef:n,lockedHeight:A,activeTool:a,setActiveTool:h,fillColor:c,setFillColor:l,strokeColor:u,setStrokeColor:d,canUndo:g.length>1,canRedo:v.length>0,handleUndo:V,handleRedo:X,handleClear:nt,handleSubmit:et,ghostPos:E,ghostSize:q}}const Qi=["#000000","#ffffff","#9CA3AF","#EF4444","#F97316","#EAB308","#22C55E","#3B82F6","#8B5CF6","#EC4899","#14B8A6","#6366F1"],rl=()=>P.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P.jsx("path",{d:"M5 3l14 8-6 2-4 6z"}),P.jsx("path",{d:"M13 13l6 6"})]}),il=()=>P.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P.jsx("path",{d:"m7 21-4-4 9.5-9.5 5.5 5.5L7 21Z"}),P.jsx("path",{d:"M22 21H7"}),P.jsx("path",{d:"m11.5 12.5 5.5 5.5"})]}),nl=()=>P.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P.jsx("polyline",{points:"3 6 5 6 21 6"}),P.jsx("path",{d:"M19 6l-1 14H6L5 6"}),P.jsx("path",{d:"M10 11v6M14 11v6"}),P.jsx("path",{d:"M9 6V4h6v2"})]}),ol=[{id:"select",label:"Select",icon:P.jsx(rl,{})},{id:"freehand",label:"Freehand",icon:"✎"},{id:"rectangle",label:"Rectangle",icon:"□"},{id:"circle",label:"Circle",icon:"○"},{id:"line",label:"Line",icon:"╱"},{id:"arrow",label:"Arrow",icon:"→"},{id:"text",label:"Text",icon:"T"},{id:"eraser",label:"Eraser",icon:P.jsx(il,{})}];function al({activeTool:o,onToolChange:t,fillColor:e,onFillChange:s,strokeColor:r,onStrokeChange:i,canUndo:n,canRedo:a,onUndo:h,onRedo:c,onClear:l,onSubmit:u,onClose:d}){const[g,f]=F.useState(!1),[v,_]=F.useState(!1),b=F.useRef(null),w=F.useRef(null);return F.useEffect(()=>{const C=T=>{g&&b.current&&!b.current.contains(T.target)&&f(!1),v&&w.current&&!w.current.contains(T.target)&&_(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[g,v]),P.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-1 bg-bv-bg border-b border-bv-border text-[10px] shrink-0 flex-wrap",children:[ol.map(C=>P.jsx("button",{title:C.label,onClick:()=>t(C.id),className:`w-7 h-[26px] rounded border flex items-center justify-center text-[13px] cursor-pointer transition-all
504
+ `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.vibrance;for(let r=0;r<e.length;r+=4){const i=e[r],n=e[r+1],a=e[r+2],h=Math.max(i,n,a),c=(i+n+a)/3,l=2*Math.abs(h-c)/255*s;e[r]+=h!==i?(h-i)*l:0,e[r+1]+=h!==n?(h-n)*l:0,e[r+2]+=h!==a?(h-a)*l:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}p(Ts,"type","Vibrance"),p(Ts,"defaults",{vibrance:0}),p(Ts,"uniformLocations",["uVibrance"]),M.setClass(Ts);function dc(o,t){if(o.match(/^[a-z]+:\/\//i))return o;if(o.match(/^\/\//))return window.location.protocol+o;if(o.match(/^[a-z]+:/i))return o;const e=document.implementation.createHTMLDocument(),s=e.createElement("base"),r=e.createElement("a");return e.head.appendChild(s),e.body.appendChild(r),t&&(s.href=t),r.href=o,r.href}const gc=(()=>{let o=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(o+=1,`u${t()}${o}`)})();function he(o){const t=[];for(let e=0,s=o.length;e<s;e++)t.push(o[e]);return t}let be=null;function oo(o={}){return be||(o.includeStyleProperties?(be=o.includeStyleProperties,be):(be=he(window.getComputedStyle(document.documentElement)),be))}function zs(o,t){const s=(o.ownerDocument.defaultView||window).getComputedStyle(o).getPropertyValue(t);return s?parseFloat(s.replace("px","")):0}function fc(o){const t=zs(o,"border-left-width"),e=zs(o,"border-right-width");return o.clientWidth+t+e}function pc(o){const t=zs(o,"border-top-width"),e=zs(o,"border-bottom-width");return o.clientHeight+t+e}function ao(o,t={}){const e=t.width||fc(o),s=t.height||pc(o);return{width:e,height:s}}function mc(){let o,t;try{t=process}catch{}const e=t&&t.env?t.env.devicePixelRatio:null;return e&&(o=parseInt(e,10),Number.isNaN(o)&&(o=1)),o||window.devicePixelRatio||1}const Ct=16384;function vc(o){(o.width>Ct||o.height>Ct)&&(o.width>Ct&&o.height>Ct?o.width>o.height?(o.height*=Ct/o.width,o.width=Ct):(o.width*=Ct/o.height,o.height=Ct):o.width>Ct?(o.height*=Ct/o.width,o.width=Ct):(o.width*=Ct/o.height,o.height=Ct))}function Gs(o){return new Promise((t,e)=>{const s=new Image;s.onload=()=>{s.decode().then(()=>{requestAnimationFrame(()=>t(s))})},s.onerror=e,s.crossOrigin="anonymous",s.decoding="async",s.src=o})}async function yc(o){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(o)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function xc(o,t,e){const s="http://www.w3.org/2000/svg",r=document.createElementNS(s,"svg"),i=document.createElementNS(s,"foreignObject");return r.setAttribute("width",`${t}`),r.setAttribute("height",`${e}`),r.setAttribute("viewBox",`0 0 ${t} ${e}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),r.appendChild(i),i.appendChild(o),yc(r)}const xt=(o,t)=>{if(o instanceof t)return!0;const e=Object.getPrototypeOf(o);return e===null?!1:e.constructor.name===t.name||xt(e,t)};function _c(o){const t=o.getPropertyValue("content");return`${o.cssText} content: '${t.replace(/'|"/g,"")}';`}function bc(o,t){return oo(t).map(e=>{const s=o.getPropertyValue(e),r=o.getPropertyPriority(e);return`${e}: ${s}${r?" !important":""};`}).join(" ")}function wc(o,t,e,s){const r=`.${o}:${t}`,i=e.cssText?_c(e):bc(e,s);return document.createTextNode(`${r}{${i}}`)}function Gi(o,t,e,s){const r=window.getComputedStyle(o,e),i=r.getPropertyValue("content");if(i===""||i==="none")return;const n=gc();try{t.className=`${t.className} ${n}`}catch{return}const a=document.createElement("style");a.appendChild(wc(n,e,r,s)),t.appendChild(a)}function Sc(o,t,e){Gi(o,t,":before",e),Gi(o,t,":after",e)}const Ni="application/font-woff",Ui="image/jpeg",Cc={woff:Ni,woff2:Ni,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Ui,jpeg:Ui,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Tc(o){const t=/\.([^./]*?)$/g.exec(o);return t?t[1]:""}function Zr(o){const t=Tc(o).toLowerCase();return Cc[t]||""}function Oc(o){return o.split(/,/)[1]}function Ar(o){return o.search(/^(data:)/)!==-1}function kc(o,t){return`data:${t};base64,${o}`}async function ho(o,t,e){const s=await fetch(o,t);if(s.status===404)throw new Error(`Resource "${s.url}" not found`);const r=await s.blob();return new Promise((i,n)=>{const a=new FileReader;a.onerror=n,a.onloadend=()=>{try{i(e({res:s,result:a.result}))}catch(h){n(h)}},a.readAsDataURL(r)})}const yr={};function Dc(o,t,e){let s=o.replace(/\?.*/,"");return e&&(s=o),/ttf|otf|eot|woff2?/i.test(s)&&(s=s.replace(/.*\//,"")),t?`[${t}]${s}`:s}async function Qr(o,t,e){const s=Dc(o,t,e.includeQueryParams);if(yr[s]!=null)return yr[s];e.cacheBust&&(o+=(/\?/.test(o)?"&":"?")+new Date().getTime());let r;try{const i=await ho(o,e.fetchRequestInit,({res:n,result:a})=>(t||(t=n.headers.get("Content-Type")||""),Oc(a)));r=kc(i,t)}catch(i){r=e.imagePlaceholder||"";let n=`Failed to fetch resource: ${o}`;i&&(n=typeof i=="string"?i:i.message),n&&console.warn(n)}return yr[s]=r,r}async function Mc(o){const t=o.toDataURL();return t==="data:,"?o.cloneNode(!1):Gs(t)}async function Ec(o,t){if(o.currentSrc){const i=document.createElement("canvas"),n=i.getContext("2d");i.width=o.clientWidth,i.height=o.clientHeight,n==null||n.drawImage(o,0,0,i.width,i.height);const a=i.toDataURL();return Gs(a)}const e=o.poster,s=Zr(e),r=await Qr(e,s,t);return Gs(r)}async function Pc(o,t){var e;try{if(!((e=o==null?void 0:o.contentDocument)===null||e===void 0)&&e.body)return await rr(o.contentDocument.body,t,!0)}catch{}return o.cloneNode(!1)}async function Ac(o,t){return xt(o,HTMLCanvasElement)?Mc(o):xt(o,HTMLVideoElement)?Ec(o,t):xt(o,HTMLIFrameElement)?Pc(o,t):o.cloneNode(co(o))}const jc=o=>o.tagName!=null&&o.tagName.toUpperCase()==="SLOT",co=o=>o.tagName!=null&&o.tagName.toUpperCase()==="SVG";async function Fc(o,t,e){var s,r;if(co(t))return t;let i=[];return jc(o)&&o.assignedNodes?i=he(o.assignedNodes()):xt(o,HTMLIFrameElement)&&(!((s=o.contentDocument)===null||s===void 0)&&s.body)?i=he(o.contentDocument.body.childNodes):i=he(((r=o.shadowRoot)!==null&&r!==void 0?r:o).childNodes),i.length===0||xt(o,HTMLVideoElement)||await i.reduce((n,a)=>n.then(()=>rr(a,e)).then(h=>{h&&t.appendChild(h)}),Promise.resolve()),t}function Lc(o,t,e){const s=t.style;if(!s)return;const r=window.getComputedStyle(o);r.cssText?(s.cssText=r.cssText,s.transformOrigin=r.transformOrigin):oo(e).forEach(i=>{let n=r.getPropertyValue(i);i==="font-size"&&n.endsWith("px")&&(n=`${Math.floor(parseFloat(n.substring(0,n.length-2)))-.1}px`),xt(o,HTMLIFrameElement)&&i==="display"&&n==="inline"&&(n="block"),i==="d"&&t.getAttribute("d")&&(n=`path(${t.getAttribute("d")})`),s.setProperty(i,n,r.getPropertyPriority(i))})}function Rc(o,t){xt(o,HTMLTextAreaElement)&&(t.innerHTML=o.value),xt(o,HTMLInputElement)&&t.setAttribute("value",o.value)}function Bc(o,t){if(xt(o,HTMLSelectElement)){const e=t,s=Array.from(e.children).find(r=>o.value===r.getAttribute("value"));s&&s.setAttribute("selected","")}}function Ic(o,t,e){return xt(t,Element)&&(Lc(o,t,e),Sc(o,t,e),Rc(o,t),Bc(o,t)),t}async function Wc(o,t){const e=o.querySelectorAll?o.querySelectorAll("use"):[];if(e.length===0)return o;const s={};for(let i=0;i<e.length;i++){const a=e[i].getAttribute("xlink:href");if(a){const h=o.querySelector(a),c=document.querySelector(a);!h&&c&&!s[a]&&(s[a]=await rr(c,t,!0))}}const r=Object.values(s);if(r.length){const i="http://www.w3.org/1999/xhtml",n=document.createElementNS(i,"svg");n.setAttribute("xmlns",i),n.style.position="absolute",n.style.width="0",n.style.height="0",n.style.overflow="hidden",n.style.display="none";const a=document.createElementNS(i,"defs");n.appendChild(a);for(let h=0;h<r.length;h++)a.appendChild(r[h]);o.appendChild(n)}return o}async function rr(o,t,e){return!e&&t.filter&&!t.filter(o)?null:Promise.resolve(o).then(s=>Ac(s,t)).then(s=>Fc(o,s,t)).then(s=>Ic(o,s,t)).then(s=>Wc(s,t))}const lo=/url\((['"]?)([^'"]+?)\1\)/g,Xc=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Yc=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Vc(o){const t=o.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Hc(o){const t=[];return o.replace(lo,(e,s,r)=>(t.push(r),e)),t.filter(e=>!Ar(e))}async function zc(o,t,e,s,r){try{const i=e?dc(t,e):t,n=Zr(t);let a;return r||(a=await Qr(i,n,s)),o.replace(Vc(t),`$1${a}$3`)}catch{}return o}function Gc(o,{preferredFontFormat:t}){return t?o.replace(Yc,e=>{for(;;){const[s,,r]=Xc.exec(e)||[];if(!r)return"";if(r===t)return`src: ${s};`}}):o}function uo(o){return o.search(lo)!==-1}async function go(o,t,e){if(!uo(o))return o;const s=Gc(o,e);return Hc(s).reduce((i,n)=>i.then(a=>zc(a,n,t,e)),Promise.resolve(s))}async function we(o,t,e){var s;const r=(s=t.style)===null||s===void 0?void 0:s.getPropertyValue(o);if(r){const i=await go(r,null,e);return t.style.setProperty(o,i,t.style.getPropertyPriority(o)),!0}return!1}async function Nc(o,t){await we("background",o,t)||await we("background-image",o,t),await we("mask",o,t)||await we("-webkit-mask",o,t)||await we("mask-image",o,t)||await we("-webkit-mask-image",o,t)}async function Uc(o,t){const e=xt(o,HTMLImageElement);if(!(e&&!Ar(o.src))&&!(xt(o,SVGImageElement)&&!Ar(o.href.baseVal)))return;const s=e?o.src:o.href.baseVal,r=await Qr(s,Zr(s),t);await new Promise((i,n)=>{o.onload=i,o.onerror=t.onImageErrorHandler?(...h)=>{try{i(t.onImageErrorHandler(...h))}catch(c){n(c)}}:n;const a=o;a.decode&&(a.decode=i),a.loading==="lazy"&&(a.loading="eager"),e?(o.srcset="",o.src=r):o.href.baseVal=r})}async function qc(o,t){const s=he(o.childNodes).map(r=>fo(r,t));await Promise.all(s).then(()=>o)}async function fo(o,t){xt(o,Element)&&(await Nc(o,t),await Uc(o,t),await qc(o,t))}function Kc(o,t){const{style:e}=o;t.backgroundColor&&(e.backgroundColor=t.backgroundColor),t.width&&(e.width=`${t.width}px`),t.height&&(e.height=`${t.height}px`);const s=t.style;return s!=null&&Object.keys(s).forEach(r=>{e[r]=s[r]}),o}const qi={};async function Ki(o){let t=qi[o];if(t!=null)return t;const s=await(await fetch(o)).text();return t={url:o,cssText:s},qi[o]=t,t}async function $i(o,t){let e=o.cssText;const s=/url\(["']?([^"')]+)["']?\)/g,i=(e.match(/url\([^)]+\)/g)||[]).map(async n=>{let a=n.replace(s,"$1");return a.startsWith("https://")||(a=new URL(a,o.url).href),ho(a,t.fetchRequestInit,({result:h})=>(e=e.replace(n,`url(${h})`),[n,h]))});return Promise.all(i).then(()=>e)}function Ji(o){if(o==null)return[];const t=[],e=/(\/\*[\s\S]*?\*\/)/gi;let s=o.replace(e,"");const r=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const h=r.exec(s);if(h===null)break;t.push(h[0])}s=s.replace(r,"");const i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,n="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",a=new RegExp(n,"gi");for(;;){let h=i.exec(s);if(h===null){if(h=a.exec(s),h===null)break;i.lastIndex=a.lastIndex}else a.lastIndex=i.lastIndex;t.push(h[0])}return t}async function $c(o,t){const e=[],s=[];return o.forEach(r=>{if("cssRules"in r)try{he(r.cssRules||[]).forEach((i,n)=>{if(i.type===CSSRule.IMPORT_RULE){let a=n+1;const h=i.href,c=Ki(h).then(l=>$i(l,t)).then(l=>Ji(l).forEach(u=>{try{r.insertRule(u,u.startsWith("@import")?a+=1:r.cssRules.length)}catch(d){console.error("Error inserting rule from remote css",{rule:u,error:d})}})).catch(l=>{console.error("Error loading remote css",l.toString())});s.push(c)}})}catch(i){const n=o.find(a=>a.href==null)||document.styleSheets[0];r.href!=null&&s.push(Ki(r.href).then(a=>$i(a,t)).then(a=>Ji(a).forEach(h=>{n.insertRule(h,n.cssRules.length)})).catch(a=>{console.error("Error loading remote stylesheet",a)})),console.error("Error inlining remote css file",i)}}),Promise.all(s).then(()=>(o.forEach(r=>{if("cssRules"in r)try{he(r.cssRules||[]).forEach(i=>{e.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${r.href}`,i)}}),e))}function Jc(o){return o.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>uo(t.style.getPropertyValue("src")))}async function Zc(o,t){if(o.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=he(o.ownerDocument.styleSheets),s=await $c(e,t);return Jc(s)}function po(o){return o.trim().replace(/["']/g,"")}function Qc(o){const t=new Set;function e(s){(s.style.fontFamily||getComputedStyle(s).fontFamily).split(",").forEach(i=>{t.add(po(i))}),Array.from(s.children).forEach(i=>{i instanceof HTMLElement&&e(i)})}return e(o),t}async function tl(o,t){const e=await Zc(o,t),s=Qc(o);return(await Promise.all(e.filter(i=>s.has(po(i.style.fontFamily))).map(i=>{const n=i.parentStyleSheet?i.parentStyleSheet.href:null;return go(i.cssText,n,t)}))).join(`
505
+ `)}async function el(o,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await tl(o,t);if(e){const s=document.createElement("style"),r=document.createTextNode(e);s.appendChild(r),o.firstChild?o.insertBefore(s,o.firstChild):o.appendChild(s)}}async function sl(o,t={}){const{width:e,height:s}=ao(o,t),r=await rr(o,t,!0);return await el(r,t),await fo(r,t),Kc(r,t),await xc(r,e,s)}async function rl(o,t={}){const{width:e,height:s}=ao(o,t),r=await sl(o,t),i=await Gs(r),n=document.createElement("canvas"),a=n.getContext("2d"),h=t.pixelRatio||mc(),c=t.canvasWidth||e,l=t.canvasHeight||s;return n.width=c*h,n.height=l*h,t.skipAutoScale||vc(n),n.style.width=`${c}`,n.style.height=`${l}`,t.backgroundColor&&(a.fillStyle=t.backgroundColor,a.fillRect(0,0,n.width,n.height)),a.drawImage(i,0,0,n.width,n.height),n}async function il(o,t={}){return(await rl(o,t)).toDataURL()}async function Zi(o,t,e,s){const r=document.createElement("div");if(r.style.cssText=`position:fixed;left:0;top:0;z-index:999999;pointer-events:none;visibility:visible;${yo};`,s){const i=document.createElement("style");i.textContent=tn(s),r.appendChild(i)}r.insertAdjacentHTML("beforeend",o),document.body.appendChild(r);try{const i=r.offsetWidth||100,n=r.offsetHeight||40,a=t?t/i:1,h=e?e/n:1,c=Math.max(a,h,1);return{dataUrl:await il(r,{skipFonts:!0,width:i,height:n,pixelRatio:c}),width:t??i,height:e??n}}finally{r.remove()}}function nl({onSubmit:o,backgroundImage:t,armedComponent:e,onComponentPlaced:s}){const r=F.useRef(null),i=F.useRef(null),n=F.useRef(null),[a,h]=F.useState("freehand"),[c,l]=F.useState("#3B82F6"),[u,d]=F.useState("#000000"),[g,f]=F.useState([]),[v,_]=F.useState([]),b=F.useRef(null),w=F.useRef(!1),C=F.useRef(!1),T=F.useRef([]),D=F.useRef(0),[A,I]=F.useState(null),[E,W]=F.useState(null),[q,Z]=F.useState(null);F.useEffect(()=>{if(!r.current||i.current)return;const y=new Er(r.current,{backgroundColor:"#ffffff",selection:!0});i.current=y;const S=()=>{if(!n.current)return;const{width:O,height:j}=n.current.getBoundingClientRect();y.setDimensions({width:O,height:j})};S();const k=new ResizeObserver(S);return n.current&&k.observe(n.current),window.addEventListener("resize",S),f([JSON.stringify(y.toJSON())]),()=>{k.disconnect(),window.removeEventListener("resize",S),y.dispose(),i.current=null}},[]),F.useEffect(()=>{const y=i.current;if(!y)return;const S=async k=>{const O=k.target,j=O==null?void 0:O._componentMeta;if(!(j!=null&&j.ghostHtml)||O.type!=="image")return;const H=Math.round((O.width??0)*(O.scaleX??1)),B=Math.round((O.height??0)*(O.scaleY??1));if(!(H<4||B<4))try{const{dataUrl:ht,width:Pt,height:rt}=await Zi(j.ghostHtml,H,B,j.ghostCss),z=await lt.fromURL(ht);z.set({left:O.left,top:O.top,scaleX:H/(z.width??Pt),scaleY:B/(z.height??rt)}),z._componentMeta=j;const wt=y.getObjects().indexOf(O);y.remove(O),y.insertAt(wt,z),y.setActiveObject(z),y.requestRenderAll()}catch{}};return y.on("object:modified",S),()=>{y.off("object:modified",S)}},[]),F.useEffect(()=>{if(!t)return;const y=i.current;y&&lt.fromURL(t).then(S=>{!S.width||!S.height||(C.current=!0,S.set({selectable:!1,evented:!1,hasBorders:!1,hasControls:!1}),y.backgroundImage=S,y.requestRenderAll())})},[t]),F.useEffect(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();S.length!==0&&(S.forEach(k=>{"fill"in k&&k.fill!==""&&k.fill!==null&&k.set("fill",c)}),y.requestRenderAll())},[c]),F.useEffect(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();S.length!==0&&(S.forEach(k=>{"stroke"in k&&k.set("stroke",u)}),y.requestRenderAll())},[u]);const L=F.useCallback(()=>{const y=i.current;if(!y)return;const S=JSON.stringify(y.toJSON());f(k=>[...k,S]),_([])},[]);F.useEffect(()=>{const y=i.current;if(y){if(y.isDrawingMode=!1,y.selection=!0,y.defaultCursor="default",y.setCursor("default"),y.getObjects().forEach(S=>{S.evented=!0,S.selectable=!0,S.hasControls=!0,S.hasBorders=!0,S.setCoords()}),y.requestRenderAll(),y.off("mouse:down"),y.off("mouse:move"),y.off("mouse:up"),a==="freehand"){y.isDrawingMode=!0;const S=new Hs(y);S.color=u,S.width=2,y.freeDrawingBrush=S,y.on("path:created",k=>{L();const O=k.path;O&&(y.setActiveObject(O),y.requestRenderAll()),h("select")})}else if(a==="eraser"){y.selection=!1;const S='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="%23555" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 21-4-4 9.5-9.5 5.5 5.5L7 21Z"/><path d="M22 21H7"/><path d="m11.5 12.5 5.5 5.5"/></svg>';y.defaultCursor=`url("data:image/svg+xml,${S}") 4 18, auto`,y.on("mouse:down",k=>{const O=y.findTarget(k.e);O&&(y.remove(O),L())})}else if(a!=="select"){if(a==="text")y.selection=!1,y.defaultCursor="text",y.on("mouse:down",S=>{if(w.current)return;const k=y.getScenePoint(S.e),O=new Jt("Text",{left:k.x,top:k.y,fontSize:16,fill:u,width:120});y.add(O),y.setActiveObject(O),O.enterEditing(),O.selectAll(),L(),y.defaultCursor="default",y.setCursor("default"),h("select"),O.once("editing:exited",()=>{y.defaultCursor="default",y.setCursor("default")})});else if(["rectangle","circle","line","arrow"].includes(a)){y.selection=!1,y.defaultCursor="crosshair",y.getObjects().forEach(k=>{k.evented=!1,k.selectable=!1});let S=null;y.on("mouse:down",k=>{y.getObjects().forEach(j=>{j.evented=!1,j.selectable=!1}),w.current=!0;const O=y.getScenePoint(k.e);b.current={x:O.x,y:O.y},a==="rectangle"?(S=new kt({left:O.x,top:O.y,width:0,height:0,fill:c==="transparent"?"transparent":c,stroke:u,strokeWidth:2,selectable:!1}),y.add(S)):a==="circle"?(S=new Xt({left:O.x,top:O.y,radius:0,fill:c==="transparent"?"transparent":c,stroke:u,strokeWidth:2,selectable:!1}),y.add(S)):(a==="line"||a==="arrow")&&(S=new Vt([O.x,O.y,O.x,O.y],{stroke:u,strokeWidth:2,selectable:!1}),y.add(S))}),y.on("mouse:move",k=>{if(!b.current||!S)return;const O=y.getScenePoint(k.e),j=b.current;if(a==="rectangle"){const H=Math.min(j.x,O.x),B=Math.min(j.y,O.y);S.set({left:H,top:B,width:Math.abs(O.x-j.x),height:Math.abs(O.y-j.y)})}else if(a==="circle"){const H=Math.abs(O.x-j.x)/2,B=Math.abs(O.y-j.y)/2;S.set({left:Math.min(j.x,O.x),top:Math.min(j.y,O.y),radius:Math.max(H,B)})}else(a==="line"||a==="arrow")&&S.set({x2:O.x,y2:O.y});y.requestRenderAll()}),y.on("mouse:up",()=>{if(S){if(a==="arrow"&&b.current){const k=S.x1,O=S.y1,j=S.x2,H=S.y2,B=Math.atan2(H-O,j-k),ht=12,Pt=new Vt([j-ht*Math.cos(B-Math.PI/6),H-ht*Math.sin(B-Math.PI/6),j,H],{stroke:u,strokeWidth:2,selectable:!1}),rt=new Vt([j-ht*Math.cos(B+Math.PI/6),H-ht*Math.sin(B+Math.PI/6),j,H],{stroke:u,strokeWidth:2,selectable:!1});y.add(Pt,rt)}L(),S.set({evented:!0,selectable:!0,hasControls:!0,hasBorders:!0}),S.setCoords(),y.setActiveObject(S),y.requestRenderAll(),h("select")}S=null,b.current=null,w.current=!1})}}}},[a,c,u,L]);const V=F.useCallback(()=>{const y=i.current;if(!y||g.length<=1)return;const S=g[g.length-1],k=g[g.length-2];_(O=>[...O,S]),f(O=>O.slice(0,-1)),y.loadFromJSON(JSON.parse(k)).then(()=>y.requestRenderAll())},[g]),X=F.useCallback(()=>{const y=i.current;if(!y||v.length===0)return;const S=v[v.length-1];_(k=>k.slice(0,-1)),f(k=>[...k,S]),y.loadFromJSON(JSON.parse(S)).then(()=>y.requestRenderAll())},[v]),nt=F.useCallback(()=>{const y=i.current;y&&(y.clear(),t?lt.fromURL(t).then(S=>{!S.width||!S.height||(S.set({selectable:!1,evented:!1,hasBorders:!1,hasControls:!1}),y.backgroundImage=S,y.requestRenderAll())}):(y.backgroundColor="#ffffff",y.requestRenderAll()),L())},[L,t]),et=F.useCallback(()=>{const y=i.current;if(!y)return;const S=y.getObjects();let k;if(S.length>0&&!C.current){let z=1/0,wt=1/0,Wt=-1/0,Tt=-1/0;for(const vo of S){const ye=vo.getBoundingRect();z=Math.min(z,ye.left),wt=Math.min(wt,ye.top),Wt=Math.max(Wt,ye.left+ye.width),Tt=Math.max(Tt,ye.top+ye.height)}const ir=y.getWidth(),mo=y.getHeight(),ti=Math.max(0,Math.floor(z-10)),ei=Math.max(0,Math.floor(wt-10)),si=Math.min(ir-ti,Math.ceil(Wt-z+10*2)),ri=Math.min(mo-ei,Math.ceil(Tt-wt+10*2));si>0&&ri>0&&(k={left:ti,top:ei,width:si,height:ri})}const O=y.toDataURL({format:"png",multiplier:1,...k}),j=(k==null?void 0:k.width)??y.getWidth(),H=(k==null?void 0:k.height)??y.getHeight(),B=[],ht=(k==null?void 0:k.left)??0,Pt=(k==null?void 0:k.top)??0;for(const rt of S){const z=rt._componentMeta;z&&B.push({componentName:z.componentName,componentPath:z.componentPath,storyId:z.storyId,args:z.args,x:Math.round((rt.left??0)-ht),y:Math.round((rt.top??0)-Pt),width:Math.round((rt.width??0)*(rt.scaleX??1)),height:Math.round((rt.height??0)*(rt.scaleY??1))})}o(O,j,H,B.length>0?B:void 0)},[o]),st=F.useCallback(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();if(S.length>0){for(const k of S)y.remove(k);y.discardActiveObject(),y.requestRenderAll(),L()}},[L]),U=F.useCallback(()=>{const y=i.current;if(!y)return;const S=y.getActiveObjects();S.length!==0&&Promise.all(S.map(k=>k.clone())).then(k=>{T.current=k,D.current=0})},[]),bt=F.useCallback(()=>{const y=i.current;if(!y||T.current.length===0)return;const S=20;D.current+=S;const k=D.current;Promise.all(T.current.map(O=>O.clone())).then(O=>{if(y.discardActiveObject(),O.forEach(j=>{j.set({left:(j.left??0)+k,top:(j.top??0)+k,evented:!0,selectable:!0}),j.setCoords(),y.add(j)}),O.length===1)y.setActiveObject(O[0]);else{const j=new y.constructor.ActiveSelection(O,{canvas:y});y.setActiveObject(j)}y.requestRenderAll(),L()})},[L]);return F.useEffect(()=>{const y=S=>{if(S.key==="Delete"||S.key==="Backspace"){const k=i.current;if(k){const O=k.getActiveObject();if(O&&O.type==="textbox"&&O.isEditing)return}st()}if((S.metaKey||S.ctrlKey)&&S.key==="z"&&(S.preventDefault(),S.shiftKey?X():V()),(S.metaKey||S.ctrlKey)&&S.key==="c"){const k=i.current;if(k){const O=k.getActiveObject();if(O&&O.type==="textbox"&&O.isEditing)return}U()}if((S.metaKey||S.ctrlKey)&&S.key==="v"){const k=i.current;if(k){const O=k.getActiveObject();if(O&&O.type==="textbox"&&O.isEditing)return}S.preventDefault(),bt()}};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[st,V,X,U,bt]),F.useEffect(()=>{if(!(e!=null&&e.ghostHtml)){Z(null),W(null);return}const y=document.createElement("div");if(y.style.cssText="position:fixed;left:-99999px;top:-99999px;visibility:hidden;pointer-events:none;",e.ghostCss){const S=document.createElement("style");S.textContent=tn(e.ghostCss),y.appendChild(S)}y.insertAdjacentHTML("beforeend",e.ghostHtml),document.body.appendChild(y),Z({width:y.offsetWidth||100,height:y.offsetHeight||40}),document.body.removeChild(y)},[e]),F.useEffect(()=>{const y=n.current;if(!y||!e){W(null);return}const S=H=>{const B=y.getBoundingClientRect();W({x:H.clientX-B.left,y:H.clientY-B.top})},k=()=>W(null),O=H=>{const B=y.getBoundingClientRect();W({x:H.clientX-B.left,y:H.clientY-B.top})},j=async H=>{H.preventDefault(),H.stopPropagation();const B=i.current;if(!B||!e.ghostHtml)return;const ht=y.getBoundingClientRect(),Pt=H.clientX-ht.left,rt=H.clientY-ht.top;try{const{dataUrl:z,width:wt,height:Wt}=await Zi(e.ghostHtml,void 0,void 0,e.ghostCss),Tt=await lt.fromURL(z);Tt.set({left:Pt-wt/2,top:rt-Wt/2,scaleX:1,scaleY:1}),Tt._componentMeta={componentName:e.componentName,componentPath:e.componentPath,storyId:e.storyId,args:e.args,ghostHtml:e.ghostHtml,ghostCss:e.ghostCss},B.add(Tt),B.setActiveObject(Tt),B.requestRenderAll(),L(),h("select")}catch(z){console.error("[DesignCanvas] Failed to rasterize component:",z);const wt=(q==null?void 0:q.width)??100,Wt=(q==null?void 0:q.height)??40,Tt=new kt({left:Pt-wt/2,top:rt-Wt/2,width:wt,height:Wt,fill:"rgba(0, 132, 139, 0.08)",stroke:"#00848B",strokeWidth:2,strokeDashArray:[4,4]});Tt._componentMeta={componentName:e.componentName,componentPath:e.componentPath,storyId:e.storyId,args:e.args,ghostHtml:e.ghostHtml,ghostCss:e.ghostCss};const ir=new Jt(e.componentName,{left:Pt-wt/2+4,top:rt-Wt/2+(Wt-14)/2,fontSize:12,fill:"#00848B",width:wt-8,selectable:!1,evented:!1});B.add(Tt,ir),B.setActiveObject(Tt),B.requestRenderAll(),L(),h("select")}s==null||s()};return y.addEventListener("mousemove",S),y.addEventListener("mouseleave",k),y.addEventListener("mouseenter",O),y.addEventListener("click",j,{capture:!0}),()=>{y.removeEventListener("mousemove",S),y.removeEventListener("mouseleave",k),y.removeEventListener("mouseenter",O),y.removeEventListener("click",j,{capture:!0})}},[e,q,L,s]),{canvasElRef:r,containerRef:n,lockedHeight:A,activeTool:a,setActiveTool:h,fillColor:c,setFillColor:l,strokeColor:u,setStrokeColor:d,canUndo:g.length>1,canRedo:v.length>0,handleUndo:V,handleRedo:X,handleClear:nt,handleSubmit:et,ghostPos:E,ghostSize:q}}const Qi=["#000000","#ffffff","#9CA3AF","#EF4444","#F97316","#EAB308","#22C55E","#3B82F6","#8B5CF6","#EC4899","#14B8A6","#6366F1"],ol=()=>P.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P.jsx("path",{d:"M5 3l14 8-6 2-4 6z"}),P.jsx("path",{d:"M13 13l6 6"})]}),al=()=>P.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P.jsx("path",{d:"m7 21-4-4 9.5-9.5 5.5 5.5L7 21Z"}),P.jsx("path",{d:"M22 21H7"}),P.jsx("path",{d:"m11.5 12.5 5.5 5.5"})]}),hl=()=>P.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[P.jsx("polyline",{points:"3 6 5 6 21 6"}),P.jsx("path",{d:"M19 6l-1 14H6L5 6"}),P.jsx("path",{d:"M10 11v6M14 11v6"}),P.jsx("path",{d:"M9 6V4h6v2"})]}),cl=[{id:"select",label:"Select",icon:P.jsx(ol,{})},{id:"freehand",label:"Freehand",icon:"✎"},{id:"rectangle",label:"Rectangle",icon:"□"},{id:"circle",label:"Circle",icon:"○"},{id:"line",label:"Line",icon:"╱"},{id:"arrow",label:"Arrow",icon:"→"},{id:"text",label:"Text",icon:"T"},{id:"eraser",label:"Eraser",icon:P.jsx(al,{})}];function ll({activeTool:o,onToolChange:t,fillColor:e,onFillChange:s,strokeColor:r,onStrokeChange:i,canUndo:n,canRedo:a,onUndo:h,onRedo:c,onClear:l,onSubmit:u,onClose:d}){const[g,f]=F.useState(!1),[v,_]=F.useState(!1),b=F.useRef(null),w=F.useRef(null);return F.useEffect(()=>{const C=T=>{g&&b.current&&!b.current.contains(T.target)&&f(!1),v&&w.current&&!w.current.contains(T.target)&&_(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[g,v]),P.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-1 bg-bv-bg border-b border-bv-border text-[10px] shrink-0 flex-wrap",children:[cl.map(C=>P.jsx("button",{title:C.label,onClick:()=>t(C.id),className:`w-7 h-[26px] rounded border flex items-center justify-center text-[13px] cursor-pointer transition-all
506
506
  ${o===C.id?"bg-bv-teal/10 border-bv-teal text-bv-teal":"bg-transparent border-transparent text-bv-text-mid hover:bg-bv-surface hover:border-bv-border hover:text-bv-text"}`,children:C.icon},C.id)),P.jsx("div",{className:"w-px h-[18px] bg-bv-border mx-1"}),P.jsxs("div",{ref:b,className:"relative",children:[P.jsx("button",{title:"Fill color",className:"w-7 h-[26px] rounded border border-transparent flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:bg-bv-surface hover:border-bv-border",onClick:()=>{f(!g),_(!1)},children:P.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"currentColor",className:"text-bv-text-mid",children:[P.jsx("path",{d:"M16.56 8.94L7.62 0 6.21 1.41l2.38 2.38-5.15 5.15a1.49 1.49 0 0 0 0 2.12l5.5 5.5c.29.29.68.44 1.06.44s.77-.15 1.06-.44l5.5-5.5c.59-.58.59-1.53 0-2.12zM5.21 10L10 5.21 14.79 10H5.21zM19 11.5s-2 2.17-2 3.5c0 1.1.9 2 2 2s2-.9 2-2c0-1.33-2-3.5-2-3.5z"}),P.jsx("path",{d:"M0 20h24v4H0z",style:{fill:e==="transparent"?"none":e,stroke:e==="transparent"?"#aaa":"none",strokeWidth:e==="transparent"?1:0}})]})}),g&&P.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bv-bg border border-bv-border rounded-lg shadow-lg p-2 w-[164px]",children:[P.jsx("div",{className:"text-[9px] font-semibold uppercase tracking-wider text-bv-muted mb-1.5",children:"Fill Color"}),P.jsx("div",{className:"grid grid-cols-6 gap-1 mb-2",children:Qi.map(C=>P.jsx("button",{className:`w-[22px] h-[22px] rounded cursor-pointer transition-all hover:scale-110
507
507
  ${e===C?"ring-2 ring-bv-teal ring-offset-1":"border border-black/10"}`,style:{background:C},onClick:()=>{s(C),f(!1)}},C))}),P.jsxs("div",{className:"pt-1 border-t border-bv-border flex items-center gap-1.5",children:[P.jsx("button",{className:`w-[22px] h-[22px] rounded cursor-pointer border border-bv-border
508
508
  ${e==="transparent"?"ring-2 ring-bv-teal ring-offset-1":""}`,style:{background:"repeating-conic-gradient(#ddd 0% 25%, white 0% 50%) 50%/8px 8px"},onClick:()=>{s("transparent"),f(!1)}}),P.jsx("span",{className:"text-[9px] text-bv-muted",children:"None"})]})]})]}),P.jsxs("div",{ref:w,className:"relative",children:[P.jsx("button",{title:"Stroke color",className:"w-7 h-[26px] rounded border border-transparent flex flex-col items-center justify-center gap-0.5 cursor-pointer transition-all hover:bg-bv-surface hover:border-bv-border",onClick:()=>{_(!v),f(!1)},children:P.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"currentColor",className:"text-bv-text-mid",children:[P.jsx("path",{d:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1 1 0 0 0 0-1.41l-2.34-2.34a1 1 0 0 0-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"}),P.jsx("rect",{x:"0",y:"21",width:"24",height:"3",style:{fill:r}})]})}),v&&P.jsxs("div",{className:"absolute top-full left-0 mt-1 z-50 bg-bv-bg border border-bv-border rounded-lg shadow-lg p-2 w-[164px]",children:[P.jsx("div",{className:"text-[9px] font-semibold uppercase tracking-wider text-bv-muted mb-1.5",children:"Stroke Color"}),P.jsx("div",{className:"grid grid-cols-6 gap-1",children:Qi.map(C=>P.jsx("button",{className:`w-[22px] h-[22px] rounded cursor-pointer transition-all hover:scale-110
509
509
  ${r===C?"ring-2 ring-bv-teal ring-offset-1":"border border-black/10"}`,style:{background:C},onClick:()=>{i(C),_(!1)}},C))})]})]}),P.jsx("div",{className:"w-px h-[18px] bg-bv-border mx-1"}),P.jsx("button",{title:"Undo",onClick:h,disabled:!n,className:`w-7 h-[26px] rounded border border-transparent flex items-center justify-center text-[13px] cursor-pointer transition-all
510
510
  ${n?"text-bv-text-mid hover:bg-bv-surface hover:border-bv-border hover:text-bv-text":"opacity-35 cursor-default"}`,children:"↶"}),P.jsx("button",{title:"Redo",onClick:c,disabled:!a,className:`w-7 h-[26px] rounded border border-transparent flex items-center justify-center text-[13px] cursor-pointer transition-all
511
- ${a?"text-bv-text-mid hover:bg-bv-surface hover:border-bv-border hover:text-bv-text":"opacity-35 cursor-default"}`,children:"↷"}),P.jsx("button",{title:"Clear canvas",onClick:l,className:"w-7 h-[26px] rounded border border-transparent flex items-center justify-center text-[13px] cursor-pointer text-bv-text-mid hover:bg-bv-surface hover:border-bv-border hover:text-bv-text transition-all",children:P.jsx(nl,{})}),d&&P.jsx("button",{onClick:d,className:"ml-auto px-2.5 py-0.5 rounded border border-bv-border bg-bv-bg text-bv-muted text-[10px] font-medium cursor-pointer hover:bg-bv-orange/10 hover:border-bv-orange hover:text-bv-orange transition-all",children:"✕ Close"}),u&&P.jsx("button",{onClick:u,className:"px-2.5 py-0.5 rounded border border-bv-teal bg-bv-teal text-white text-[10px] font-medium cursor-pointer hover:bg-bv-teal/80 transition-all",children:"✓ Add to Drafts"})]})}function hl({onSubmit:o,onClose:t,backgroundImage:e,armedComponent:s,onComponentPlaced:r}){const{canvasElRef:i,containerRef:n,activeTool:a,setActiveTool:h,fillColor:c,setFillColor:l,strokeColor:u,setStrokeColor:d,canUndo:g,canRedo:f,handleUndo:v,handleRedo:_,handleClear:b,handleSubmit:w,ghostPos:C,ghostSize:T}=sl({onSubmit:o,backgroundImage:e,armedComponent:s,onComponentPlaced:r}),D=!!s;return P.jsxs("div",{className:"flex flex-col h-full","data-testid":"design-canvas",children:[P.jsx(al,{activeTool:a,onToolChange:h,fillColor:c,onFillChange:l,strokeColor:u,onStrokeChange:d,canUndo:g,canRedo:f,onUndo:v,onRedo:_,onClear:b,onSubmit:w,onClose:t}),P.jsxs("div",{ref:n,className:`bg-white overflow-hidden relative ${D?"cursor-crosshair":""}`,style:{flex:1},children:[P.jsx("canvas",{ref:i}),D&&C&&(s==null?void 0:s.ghostHtml)&&P.jsx("div",{style:{position:"absolute",left:C.x-((T==null?void 0:T.width)??0)/2,top:C.y-((T==null?void 0:T.height)??0)/2,pointerEvents:"none",opacity:.6,outline:"2px dashed #00848B",outlineOffset:2,zIndex:10},dangerouslySetInnerHTML:{__html:s.ghostHtml}}),D&&P.jsxs("div",{style:{position:"absolute",top:4,left:"50%",transform:"translateX(-50%)",background:"rgba(0, 132, 139, 0.9)",color:"#fff",fontSize:11,fontWeight:600,padding:"2px 10px",borderRadius:4,pointerEvents:"none",zIndex:20,whiteSpace:"nowrap"},children:["Click to place ",s==null?void 0:s.componentName]})]})]})}function ll(){const[o,t]=F.useState(null),[e,s]=F.useState(null);F.useEffect(()=>{yo(()=>{Ie({type:"REGISTER",role:"design"})}),xo(a=>{a.type==="ELEMENT_CONTEXT"?t({componentName:a.componentName,instanceCount:a.instanceCount,target:a.target,context:a.context,insertMode:a.insertMode??"after",screenshot:a.screenshot}):a.type==="COMPONENT_ARM"?s({componentName:a.componentName,storyId:a.storyId,ghostHtml:a.ghostHtml,componentPath:a.componentPath,args:a.args}):(a.type==="COMPONENT_DISARM"||a.type==="COMPONENT_DISARMED")&&s(null)}),vo()},[]);const r=F.useCallback((a,h,c,l)=>{Ie({type:"DESIGN_SUBMIT",image:a,componentName:(o==null?void 0:o.componentName)??"",target:(o==null?void 0:o.target)??{tag:"",classes:"",innerText:""},context:(o==null?void 0:o.context)??"",insertMode:(o==null?void 0:o.insertMode)??"after",canvasWidth:h,canvasHeight:c,canvasComponents:l})},[o]),i=()=>{Ie({type:"DESIGN_CLOSE"})},n=F.useCallback(()=>{s(null),Ie({type:"COMPONENT_DISARMED",to:"panel"}),Ie({type:"COMPONENT_DISARM",to:"overlay"})},[]);return P.jsx("div",{className:"h-full w-full flex flex-col",children:P.jsx("div",{className:"flex-1 overflow-hidden",children:P.jsx(hl,{onSubmit:r,onClose:i,backgroundImage:o==null?void 0:o.screenshot,armedComponent:e,onComponentPlaced:n})})})}export{ll as DesignMode};
511
+ ${a?"text-bv-text-mid hover:bg-bv-surface hover:border-bv-border hover:text-bv-text":"opacity-35 cursor-default"}`,children:"↷"}),P.jsx("button",{title:"Clear canvas",onClick:l,className:"w-7 h-[26px] rounded border border-transparent flex items-center justify-center text-[13px] cursor-pointer text-bv-text-mid hover:bg-bv-surface hover:border-bv-border hover:text-bv-text transition-all",children:P.jsx(hl,{})}),d&&P.jsx("button",{onClick:d,className:"ml-auto px-2.5 py-0.5 rounded border border-bv-border bg-bv-bg text-bv-muted text-[10px] font-medium cursor-pointer hover:bg-bv-orange/10 hover:border-bv-orange hover:text-bv-orange transition-all",children:"✕ Close"}),u&&P.jsx("button",{onClick:u,className:"px-2.5 py-0.5 rounded border border-bv-teal bg-bv-teal text-white text-[10px] font-medium cursor-pointer hover:bg-bv-teal/80 transition-all",children:"✓ Add to Drafts"})]})}function ul({onSubmit:o,onClose:t,backgroundImage:e,armedComponent:s,onComponentPlaced:r}){const{canvasElRef:i,containerRef:n,activeTool:a,setActiveTool:h,fillColor:c,setFillColor:l,strokeColor:u,setStrokeColor:d,canUndo:g,canRedo:f,handleUndo:v,handleRedo:_,handleClear:b,handleSubmit:w,ghostPos:C,ghostSize:T}=nl({onSubmit:o,backgroundImage:e,armedComponent:s,onComponentPlaced:r}),D=!!s;return P.jsxs("div",{className:"flex flex-col h-full","data-testid":"design-canvas",children:[P.jsx(ll,{activeTool:a,onToolChange:h,fillColor:c,onFillChange:l,strokeColor:u,onStrokeChange:d,canUndo:g,canRedo:f,onUndo:v,onRedo:_,onClear:b,onSubmit:w,onClose:t}),P.jsxs("div",{ref:n,className:`bg-white overflow-hidden relative ${D?"cursor-crosshair":""}`,style:{flex:1},children:[P.jsx("canvas",{ref:i}),D&&C&&(s==null?void 0:s.ghostHtml)&&(s==null?void 0:s.ghostCss)&&P.jsx(xo,{ghostHtml:s.ghostHtml,ghostCss:s.ghostCss,style:{position:"absolute",left:C.x-((T==null?void 0:T.width)??0)/2,top:C.y-((T==null?void 0:T.height)??0)/2,pointerEvents:"none",opacity:.6,outline:"2px dashed #00848B",outlineOffset:2,zIndex:10}}),D&&P.jsxs("div",{style:{position:"absolute",top:4,left:"50%",transform:"translateX(-50%)",background:"rgba(0, 132, 139, 0.9)",color:"#fff",fontSize:11,fontWeight:600,padding:"2px 10px",borderRadius:4,pointerEvents:"none",zIndex:20,whiteSpace:"nowrap"},children:["Click to place ",s==null?void 0:s.componentName]})]})]})}function gl(){const[o,t]=F.useState(null),[e,s]=F.useState(null);F.useEffect(()=>{bo(()=>{Ie({type:"REGISTER",role:"design"})}),wo(a=>{a.type==="ELEMENT_CONTEXT"?t({componentName:a.componentName,instanceCount:a.instanceCount,target:a.target,context:a.context,insertMode:a.insertMode??"after",screenshot:a.screenshot}):a.type==="COMPONENT_ARM"?s({componentName:a.componentName,storyId:a.storyId,ghostHtml:a.ghostHtml,ghostCss:a.ghostCss,componentPath:a.componentPath,args:a.args}):(a.type==="COMPONENT_DISARM"||a.type==="COMPONENT_DISARMED")&&s(null)}),_o()},[]);const r=F.useCallback((a,h,c,l)=>{Ie({type:"DESIGN_SUBMIT",image:a,componentName:(o==null?void 0:o.componentName)??"",target:(o==null?void 0:o.target)??{tag:"",classes:"",innerText:""},context:(o==null?void 0:o.context)??"",insertMode:(o==null?void 0:o.insertMode)??"after",canvasWidth:h,canvasHeight:c,canvasComponents:l})},[o]),i=()=>{Ie({type:"DESIGN_CLOSE"})},n=F.useCallback(()=>{s(null),Ie({type:"COMPONENT_DISARMED",to:"panel"}),Ie({type:"COMPONENT_DISARM",to:"overlay"})},[]);return P.jsx("div",{className:"h-full w-full flex flex-col",children:P.jsx("div",{className:"flex-1 overflow-hidden",children:P.jsx(ul,{onSubmit:r,onClose:i,backgroundImage:o==null?void 0:o.screenshot,armedComponent:e,onComponentPlaced:n})})})}export{gl as DesignMode};