@bitovi/vybit 0.11.5 → 0.11.7

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,511 +0,0 @@
1
- import{r as F,j as A,c as co,s as Be,o as lo,a as uo}from"./index-D2eK_68s.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 Zr(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?Zr(Object(e),!0).forEach(function(s){p(o,s,e[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(o,Object.getOwnPropertyDescriptors(e)):Zr(Object(e)).forEach(function(s){Object.defineProperty(o,s,Object.getOwnPropertyDescriptor(e,s))})}return o}function K(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 Yt(o,t){return t||(t=o.slice(0)),Object.freeze(Object.defineProperties(o,{raw:{value:Object.freeze(t)}}))}class Qr{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 V=new class extends Qr{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 Qr,e=(o==null?void 0:o.reduce((s,r)=>(s[r]=t[r],s),{}))||t;this.configure(e)}},he=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 Wt extends Error{constructor(t,e){super("fabric: ".concat(t),e)}}class go extends Wt{constructor(t){super("".concat(t," 'options.signal' is in 'aborted' state"))}}class fo{}class po extends fo{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(),he("log","WebGL: max texture size ".concat(this.maxTextureSize)))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const mo={};let ti;const Vt=()=>ti||(ti={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new po,dispose(){},copyPasteData:mo}),Ee=()=>Vt().document,Gs=()=>Vt().window,qi=()=>{var o;return Math.max((o=V.devicePixelRatio)!==null&&o!==void 0?o:Gs().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}=V,e=Math.sqrt(t*o);return[Math.floor(e),Math.floor(t/e)]}},vr="6.9.1";function Ts(){}const Je=Math.PI/2,Es=2*Math.PI,Pr=Math.PI/180,gt=Object.freeze([1,0,0,1,0,0]),Ar=16,ie=.4477152502,R="center",z="left",pt="top",yr="bottom",Z="right",mt="none",jr=/\r?\n/,Ki="moving",Ns="scaling",$i="rotating",Fr="rotate",Ji="skewing",Ge="resizing",vo="modifyPoly",yo="modifyPath",Ps="changed",Us="scale",xt="scaleX",Ot="scaleY",Pe="skewX",Ae="skewY",nt="fill",vt="stroke",As="modified",ye="json",rr="svg",D=new class{constructor(){this[ye]=new Map,this[rr]=new Map}has(o){return this[ye].has(o)}getClass(o){const t=this[ye].get(o);if(!t)throw new Wt("No class registered for ".concat(o));return t}setClass(o,t){t?this[ye].set(t,o):(this[ye].set(o.type,o),this[ye].set(o.type.toLowerCase(),o))}getSVGClass(o){return this[rr].get(o)}setSVGClass(o,t){this[rr].set(t??o.type.toLowerCase(),o)}},js=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 xo{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 we=(o,t)=>{const e=o.indexOf(t);return e!==-1&&o.splice(e,1),o},$t=o=>{if(o===0)return 1;switch(Math.abs(o)/Je){case 1:case 3:return 0;case 2:return-1}return Math.cos(o)},Jt=o=>{if(o===0)return 0;const t=o/Je,e=Math.sign(o);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(o)};class y{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 y(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new y(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new y(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new y(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new y(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new y(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new y(this.x/t.x,this.y/t.y)}scalarDivide(t){return new y(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 y(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 y(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new y(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 y(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Lr;const s=Jt(t),r=$t(t),i=this.subtract(e);return new y(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 y(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 Lr=new y(0,0),Os=o=>!!o&&Array.isArray(o._objects);function Zi(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])&&(we(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(we(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 we(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 we(this._objects,s),this._objects.splice(n,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,r){return s!==this._objects[r]&&(we(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 y(r,i),u=l.add(new y(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 Qi extends xo{_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 ks(o){return Gs().requestAnimationFrame(o)}function _o(o){return Gs().cancelAnimationFrame(o)}let bo=0;const ce=()=>bo++,Zt=()=>{const o=Ee().createElement("canvas");if(!o||o.getContext===void 0)throw new Wt("Failed to create `canvas` element");return o},wo=()=>Ee().createElement("img"),kt=o=>{const t=Zt();return t.width=o.width,t.height=o.height,t},tn=(o,t,e)=>o.toDataURL("image/".concat(t),e),en=(o,t,e)=>new Promise((s,r)=>{o.toBlob(s,"image/".concat(t),e)}),Q=o=>o*Pr,Qt=o=>o/Pr,So=o=>o.every((t,e)=>t===gt[e]),ft=(o,t,e)=>new y(o).transform(t,e),jt=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 y(o[4],o[5]).transform(e,!0);return e[4]=-s,e[5]=-r,e},at=(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]],Rr=(o,t)=>o.reduceRight((e,s)=>s&&e?at(s,e,t):s||e,void 0)||gt.concat(),sn=o=>{let[t,e]=o;return Math.atan2(e,t)},Fs=o=>{const t=sn(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:Qt(t),scaleX:s,scaleY:r,skewX:Qt(i),skewY:0,translateX:o[4]||0,translateY:o[5]||0}},Ze=function(o){return[1,0,0,1,o,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function je(){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=Q(o),r=$t(s),i=Jt(s);return[r,i,-i,r,t?t-(r*t-i*e):0,e?e-(i*t+r*e):0]}const Br=function(o){return[o,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:o,0,0]},rn=o=>Math.tan(Q(o)),nn=o=>[1,0,rn(o),1,0,0],on=o=>[1,rn(o),0,1,0,0],qs=o=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:r=!1,skewX:i=0,skewY:n=0}=o,a=Br(s?-t:t,r?-e:e);return i&&(a=at(a,nn(i),!0)),n&&(a=at(a,on(n),!0)),a},Co=o=>{const{translateX:t=0,translateY:e=0,angle:s=0}=o;let r=Ze(t,e);s&&(r=at(r,je({angle:s})));const i=qs(o);return So(i)||(r=at(r,i)),r},Ds=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 go("loadImage"));const i=wo();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 Wt("Error loading ".concat(i.src)))},e&&(i.crossOrigin=e),i.src=o):a()})},Ne=function(o){let{signal:t,reviver:e=Ts}=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=>D.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)})})},Ks=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&&D.has(a.type)?Ne([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)})})},Fe=function(o){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in o&&(t[e]=o[e]),t),{})},Ir=(o,t)=>Object.keys(o).reduce((e,s)=>(t(o[s],s,o)&&(e[s]=o[s]),e),{}),q=(o,t)=>parseFloat(Number(o).toFixed(t)),Ue=o=>"matrix("+o.map(t=>q(t,V.NUM_FRACTION_DIGITS)).join(" ")+")",Tt=o=>!!o&&o.toLive!==void 0,ei=o=>!!o&&typeof o.toObject=="function",si=o=>!!o&&o.offsetX!==void 0&&"source"in o,ue=o=>!!o&&"multiSelectionStacking"in o;function an(o){const t=o&&At(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 At=o=>o.ownerDocument||null,hn=o=>{var t;return((t=o.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},cn=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))},xr=(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 ri(o){return o.onselectstart!==void 0&&(o.onselectstart=()=>!1),o.style.userSelect=mt,o}class ln{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&&Ee().getElementById(t)||Zt();var s;if(e.hasAttribute("data-fabric"))throw new Wt("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;cn(s,r,t,e)}setCSSDimensions(t){xr(this.lower.el,t)}calcOffset(){return function(t){var e;const s=t&&At(t),r={left:0,top:0};if(!s)return r;const i=((e=hn(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=an(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(){Vt().dispose(this.lower.el),delete this.lower}}const To={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...gt]},Oo=["objects"];class Qe extends Zi(Qi){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 Qe.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 ln(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&&(he("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?qi():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=ft(t,jt(r));r[0]=e,r[3]=e;const n=ft(i,r);r[4]+=s.x-n.x,r[5]+=s.y-n.y,this.setViewportTransform(r)}setZoom(t){this.zoomToPoint(new y(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 y(-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=ks(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=jt(this.viewportTransform),r=ft({x:0,y:0},s),i=ft({x:t,y:e},s),n=r.min(i),a=r.max(i);return this.vptCoords={tl:n,tr:new y(a.x,n.y),bl:new y(n.x,a.y),br:a}}cancelRequestedRender(){this.nextRenderHandle&&(_o(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=Tt(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 y(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new y(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new y(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 y(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new y(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return ft(this.getCenterPoint(),jt(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:vr},Fe(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 Tt(n)?n.excludeFromExport||(s.background=n.toObject(e)):n&&(s.background=n),Tt(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
- `)),this._setSVGBgOverlayColor(s,"background"),this._setSVGBgOverlayImage(s,"backgroundImage",e),this._setSVGObjects(s,e),this.clipPath&&s.push(`</g>
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
- `,'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ',`"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
7
- `)}_setSVGHeader(t,e){const s=e.width||"".concat(this.width),r=e.height||"".concat(this.height),i=V.NUM_FRACTION_DIGITS,n=e.viewBox;let a;if(n)a='viewBox="'.concat(n.x," ").concat(n.y," ").concat(n.width," ").concat(n.height,'" ');else if(this.svgViewportTransformation){const h=this.viewportTransform;a='viewBox="'.concat(q(-h[4]/h[0],i)," ").concat(q(-h[5]/h[3],i)," ").concat(q(this.width/h[0],i)," ").concat(q(this.height/h[3],i),'" ')}else a='viewBox="0 0 '.concat(this.width," ").concat(this.height,'" ');t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',r,'" ',a,`xml:space="preserve">
8
- `,"<desc>Created with Fabric.js ",vr,`</desc>
9
- `,`<defs>
10
- `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
11
- `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId="CLIPPATH_".concat(ce()),'<clipPath id="'.concat(e.clipPathId,`" >
12
- `).concat(e.toClipPathSVG(t.reviver),`</clipPath>
13
- `)):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this["".concat(t,"Color")];if(Tt(e)){const s=this["".concat(t,"Vpt")],r=this.viewportTransform,i={isType:()=>!1,width:this.width/(s?r[0]:1),height:this.height/(s?r[3]:1)};return e.toSVG(i,{additionalTransform:s?Ue(r):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=V.fontPaths;this._objects.forEach(function i(n){t.push(n),Os(n)&&n._objects.forEach(i)}),t.forEach(i=>{if(!(n=i)||typeof n._renderText!="function")return;var n;const{styles:a,fontFamily:h}=i;!e[h]&&s[h]&&(e[h]=!0,a&&Object.values(a).forEach(c=>{Object.values(c).forEach(l=>{let{fontFamily:u=""}=l;!e[u]&&s[u]&&(e[u]=!0)})}))});const r=Object.keys(e).map(i=>` @font-face {
14
- font-family: '`.concat(i,`';
15
- src: url('`).concat(s[i],`');
16
- }
17
- `)).join("");return r?` <style type="text/css"><![CDATA[
18
- `.concat(r,`]]></style>
19
- `):""}_setSVGObjects(t,e){this.forEachObject(s=>{s.excludeFromExport||this._setSVGObject(t,s,e)})}_setSVGObject(t,e,s){t.push(e.toSVG(s))}_setSVGBgOverlayImage(t,e,s){const 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(Tt(s)){const r=s.repeat||"",i=this.width,n=this.height,a=this["".concat(e,"Vpt")]?Ue(jt(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"||!si(s)?i:s.source.width,'" height="').concat(r!=="repeat-x"&&r!=="no-repeat"||!si(s)?n:s.source.height,'" fill="url(#SVGID_').concat(s.id,`)"></rect>
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 Wt("`json` is undefined"));const r=typeof t=="string"?JSON.parse(t):t,{objects:i=[]}=r,n=K(r,Oo),{backgroundImage:a,background:h,overlayImage:c,overlay:l,clipPath:u}=n,d=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Ne(i,{reviver:e,signal:s}),Ks({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=kt(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const{format:e="png",quality:s=1,multiplier:r=1,enableRetinaScaling:i=!1}=t,n=r*(i?this.getRetinaScaling():1);return tn(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 en(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],x=this.enableRetinaScaling,b=kt({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=x,this.skipControlsDrawing=d,b}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),js.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(Qe,"ownDefaults",To);const ko=["touchstart","touchmove","touchend"],Do=o=>{const t=an(o.target),e=function(s){const r=s.changedTouches;return r&&r[0]?r[0]:s}(o);return new y(e.clientX+t.left,e.clientY+t.top)},_r=o=>ko.includes(o.type)||o.pointerType==="touch",ii=o=>{o.preventDefault(),o.stopPropagation()},Kt=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}},Mo=["translateX","translateY","scaleX","scaleY"],Eo=(o,t)=>Ls(o,at(t,o.calcOwnMatrix())),Ls=(o,t)=>{const e=Fs(t),{translateX:s,translateY:r,scaleX:i,scaleY:n}=e,a=K(e,Mo),h=new y(s,r);o.flipX=!1,o.flipY=!1,Object.assign(o,a),o.set({scaleX:i,scaleY:n}),o.setPositionByOrigin(h,R,R)},Po=o=>{o.scaleX=1,o.scaleY=1,o.skewX=0,o.skewY=0,o.flipX=!1,o.flipY=!1,o.rotate(0)},un=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}),Wr=(o,t,e)=>{const s=o/2,r=t/2,i=[new y(-s,-r),new y(s,-r),new y(-s,r),new y(s,r)].map(a=>a.transform(e)),n=Kt(i);return new y(n.width,n.height)},$s=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:gt;return at(jt(arguments.length>1&&arguments[1]!==void 0?arguments[1]:gt),o)},Oe=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:gt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:gt;return o.transform($s(t,e))},Ao=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:gt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:gt;return o.transform($s(t,e),!0)},jo=(o,t,e)=>{const s=$s(t,e);return Ls(o,at(s,o.calcOwnMatrix())),s},dn=(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)},Fo={left:-.5,top:-.5,center:0,bottom:.5,right:.5},st=o=>typeof o=="string"?Fo[o]:o-.5,Rs="not-allowed";function gn(o){return st(o.originX)===st(R)&&st(o.originY)===st(R)}function ni(o){return .5-st(o)}const Lt=(o,t)=>o[t],fn=(o,t,e,s)=>({e:o,transform:t,pointer:new y(e,s)});function pn(o,t){const e=o.getTotalAngle()+Qt(Math.atan2(t.y,t.x))+360;return Math.round(e%360/45)}function Xr(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 x=d.getRelativeCenterPoint(),b=f!==void 0&&v!==void 0?d.translateToGivenOrigin(x,R,R,f,v):new y(d.left,d.top);return(d.angle?g.rotate(-Q(d.angle),x):g).subtract(b)}(n,new y(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 Lo=(o,t,e,s)=>{const{target:r,offsetX:i,offsetY:n}=t,a=e-i,h=s-n,c=!Lt(r,"lockMovementX")&&r.left!==a,l=!Lt(r,"lockMovementY")&&r.top!==h;return c&&r.set(z,a),l&&r.set(pt,h),(c||l)&&dn(Ki,fn(o,t,e,s)),c||l},Bs=o=>o.replace(/\s+/g," "),oi={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aqua:"#0FF",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000",blanchedalmond:"#FFEBCD",blue:"#00F",blueviolet:"#8A2BE2",brown:"#A52A2A",burlywood:"#DEB887",cadetblue:"#5F9EA0",chartreuse:"#7FFF00",chocolate:"#D2691E",coral:"#FF7F50",cornflowerblue:"#6495ED",cornsilk:"#FFF8DC",crimson:"#DC143C",cyan:"#0FF",darkblue:"#00008B",darkcyan:"#008B8B",darkgoldenrod:"#B8860B",darkgray:"#A9A9A9",darkgrey:"#A9A9A9",darkgreen:"#006400",darkkhaki:"#BDB76B",darkmagenta:"#8B008B",darkolivegreen:"#556B2F",darkorange:"#FF8C00",darkorchid:"#9932CC",darkred:"#8B0000",darksalmon:"#E9967A",darkseagreen:"#8FBC8F",darkslateblue:"#483D8B",darkslategray:"#2F4F4F",darkslategrey:"#2F4F4F",darkturquoise:"#00CED1",darkviolet:"#9400D3",deeppink:"#FF1493",deepskyblue:"#00BFFF",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1E90FF",firebrick:"#B22222",floralwhite:"#FFFAF0",forestgreen:"#228B22",fuchsia:"#F0F",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",gray:"#808080",grey:"#808080",green:"#008000",greenyellow:"#ADFF2F",honeydew:"#F0FFF0",hotpink:"#FF69B4",indianred:"#CD5C5C",indigo:"#4B0082",ivory:"#FFFFF0",khaki:"#F0E68C",lavender:"#E6E6FA",lavenderblush:"#FFF0F5",lawngreen:"#7CFC00",lemonchiffon:"#FFFACD",lightblue:"#ADD8E6",lightcoral:"#F08080",lightcyan:"#E0FFFF",lightgoldenrodyellow:"#FAFAD2",lightgray:"#D3D3D3",lightgrey:"#D3D3D3",lightgreen:"#90EE90",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#789",lightslategrey:"#789",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",lime:"#0F0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#F0F",maroon:"#800000",mediumaquamarine:"#66CDAA",mediumblue:"#0000CD",mediumorchid:"#BA55D3",mediumpurple:"#9370DB",mediumseagreen:"#3CB371",mediumslateblue:"#7B68EE",mediumspringgreen:"#00FA9A",mediumturquoise:"#48D1CC",mediumvioletred:"#C71585",midnightblue:"#191970",mintcream:"#F5FFFA",mistyrose:"#FFE4E1",moccasin:"#FFE4B5",navajowhite:"#FFDEAD",navy:"#000080",oldlace:"#FDF5E6",olive:"#808000",olivedrab:"#6B8E23",orange:"#FFA500",orangered:"#FF4500",orchid:"#DA70D6",palegoldenrod:"#EEE8AA",palegreen:"#98FB98",paleturquoise:"#AFEEEE",palevioletred:"#DB7093",papayawhip:"#FFEFD5",peachpuff:"#FFDAB9",peru:"#CD853F",pink:"#FFC0CB",plum:"#DDA0DD",powderblue:"#B0E0E6",purple:"#800080",rebeccapurple:"#639",red:"#F00",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",silver:"#C0C0C0",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",teal:"#008080",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",white:"#FFF",whitesmoke:"#F5F5F5",yellow:"#FF0",yellowgreen:"#9ACD32"},ir=(o,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?o+6*(t-o)*e:e<.5?t:e<2/3?o+(t-o)*(2/3-e)*6:o),ai=(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]},hi=function(){let o=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(o)/(o.endsWith("%")?100:1)},ts=o=>Math.min(Math.round(o),255).toString(16).toUpperCase().padStart(2,"0"),ci=o=>{let[t,e,s,r=1]=o;const i=Math.round(.3*t+.59*e+.11*s);return[i,i,i,r]};class H{constructor(t){if(p(this,"isUnrecognised",!1),t)if(t instanceof H)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 oi&&(t=oi[t]),t==="transparent"?[255,255,255,0]:H.sourceFromHex(t)||H.sourceFromRgb(t)||H.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]=ai(...this.getSource());return"hsl(".concat(t,",").concat(e,"%,").concat(s,"%)")}toHsla(){const[t,e,s,r]=ai(...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(ts(t)).concat(ts(e)).concat(ts(s)).concat(ts(Math.round(255*r)))}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(ci(this.getSource())),this}toBlackWhite(t){const[e,,,s]=ci(this.getSource()),r=e<(t||127)?0:255;return this.setSource([r,r,r,s]),this}overlayWith(t){t instanceof H||(t=new H(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 H.fromRgba(t)}static fromRgba(t){return new H(H.sourceFromRgb(t))}static sourceFromRgb(t){const e=Bs(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,hi(e[4])]}}static fromHsl(t){return H.fromHsla(t)}static fromHsla(t){return new H(H.sourceFromHsl(t))}static sourceFromHsl(t){const e=Bs(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=(H.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=ir(l,c,s+1/3),a=ir(l,c,s),h=ir(l,c,s-1/3)}return[Math.round(255*n),Math.round(255*a),Math.round(255*h),hi(e[4])]}static fromHex(t){return new H(H.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")?Qt(s):e.includes("turn")?360*s:s}}const ke=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Ar;const e=/\D{0,2}$/.exec(o),s=parseFloat(o),r=V.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}},Ro=o=>{const[t,e]=o.trim().split(" "),[s,r]=(i=t)&&i!==mt?[i.slice(1,4),i.slice(5,8)]:i===mt?[i,i]:["Mid","Mid"];var i;return{meetOrSlice:e||"meet",alignX:s,alignY:r}},qe=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 H(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 mn{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",r=this.strokeDashArray?this.strokeDashArray.join(" "):mt,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=qe(nt,this.fill);return[qe(vt,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(Ue(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 x;h&&(h.clipPathId="CLIPPATH_".concat(ce()),x='<clipPath id="'.concat(h.clipPathId,`" >
22
- `).concat(h.toClipPathSVG(s),`</clipPath>
23
- `)),l&&f.push("<g ",a,this.getSvgCommons(),` >
24
- `),f.push("<g ",this.getSvgTransform(!1),l?"":a+this.getSvgCommons(),` >
25
- `);const b=[n,c,e?"":this.addPaintOrder()," ",i?'transform="'.concat(i,'" '):""].join("");return t[v]=b,Tt(d)&&f.push(d.toSVG(this)),Tt(u)&&f.push(u.toSVG(this)),g&&f.push(g.toSVG(this)),h&&f.push(x),f.push(t.join("")),f.push(`</g>
26
- `),l&&f.push(`</g>
27
- `),s?s(f.join("")):f.join("")}addPaintOrder(){return this.paintFirst!==nt?' paint-order="'.concat(this.paintFirst,'" '):""}}function Js(o){return new RegExp("^("+o.join("|")+")\\b","i")}const pe="textDecorationThickness",vn=["fontSize","fontWeight","fontFamily","fontStyle"],yn=["underline","overline","linethrough"],xn=[...vn,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],_n=[...xn,...yn,"textBackgroundColor","direction",pe],Bo=[...vn,...yn,vt,"strokeWidth",nt,"deltaY","textBackgroundColor",pe],Io={_reNewline:jr,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:z,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:z,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",CACHE_FONT_SIZE:400,MIN_TEXT_WIDTH:2,superscript:{size:.6,baseline:-.35},subscript:{size:.6,baseline:.11},_fontSizeFraction:.222,offsets:{underline:.1,linethrough:-.28167,overline:-.81333},_fontSizeMult:1.13,[pe]:66.667},Bt="justify",Is="justify-left",Ye="justify-right",He="justify-center";var li,ui,di;const Ft=String.raw(li||(li=Yt(["[-+]?(?:d*.d+|d+.?)(?:[eE][-+]?d+)?"],["[-+]?(?:\\d*\\.\\d+|\\d+\\.?)(?:[eE][-+]?\\d+)?"]))),nr=String.raw(ui||(ui=Yt(["(?:s*,?s+|s*,s*)"],["(?:\\s*,?\\s+|\\s*,\\s*)"]))),Wo=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+Ft+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+Ft+"))?\\s+(.*)"),Xo={cx:z,x:z,r:"radius",cy:pt,y:pt,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":pe},or="font-size",ar="clip-path";Js(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]);Js(["symbol","image","marker","pattern","view","svg"]);const gi=Js(["symbol","g","a","svg","clipPath","defs"]);new RegExp(String.raw(di||(di=Yt(["^s*(",")","(",")","(",")","(",")s*$"],["^\\s*(",")","(",")","(",")","(",")\\s*$"])),Ft,nr,Ft,nr,Ft,nr,Ft));const Vo=new y(1,0),bn=new y,wn=(o,t)=>o.rotate(t),br=(o,t)=>new y(t).subtract(o),wr=o=>o.distanceFrom(bn),Sr=(o,t)=>Math.atan2(ze(o,t),Ho(o,t)),Yo=o=>Sr(Vo,o),Vr=o=>o.eq(bn)?o:o.scalarDivide(wr(o)),Sn=function(o){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return Vr(new y(-o.y,o.x).scalarMultiply(t?1:-1))},ze=(o,t)=>o.x*t.y-o.y*t.x,Ho=(o,t)=>o.x*t.x+o.y*t.y,fi=(o,t,e)=>{if(o.eq(t)||o.eq(e))return!0;const s=ze(t,e),r=ze(t,o),i=ze(e,o);return s>=0?r>=0&&i<=0:!(r<=0&&i>=0)},pi="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",mi=new RegExp("(?:\\s|^)"+pi+pi+"("+Ft+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Xt{constructor(t){const e=typeof t=="string"?Xt.parseShadow(t):t;Object.assign(this,Xt.ownDefaults,e),this.id=ce()}static parseShadow(t){const e=t.trim(),[,s=0,r=0,i=0]=(mi.exec(e)||[]).map(n=>parseFloat(n)||0);return{color:(e.replace(mi,"")||"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=wn(new y(this.offsetX,this.offsetY),Q(-t.angle)),s=new H(this.color);let r=40,i=40;return t.width&&t.height&&(r=100*q((Math.abs(e.x)+this.blur)/t.width,V.NUM_FRACTION_DIGITS)+20,i=100*q((Math.abs(e.y)+this.blur)/t.height,V.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
- <feGaussianBlur in="SourceAlpha" stdDeviation="`).concat(q(this.blur?this.blur/2:0,V.NUM_FRACTION_DIGITS),`"></feGaussianBlur>
29
- <feOffset dx="`).concat(q(e.x,V.NUM_FRACTION_DIGITS),'" dy="').concat(q(e.y,V.NUM_FRACTION_DIGITS),`" result="oBlur" ></feOffset>
30
- <feFlood flood-color="`).concat(s.toRgb(),'" flood-opacity="').concat(s.getAlpha(),`"/>
31
- <feComposite in2="oBlur" operator="in" />
32
- <feMerge>
33
- <feMergeNode></feMergeNode>
34
- <feMergeNode in="SourceGraphic"></feMergeNode>
35
- </feMerge>
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=Xt.ownDefaults;return this.includeDefaultValues?t:Ir(t,(s,r)=>s!==e[r])}static async fromObject(t){return new this(t)}}p(Xt,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),p(Xt,"type","shadow"),D.setClass(Xt,"shadow");const Me=(o,t,e)=>Math.max(o,Math.min(t,e)),zo=[pt,z,xt,Ot,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Pe,Ae],te=[nt,vt,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],Go={top:0,left:0,width:0,height:0,angle:0,flipX:!1,flipY:!1,scaleX:1,scaleY:1,minScaleLimit:0,skewX:0,skewY:0,originX:z,originY:pt,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:nt,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},No=(o,t,e,s)=>-e*Math.cos(o/s*Je)+e+t,Uo=()=>!1;class Yr{constructor(t){let{startValue:e,byValue:s,duration:r=500,delay:i=0,easing:n=No,onStart:a=Ts,onChange:h=Ts,onComplete:c=Ts,abort:l=Uo,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(()=>ks(t),this.delay):ks(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),ks(this.tick)))}register(){js.push(this)}unregister(){js.remove(this)}abort(){this._state="aborted",this.unregister()}}const qo=["startValue","endValue"];class Ko extends Yr{constructor(t){let{startValue:e=0,endValue:s=100}=t;super(m(m({},K(t,qo)),{},{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 $o=["startValue","endValue"];class Jo extends Yr{constructor(t){let{startValue:e=[0],endValue:s=[100]}=t;super(m(m({},K(t,$o)),{},{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 Zo=["startValue","endValue","easing","onChange","onComplete","abort"],Qo=(o,t,e,s)=>t+e*(1-Math.cos(o/s*Je)),hr=o=>o&&((t,e,s)=>o(new H(t).toRgba(),e,s));class ta extends Yr{constructor(t){let{startValue:e,endValue:s,easing:r=Qo,onChange:i,onComplete:n,abort:a}=t,h=K(t,Zo);const c=new H(e).getSource(),l=new H(s).getSource();super(m(m({},h),{},{startValue:c,byValue:l.map((u,d)=>u-c[d]),easing:r,onChange:hr(i),onComplete:hr(n),abort:hr(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),Me(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 Cn(o){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(o)?new Jo(o):new Ko(o);return t.start(),t}function ea(o){const t=new ta(o);return t.start(),t}class ${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=br(e,s),n=br(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 y(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 x=g/v,b=f/v;return(i||0<=x&&x<=1)&&(n||0<=b&&b<=1)?new $("Intersection").append(new y(t.x+x*a,t.y+x*h)):new $}if(g===0||f===0){const x=i||n||$.isPointContained(t,s,r)||$.isPointContained(e,s,r)||$.isPointContained(s,t,e)||$.isPointContained(r,t,e);return new $(x?"Coincident":void 0)}return new $("Parallel")}static intersectSegmentLine(t,e,s,r){return $.intersectLineLine(t,e,s,r,!1,!0)}static intersectSegmentSegment(t,e,s,r){return $.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 $,n=s.length;for(let a,h,c,l=0;l<n;l++){if(a=s[l],h=s[(l+1)%n],c=$.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 $.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new $,r=t.length,i=[];for(let n=0;n<r;n++){const a=t[n],h=t[(n+1)%r],c=$.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 $("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 y(i.x,r.y),a=new y(r.x,i.y);return $.intersectPolygonPolygon(t,[r,n,i,a])}}class sa extends Qi{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?ft(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=ft(t,jt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new y(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=>ft(a,n))}return i}intersectsWithRect(t,e){return $.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=$.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 $.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 Kt(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(xt,t),this._set(Ot,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?Qt(sn(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||gt.concat()}calcACoords(){const t=je({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),r=Ze(e,s),i=at(r,t),n=this._getTransformedDimensions(),a=n.x/2,h=n.y/2;return{tl:ft({x:-a,y:-h},i),tr:ft({x:a,y:-h},i),bl:ft({x:-a,y:h},i),br:ft({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,st(this.originX),st(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=at(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=Co(r);return this.ownMatrixCache={key:t,value:i},i}_getNonTransformedDimensions(){return new y(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 y(n*e.scaleX,a*e.scaleY):Wr(n,a,qs(e)),h.scalarAdd(i)}translateToGivenOrigin(t,e,s,r,i){let n=t.x,a=t.y;const h=st(r)-st(e),c=st(i)-st(s);if(h||c){const l=this._getTransformedDimensions();n+=h*l.x,a+=c*l.y}return new y(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(Q(this.angle),t):r}translateToOriginPoint(t,e,s){const r=this.translateToGivenOrigin(t,R,R,e,s);return this.angle?r.rotate(Q(this.angle),t):r}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?ft(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new y(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(),z,pt)}}const ra=["type"],ia=["extraParam"];let zt=class Ms extends sa{static getDefaults(){return Ms.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){he("warn","Setting type has no effect",t)}constructor(t){super(),p(this,"_cacheContext",null),Object.assign(this,Ms.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Zt(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,r=V.maxCacheSideLimit,i=V.minCacheSideLimit;if(e<=r&&s<=r&&e*s<=V.perfLimitSizeTotal)return e<i&&(t.width=i),s<i&&(t.height=i),t;const n=e/s,[a,h]=Ve.limitDimsByArea(n),c=Me(i,a,r),l=Me(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 y(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=Fs(this.calcTransformMatrix());return new y(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!==xt&&t!==Ot||(e=this._constrainScale(e)),t===xt&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Xt||(e=new Xt(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===vt&&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=kt(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=jt(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,Tt(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&&(Tt(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)||gt,a=i*r,h=n*r,c=e.nonScaling?new y(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*V.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(!Tt(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===vt?(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=kt({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 y(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(D.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=un(this),s=this.group,r=this.shadow,i=Math.abs,n=t.enableRetinaScaling?qi():1,a=(t.multiplier||1)*n,h=t.canvasProvider||(w=>new Qe(w,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Po(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&jo(this,this.getViewportTransform()),this.setCoords();const c=Zt(),l=this.getBoundingRect(),u=this.shadow,d=new y;if(u){const w=u.blur,C=u.nonScaling?new y(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 y(v.width/2,v.height/2),R,R);const x=this.canvas;v._objects=[this],this.set("canvas",v),this.setCoords();const b=v.toCanvasElement(a||1,t);return this.set("canvas",x),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 tn(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return en(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(){js.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&Vt().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,x)=>(x===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?ea(l):Cn(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(Ms.customProperties,this.constructor.customProperties||[]);let e;const s=V.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:x,strokeDashOffset:b,strokeLineJoin:w,strokeUniform:C,strokeMiterLimit:O,scaleX:k,scaleY:E,angle:B,flipX:P,flipY:I,opacity:U,visible:J,backgroundColor:L,fillRule:Y,paintFirst:W,globalCompositeOperation:rt,skewX:tt,skewY:et}=this;r&&!r.excludeFromExport&&(e=r.toObject(t.concat("inverted","absolutePositioned")));const G=_=>q(_,s),_t=m(m({},Fe(this,t)),{},{type:this.constructor.type,version:vr,originX:u,originY:d,left:G(c),top:G(l),width:G(g),height:G(f),fill:ei(i)?i.toObject():i,stroke:ei(n)?n.toObject():n,strokeWidth:G(v),strokeDashArray:h&&h.concat(),strokeLineCap:x,strokeDashOffset:b,strokeLineJoin:w,strokeUniform:C,strokeMiterLimit:G(O),scaleX:G(k),scaleY:G(E),angle:G(B),flipX:P,flipY:I,opacity:G(U),shadow:a&&a.toObject(),visible:J,backgroundColor:L,fillRule:Y,paintFirst:W,globalCompositeOperation:rt,skewX:G(tt),skewY:G(et)},e?{clipPath:e}:null);return this.includeDefaultValues?_t:this._removeDefaultValues(_t)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Ir(t,(r,i)=>{if(i===z||i===pt||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=K(t,ra),s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{extraParam:r}=s,i=K(s,ia);return Ks(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(zt,"stateProperties",zo),p(zt,"cacheProperties",te),p(zt,"ownDefaults",Go),p(zt,"type","FabricObject"),p(zt,"colorProperties",[nt,vt,"backgroundColor"]),p(zt,"customProperties",[]),D.setClass(zt),D.setClass(zt,"object");const Le=(o,t,e)=>(s,r,i,n)=>{const a=t(s,r,i,n);return a&&dn(o,m(m({},fn(s,r,i,n)),e)),a};function Re(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 vi=Le(Ge,Re((o,t,e,s)=>{const r=Xr(t,t.originX,t.originY,e,s);if(st(t.originX)===st(R)||st(t.originX)===st(Z)&&r.x<0||st(t.originX)===st(z)&&r.x>0){const{target:i}=t,n=i.strokeWidth/(i.strokeUniform?i.scaleX:1),a=gn(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 na(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?vt:nt,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,Es,!1),o[h](),c&&o.stroke(),o.restore()}function oa(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?vt:nt,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(Q(d)),o["".concat(h,"Rect")](-l,-u,i,n),c&&o.strokeRect(-l,-u,i,n),o.restore()}class Et{constructor(t){p(this,"visible",!0),p(this,"actionName",Us),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)&&$.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 y(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,r,i,n){const a=Rr([Ze(s,r),je({angle:t}),Br((i?this.touchSizeX:this.sizeX)||e,(i?this.touchSizeY:this.sizeY)||e)]);return{tl:new y(-.5,-.5).transform(a),tr:new y(.5,-.5).transform(a),br:new y(.5,.5).transform(a),bl:new y(-.5,.5).transform(a)}}render(t,e,s,r,i){((r=r||{}).cornerStyle||i.cornerStyle)==="circle"?na.call(this,t,e,s,r,i):oa.call(this,t,e,s,r,i)}}const aa=(o,t,e)=>e.lockRotation?Rs:t.cursorStyle,ha=Le($i,Re((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(Lt(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=Qt(d-u+a);if(r.snapAngle&&r.snapAngle>0){const v=r.snapAngle,x=r.snapThreshold||v,b=Math.ceil(g/v)*v,w=Math.floor(g/v)*v;Math.abs(g-w)<x?g=w:Math.abs(g-b)<x&&(g=b)}g<0&&(g=360+g),g%=360;const f=r.angle!==g;return r.angle=g,f}));function Tn(o,t){const e=t.canvas,s=o[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function On(o,t,e){const s=Lt(o,"lockScalingX"),r=Lt(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 ca=["e","se","s","sw","w","nw","n","ne","e"],Xe=(o,t,e)=>{const s=Tn(o,e);if(On(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",s))return Rs;const r=pn(e,t);return"".concat(ca[r],"-resize")};function Hr(o,t,e,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const i=t.target,n=r.by,a=Tn(o,i);let h,c,l,u,d,g;if(On(i,n,a))return!1;if(t.gestureScale)c=t.scaleX*t.gestureScale,l=t.scaleY*t.gestureScale;else{if(h=Xr(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),Lt(i,"lockScalingFlip")&&(t.signX!==d||t.signY!==g))return!1;if(u=i._getTransformedDimensions(),a&&!n){const x=Math.abs(h.x)+Math.abs(h.y),{original:b}=t,w=x/(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);gn(t)&&(c*=2,l*=2),t.signX!==d&&n!=="y"&&(t.originX=ni(t.originX),c*=-1,t.signX=d),t.signY!==g&&n!=="x"&&(t.originY=ni(t.originY),l*=-1,t.signY=g)}const f=i.scaleX,v=i.scaleY;return n?(n==="x"&&i.set(xt,c),n==="y"&&i.set(Ot,l)):(!Lt(i,"lockScalingX")&&i.set(xt,c),!Lt(i,"lockScalingY")&&i.set(Ot,l)),f!==i.scaleX||v!==i.scaleY}const es=Le(Ns,Re((o,t,e,s)=>Hr(o,t,e,s))),la=Le(Ns,Re((o,t,e,s)=>Hr(o,t,e,s,{by:"x"}))),ua=Le(Ns,Re((o,t,e,s)=>Hr(o,t,e,s,{by:"y"}))),da=["target","ex","ey","skewingSide"],cr={x:{counterAxis:"y",scale:xt,skew:Pe,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:Ot,skew:Ae,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},ga=["ns","nesw","ew","nwse"],fa=(o,t,e)=>{if(t.x!==0&&Lt(e,"lockSkewingY")||t.y!==0&&Lt(e,"lockSkewingX"))return Rs;const s=pn(e,t)%4;return"".concat(ga[s],"-resize")};function kn(o,t,e,s,r){const{target:i}=e,{counterAxis:n,origin:a,lockSkewing:h,skew:c,flip:l}=cr[o];if(Lt(i,h))return!1;const{origin:u,flip:d}=cr[n],g=st(e[u])*(i[d]?-1:1),f=-Math.sign(g)*(i[l]?-1:1),v=.5*-((i[c]===0&&Xr(e,R,R,s,r)[o]>0||i[c]>0?1:-1)*f)+.5;return Le(Ji,Re((b,w,C,O)=>function(k,E,B){let{target:P,ex:I,ey:U,skewingSide:J}=E,L=K(E,da);const{skew:Y}=cr[k],W=B.subtract(new y(I,U)).divide(new y(P.scaleX,P.scaleY))[k],rt=P[Y],tt=L[Y],et=Math.tan(Q(tt)),G=k==="y"?P._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:P._getTransformedDimensions({scaleX:1,scaleY:1}).y,_t=2*W*J/Math.max(G,1)+et,_=Qt(Math.atan(_t));P.set(Y,_);const S=rt!==P[Y];if(S&&k==="y"){const{skewX:M,scaleX:T}=P,j=P._getTransformedDimensions({skewY:rt}),N=P._getTransformedDimensions(),X=M!==0?j.x/N.x:1;X!==1&&P.set(xt,X*T)}return S}(o,w,new y(C,O))))(t,m(m({},e),{},{[a]:v,skewingSide:f}),s,r)}const pa=(o,t,e,s)=>kn("x",o,t,e,s),ma=(o,t,e,s)=>kn("y",o,t,e,s);function Zs(o,t){return o[t.canvas.altActionKey]}const ss=(o,t,e)=>{const s=Zs(o,e);return t.x===0?s?Pe:Ot:t.y===0?s?Ae:xt:""},Se=(o,t,e)=>Zs(o,e)?fa(0,t,e):Xe(o,t,e),yi=(o,t,e,s)=>Zs(o,t.target)?ma(o,t,e,s):la(o,t,e,s),xi=(o,t,e,s)=>Zs(o,t.target)?pa(o,t,e,s):ua(o,t,e,s),Dn=()=>({ml:new Et({x:-.5,y:0,cursorStyleHandler:Se,actionHandler:yi,getActionName:ss}),mr:new Et({x:.5,y:0,cursorStyleHandler:Se,actionHandler:yi,getActionName:ss}),mb:new Et({x:0,y:.5,cursorStyleHandler:Se,actionHandler:xi,getActionName:ss}),mt:new Et({x:0,y:-.5,cursorStyleHandler:Se,actionHandler:xi,getActionName:ss}),tl:new Et({x:-.5,y:-.5,cursorStyleHandler:Xe,actionHandler:es}),tr:new Et({x:.5,y:-.5,cursorStyleHandler:Xe,actionHandler:es}),bl:new Et({x:-.5,y:.5,cursorStyleHandler:Xe,actionHandler:es}),br:new Et({x:.5,y:.5,cursorStyleHandler:Xe,actionHandler:es}),mtr:new Et({x:0,y:-.5,actionHandler:ha,cursorStyleHandler:aa,offsetY:-40,withConnection:!0,actionName:Fr})}),va=()=>({mr:new Et({x:.5,y:0,actionHandler:vi,cursorStyleHandler:Se,actionName:Ge}),ml:new Et({x:-.5,y:0,actionHandler:vi,cursorStyleHandler:Se,actionName:Ge})}),ya=()=>m(m({},Dn()),va());class Ke extends zt{static getDefaults(){return m(m({},super.getDefaults()),Ke.ownDefaults)}constructor(t){super(),Object.assign(this,this.constructor.createControls(),Ke.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Dn()}}_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(Us))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=Ze(e.x,e.y),r=je({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),i=at(s,r),n=at(t,i),a=at(n,[1/t[0],0,0,1/t[3],0,0]),h=this.group?Fs(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(Q(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=at(n,this.calcTransformMatrix()),l=Fs(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(Q(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=Wr(this.width,this.height,qs(e)),n=this.isStrokeAccountedForInDimensions()?Lr:(this.strokeUniform?new y().scalarAdd(this.canvas?this.canvas.getZoom():1):new y(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 Mn(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(Ke,"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 ct extends Ke{}Mn(ct,[mn]),D.setClass(ct),D.setClass(ct,"object");const xa=(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 En{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new y(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new y(1/this.options.scaleX,1/this.options.scaleY):new y(1,1)}createSideVector(t,e){const s=br(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 y(t);return e.y+=e.x*Math.tan(Q(this.options.skewY)),e.x+=e.y*Math.tan(Q(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const _a=new y;class De extends En{static getOrthogonalRotationFactor(t,e){const s=e?Sr(t,e):Yo(t);return Math.abs(s)<Je?-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 y(t),this.B=new y(e),this.C=new y(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=Sr(this.AB,this.AC),this.bisector=Vr(wn(this.AB.eq(_a)?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=Sn(r),n=De.getOrthogonalRotationFactor(i,this.bisector);return this.scaleUnitVector(i,s*n)}projectBevel(){const t=[];return(this.alpha%Es==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?wr(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return wr(r)/this.strokeProjectionMagnitude<=i&&t.push(this.applySkew(this.A.add(r))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],r=new y(De.getOrthogonalRotationFactor(this.bisector),De.getOrthogonalRotationFactor(new y(this.bisector.y,this.bisector.x)));return[new y(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r),new y(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r)].forEach(i=>{fi(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 y(Math.tan(Q(r)),Math.tan(Q(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 y(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 y(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=>{fi(v,t,e)&&s.push(this.applySkew(this.A).add(v))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%Es==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=ze(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 _i extends En{constructor(t,e,s){super(s),this.A=new y(t),this.T=new y(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(Sn(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 y(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 De(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new y(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(Vr(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 ba=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 y(n)),i),[new y(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 _i(i,i,t).project()):!e||n!==0&&n!==a.length-1?s.push(...new De(i,h,c,t).project()):s.push(...new _i(i,n===0?c:h,t).project())}),s},zr=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},wa=o=>o.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let Ie;const Gr=o=>{if(Ie||Ie||(Ie="Intl"in Gs()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),Ie){const t=Ie.segment(o);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return Sa(o)},Sa=o=>{const t=[];for(let e,s=0;s<o.length;s++)(e=Ca(o,s))!==!1&&t.push(e);return t},Ca=(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},Nr=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)},Ta=(o,t)=>{const e=t.split(`
38
- `),s=[];let r=-1,i={};o=zr(o);for(let n=0;n<e.length;n++){const a=Gr(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&&(Nr(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},Oa=(o,t)=>{if(!Array.isArray(o))return zr(o);const e=t.split(jr),s={};let r=-1,i=0;for(let n=0;n<e.length;n++){const a=Gr(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},le=["display","transform",nt,"fill-opacity","fill-rule","opacity",vt,"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 bi(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 ka(o,t){let e=!0;const s=bi(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=bi(r=r.parentElement,n);return i.length===0}(o,t)),s&&e&&t.length===0}const Da=o=>{var t;return(t=Xo[o])!==null&&t!==void 0?t:o},Ma=new RegExp("(".concat(Ft,")"),"gi"),Ea=o=>Bs(o.replace(Ma," $1 ").replace(/,/gi," "));var wi,Si,Ci,Ti,Oi,ki,Di;const dt="(".concat(Ft,")"),Pa=String.raw(wi||(wi=Yt(["(skewX)(",")"],["(skewX)\\(","\\)"])),dt),Aa=String.raw(Si||(Si=Yt(["(skewY)(",")"],["(skewY)\\(","\\)"])),dt),ja=String.raw(Ci||(Ci=Yt(["(rotate)(","(?: "," ",")?)"],["(rotate)\\(","(?: "," ",")?\\)"])),dt,dt,dt),Fa=String.raw(Ti||(Ti=Yt(["(scale)(","(?: ",")?)"],["(scale)\\(","(?: ",")?\\)"])),dt,dt),La=String.raw(Oi||(Oi=Yt(["(translate)(","(?: ",")?)"],["(translate)\\(","(?: ",")?\\)"])),dt,dt),Ra=String.raw(ki||(ki=Yt(["(matrix)("," "," "," "," "," ",")"],["(matrix)\\("," "," "," "," "," ","\\)"])),dt,dt,dt,dt,dt,dt),Ur="(?:".concat(Ra,"|").concat(La,"|").concat(ja,"|").concat(Fa,"|").concat(Pa,"|").concat(Aa,")"),Ba="(?:".concat(Ur,"*)"),Ia=String.raw(Di||(Di=Yt(["^s*(?:","?)s*$"],["^\\s*(?:","?)\\s*$"])),Ba),Wa=new RegExp(Ia),Xa=new RegExp(Ur),Va=new RegExp(Ur,"g");function Cr(o){const t=[];if(!(o=Ea(o).replace(/\s*([()])\s*/gi,"$1"))||o&&!Wa.test(o))return[...gt];for(const e of o.matchAll(Va)){const s=Xa.exec(e[0]);if(!s)continue;let r=gt;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=Ze(h,c);break;case Fr:r=je({angle:h},{x:c,y:l});break;case Us:r=Br(h,c);break;case Pe:r=nn(h);break;case Ae:r=on(h);break;case"matrix":r=[h,c,l,u,d,g]}t.push(r)}return Rr(t)}function Ya(o,t,e,s){const r=Array.isArray(t);let i,n=t;if(o!==nt&&o!==vt||t!==mt){if(o==="strokeUniform")return t==="non-scaling-stroke";if(o==="strokeDashArray")n=t===mt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(o==="transformMatrix")n=e&&e.transformMatrix?at(e.transformMatrix,Cr(t)):Cr(t);else if(o==="visible")n=t!==mt&&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"?z:t==="end"?Z:R;else if(o==="charSpacing"||o===pe)i=ke(t,s)/s*1e3;else if(o==="paintFirst"){const a=t.indexOf(nt),h=t.indexOf(vt);n=nt,(a>-1&&h>-1&&h<a||a===-1&&h>-1)&&(n=vt)}else{if(o==="href"||o==="xlink:href"||o==="font"||o==="id")return t;if(o==="imageSmoothing")return t==="optimizeQuality";i=r?t.map(ke):ke(t,s)}}else n="";return!r&&isNaN(i)?n:i}function Ha(o,t){const e=o.match(Wo);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=ke(i)),a&&(t.fontFamily=a),n&&(t.lineHeight=n==="normal"?1:n)}function za(o,t){o.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,r]=e.split(":");t[s.trim().toLowerCase()]=r.trim()})}function Ga(o){const t={},e=o.getAttribute("style");return e&&(typeof e=="string"?za(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 Na={stroke:"strokeOpacity",fill:"fillOpacity"};function ee(o,t,e){if(!o)return{};let s,r={},i=Ar;o.parentNode&&gi.test(o.parentNode.nodeName)&&(r=ee(o.parentElement,t,e),r.fontSize&&(s=i=ke(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)ka(c,d.split(" "))&&(u=m(m({},u),l[d]));return u}(o,e)),Ga(o));n[ar]&&o.setAttribute(ar,n[ar]),n[or]&&(s=ke(n[or],i),n[or]="".concat(s));const a={};for(const c in n){const l=Da(c),u=Ya(l,n[c],r,s);a[l]=u}a&&a.font&&Ha(a.font,a);const h=m(m({},r),a);return gi.test(o.nodeName)?h:function(c){const l=ct.getDefaults();return Object.entries(Na).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 H(c[d]);c[d]=f.setAlpha(q(f.getAlpha()*c[g],2)).toRgba()}),c}(h)}const Ua=["left","top","width","height","visible"],Pn=["rx","ry"];class Ct extends ct{static getDefaults(){return m(m({},super.getDefaults()),Ct.ownDefaults)}constructor(t){super(),Object.assign(this,Ct.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-ie*n,i,r+e,i+ie*a,r+e,i+a),t.lineTo(r+e,i+s-a),h&&t.bezierCurveTo(r+e,i+s-ie*a,r+e-ie*n,i+s,r+e-n,i+s),t.lineTo(r+n,i+s),h&&t.bezierCurveTo(r+ie*n,i+s,r,i+s-ie*a,r,i+s-a),t.lineTo(r,i+a),h&&t.bezierCurveTo(r,i+ie*a,r+ie*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([...Pn,...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=ee(t,this.ATTRIBUTE_NAMES,s),{left:i=0,top:n=0,width:a=0,height:h=0,visible:c=!0}=r,l=K(r,Ua);return new this(m(m(m({},e),l),{},{left:i,top:n,width:a,height:h,visible:!!(c&&a&&h)}))}}p(Ct,"type","Rect"),p(Ct,"cacheProperties",[...te,...Pn]),p(Ct,"ownDefaults",{rx:0,ry:0}),p(Ct,"ATTRIBUTE_NAMES",[...le,"x","y","rx","ry","width","height"]),D.setClass(Ct),D.setSVGClass(Ct);const Nt="initialization",Ws="added",qr="removed",Xs="imperative",An=(o,t)=>{const{strokeUniform:e,strokeWidth:s,width:r,height:i,group:n}=t,a=n&&n!==o?$s(n.calcTransformMatrix(),o.calcTransformMatrix()):null,h=a?t.getRelativeCenterPoint().transform(a):t.getRelativeCenterPoint(),c=!t.isStrokeAccountedForInDimensions(),l=e&&c?Ao(new y(s,s),void 0,o.calcTransformMatrix()):Lr,u=!e&&c?s:0,d=Wr(r+u,i+u,Rr([a,t.calcOwnMatrix()],!0)).add(l).scalarDivide(2);return[h.subtract(d),h.add(d)]};class Qs{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:r}=t;return e===Nt||e===Xs||!!s&&r!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Nt&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:r}=e;if(s===Xs&&e.overrides)return e.overrides;if(t.length===0)return;const{left:i,top:n,width:a,height:h}=Kt(t.map(u=>An(r,u)).reduce((u,d)=>u.concat(d),[])),c=new y(a,h),l=new y(i,n).add(c.scalarDivide(2));if(s===Nt){const u=this.getInitialSize(e,{size:c,center:l});return{center:l,relativeCorrection:new y(0,0),size:u}}return{center:l.transform(r.calcOwnMatrix()),size:c}}}p(Qs,"type","strategy");class Tr extends Qs{shouldPerformLayout(t){return!0}}p(Tr,"type","fit-content"),D.setClass(Tr);const qa=["strategy"],Ka=["target","strategy","bubbles","prevStrategy"],jn="layoutManager";class $e{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Tr;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[As,Ki,Ge,$i,Ns,Ji,Ps,vo,yo].map(r=>t.on(r,i=>this.performLayout(r===As?{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===Nt||s===Ws?this.subscribeTargets(t):s===qr&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),r&&r.fire("object:layout:before",{target:e,context:t}),s===Xs&&t.deep){const i=K(t,qa);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===Nt?new y:e.getRelativeCenterPoint(),{center:a,correction:h=new y,relativeCorrection:c=new y}=i,l=n.subtract(a).add(h).transform(r===Nt?gt:jt(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===Nt?s.set({left:(n=t.x)!==null&&n!==void 0?n:i.x+r.x*st(s.originX),top:(a=t.y)!==null&&a!==void 0?a:i.y+r.y*st(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=K(t,Ka),{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:jn,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}D.setClass($e,jn);const $a=["type","objects","layoutManager"];class Ja extends $e{performLayout(){}}class fe extends Zi(ct){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(),p(this,"_activeObjects",[]),p(this,"__objectSelectionTracker",void 0),p(this,"__objectSelectionDisposer",void 0),Object.assign(this,fe.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 $e,this.layoutManager.performLayout({type:Nt,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(he("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(he("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(Ws,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(Ws,i),n}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(qr,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&&Ls(t,at(jt(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||(Ls(t,at(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=ct.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(...jt(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:Xs},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=Ct.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
- `],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=K(t,$a);return Promise.all([Ne(r,e),Ks(n,e)]).then(a=>{let[h,c]=a;const l=new this(h,m(m(m({},n),c),{},{layoutManager:new Ja}));if(i){const u=D.getClass(i.type),d=D.getClass(i.strategy);l.layoutManager=new u(new d)}else l.layoutManager=new $e;return l.layoutManager.subscribeTargets({type:Nt,target:l,targets:l.getObjects()}),l.setCoords(),l})}}p(fe,"type","Group"),p(fe,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),D.setClass(fe);const Za=(o,t)=>Math.min(t.width/o.width,t.height/o.height),Qa=(o,t)=>Math.max(t.width/o.width,t.height/o.height),Or="\\s*,?\\s*",We="".concat(Or,"(").concat(Ft,")"),th="".concat(We).concat(We).concat(We).concat(Or,"([01])").concat(Or,"([01])").concat(We).concat(We),eh={m:"l",M:"L"},sh=(o,t,e,s,r,i,n,a,h,c,l)=>{const u=$t(o),d=Jt(o),g=$t(t),f=Jt(t),v=e*r*g-s*i*f+n,x=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),x+h*(s*r*f-e*i*g),v,x]},Mi=(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 Ei(o,t,e,s,r,i,n,a){let h;if(V.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 O=0;O<2;++O){if(O>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 I=-v/g;0<I&&I<1&&u.push(I);continue}const k=g*g-4*v*f;if(k<0)continue;const E=c(k),B=(-g+E)/(2*f);0<B&&B<1&&u.push(B);const P=(-g-E)/(2*f);0<P&&P<1&&u.push(P)}let x=u.length;const b=x,w=Fn(o,t,e,s,r,i,n,a);for(;x--;){const{x:O,y:k}=w(u[x]);d[0][x]=O,d[1][x]=k}d[0][b]=o,d[1][b]=t,d[0][b+1]=n,d[1][b+1]=a;const C=[new y(Math.min(...d[0]),Math.min(...d[1])),new y(Math.max(...d[0]),Math.max(...d[1]))];return V.cachesBoundsOfCurve&&(Ve.boundsOfCurveCache[h]=C),C}const rh=(o,t,e)=>{let[s,r,i,n,a,h,c,l]=e;const u=((d,g,f,v,x,b,w)=>{if(f===0||v===0)return[];let C=0,O=0,k=0;const E=Math.PI,B=w*Pr,P=Jt(B),I=$t(B),U=.5*(-I*d-P*g),J=.5*(-I*g+P*d),L=f**2,Y=v**2,W=J**2,rt=U**2,tt=L*Y-L*W-Y*rt;let et=Math.abs(f),G=Math.abs(v);if(tt<0){const it=Math.sqrt(1-tt/(L*Y));et*=it,G*=it}else k=(x===b?-1:1)*Math.sqrt(tt/(L*W+Y*rt));const _t=k*et*J/G,_=-k*G*U/et,S=I*_t-P*_+.5*d,M=P*_t+I*_+.5*g;let T=Mi(1,0,(U-_t)/et,(J-_)/G),j=Mi((U-_t)/et,(J-_)/G,(-U-_t)/et,(-J-_)/G);b===0&&j>0?j-=2*E:b===1&&j<0&&(j+=2*E);const N=Math.ceil(Math.abs(j/E*2)),X=[],lt=j/N,Ht=8/3*Math.sin(lt/4)*Math.sin(lt/4)/Math.sin(lt/2);let Dt=T+lt;for(let it=0;it<N;it++)X[it]=sh(T,Dt,I,P,et,G,S,M,Ht,C,O),C=X[it][5],O=X[it][6],T=Dt,Dt+=lt;return X})(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},ih=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":rh(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),Fn=(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 y(n*c+r*l+e*u+o*d,a*c+i*l+s*u+t*d)},Ln=o=>o**2,Rn=o=>2*o*(1-o),Bn=o=>(1-o)**2,nh=(o,t,e,s,r,i,n,a)=>h=>{const c=Ln(h),l=Rn(h),u=Bn(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)},oh=(o,t,e,s,r,i)=>n=>{const a=Ln(n),h=Rn(n),c=Bn(n);return new y(r*a+e*h+o*c,i*a+s*h+t*c)},ah=(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)},Pi=(o,t,e)=>{let s=new y(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},hh=(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)})},In=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=Fn(r,i,c[1],c[2],c[3],c[4],c[5],c[6]),e=l,e.iterator=t,e.angleFinder=nh(r,i,c[1],c[2],c[3],c[4],c[5],c[6]),e.length=Pi(t,r,i),r=c[5],i=c[6];break;case"Q":t=oh(r,i,c[1],c[2],c[3],c[4]),e=l,e.iterator=t,e.angleFinder=ah(r,i,c[1],c[2],c[3],c[4]),e.length=Pi(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},ch=function(o,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:In(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 y(r.x,r.y).lerp(new y(r.destX,r.destY),i)),{},{angle:Math.atan2(r.destY-r.y,r.destX-r.x)});case"L":return m(m({},new y(r.x,r.y).lerp(new y(n[1],n[2]),i)),{},{angle:Math.atan2(n[2]-r.y,n[1]-r.x)});case"C":case"Q":return hh(r,t)}},lh=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Ai=new RegExp(th,"g"),uh=new RegExp(Ft,"gi"),dh={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},gh=o=>{var t;const e=[],s=(t=o.match(lh))!==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=dh[i.toLowerCase()];let a=[];if(i==="a"||i==="A"){Ai.lastIndex=0;for(let h=null;h=Ai.exec(r);)a.push(...h.slice(1))}else a=r.match(uh)||[];for(let h=0;h<a.length;h+=n){const c=new Array(n),l=eh[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},fh=function(o){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new y(o[0]),s=new y(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},Wn=(o,t)=>o.map(e=>e.map((s,r)=>r===0||t===void 0?s:q(s,t)).join(" ")).join(" ");function kr(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 ph extends ln{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=Zt();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=Ee().createElement("div");return t.setAttribute("data-fabric","wrapper"),kr(t,{position:"relative"}),ri(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:r}=e;kr(t,m(m({},s),{},{"touch-action":r?"manipulation":mt})),ri(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:r}=this.upper;cn(s,r,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),xr(this.upper.el,t),xr(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(),Vt().dispose(this.upper.el),delete this.upper,delete this.container}}class tr extends Qe{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()),tr.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 ph(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 xa(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===Us||e===xt||e===Ot||e===Ge?r=this.centeredScaling||t.centeredScaling:e===Fr&&(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=Z:["mr","tr","br"].includes(e)&&(s.x=z),["tl","mt","tr"].includes(e)?s.y=yr:["bl","mb","br"].includes(e)&&(s.y=pt)),s}_setupCurrentTransform(t,e,s){var r;const i=e.group?Oe(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):Lo,c=((g,f,v,x)=>{if(!f||!g)return"drag";const b=x.controls[f];return b.getActionName(v,b,x)})(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:Q(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:l,original:m(m({},un(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 y(e,s).transform(this.viewportTransform),a=new y(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,ct.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,_r(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=$t(l)*i,d=Jt(l)*i,g=u+d,f=u-d;s=[new y(n.x-f,n.y-g),new y(a.x+g,a.y-f),new y(h.x+f,h.y+g),new y(c.x-g,c.y+f)]}return $.isPointInPolygon(e,s)}_checkTarget(t,e){return!!(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,Oe(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(Os(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&&Os(s)&&s.interactive&&this.targets[0]){const r=this.targets;for(let i=r.length-1;i>0;i--){const n=r[i];if(!Os(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=Do(t),n=r.width||0,a=r.height||0;n&&a||(pt in r&&yr in r&&(a=Math.abs(r.top-r.bottom)),Z in r&&z 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=Oe(i,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(i.x/=h,i.y/=h);const c=n===0||a===0?new y(1,1):new y(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=Zt(),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 ue(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,ue(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),ue(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(As,r))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;ue(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&&ue(e)&&this._activeObject===e){const s=Fe(t,["angle","flipX","flipY",z,xt,Ot,Pe,Ae,pt]);return Eo(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const r=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(r)}}p(tr,"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 mh{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),we(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 vh=["target","oldTarget","fireCanvas","e"],bt={passive:!1},xe=(o,t)=>{const e=o.getViewportPoint(t),s=o.getScenePoint(t);return{viewportPoint:e,scenePoint:s,pointer:e,absolutePointer:s}},ne=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)},St=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)},yh={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 Dr extends tr{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),p(this,"_isClick",void 0),p(this,"textEditingManager",new mh(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(ne,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const s=this.upperCanvasEl,r=this._getEventPrefix();t(hn(s),"resize",this._onResize),t(s,r+"down",this._onMouseDown),t(s,"".concat(r,"move"),this._onMouseMove,bt),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,bt)}removeListeners(){this.addOrRemove(St,"remove");const t=this._getEventPrefix(),e=At(this.upperCanvasEl);St(e,"".concat(t,"up"),this._onMouseUp),St(e,"touchend",this._onTouchEnd,bt),St(e,"".concat(t,"move"),this._onMouseMove,bt),St(e,"touchmove",this._onMouseMove,bt),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this.__onMouseWheel(t)}_onMouseOut(t){const e=this._hoveredTarget,s=m({e:t},xe(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},xe(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 ne(this.upperCanvasEl,"drag",this._onDragProgress)}ii(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!==mt,s=e?this._activeObject:void 0,r={e:t,target:this._dragSource,subTargets:this.targets,dragSource:this._dragSource,didDrop:e,dropTarget:s};St(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},xe(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&&ii(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=At(r);ne(n,"touchend",this._onTouchEnd,bt),e&&ne(n,"touchmove",this._onMouseMove,bt),St(r,"".concat(i,"down"),this._onMouseDown)}_onMouseDown(t){this.__onMouseDown(t),this._resetTransformEventData();const e=this.upperCanvasEl,s=this._getEventPrefix();St(e,"".concat(s,"move"),this._onMouseMove,bt);const r=At(e);ne(r,"".concat(s,"up"),this._onMouseUp),ne(r,"".concat(s,"move"),this._onMouseMove,bt)}_onTouchEnd(t){if(t.touches.length>0)return;this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=At(this.upperCanvasEl);St(s,"touchend",this._onTouchEnd,bt),St(s,"touchmove",this._onMouseMove,bt),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{ne(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=At(this.upperCanvasEl);St(r,"".concat(s,"up"),this._onMouseUp),St(r,"".concat(s,"move"),this._onMouseMove,bt),ne(e,"".concat(s,"move"),this._onMouseMove,bt)}}_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),_r(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},xe(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),_r(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=Oe(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=K(e,vh);const{targetIn:h,targetOut:c,canvasIn:l,canvasOut:u}=yh[t],d=r!==s;if(r&&d){const g=m(m({},a),{},{e:n,target:r,nextTarget:s},xe(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},xe(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?Oe(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=ue(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=ue(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(D.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 y(e,s),a=n.add(new y(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=D.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 Xn={x1:0,y1:0,x2:0,y2:0},xh=m(m({},Xn),{},{r1:0,r2:0}),Ce=(o,t)=>isNaN(o)&&typeof t=="number"?t:o;function Vn(o){return o&&/%$/.test(o)&&Number.isFinite(parseFloat(o))}function Yn(o,t){const e=typeof o=="number"?o:typeof o=="string"?parseFloat(o)/(Vn(o)?100:1):NaN;return Me(0,Ce(e,t),1)}const _h=/\s*;\s*/,bh=/\s*:\s*/;function wh(o,t){let e,s;const r=o.getAttribute("style");if(r){const n=r.split(_h);n[n.length-1]===""&&n.pop();for(let a=n.length;a--;){const[h,c]=n[a].split(bh).map(l=>l.trim());h==="stop-color"?e=c:h==="stop-opacity"&&(s=c)}}const i=new H(e||o.getAttribute("stop-color")||"rgb(0,0,0)");return{offset:Yn(o.getAttribute("offset"),0),color:i.toRgb(),opacity:Ce(parseFloat(s||o.getAttribute("stop-opacity")||""),1)*i.getAlpha()*t}}function Sh(o,t){const e=[],s=o.getElementsByTagName("stop"),r=Yn(t,1);for(let i=s.length;i--;)e.push(wh(s[i],r));return e}function Hn(o){return o.nodeName==="linearGradient"||o.nodeName==="LINEARGRADIENT"?"linear":"radial"}function zn(o){return o.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function Mt(o,t){return o.getAttribute(t)}function Ch(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&&Vn(u)&&(r*=.01,a==="pixels"&&(l!=="x1"&&l!=="x2"&&l!=="r2"||(r*=i),l!=="y1"&&l!=="y2"||(r*=n)))}return h[l]=r,h},{})}(Hn(o)==="linear"?function(e){return{x1:Mt(e,"x1")||0,y1:Mt(e,"y1")||0,x2:Mt(e,"x2")||"100%",y2:Mt(e,"y2")||0}}(o):function(e){return{x1:Mt(e,"fx")||Mt(e,"cx")||"50%",y1:Mt(e,"fy")||Mt(e,"cy")||"50%",r1:0,x2:Mt(e,"cx")||"50%",y2:Mt(e,"cy")||"50%",r2:Mt(e,"r")||"50%"}}(o),m(m({},t),{},{gradientUnits:zn(o)}))}class rs{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"?xh:Xn),r),colorStops:i,offsetX:n,offsetY:a,gradientTransform:h,id:c?"".concat(c,"_").concat(ce()):ce()})}addColorStop(t){for(const e in t){const s=new H(t[e]);this.colorStops.push({offset:parseFloat(e),color:s.toRgb(),opacity:s.getAlpha()})}return this}toObject(t){return m(m({},Fe(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():gt.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(Ue(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
- `)}else if(this.type==="radial"){const{x1:u,y1:d,x2:g,y2:f,r1:v,r2:x}=this.coords,b=v>x;s.push("<radialGradient ",l,' cx="',b?u:g,'" cy="',b?d:f,'" r="',b?v:x,'" fx="',b?g:u,'" fy="',b?f:d,`">
43
- `),b&&(n.reverse(),n.forEach(C=>{C.offset=1-C.offset}));const w=Math.min(v,x);if(w>0){const C=w/Math.max(v,x);n.forEach(O=>{O.offset+=C*(1-O.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
- `)}),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 H(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=zn(t),i=e._findCenterFromElement();return new this(m({id:t.getAttribute("id")||void 0,type:Hn(t),coords:Ch(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:Sh(t,s.opacity),gradientUnits:r,gradientTransform:Cr(t.getAttribute("gradientTransform")||"")},r==="pixels"?{offsetX:e.width/2-i.x,offsetY:e.height/2-i.y}:{offsetX:0,offsetY:0}))}}p(rs,"type","Gradient"),D.setClass(rs,"gradient"),D.setClass(rs,"linear"),D.setClass(rs,"radial");const Th=["type","source","patternTransform"];class lr{get type(){return"pattern"}set type(t){he("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=ce(),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({},Fe(this,t)),{},{type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:q(this.offsetX,V.NUM_FRACTION_DIGITS),offsetY:q(this.offsetY,V.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=Ce(this.offsetX/e,0),h=Ce(this.offsetY/s,0),c=i==="repeat-y"||i==="no-repeat"?1+Math.abs(a||0):Ce(r.width/e,0),l=i==="repeat-x"||i==="no-repeat"?1+Math.abs(h||0):Ce(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=K(t,Th);const a=await Ds(r,m(m({},e),{},{crossOrigin:n.crossOrigin}));return new this(m(m({},n),{},{patternTransform:i&&i.slice(0),source:a}))}}p(lr,"type","Pattern"),D.setClass(lr),D.setClass(lr,"pattern");class Oh{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 H(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 kh=["path","left","top"],Dh=["d"];class oe extends ct{constructor(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},{path:s,left:r,top:i}=e,n=K(e,kh);super(),Object.assign(this,oe.ownDefaults),this.setOptions(n),this._setPath(t||[],!0),typeof r=="number"&&this.set(z,r),typeof i=="number"&&this.set(pt,i)}_setPath(t,e){this.path=ih(Array.isArray(t)?t:gh(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new y(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=Wn(this.path,V.NUM_FRACTION_DIGITS);return["<path ","COMMON_PARTS",'d="'.concat(t,`" stroke-linecap="round" />
47
- `)]}_getOffsetTransform(){const t=V.NUM_FRACTION_DIGITS;return" translate(".concat(q(-this.pathOffset.x,t),", ").concat(q(-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(...Ei(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(...Ei(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 Kt(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return m(m({},t),{},{pathOffset:new y(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=ee(t,this.ATTRIBUTE_NAMES,s),{d:i}=r;return new this(i,m(m(m({},K(r,Dh)),e),{},{left:void 0,top:void 0}))}}p(oe,"type","Path"),p(oe,"cacheProperties",[...te,"path","fillRule"]),p(oe,"ATTRIBUTE_NAMES",[...le,"d"]),D.setClass(oe),D.setSVGClass(oe);class Ys extends Oh{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=Ys.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++)Ys.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 fh(t,e)}createPath(t){const e=new oe(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 Xt(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 Wn(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 Mh=["left","top","radius"],Gn=["radius","startAngle","endAngle","counterClockwise"];class Rt extends ct{static getDefaults(){return m(m({},super.getDefaults()),Rt.ownDefaults)}constructor(t){super(),Object.assign(this,Rt.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,Q(this.startAngle),Q(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(xt)}getRadiusY(){return this.get("radius")*this.get(Ot)}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([...Gn,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',"".concat(this.radius),`" />
48
- `];{const{radius:e}=this,s=Q(this.startAngle),r=Q(this.endAngle),i=$t(s)*e,n=Jt(s)*e,a=$t(r)*e,h=Jt(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=ee(t,this.ATTRIBUTE_NAMES,s),{left:i=0,top:n=0,radius:a=0}=r;return new this(m(m({},K(r,Mh)),{},{radius:a,left:i-a,top:n-a}))}static fromObject(t){return super._fromObject(t)}}p(Rt,"type","Circle"),p(Rt,"cacheProperties",[...te,...Gn]),p(Rt,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),p(Rt,"ATTRIBUTE_NAMES",["cx","cy","r",...le]),D.setClass(Rt),D.setSVGClass(Rt);const Eh=["x1","y1","x2","y2"],Ph=["x1","y1","x2","y2"],Mr=["x1","x2","y1","y2"];class It extends ct{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,It.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(z,n),typeof a=="number"&&this.set(pt,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}=Kt([{x:t,y:e},{x:s,y:r}]),c=new y(i+a/2,n+h/2);this.setPositionByOrigin(c,R,R)}_set(t,e){return super._set(t,e),Mr.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;Tt(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 y((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=ee(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],K(r,Eh))}static fromObject(t){let{x1:e,y1:s,x2:r,y2:i}=t,n=K(t,Ph);return this._fromObject(m(m({},n),{},{points:[e,s,r,i]}),{extraParam:"points"})}}p(It,"type","Line"),p(It,"cacheProperties",[...te,...Mr]),p(It,"ATTRIBUTE_NAMES",le.concat(Mr)),D.setClass(It),D.setSVGClass(It);class de extends ct{static getDefaults(){return m(m({},super.getDefaults()),de.ownDefaults)}constructor(t){super(),Object.assign(this,de.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(de,"type","Triangle"),p(de,"ownDefaults",{width:100,height:100}),D.setClass(de),D.setSVGClass(de);const Nn=["rx","ry"];class Gt extends ct{static getDefaults(){return m(m({},super.getDefaults()),Gt.ownDefaults)}constructor(t){super(),Object.assign(this,Gt.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(xt)}getRy(){return this.get("ry")*this.get(Ot)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...Nn,...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,Es,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const r=ee(t,this.ATTRIBUTE_NAMES,s);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}}function Ah(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(Gt,"type","Ellipse"),p(Gt,"cacheProperties",[...te,...Nn]),p(Gt,"ownDefaults",{rx:0,ry:0}),p(Gt,"ATTRIBUTE_NAMES",[...le,"cx","cy","rx","ry"]),D.setClass(Gt),D.setSVGClass(Gt);const jh=["left","top"],Un={exactBoundingBox:!1};class Pt extends ct{static getDefaults(){return m(m({},super.getDefaults()),Pt.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,Pt.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:r}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set(z,s),typeof r=="number"&&this.set(pt,r)}isOpen(){return!0}_projectStrokeOnPoints(t){return ba(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 y,strokeOffset:new y,strokeDiff:new y};const s=Kt(e),r=qs(m(m({},t),{},{scaleX:1,scaleY:1})),i=Kt(this.points.map(c=>ft(c,r,!0))),n=new y(this.scaleX,this.scaleY);let a=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(a-=h*Math.tan(Q(this.skewX)),h-=a*Math.tan(Q(this.skewY))),m(m({},s),{},{pathOffset:new y(a,h),strokeOffset:new y(i.left,i.top).subtract(new y(s.left,s.top)).multiply(n),strokeDiff:new y(s.width,s.height).subtract(new y(i.width,i.height)).multiply(n)})}_findCenterFromElement(){const t=Kt(this.points);return new y(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 y(e+r/2,s+i/2),R,R)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new y(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 y((e=t.width)!==null&&e!==void 0?e:a,(s=t.height)!==null&&s!==void 0?s:h)}else{var r,i;n=new y((r=t.width)!==null&&r!==void 0?r:this.width,(i=t.height)!==null&&i!==void 0?i:this.height)}return n.multiply(new y(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===xt||t===Ot)&&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=V.NUM_FRACTION_DIGITS;for(let i=0,n=this.points.length;i<n;i++)t.push(q(this.points[i].x-e,r),",",q(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(Ah(t.getAttribute("points")),m(m({},K(ee(t,this.ATTRIBUTE_NAMES,s),jh)),e))}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}p(Pt,"ownDefaults",Un),p(Pt,"type","Polyline"),p(Pt,"layoutProperties",[Pe,Ae,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),p(Pt,"cacheProperties",[...te,"points"]),p(Pt,"ATTRIBUTE_NAMES",[...le]),D.setClass(Pt),D.setSVGClass(Pt);class is extends Pt{isOpen(){return!1}}p(is,"ownDefaults",Un),p(is,"type","Polygon"),D.setClass(is),D.setSVGClass(is);class qn extends ct{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=Ir(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({},Fe(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(qn,"_styleProperties",Bo);const Fh=/ +/g,Lh=/"/g;function ur(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]:V.NUM_FRACTION_DIGITS;const d=qe(nt,i,!1),[g,f,v,x]=[a,h,c,l].map(b=>q(b,u));return"<rect ".concat(d,' x="').concat(g,'" y="').concat(f,'" width="').concat(v,'" height="').concat(x,'"></rect>')}(o,{left:t,top:e,width:s,height:r}),`
53
- `)}const Rh=["textAnchor","textDecoration","dx","dy","top","left","fontSize","strokeWidth"];let dr;class ut extends qn{static getDefaults(){return m(m({},super.getDefaults()),ut.ownDefaults)}constructor(t,e){super(),p(this,"__charBounds",[]),Object.assign(this,ut.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=In(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(Bt)&&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===Bt||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===vt?(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=pt;break;case"descender":t.textBaseline=yr}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 x=0;x<h;x++){const b=this.__charBounds[i][x];u=this.getValueOfPropertyAt(i,x,"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 dr||(dr=kt({width:0,height:0}).getContext("2d")),dr}();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===Z,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 z:l=i?u-r:0;break;case R:l=(u-r)/2;break;case Z: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=ch(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===Z?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(nt))&&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(Bt),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,x,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?z:Z),i-=this.getHeightOfLineImpl(n)*this._fontSizeFraction,c)return this._renderChar(t,e,n,0,s.join(""),r,i),void e.restore();for(let O=0,k=s.length-1;O<=k;O++)x=O===k||this.charSpacing||h,w+=s[O],v=this.__charBounds[n][O],C===0?(r+=u*(v.kernedWidth-v.width),C+=v.width):C+=v.kernedWidth,a&&!x&&this._reSpaceAndTab.test(s[O])&&(x=!0),x||(g=g||this.getCompleteStyleDeclaration(n,O),f=this.getCompleteStyleDeclaration(n,O+1),x=Nr(g,f,!1)),x&&(h?(e.save(),e.translate(v.renderLeft,v.renderTop),e.rotate(v.angle),this._renderChar(t,e,n,O,w,-C/2,0),e.restore()):(b=r,this._renderChar(t,e,n,O,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=kt({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 Tt(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===Bt||r===He&&!n||r===Ye&&!n||r===Is&&!n?0:(r===R&&(a=s/2),r===Z&&(a=s),r===He&&(a=s/2),r===Ye&&(a=s),i==="rtl"&&(r===Z||r===Bt||r===Ye?a=0:r===z||r===Is?a=-s:r!==R&&r!==He||(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,x=0,b=this.getValueOfPropertyAt(c,0,e),w=this.getValueOfPropertyAt(c,0,nt),C=this.getValueOfPropertyAt(c,0,pe),O=b,k=w,E=C;const B=s+g*(1-this._fontSizeFraction);let P=this.getHeightOfChar(c,0),I=this.getValueOfPropertyAt(c,0,"deltaY");for(let L=0,Y=d.length;L<Y;L++){const W=this.__charBounds[c][L];O=this.getValueOfPropertyAt(c,L,e),k=this.getValueOfPropertyAt(c,L,nt),E=this.getValueOfPropertyAt(c,L,pe);const rt=this.getHeightOfChar(c,L),tt=this.getValueOfPropertyAt(c,L,"deltaY");if(i&&O&&k){const et=this.fontSize*E/1e3;t.save(),t.fillStyle=w,t.translate(W.renderLeft,W.renderTop),t.rotate(W.angle),t.fillRect(-W.kernedWidth/2,h*rt+tt-a*et,W.kernedWidth,et),t.restore()}else if((O!==b||k!==w||rt!==P||E!==C||tt!==I)&&x>0){const et=this.fontSize*C/1e3;let G=r+f+v;this.direction==="rtl"&&(G=this.width-G-x),b&&w&&C&&(t.fillStyle=w,t.fillRect(G,B+h*P+I-a*et,x,et)),v=W.left,x=W.width,b=O,C=E,w=k,P=rt,I=tt}else x+=W.kernedWidth}let U=r+f+v;this.direction==="rtl"&&(U=this.width-U-x),t.fillStyle=k;const J=this.fontSize*E/1e3;O&&k&&E&&t.fillRect(U,B+h*P+I-a*J,x-n,J),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(",")||ut.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 Gr(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([..._n,...t])),{},{styles:Ta(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=ee(t,ut.ATTRIBUTE_NAMES,s),i=m(m({},e),r),{textAnchor:n=z,textDecoration:a="",dx:h=0,dy:c=0,top:l=0,left:u=0,fontSize:d=Ar,strokeWidth:g=1}=i,f=K(i,Rh),v=new this(Bs(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)),x=v.getScaledHeight()/v.height,b=((v.height+v.strokeWidth)*v.lineHeight-v.height)*x,w=v.getScaledHeight()+b;let C=0;return n===R&&(C=v.getScaledWidth()/2),n===Z&&(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:Oa(t.styles||{},t.text)}),{extraParam:"text"})}}p(ut,"textLayoutProperties",xn),p(ut,"cacheProperties",[...te,..._n]),p(ut,"ownDefaults",Io),p(ut,"type","Text"),p(ut,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),p(ut,"ATTRIBUTE_NAMES",le.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),Mn(ut,[class extends mn{_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:Ue(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(Lh,"'"),'" '),'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(...ur(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=V.NUM_FRACTION_DIGITS,n=this.getSvgSpanStyles(t,o!==o.trim()||!!o.match(Fh)),a=n?'style="'.concat(n,'"'):"",h=t.deltaY,c=h?' dy="'.concat(q(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(q(Qt(l),i),'"'));const x=je({angle:Qt(l)});x[4]=u,x[5]=d;const b=new y(-v,0).transform(x);e=b.x,s=b.y}return'<tspan x="'.concat(q(e,i),'" y="').concat(q(s,i),'" ').concat(c).concat(f).concat(a,">").concat(wa(o),"</tspan>")}_setSVGTextLineText(o,t,e,s){const r=this.getHeightOfLine(t),i=this.textAlign.includes(Bt),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=Nr(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(...ur(c,e+h,s,a,i)),h=u,a=d,c=n):a+=g}n&&o.push(...ur(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(q(this.textDecorationThickness*this.getObjectScaling().y/10,V.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?qe(vt,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(q(v*this.getObjectScaling().y/10,V.NUM_FRACTION_DIGITS),"%; "):"",i?qe(nt,i):"",c?"baseline-shift: ".concat(-c,"; "):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(o){return["overline","underline","line-through"].filter(t=>o[t.replace("-","")]).join(" ")}}]),D.setClass(ut),D.setSVGClass(ut);class Bh{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 y(n.flipX?-1:1,n.flipY?-1:1),c=n._getCursorBoundaries(r),l=new y(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 y(g.left,g.top)),v=a.viewportTransform,x=f.add(u).transform(v,!0),b=n.backgroundColor,w=zr(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 O=n.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});n.backgroundColor=b,n.styles=w,n.dirty=!0,kr(O,{position:"fixed",left:"".concat(-O.width,"px"),border:mt,width:"".concat(O.width/d,"px"),height:"".concat(O.height/d,"px")}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{O.remove()},At(t.target||this.target.hiddenTextarea).body.appendChild(O),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(O,x.x,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(Ps,{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)||mt;h===mt?(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(Ps,{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 ji=/[ \n\.,;!\?\-]/;class Ih extends ut{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 Cn({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||!jr.test(s[t-1]))?t-1:t,i=s[r];for(;r>0&&r<s.length&&!ji.test(i);)r+=e,i=s[r];return e===-1&&ji.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;At(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 y(e.left+a,e.top+e.topOffset+n).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new y(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(As),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=z:this._selectionDirection===Z&&(this._selectionDirection=z,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===Z?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=Z:this._selectionDirection===z&&(this._selectionDirection=Z,this.selectionStart=e),this.selectionEnd=s)}}class Wh extends Ih{initHiddenTextarea(){const t=this.canvas&&At(this.canvas.getElement())||Ee(),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(Ps),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,x,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 O=a.slice(w.selectionEnd-b,w.selectionEnd);if(f&&f.length&&(O.length&&(g=this.getSelectionStyles(l,l+1,!1),g=O.map(()=>g[0])),d?(v=l,x=u):C?(v=u-f.length,x=u):(v=u,x=u+f.length),this.removeStyleFromTo(v,x)),O.length){const{copyPasteData:k}=Vt();e&&O.join("")===k.copiedText&&!V.disableStyleCopyPaste&&(g=k.copiedTextStyle),this.insertNewStyleBlock(O,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}=Vt();t.copiedText=this.getSelectedText(),V.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===Z);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const r=this.text.length;this.selectionStart=Me(0,this.selectionStart,r),this.selectionEnd=Me(0,this.selectionEnd,r),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===z?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),t!==0}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),t!==0}moveCursorLeft(t){this.selectionStart===0&&this.selectionEnd===0||this._moveCursorLeftOrRight("Left",t)}_move(t,e,s){let 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=z,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===Z&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=z,this._moveLeft(t,"selectionStart")):void 0}moveCursorRight(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorLeftOrRight("Right",t)}_moveCursorLeftOrRight(t,e){const s="moveCursor".concat(t).concat(e.shiftKey?"WithShift":"WithoutShift");this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===z&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=Z,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=Z,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const Fi=o=>!!o.button;class Xh extends Wh{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 Bh(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&&!Fi(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||Fi(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(jt(this.calcTransformMatrix())).add(new y(-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 ns="moveCursorUp",os="moveCursorDown",as="moveCursorLeft",hs="moveCursorRight",cs="exitEditing",Li=(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])},Vh=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:cs,27:cs,33:ns,34:os,35:hs,36:as,37:as,38:ns,39:hs,40:os},keysMapRtl:{9:cs,27:cs,33:ns,34:os,35:as,36:hs,37:hs,38:ns,39:as,40:os},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"}},{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1});class Ut extends Xh{static getDefaults(){return m(m({},super.getDefaults()),Ut.ownDefaults)}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,m(m({},Ut.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 Dr&&this.canvas.textEditingManager.remove(this),e instanceof Dr&&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=kt(t.canvas),n=i.getContext("2d"),Li(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=kt(t.canvas),l=c.getContext("2d");if(Li(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===Z||this.textAlign===Bt||this.textAlign===Ye?h.left*=-1:this.textAlign===z||this.textAlign===Is?h.left=n-(s>0?s:0):this.textAlign!==R&&this.textAlign!==He||(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(Bt),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),x=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 B=this._getWidthOfCharSpacing();w=this.__charBounds[l][d-1].left+this.__charBounds[l][d-1].width-B}x=v,(this.lineHeight<1||g===l&&this.lineHeight>1)&&(v/=this.lineHeight);let C=s.left+f+b,O=v,k=0;const E=w-b;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",O=1,k=v):t.fillStyle=this.selectionColor,this.direction==="rtl"&&(this.textAlign===Z||this.textAlign===Bt||this.textAlign===Ye?C=this.width-C-E:this.textAlign===z||this.textAlign===Is?C=s.left+f-w:this.textAlign!==R&&this.textAlign!==He||(C=s.left+f-w)),t.fillRect(C,s.top+s.topOffset+k,E,O),s.topOffset+=x}}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,nt)}_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(Ut,"ownDefaults",Vh),p(Ut,"type","IText"),D.setClass(Ut),D.setClass(Ut,"i-text");class qt extends Ut{static getDefaults(){return m(m({},super.getDefaults()),qt.ownDefaults)}constructor(t,e){super(t,m(m({},qt.ownDefaults),e))}static createControls(){return{controls:ya()}}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(Bt)&&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 x=Math.max(e,r,this.dynamicMinWidth),b=i[t];let w;for(g=0,w=0;w<b.length;w++){const{word:C,width:O}=b[w];g+=C.length,u+=f+O-a,u>x&&!v?(c.push(d),d=[],u=O,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(qt,"type","Textbox"),p(qt,"textLayoutProperties",[...Ut.textLayoutProperties,"width"]),p(qt,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),D.setClass(qt);class Ri extends Qs{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}=Kt(An(s,r)),h=new y(n,a);if(r.absolutePositioned)return{center:Oe(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 y,correction:u=new y}=this.calcBoundingBox(e,t)||{};return{center:l.add(c),correction:u.subtract(c),size:h}}return{center:s.getRelativeCenterPoint().add(c),size:h}}}}p(Ri,"type","clip-path"),D.setClass(Ri);class Bi extends Qs{getInitialSize(t,e){let{target:s}=t,{size:r}=e;return new y(s.width||r.x,s.height||r.y)}}p(Bi,"type","fixed"),D.setClass(Bi);class Yh extends $e{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 ge extends fe{static getDefaults(){return m(m({},super.getDefaults()),ge.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,ge.ownDefaults),this.setOptions(e);const{left:s,top:r,layoutManager:i}=e;this.groupInit(t,{left:s,top:r,layoutManager:i??new Yh})}_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))?(he("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===qr?s.forEach(r=>{r._onAfterObjectsChange(Ws,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(ge,"type","ActiveSelection"),p(ge,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),D.setClass(ge),D.setClass(ge,"activeSelection");class Hh{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 Kn{constructor(){let{tileSize:t=V.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=kt({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,x=d.destinationWidth,b=d.destinationHeight;f===x&&v===b||(g.width=x,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 gr;function zh(){const{WebGLProbe:o}=Vt();return o.queryWebGL(Zt()),V.enableGLFiltering&&o.isSupported(V.textureSize)?new Kn({tileSize:V.textureSize}):new Hh}function fr(){return!gr&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(gr=zh()),gr}const Gh=["filters","resizeFilter","src","crossOrigin","type"],$n=["cropX","cropY"];class ht extends ct{static getDefaults(){return m(m({},super.getDefaults()),ht.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,ht.ownDefaults),this.setOptions(e),this.cacheKey="texture".concat(ce()),this.setElement(typeof t=="string"?(this.canvas&&At(this.canvas.getElement())||Ee()).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(ht.CSS_CANVAS),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=fr(!1);e instanceof Kn&&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&&Vt().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([...$n,...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=ce();i.push('<clipPath id="imageCrop_'+c+`">
58
- `,' <rect x="'+s+'" y="'+r+'" width="'+this.width+'" height="'+this.height+`" />
59
- `,`</clipPath>
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
- `)),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!==nt?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 Ds(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=kt(n),{width:h,height:c}=n;this._element=a,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=i,fr().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=kt({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);fr().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,x=-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,x,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=Ro(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===mt&&t.alignY===mt?(h=e/n,c=s/a):(t.meetOrSlice==="meet"&&(h=c=Za(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=Qa(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=K(t,Gh);return Promise.all([Ds(i,m(m({},e),{},{crossOrigin:n})),s&&Ne(s,e),r&&Ne([r],e),Ks(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 Ds(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=ee(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(r["xlink:href"]||r.href,e,r).catch(i=>(he("log","Unable to parse Image",i),null))}}p(ht,"type","Image"),p(ht,"cacheProperties",[...te,...$n]),p(ht,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),p(ht,"CSS_CANVAS","canvas-img"),p(ht,"ATTRIBUTE_NAMES",[...le,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),D.setClass(ht),D.setSVGClass(ht);Js(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);const er=o=>o.webgl!==void 0,Kr="precision highp float",Nh=`
63
- `.concat(Kr,`;
64
- varying vec2 vTexCoord;
65
- uniform sampler2D uTexture;
66
- void main() {
67
- gl_FragColor = texture2D(uTexture, vTexCoord);
68
- }`),Uh=["type"],qh=["type"],Kh=new RegExp(Kr,"g");class ot{get type(){return this.constructor.type}constructor(){let t=K(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},Uh);Object.assign(this,this.constructor.defaults,t)}getFragmentSource(){return Nh}getVertexSource(){return`
69
- attribute vec2 aPosition;
70
- varying vec2 vTexCoord;
71
- void main() {
72
- vTexCoord = aPosition;
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"}}=Vt();r!=="highp"&&(e=e.replace(Kh,Kr.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 Wt("Vertex, fragment shader or program creation error");if(t.shaderSource(i,s),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Wt("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 Wt("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 Wt('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){er(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=kt({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(K(t,qh))}}p(ot,"type","BaseFilter"),p(ot,"uniformLocations",[]);const $h={multiply:`gl_FragColor.rgb *= uColor.rgb;
75
- `,screen:`gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);
76
- `,add:`gl_FragColor.rgb += uColor.rgb;
77
- `,difference:`gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);
78
- `,subtract:`gl_FragColor.rgb -= uColor.rgb;
79
- `,lighten:`gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);
80
- `,darken:`gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);
81
- `,exclusion:`gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);
82
- `,overlay:`
83
- if (uColor.r < 0.5) {
84
- gl_FragColor.r *= 2.0 * uColor.r;
85
- } else {
86
- gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);
87
- }
88
- if (uColor.g < 0.5) {
89
- gl_FragColor.g *= 2.0 * uColor.g;
90
- } else {
91
- gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);
92
- }
93
- if (uColor.b < 0.5) {
94
- gl_FragColor.b *= 2.0 * uColor.b;
95
- } else {
96
- gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);
97
- }
98
- `,tint:`
99
- gl_FragColor.rgb *= (1.0 - uColor.a);
100
- gl_FragColor.rgb += uColor.rgb;
101
- `};class ls extends ot{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return`
102
- precision highp float;
103
- uniform sampler2D uTexture;
104
- uniform vec4 uColor;
105
- varying vec2 vTexCoord;
106
- void main() {
107
- vec4 color = texture2D(uTexture, vTexCoord);
108
- gl_FragColor = color;
109
- if (color.a > 0.0) {
110
- `.concat($h[this.mode],`
111
- }
112
- }
113
- `)}applyTo2d(t){let{imageData:{data:e}}=t;const s=new H(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 H(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(ls,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),p(ls,"type","BlendColor"),p(ls,"uniformLocations",["uColor"]),D.setClass(ls);const Jh={multiply:`
114
- precision highp float;
115
- uniform sampler2D uTexture;
116
- uniform sampler2D uImage;
117
- uniform vec4 uColor;
118
- varying vec2 vTexCoord;
119
- varying vec2 vTexCoord2;
120
- void main() {
121
- vec4 color = texture2D(uTexture, vTexCoord);
122
- vec4 color2 = texture2D(uImage, vTexCoord2);
123
- color.rgba *= color2.rgba;
124
- gl_FragColor = color;
125
- }
126
- `,mask:`
127
- precision highp float;
128
- uniform sampler2D uTexture;
129
- uniform sampler2D uImage;
130
- uniform vec4 uColor;
131
- varying vec2 vTexCoord;
132
- varying vec2 vTexCoord2;
133
- void main() {
134
- vec4 color = texture2D(uTexture, vTexCoord);
135
- vec4 color2 = texture2D(uImage, vTexCoord2);
136
- color.a = color2.a;
137
- gl_FragColor = color;
138
- }
139
- `},Zh=["type","image"];class us extends ot{getCacheKey(){return"".concat(this.type,"_").concat(this.mode)}getFragmentSource(){return Jh[this.mode]}getVertexSource(){return`
140
- attribute vec2 aPosition;
141
- varying vec2 vTexCoord;
142
- varying vec2 vTexCoord2;
143
- uniform mat3 uTransformMatrix;
144
- void main() {
145
- vTexCoord = aPosition;
146
- vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;
147
- gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);
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=Zt());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],x=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*x/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=K(t,Zh);return ht.fromObject(r,e).then(n=>new this(m(m({},i),{},{image:n})))}}p(us,"type","BlendImage"),p(us,"defaults",{mode:"multiply",alpha:1}),p(us,"uniformLocations",["uTransformMatrix","uImage"]),D.setClass(us);class ds extends ot{getFragmentSource(){return`
150
- precision highp float;
151
- uniform sampler2D uTexture;
152
- uniform vec2 uDelta;
153
- varying vec2 vTexCoord;
154
- const float nSamples = 15.0;
155
- vec3 v3offset = vec3(12.9898, 78.233, 151.7182);
156
- float random(vec3 scale) {
157
- /* use the fragment position for a different seed per-pixel */
158
- return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);
159
- }
160
- void main() {
161
- vec4 color = vec4(0.0);
162
- float totalC = 0.0;
163
- float totalA = 0.0;
164
- float offset = random(v3offset);
165
- for (float t = -nSamples; t <= nSamples; t++) {
166
- float percent = (t + offset - 0.5) / nSamples;
167
- vec4 sample = texture2D(uTexture, vTexCoord + uDelta * percent);
168
- float weight = 1.0 - abs(percent);
169
- float alpha = weight * sample.a;
170
- color.rgb += sample.rgb * alpha;
171
- color.a += alpha;
172
- totalA += weight;
173
- totalC += alpha;
174
- }
175
- gl_FragColor.rgb = color.rgb / totalC;
176
- gl_FragColor.a = color.a / totalA;
177
- }
178
- `}applyTo(t){er(t)?(this.aspectRatio=t.sourceWidth/t.sourceHeight,t.passes++,this._setupFrameBuffer(t),this.horizontal=!0,this.applyToWebGL(t),this._swapTextures(t),this._setupFrameBuffer(t),this.horizontal=!1,this.applyToWebGL(t),this._swapTextures(t)):this.applyTo2d(t)}applyTo2d(t){let{imageData:{data:e,width:s,height:r}}=t;this.aspectRatio=s/r,this.horizontal=!0;let i=this.getBlurValue()*s;const n=new Uint8ClampedArray(e),a=15,h=4*s;for(let c=0;c<e.length;c+=4){let l=0,u=0,d=0,g=0,f=0;const v=c-c%h,x=v+h;for(let b=-14;b<a;b++){const w=b/a,C=4*Math.floor(i*w),O=1-Math.abs(w);let k=c+C;k<v?k=v:k>x&&(k=x);const E=e[k+3]*O;l+=e[k]*E,u+=e[k+1]*E,d+=e[k+2]*E,g+=E,f+=O}n[c]=l/g,n[c+1]=u/g,n[c+2]=d/g,n[c+3]=g/f}this.horizontal=!1,i=this.getBlurValue()*r;for(let c=0;c<n.length;c+=4){let l=0,u=0,d=0,g=0,f=0;const v=c%h,x=n.length-h+v;for(let b=-14;b<a;b++){const w=b/a,C=Math.floor(i*w)*h,O=1-Math.abs(w);let k=c+C;k<v?k=v:k>x&&(k=x);const E=n[k+3]*O;l+=n[k]*E,u+=n[k+1]*E,d+=n[k+2]*E,g+=E,f+=O}e[c]=l/g,e[c+1]=u/g,e[c+2]=d/g,e[c+3]=g/f}}sendUniformData(t,e){const s=this.chooseRightDelta();t.uniform2fv(e.uDelta,s)}isNeutralState(){return this.blur===0}getBlurValue(){let t=1;const{horizontal:e,aspectRatio:s}=this;return e?s>1&&(t=1/s):s<1&&(t=s),t*this.blur*.12}chooseRightDelta(){const t=this.getBlurValue();return this.horizontal?[t,0]:[0,t]}}p(ds,"type","Blur"),p(ds,"defaults",{blur:0}),p(ds,"uniformLocations",["uDelta"]),D.setClass(ds);class gs extends ot{getFragmentSource(){return`
179
- precision highp float;
180
- uniform sampler2D uTexture;
181
- uniform float uBrightness;
182
- varying vec2 vTexCoord;
183
- void main() {
184
- vec4 color = texture2D(uTexture, vTexCoord);
185
- color.rgb += uBrightness;
186
- gl_FragColor = color;
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(gs,"type","Brightness"),p(gs,"defaults",{brightness:0}),p(gs,"uniformLocations",["uBrightness"]),D.setClass(gs);const Jn={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class Te extends ot{getFragmentSource(){return`
189
- precision highp float;
190
- uniform sampler2D uTexture;
191
- varying vec2 vTexCoord;
192
- uniform mat4 uColorMatrix;
193
- uniform vec4 uConstants;
194
- void main() {
195
- vec4 color = texture2D(uTexture, vTexCoord);
196
- color *= uColorMatrix;
197
- color += uConstants;
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 me(o,t){var e;const s=(p(e=class extends Te{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",o),p(e,"defaults",{colorsOnly:!1,matrix:t}),e);return D.setClass(s,o),s}p(Te,"type","ColorMatrix"),p(Te,"defaults",Jn),p(Te,"uniformLocations",["uColorMatrix","uConstants"]),D.setClass(Te);me("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]);me("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]);me("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]);me("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]);me("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]);me("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]);me("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 Ii extends ot{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){er(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=>D.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}p(Ii,"type","Composed"),D.setClass(Ii);class fs extends ot{getFragmentSource(){return`
200
- precision highp float;
201
- uniform sampler2D uTexture;
202
- uniform float uContrast;
203
- varying vec2 vTexCoord;
204
- void main() {
205
- vec4 color = texture2D(uTexture, vTexCoord);
206
- float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));
207
- color.rgb = contrastF * (color.rgb - 0.5) + 0.5;
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(fs,"type","Contrast"),p(fs,"defaults",{contrast:0}),p(fs,"uniformLocations",["uContrast"]),D.setClass(fs);const Qh={Convolute_3_1:`
210
- precision highp float;
211
- uniform sampler2D uTexture;
212
- uniform float uMatrix[9];
213
- uniform float uStepW;
214
- uniform float uStepH;
215
- varying vec2 vTexCoord;
216
- void main() {
217
- vec4 color = vec4(0, 0, 0, 0);
218
- for (float h = 0.0; h < 3.0; h+=1.0) {
219
- for (float w = 0.0; w < 3.0; w+=1.0) {
220
- vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));
221
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];
222
- }
223
- }
224
- gl_FragColor = color;
225
- }
226
- `,Convolute_3_0:`
227
- precision highp float;
228
- uniform sampler2D uTexture;
229
- uniform float uMatrix[9];
230
- uniform float uStepW;
231
- uniform float uStepH;
232
- varying vec2 vTexCoord;
233
- void main() {
234
- vec4 color = vec4(0, 0, 0, 1);
235
- for (float h = 0.0; h < 3.0; h+=1.0) {
236
- for (float w = 0.0; w < 3.0; w+=1.0) {
237
- vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));
238
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];
239
- }
240
- }
241
- float alpha = texture2D(uTexture, vTexCoord).a;
242
- gl_FragColor = color;
243
- gl_FragColor.a = alpha;
244
- }
245
- `,Convolute_5_1:`
246
- precision highp float;
247
- uniform sampler2D uTexture;
248
- uniform float uMatrix[25];
249
- uniform float uStepW;
250
- uniform float uStepH;
251
- varying vec2 vTexCoord;
252
- void main() {
253
- vec4 color = vec4(0, 0, 0, 0);
254
- for (float h = 0.0; h < 5.0; h+=1.0) {
255
- for (float w = 0.0; w < 5.0; w+=1.0) {
256
- vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));
257
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];
258
- }
259
- }
260
- gl_FragColor = color;
261
- }
262
- `,Convolute_5_0:`
263
- precision highp float;
264
- uniform sampler2D uTexture;
265
- uniform float uMatrix[25];
266
- uniform float uStepW;
267
- uniform float uStepH;
268
- varying vec2 vTexCoord;
269
- void main() {
270
- vec4 color = vec4(0, 0, 0, 1);
271
- for (float h = 0.0; h < 5.0; h+=1.0) {
272
- for (float w = 0.0; w < 5.0; w+=1.0) {
273
- vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));
274
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];
275
- }
276
- }
277
- float alpha = texture2D(uTexture, vTexCoord).a;
278
- gl_FragColor = color;
279
- gl_FragColor.a = alpha;
280
- }
281
- `,Convolute_7_1:`
282
- precision highp float;
283
- uniform sampler2D uTexture;
284
- uniform float uMatrix[49];
285
- uniform float uStepW;
286
- uniform float uStepH;
287
- varying vec2 vTexCoord;
288
- void main() {
289
- vec4 color = vec4(0, 0, 0, 0);
290
- for (float h = 0.0; h < 7.0; h+=1.0) {
291
- for (float w = 0.0; w < 7.0; w+=1.0) {
292
- vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));
293
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];
294
- }
295
- }
296
- gl_FragColor = color;
297
- }
298
- `,Convolute_7_0:`
299
- precision highp float;
300
- uniform sampler2D uTexture;
301
- uniform float uMatrix[49];
302
- uniform float uStepW;
303
- uniform float uStepH;
304
- varying vec2 vTexCoord;
305
- void main() {
306
- vec4 color = vec4(0, 0, 0, 1);
307
- for (float h = 0.0; h < 7.0; h+=1.0) {
308
- for (float w = 0.0; w < 7.0; w+=1.0) {
309
- vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));
310
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];
311
- }
312
- }
313
- float alpha = texture2D(uTexture, vTexCoord).a;
314
- gl_FragColor = color;
315
- gl_FragColor.a = alpha;
316
- }
317
- `,Convolute_9_1:`
318
- precision highp float;
319
- uniform sampler2D uTexture;
320
- uniform float uMatrix[81];
321
- uniform float uStepW;
322
- uniform float uStepH;
323
- varying vec2 vTexCoord;
324
- void main() {
325
- vec4 color = vec4(0, 0, 0, 0);
326
- for (float h = 0.0; h < 9.0; h+=1.0) {
327
- for (float w = 0.0; w < 9.0; w+=1.0) {
328
- vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));
329
- color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];
330
- }
331
- }
332
- gl_FragColor = color;
333
- }
334
- `,Convolute_9_0:`
335
- precision highp float;
336
- uniform sampler2D uTexture;
337
- uniform float uMatrix[81];
338
- uniform float uStepW;
339
- uniform float uStepH;
340
- varying vec2 vTexCoord;
341
- void main() {
342
- vec4 color = vec4(0, 0, 0, 1);
343
- for (float h = 0.0; h < 9.0; h+=1.0) {
344
- for (float w = 0.0; w < 9.0; w+=1.0) {
345
- vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));
346
- color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];
347
- }
348
- }
349
- float alpha = texture2D(uTexture, vTexCoord).a;
350
- gl_FragColor = color;
351
- gl_FragColor.a = alpha;
352
- }
353
- `};class ps extends ot{getCacheKey(){return"".concat(this.type,"_").concat(Math.sqrt(this.matrix.length),"_").concat(this.opaque?1:0)}getFragmentSource(){return Qh[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,x,b,w,C,O,k,E,B,P;for(E=0;E<h;E++)for(k=0;k<a;k++){for(x=4*(E*a+k),d=0,g=0,f=0,v=0,P=0;P<i;P++)for(B=0;B<i;B++)w=E+P-n,b=k+B-n,w<0||w>=h||b<0||b>=a||(C=4*(w*a+b),O=r[P*i+B],d+=s[C]*O,g+=s[C+1]*O,f+=s[C+2]*O,u||(v+=s[C+3]*O));l[x]=d,l[x+1]=g,l[x+2]=f,l[x+3]=u?s[x+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(ps,"type","Convolute"),p(ps,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),p(ps,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),D.setClass(ps);const Zn="Gamma";class ms extends ot{getFragmentSource(){return`
354
- precision highp float;
355
- uniform sampler2D uTexture;
356
- uniform vec3 uGamma;
357
- varying vec2 vTexCoord;
358
- void main() {
359
- vec4 color = texture2D(uTexture, vTexCoord);
360
- vec3 correction = (1.0 / uGamma);
361
- color.r = pow(color.r, correction.r);
362
- color.g = pow(color.g, correction.g);
363
- color.b = pow(color.b, correction.b);
364
- gl_FragColor = color;
365
- gl_FragColor.rgb *= color.a;
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:Zn,gamma:this.gamma.concat()}}}p(ms,"type",Zn),p(ms,"defaults",{gamma:[1,1,1]}),p(ms,"uniformLocations",["uGamma"]),D.setClass(ms);const tc={average:`
368
- precision highp float;
369
- uniform sampler2D uTexture;
370
- varying vec2 vTexCoord;
371
- void main() {
372
- vec4 color = texture2D(uTexture, vTexCoord);
373
- float average = (color.r + color.b + color.g) / 3.0;
374
- gl_FragColor = vec4(average, average, average, color.a);
375
- }
376
- `,lightness:`
377
- precision highp float;
378
- uniform sampler2D uTexture;
379
- uniform int uMode;
380
- varying vec2 vTexCoord;
381
- void main() {
382
- vec4 col = texture2D(uTexture, vTexCoord);
383
- float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;
384
- gl_FragColor = vec4(average, average, average, col.a);
385
- }
386
- `,luminosity:`
387
- precision highp float;
388
- uniform sampler2D uTexture;
389
- uniform int uMode;
390
- varying vec2 vTexCoord;
391
- void main() {
392
- vec4 col = texture2D(uTexture, vTexCoord);
393
- float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;
394
- gl_FragColor = vec4(average, average, average, col.a);
395
- }
396
- `};class vs extends ot{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 tc[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}p(vs,"type","Grayscale"),p(vs,"defaults",{mode:"average"}),p(vs,"uniformLocations",["uMode"]),D.setClass(vs);const ec=m(m({},Jn),{},{rotation:0});class pr extends Te{calculateMatrix(){const t=this.rotation*Math.PI,e=$t(t),s=Jt(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(pr,"type","HueRotation"),p(pr,"defaults",ec),D.setClass(pr);class ys extends ot{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
- precision highp float;
398
- uniform sampler2D uTexture;
399
- uniform int uInvert;
400
- uniform int uAlpha;
401
- varying vec2 vTexCoord;
402
- void main() {
403
- vec4 color = texture2D(uTexture, vTexCoord);
404
- if (uInvert == 1) {
405
- if (uAlpha == 1) {
406
- gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,1.0 -color.a);
407
- } else {
408
- gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);
409
- }
410
- } else {
411
- gl_FragColor = color;
412
- }
413
- }
414
- `}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}p(ys,"type","Invert"),p(ys,"defaults",{alpha:!1,invert:!0}),p(ys,"uniformLocations",["uInvert","uAlpha"]),D.setClass(ys);class xs extends ot{getFragmentSource(){return`
415
- precision highp float;
416
- uniform sampler2D uTexture;
417
- uniform float uStepH;
418
- uniform float uNoise;
419
- uniform float uSeed;
420
- varying vec2 vTexCoord;
421
- float rand(vec2 co, float seed, float vScale) {
422
- return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);
423
- }
424
- void main() {
425
- vec4 color = texture2D(uTexture, vTexCoord);
426
- color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;
427
- gl_FragColor = color;
428
- }
429
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=this.noise;for(let r=0;r<e.length;r+=4){const i=(.5-Math.random())*s;e[r]+=i,e[r+1]+=i,e[r+2]+=i}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return this.noise===0}}p(xs,"type","Noise"),p(xs,"defaults",{noise:0}),p(xs,"uniformLocations",["uNoise","uSeed"]),D.setClass(xs);class _s extends ot{applyTo2d(t){let{imageData:{data:e,width:s,height:r}}=t;for(let i=0;i<r;i+=this.blocksize)for(let n=0;n<s;n+=this.blocksize){const a=4*i*s+4*n,h=e[a],c=e[a+1],l=e[a+2],u=e[a+3];for(let d=i;d<Math.min(i+this.blocksize,r);d++)for(let g=n;g<Math.min(n+this.blocksize,s);g++){const f=4*d*s+4*g;e[f]=h,e[f+1]=c,e[f+2]=l,e[f+3]=u}}}isNeutralState(){return this.blocksize===1}getFragmentSource(){return`
430
- precision highp float;
431
- uniform sampler2D uTexture;
432
- uniform float uBlocksize;
433
- uniform float uStepW;
434
- uniform float uStepH;
435
- varying vec2 vTexCoord;
436
- void main() {
437
- float blockW = uBlocksize * uStepW;
438
- float blockH = uBlocksize * uStepH;
439
- int posX = int(vTexCoord.x / blockW);
440
- int posY = int(vTexCoord.y / blockH);
441
- float fposX = float(posX);
442
- float fposY = float(posY);
443
- vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);
444
- vec4 color = texture2D(uTexture, squareCoords);
445
- gl_FragColor = color;
446
- }
447
- `}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}p(_s,"type","Pixelate"),p(_s,"defaults",{blocksize:4}),p(_s,"uniformLocations",["uBlocksize"]),D.setClass(_s);class bs extends ot{getFragmentSource(){return`
448
- precision highp float;
449
- uniform sampler2D uTexture;
450
- uniform vec4 uLow;
451
- uniform vec4 uHigh;
452
- varying vec2 vTexCoord;
453
- void main() {
454
- gl_FragColor = texture2D(uTexture, vTexCoord);
455
- if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {
456
- gl_FragColor.a = 0.0;
457
- }
458
- }
459
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=255*this.distance,r=new H(this.color).getSource(),i=[r[0]-s,r[1]-s,r[2]-s],n=[r[0]+s,r[1]+s,r[2]+s];for(let a=0;a<e.length;a+=4){const h=e[a],c=e[a+1],l=e[a+2];h>i[0]&&c>i[1]&&l>i[2]&&h<n[0]&&c<n[1]&&l<n[2]&&(e[a+3]=0)}}sendUniformData(t,e){const s=new H(this.color).getSource(),r=this.distance,i=[0+s[0]/255-r,0+s[1]/255-r,0+s[2]/255-r,1],n=[s[0]/255+r,s[1]/255+r,s[2]/255+r,1];t.uniform4fv(e.uLow,i),t.uniform4fv(e.uHigh,n)}}p(bs,"type","RemoveColor"),p(bs,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),p(bs,"uniformLocations",["uLow","uHigh"]),D.setClass(bs);class ws extends ot{sendUniformData(t,e){t.uniform2fv(e.uDelta,this.horizontal?[1/this.width,0]:[0,1/this.height]),t.uniform1fv(e.uTaps,this.taps)}getFilterWindow(){const t=this.tempScale;return Math.ceil(this.lanczosLobes/t)}getCacheKey(){const t=this.getFilterWindow();return"".concat(this.type,"_").concat(t)}getFragmentSource(){const t=this.getFilterWindow();return this.generateShader(t)}getTaps(){const t=this.lanczosCreate(this.lanczosLobes),e=this.tempScale,s=this.getFilterWindow(),r=new Array(s);for(let i=1;i<=s;i++)r[i-1]=t(i*e);return r}generateShader(t){const e=new Array(t);for(let s=1;s<=t;s++)e[s-1]="".concat(s,".0 * uDelta");return`
460
- precision highp float;
461
- uniform sampler2D uTexture;
462
- uniform vec2 uDelta;
463
- varying vec2 vTexCoord;
464
- uniform float uTaps[`.concat(t,`];
465
- void main() {
466
- vec4 color = texture2D(uTexture, vTexCoord);
467
- float sum = 1.0;
468
- `).concat(e.map((s,r)=>`
469
- color += texture2D(uTexture, vTexCoord + `.concat(s,") * uTaps[").concat(r,"] + texture2D(uTexture, vTexCoord - ").concat(s,") * uTaps[").concat(r,`];
470
- sum += 2.0 * uTaps[`).concat(r,`];
471
- `)).join(`
472
- `),`
473
- gl_FragColor = color / sum;
474
- }
475
- `)}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){er(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return this.scaleX===1&&this.scaleY===1}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<11920929e-14&&e>-11920929e-14)return 1;const s=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(s)/s}}applyTo2d(t){const e=t.imageData,s=this.scaleX,r=this.scaleY;this.rcpScaleX=1/s,this.rcpScaleY=1/r;const i=e.width,n=e.height,a=Math.round(i*s),h=Math.round(n*r);let c;c=this.resizeType==="sliceHack"?this.sliceByTwo(t,i,n,a,h):this.resizeType==="hermite"?this.hermiteFastResize(t,i,n,a,h):this.resizeType==="bilinear"?this.bilinearFiltering(t,i,n,a,h):this.resizeType==="lanczos"?this.lanczosResize(t,i,n,a,h):new ImageData(a,h),t.imageData=c}sliceByTwo(t,e,s,r,i){const n=t.imageData,a=.5;let h=!1,c=!1,l=e*a,u=s*a;const d=t.filterBackend.resources;let g=0,f=0;const v=e;let x=0;d.sliceByTwo||(d.sliceByTwo=Zt());const b=d.sliceByTwo;(b.width<1.5*e||b.height<s)&&(b.width=1.5*e,b.height=s);const w=b.getContext("2d");for(w.clearRect(0,0,1.5*e,s),w.putImageData(n,0,0),r=Math.floor(r),i=Math.floor(i);!h||!c;)e=l,s=u,r<Math.floor(l*a)?l=Math.floor(l*a):(l=r,h=!0),i<Math.floor(u*a)?u=Math.floor(u*a):(u=i,c=!0),w.drawImage(b,g,f,e,s,v,x,l,u),g=v,f=x,x+=u;return w.getImageData(g,f,r,i)}lanczosResize(t,e,s,r,i){const n=t.imageData.data,a=t.ctx.createImageData(r,i),h=a.data,c=this.lanczosCreate(this.lanczosLobes),l=this.rcpScaleX,u=this.rcpScaleY,d=2/this.rcpScaleX,g=2/this.rcpScaleY,f=Math.ceil(l*this.lanczosLobes/2),v=Math.ceil(u*this.lanczosLobes/2),x={},b={x:0,y:0},w={x:0,y:0};return function C(O){let k,E,B,P,I,U,J,L,Y,W,rt;for(b.x=(O+.5)*l,w.x=Math.floor(b.x),k=0;k<i;k++){for(b.y=(k+.5)*u,w.y=Math.floor(b.y),I=0,U=0,J=0,L=0,Y=0,E=w.x-f;E<=w.x+f;E++)if(!(E<0||E>=e)){W=Math.floor(1e3*Math.abs(E-b.x)),x[W]||(x[W]={});for(let tt=w.y-v;tt<=w.y+v;tt++)tt<0||tt>=s||(rt=Math.floor(1e3*Math.abs(tt-b.y)),x[W][rt]||(x[W][rt]=c(Math.sqrt(Math.pow(W*d,2)+Math.pow(rt*g,2))/1e3)),B=x[W][rt],B>0&&(P=4*(tt*e+E),I+=B,U+=B*n[P],J+=B*n[P+1],L+=B*n[P+2],Y+=B*n[P+3]))}P=4*(k*r+O),h[P]=U/I,h[P+1]=J/I,h[P+2]=L/I,h[P+3]=Y/I}return++O<r?C(O):a}(0)}bilinearFiltering(t,e,s,r,i){let n,a,h,c,l,u,d,g,f,v,x,b,w,C=0;const O=this.rcpScaleX,k=this.rcpScaleY,E=4*(e-1),B=t.imageData.data,P=t.ctx.createImageData(r,i),I=P.data;for(d=0;d<i;d++)for(g=0;g<r;g++)for(l=Math.floor(O*g),u=Math.floor(k*d),f=O*g-l,v=k*d-u,w=4*(u*e+l),x=0;x<4;x++)n=B[w+x],a=B[w+4+x],h=B[w+E+x],c=B[w+E+4+x],b=n*(1-f)*(1-v)+a*f*(1-v)+h*v*(1-f)+c*f*v,I[C++]=b;return P}hermiteFastResize(t,e,s,r,i){const n=this.rcpScaleX,a=this.rcpScaleY,h=Math.ceil(n/2),c=Math.ceil(a/2),l=t.imageData.data,u=t.ctx.createImageData(r,i),d=u.data;for(let g=0;g<i;g++)for(let f=0;f<r;f++){const v=4*(f+g*r);let x=0,b=0,w=0,C=0,O=0,k=0,E=0;const B=(g+.5)*a;for(let P=Math.floor(g*a);P<(g+1)*a;P++){const I=Math.abs(B-(P+.5))/c,U=(f+.5)*n,J=I*I;for(let L=Math.floor(f*n);L<(f+1)*n;L++){let Y=Math.abs(U-(L+.5))/h;const W=Math.sqrt(J+Y*Y);W>1&&W<-1||(x=2*W*W*W-3*W*W+1,x>0&&(Y=4*(L+P*e),E+=x*l[Y+3],w+=x,l[Y+3]<255&&(x=x*l[Y+3]/250),C+=x*l[Y],O+=x*l[Y+1],k+=x*l[Y+2],b+=x))}}d[v]=C/b,d[v+1]=O/b,d[v+2]=k/b,d[v+3]=E/w}return u}}p(ws,"type","Resize"),p(ws,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),p(ws,"uniformLocations",["uDelta","uTaps"]),D.setClass(ws);class Ss extends ot{getFragmentSource(){return`
476
- precision highp float;
477
- uniform sampler2D uTexture;
478
- uniform float uSaturation;
479
- varying vec2 vTexCoord;
480
- void main() {
481
- vec4 color = texture2D(uTexture, vTexCoord);
482
- float rgMax = max(color.r, color.g);
483
- float rgbMax = max(rgMax, color.b);
484
- color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;
485
- color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;
486
- color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;
487
- gl_FragColor = color;
488
- }
489
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=-this.saturation;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);e[r]+=h!==i?(h-i)*s:0,e[r+1]+=h!==n?(h-n)*s:0,e[r+2]+=h!==a?(h-a)*s:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return this.saturation===0}}p(Ss,"type","Saturation"),p(Ss,"defaults",{saturation:0}),p(Ss,"uniformLocations",["uSaturation"]),D.setClass(Ss);class Cs extends ot{getFragmentSource(){return`
490
- precision highp float;
491
- uniform sampler2D uTexture;
492
- uniform float uVibrance;
493
- varying vec2 vTexCoord;
494
- void main() {
495
- vec4 color = texture2D(uTexture, vTexCoord);
496
- float max = max(color.r, max(color.g, color.b));
497
- float avg = (color.r + color.g + color.b) / 3.0;
498
- float amt = (abs(max - avg) * 2.0) * uVibrance;
499
- color.r += max != color.r ? (max - color.r) * amt : 0.00;
500
- color.g += max != color.g ? (max - color.g) * amt : 0.00;
501
- color.b += max != color.b ? (max - color.b) * amt : 0.00;
502
- gl_FragColor = color;
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(Cs,"type","Vibrance"),p(Cs,"defaults",{vibrance:0}),p(Cs,"uniformLocations",["uVibrance"]),D.setClass(Cs);function sc(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 rc=(()=>{let o=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(o+=1,`u${t()}${o}`)})();function ae(o){const t=[];for(let e=0,s=o.length;e<s;e++)t.push(o[e]);return t}let _e=null;function Qn(o={}){return _e||(o.includeStyleProperties?(_e=o.includeStyleProperties,_e):(_e=ae(window.getComputedStyle(document.documentElement)),_e))}function Hs(o,t){const s=(o.ownerDocument.defaultView||window).getComputedStyle(o).getPropertyValue(t);return s?parseFloat(s.replace("px","")):0}function ic(o){const t=Hs(o,"border-left-width"),e=Hs(o,"border-right-width");return o.clientWidth+t+e}function nc(o){const t=Hs(o,"border-top-width"),e=Hs(o,"border-bottom-width");return o.clientHeight+t+e}function to(o,t={}){const e=t.width||ic(o),s=t.height||nc(o);return{width:e,height:s}}function oc(){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 wt=16384;function ac(o){(o.width>wt||o.height>wt)&&(o.width>wt&&o.height>wt?o.width>o.height?(o.height*=wt/o.width,o.width=wt):(o.width*=wt/o.height,o.height=wt):o.width>wt?(o.height*=wt/o.width,o.width=wt):(o.width*=wt/o.height,o.height=wt))}function zs(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 hc(o){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(o)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function cc(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),hc(r)}const yt=(o,t)=>{if(o instanceof t)return!0;const e=Object.getPrototypeOf(o);return e===null?!1:e.constructor.name===t.name||yt(e,t)};function lc(o){const t=o.getPropertyValue("content");return`${o.cssText} content: '${t.replace(/'|"/g,"")}';`}function uc(o,t){return Qn(t).map(e=>{const s=o.getPropertyValue(e),r=o.getPropertyPriority(e);return`${e}: ${s}${r?" !important":""};`}).join(" ")}function dc(o,t,e,s){const r=`.${o}:${t}`,i=e.cssText?lc(e):uc(e,s);return document.createTextNode(`${r}{${i}}`)}function Wi(o,t,e,s){const r=window.getComputedStyle(o,e),i=r.getPropertyValue("content");if(i===""||i==="none")return;const n=rc();try{t.className=`${t.className} ${n}`}catch{return}const a=document.createElement("style");a.appendChild(dc(n,e,r,s)),t.appendChild(a)}function gc(o,t,e){Wi(o,t,":before",e),Wi(o,t,":after",e)}const Xi="application/font-woff",Vi="image/jpeg",fc={woff:Xi,woff2:Xi,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Vi,jpeg:Vi,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function pc(o){const t=/\.([^./]*?)$/g.exec(o);return t?t[1]:""}function $r(o){const t=pc(o).toLowerCase();return fc[t]||""}function mc(o){return o.split(/,/)[1]}function Er(o){return o.search(/^(data:)/)!==-1}function vc(o,t){return`data:${t};base64,${o}`}async function eo(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 mr={};function yc(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 Jr(o,t,e){const s=yc(o,t,e.includeQueryParams);if(mr[s]!=null)return mr[s];e.cacheBust&&(o+=(/\?/.test(o)?"&":"?")+new Date().getTime());let r;try{const i=await eo(o,e.fetchRequestInit,({res:n,result:a})=>(t||(t=n.headers.get("Content-Type")||""),mc(a)));r=vc(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 mr[s]=r,r}async function xc(o){const t=o.toDataURL();return t==="data:,"?o.cloneNode(!1):zs(t)}async function _c(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 zs(a)}const e=o.poster,s=$r(e),r=await Jr(e,s,t);return zs(r)}async function bc(o,t){var e;try{if(!((e=o==null?void 0:o.contentDocument)===null||e===void 0)&&e.body)return await sr(o.contentDocument.body,t,!0)}catch{}return o.cloneNode(!1)}async function wc(o,t){return yt(o,HTMLCanvasElement)?xc(o):yt(o,HTMLVideoElement)?_c(o,t):yt(o,HTMLIFrameElement)?bc(o,t):o.cloneNode(so(o))}const Sc=o=>o.tagName!=null&&o.tagName.toUpperCase()==="SLOT",so=o=>o.tagName!=null&&o.tagName.toUpperCase()==="SVG";async function Cc(o,t,e){var s,r;if(so(t))return t;let i=[];return Sc(o)&&o.assignedNodes?i=ae(o.assignedNodes()):yt(o,HTMLIFrameElement)&&(!((s=o.contentDocument)===null||s===void 0)&&s.body)?i=ae(o.contentDocument.body.childNodes):i=ae(((r=o.shadowRoot)!==null&&r!==void 0?r:o).childNodes),i.length===0||yt(o,HTMLVideoElement)||await i.reduce((n,a)=>n.then(()=>sr(a,e)).then(h=>{h&&t.appendChild(h)}),Promise.resolve()),t}function Tc(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):Qn(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`),yt(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 Oc(o,t){yt(o,HTMLTextAreaElement)&&(t.innerHTML=o.value),yt(o,HTMLInputElement)&&t.setAttribute("value",o.value)}function kc(o,t){if(yt(o,HTMLSelectElement)){const e=t,s=Array.from(e.children).find(r=>o.value===r.getAttribute("value"));s&&s.setAttribute("selected","")}}function Dc(o,t,e){return yt(t,Element)&&(Tc(o,t,e),gc(o,t,e),Oc(o,t),kc(o,t)),t}async function Mc(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 sr(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 sr(o,t,e){return!e&&t.filter&&!t.filter(o)?null:Promise.resolve(o).then(s=>wc(s,t)).then(s=>Cc(o,s,t)).then(s=>Dc(o,s,t)).then(s=>Mc(s,t))}const ro=/url\((['"]?)([^'"]+?)\1\)/g,Ec=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Pc=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Ac(o){const t=o.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function jc(o){const t=[];return o.replace(ro,(e,s,r)=>(t.push(r),e)),t.filter(e=>!Er(e))}async function Fc(o,t,e,s,r){try{const i=e?sc(t,e):t,n=$r(t);let a;return r||(a=await Jr(i,n,s)),o.replace(Ac(t),`$1${a}$3`)}catch{}return o}function Lc(o,{preferredFontFormat:t}){return t?o.replace(Pc,e=>{for(;;){const[s,,r]=Ec.exec(e)||[];if(!r)return"";if(r===t)return`src: ${s};`}}):o}function io(o){return o.search(ro)!==-1}async function no(o,t,e){if(!io(o))return o;const s=Lc(o,e);return jc(s).reduce((i,n)=>i.then(a=>Fc(a,n,t,e)),Promise.resolve(s))}async function be(o,t,e){var s;const r=(s=t.style)===null||s===void 0?void 0:s.getPropertyValue(o);if(r){const i=await no(r,null,e);return t.style.setProperty(o,i,t.style.getPropertyPriority(o)),!0}return!1}async function Rc(o,t){await be("background",o,t)||await be("background-image",o,t),await be("mask",o,t)||await be("-webkit-mask",o,t)||await be("mask-image",o,t)||await be("-webkit-mask-image",o,t)}async function Bc(o,t){const e=yt(o,HTMLImageElement);if(!(e&&!Er(o.src))&&!(yt(o,SVGImageElement)&&!Er(o.href.baseVal)))return;const s=e?o.src:o.href.baseVal,r=await Jr(s,$r(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 Ic(o,t){const s=ae(o.childNodes).map(r=>oo(r,t));await Promise.all(s).then(()=>o)}async function oo(o,t){yt(o,Element)&&(await Rc(o,t),await Bc(o,t),await Ic(o,t))}function Wc(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 Yi={};async function Hi(o){let t=Yi[o];if(t!=null)return t;const s=await(await fetch(o)).text();return t={url:o,cssText:s},Yi[o]=t,t}async function zi(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),eo(a,t.fetchRequestInit,({result:h})=>(e=e.replace(n,`url(${h})`),[n,h]))});return Promise.all(i).then(()=>e)}function Gi(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 Xc(o,t){const e=[],s=[];return o.forEach(r=>{if("cssRules"in r)try{ae(r.cssRules||[]).forEach((i,n)=>{if(i.type===CSSRule.IMPORT_RULE){let a=n+1;const h=i.href,c=Hi(h).then(l=>zi(l,t)).then(l=>Gi(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(Hi(r.href).then(a=>zi(a,t)).then(a=>Gi(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{ae(r.cssRules||[]).forEach(i=>{e.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${r.href}`,i)}}),e))}function Vc(o){return o.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>io(t.style.getPropertyValue("src")))}async function Yc(o,t){if(o.ownerDocument==null)throw new Error("Provided element is not within a Document");const e=ae(o.ownerDocument.styleSheets),s=await Xc(e,t);return Vc(s)}function ao(o){return o.trim().replace(/["']/g,"")}function Hc(o){const t=new Set;function e(s){(s.style.fontFamily||getComputedStyle(s).fontFamily).split(",").forEach(i=>{t.add(ao(i))}),Array.from(s.children).forEach(i=>{i instanceof HTMLElement&&e(i)})}return e(o),t}async function zc(o,t){const e=await Yc(o,t),s=Hc(o);return(await Promise.all(e.filter(i=>s.has(ao(i.style.fontFamily))).map(i=>{const n=i.parentStyleSheet?i.parentStyleSheet.href:null;return no(i.cssText,n,t)}))).join(`
505
- `)}async function Gc(o,t){const e=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await zc(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 Nc(o,t={}){const{width:e,height:s}=to(o,t),r=await sr(o,t,!0);return await Gc(r,t),await oo(r,t),Wc(r,t),await cc(r,e,s)}async function Uc(o,t={}){const{width:e,height:s}=to(o,t),r=await Nc(o,t),i=await zs(r),n=document.createElement("canvas"),a=n.getContext("2d"),h=t.pixelRatio||oc(),c=t.canvasWidth||e,l=t.canvasHeight||s;return n.width=c*h,n.height=l*h,t.skipAutoScale||ac(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 qc(o,t={}){return(await Uc(o,t)).toDataURL()}async function Ni(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 qc(s,{skipFonts:!0,width:r,height:i,pixelRatio:h}),width:t??r,height:e??i}}finally{s.remove()}}function Kc({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,x]=F.useState([]),b=F.useRef(null),w=F.useRef(!1),C=F.useRef(!1),O=F.useRef([]),k=F.useRef(0),[E,B]=F.useState(null),[P,I]=F.useState(null),[U,J]=F.useState(null);F.useEffect(()=>{if(!r.current||i.current)return;const _=new Dr(r.current,{backgroundColor:"#ffffff",selection:!0});i.current=_;const S=()=>{if(!n.current||C.current)return;const{width:T,height:j}=n.current.getBoundingClientRect();_.setDimensions({width:T,height:j})};S();const M=new ResizeObserver(S);return n.current&&M.observe(n.current),f([JSON.stringify(_.toJSON())]),()=>{M.disconnect(),_.dispose(),i.current=null}},[]),F.useEffect(()=>{const _=i.current;if(!_)return;const S=async M=>{const T=M.target,j=T==null?void 0:T._componentMeta;if(!(j!=null&&j.ghostHtml)||T.type!=="image")return;const N=Math.round((T.width??0)*(T.scaleX??1)),X=Math.round((T.height??0)*(T.scaleY??1));if(!(N<4||X<4))try{const{dataUrl:lt,width:Ht,height:Dt}=await Ni(j.ghostHtml,N,X),it=await ht.fromURL(lt);it.set({left:T.left,top:T.top,scaleX:N/(it.width??Ht),scaleY:X/(it.height??Dt)}),it._componentMeta=j;const se=_.getObjects().indexOf(T);_.remove(T),_.insertAt(se,it),_.setActiveObject(it),_.requestRenderAll()}catch{}};return _.on("object:modified",S),()=>{_.off("object:modified",S)}},[]),F.useEffect(()=>{if(!t)return;const _=i.current;_&&ht.fromURL(t).then(S=>{!S.width||!S.height||(C.current=!0,_.setDimensions({width:S.width,height:S.height}),B(S.height),S.set({selectable:!1,evented:!1,hasBorders:!1,hasControls:!1}),_.backgroundImage=S,_.requestRenderAll())})},[t]),F.useEffect(()=>{const _=i.current;if(!_)return;const S=_.getActiveObjects();S.length!==0&&(S.forEach(M=>{"fill"in M&&M.fill!==""&&M.fill!==null&&M.set("fill",c)}),_.requestRenderAll())},[c]),F.useEffect(()=>{const _=i.current;if(!_)return;const S=_.getActiveObjects();S.length!==0&&(S.forEach(M=>{"stroke"in M&&M.set("stroke",u)}),_.requestRenderAll())},[u]);const L=F.useCallback(()=>{const _=i.current;if(!_)return;const S=JSON.stringify(_.toJSON());f(M=>[...M,S]),x([])},[]);F.useEffect(()=>{const _=i.current;if(_){if(_.isDrawingMode=!1,_.selection=!0,_.defaultCursor="default",_.getObjects().forEach(S=>{S.evented=!0,S.selectable=!0,S.hasControls=!0,S.hasBorders=!0,S.setCoords()}),_.requestRenderAll(),_.off("mouse:down"),_.off("mouse:move"),_.off("mouse:up"),a==="freehand"){_.isDrawingMode=!0;const S=new Ys(_);S.color=u,S.width=2,_.freeDrawingBrush=S,_.on("path:created",M=>{L();const T=M.path;T&&(_.setActiveObject(T),_.requestRenderAll()),h("select")})}else if(a==="eraser"){_.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>';_.defaultCursor=`url("data:image/svg+xml,${S}") 4 18, auto`,_.on("mouse:down",M=>{const T=_.findTarget(M.e);T&&(_.remove(T),L())})}else if(a!=="select"){if(a==="text")_.selection=!1,_.defaultCursor="text",_.on("mouse:down",S=>{if(w.current)return;const M=_.getScenePoint(S.e),T=new qt("Text",{left:M.x,top:M.y,fontSize:16,fill:u,width:120});_.add(T),_.setActiveObject(T),T.enterEditing(),T.selectAll(),L()});else if(["rectangle","circle","line","arrow"].includes(a)){_.selection=!1,_.defaultCursor="crosshair",_.getObjects().forEach(M=>{M.evented=!1,M.selectable=!1});let S=null;_.on("mouse:down",M=>{_.getObjects().forEach(j=>{j.evented=!1,j.selectable=!1}),w.current=!0;const T=_.getScenePoint(M.e);b.current={x:T.x,y:T.y},a==="rectangle"?(S=new Ct({left:T.x,top:T.y,width:0,height:0,fill:c==="transparent"?"transparent":c,stroke:u,strokeWidth:2,selectable:!1}),_.add(S)):a==="circle"?(S=new Rt({left:T.x,top:T.y,radius:0,fill:c==="transparent"?"transparent":c,stroke:u,strokeWidth:2,selectable:!1}),_.add(S)):(a==="line"||a==="arrow")&&(S=new It([T.x,T.y,T.x,T.y],{stroke:u,strokeWidth:2,selectable:!1}),_.add(S))}),_.on("mouse:move",M=>{if(!b.current||!S)return;const T=_.getScenePoint(M.e),j=b.current;if(a==="rectangle"){const N=Math.min(j.x,T.x),X=Math.min(j.y,T.y);S.set({left:N,top:X,width:Math.abs(T.x-j.x),height:Math.abs(T.y-j.y)})}else if(a==="circle"){const N=Math.abs(T.x-j.x)/2,X=Math.abs(T.y-j.y)/2;S.set({left:Math.min(j.x,T.x),top:Math.min(j.y,T.y),radius:Math.max(N,X)})}else(a==="line"||a==="arrow")&&S.set({x2:T.x,y2:T.y});_.requestRenderAll()}),_.on("mouse:up",()=>{if(S){if(a==="arrow"&&b.current){const M=S.x1,T=S.y1,j=S.x2,N=S.y2,X=Math.atan2(N-T,j-M),lt=12,Ht=new It([j-lt*Math.cos(X-Math.PI/6),N-lt*Math.sin(X-Math.PI/6),j,N],{stroke:u,strokeWidth:2,selectable:!1}),Dt=new It([j-lt*Math.cos(X+Math.PI/6),N-lt*Math.sin(X+Math.PI/6),j,N],{stroke:u,strokeWidth:2,selectable:!1});_.add(Ht,Dt)}L(),S.set({evented:!0,selectable:!0,hasControls:!0,hasBorders:!0}),S.setCoords(),_.setActiveObject(S),_.requestRenderAll(),h("select")}S=null,b.current=null,w.current=!1})}}}},[a,c,u,L]);const Y=F.useCallback(()=>{const _=i.current;if(!_||g.length<=1)return;const S=g[g.length-1],M=g[g.length-2];x(T=>[...T,S]),f(T=>T.slice(0,-1)),_.loadFromJSON(JSON.parse(M)).then(()=>_.requestRenderAll())},[g]),W=F.useCallback(()=>{const _=i.current;if(!_||v.length===0)return;const S=v[v.length-1];x(M=>M.slice(0,-1)),f(M=>[...M,S]),_.loadFromJSON(JSON.parse(S)).then(()=>_.requestRenderAll())},[v]),rt=F.useCallback(()=>{const _=i.current;_&&(_.clear(),t?ht.fromURL(t).then(S=>{!S.width||!S.height||(S.set({selectable:!1,evented:!1,hasBorders:!1,hasControls:!1}),_.backgroundImage=S,_.requestRenderAll())}):(_.backgroundColor="#ffffff",_.requestRenderAll()),L())},[L,t]),tt=F.useCallback(()=>{const _=i.current;if(!_)return;const S=_.toDataURL({format:"png",multiplier:1}),M=[];for(const T of _.getObjects()){const j=T._componentMeta;j&&M.push({componentName:j.componentName,componentPath:j.componentPath,storyId:j.storyId,args:j.args,x:Math.round(T.left??0),y:Math.round(T.top??0),width:Math.round((T.width??0)*(T.scaleX??1)),height:Math.round((T.height??0)*(T.scaleY??1))})}o(S,_.getWidth(),_.getHeight(),M.length>0?M:void 0)},[o]),et=F.useCallback(()=>{const _=i.current;if(!_)return;const S=_.getActiveObjects();if(S.length>0){for(const M of S)_.remove(M);_.discardActiveObject(),_.requestRenderAll(),L()}},[L]),G=F.useCallback(()=>{const _=i.current;if(!_)return;const S=_.getActiveObjects();S.length!==0&&Promise.all(S.map(M=>M.clone())).then(M=>{O.current=M,k.current=0})},[]),_t=F.useCallback(()=>{const _=i.current;if(!_||O.current.length===0)return;const S=20;k.current+=S;const M=k.current;Promise.all(O.current.map(T=>T.clone())).then(T=>{if(_.discardActiveObject(),T.forEach(j=>{j.set({left:(j.left??0)+M,top:(j.top??0)+M,evented:!0,selectable:!0}),j.setCoords(),_.add(j)}),T.length===1)_.setActiveObject(T[0]);else{const j=new _.constructor.ActiveSelection(T,{canvas:_});_.setActiveObject(j)}_.requestRenderAll(),L()})},[L]);return F.useEffect(()=>{const _=S=>{if(S.key==="Delete"||S.key==="Backspace"){const M=i.current;if(M){const T=M.getActiveObject();if(T&&T.type==="textbox"&&T.isEditing)return}et()}if((S.metaKey||S.ctrlKey)&&S.key==="z"&&(S.preventDefault(),S.shiftKey?W():Y()),(S.metaKey||S.ctrlKey)&&S.key==="c"){const M=i.current;if(M){const T=M.getActiveObject();if(T&&T.type==="textbox"&&T.isEditing)return}G()}if((S.metaKey||S.ctrlKey)&&S.key==="v"){const M=i.current;if(M){const T=M.getActiveObject();if(T&&T.type==="textbox"&&T.isEditing)return}S.preventDefault(),_t()}};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[et,Y,W,G,_t]),F.useEffect(()=>{if(!(e!=null&&e.ghostHtml)){J(null),I(null);return}const _=document.createElement("div");_.style.cssText="position:fixed;left:-99999px;top:-99999px;visibility:hidden;pointer-events:none;",_.innerHTML=e.ghostHtml,document.body.appendChild(_),J({width:_.offsetWidth||100,height:_.offsetHeight||40}),document.body.removeChild(_)},[e]),F.useEffect(()=>{const _=n.current;if(!_||!e){I(null);return}const S=N=>{const X=_.getBoundingClientRect();I({x:N.clientX-X.left,y:N.clientY-X.top})},M=()=>I(null),T=N=>{const X=_.getBoundingClientRect();I({x:N.clientX-X.left,y:N.clientY-X.top})},j=async N=>{N.preventDefault(),N.stopPropagation();const X=i.current;if(!X||!e.ghostHtml)return;const lt=_.getBoundingClientRect(),Ht=N.clientX-lt.left,Dt=N.clientY-lt.top;try{const{dataUrl:it,width:se,height:ve}=await Ni(e.ghostHtml),re=await ht.fromURL(it);re.set({left:Ht-se/2,top:Dt-ve/2,scaleX:1,scaleY:1}),re._componentMeta={componentName:e.componentName,componentPath:e.componentPath,storyId:e.storyId,args:e.args,ghostHtml:e.ghostHtml},X.add(re),X.setActiveObject(re),X.requestRenderAll(),L(),h("select")}catch(it){console.error("[DesignCanvas] Failed to rasterize component:",it);const se=(U==null?void 0:U.width)??100,ve=(U==null?void 0:U.height)??40,re=new Ct({left:Ht-se/2,top:Dt-ve/2,width:se,height:ve,fill:"rgba(0, 132, 139, 0.08)",stroke:"#00848B",strokeWidth:2,strokeDashArray:[4,4]});re._componentMeta={componentName:e.componentName,componentPath:e.componentPath,storyId:e.storyId,args:e.args,ghostHtml:e.ghostHtml};const ho=new qt(e.componentName,{left:Ht-se/2+4,top:Dt-ve/2+(ve-14)/2,fontSize:12,fill:"#00848B",width:se-8,selectable:!1,evented:!1});X.add(re,ho),X.setActiveObject(re),X.requestRenderAll(),L(),h("select")}s==null||s()};return _.addEventListener("mousemove",S),_.addEventListener("mouseleave",M),_.addEventListener("mouseenter",T),_.addEventListener("click",j,{capture:!0}),()=>{_.removeEventListener("mousemove",S),_.removeEventListener("mouseleave",M),_.removeEventListener("mouseenter",T),_.removeEventListener("click",j,{capture:!0})}},[e,U,L,s]),{canvasElRef:r,containerRef:n,lockedHeight:E,activeTool:a,setActiveTool:h,fillColor:c,setFillColor:l,strokeColor:u,setStrokeColor:d,canUndo:g.length>1,canRedo:v.length>0,handleUndo:Y,handleRedo:W,handleClear:rt,handleSubmit:tt,ghostPos:P,ghostSize:U}}const Ui=["#000000","#ffffff","#9CA3AF","#EF4444","#F97316","#EAB308","#22C55E","#3B82F6","#8B5CF6","#EC4899","#14B8A6","#6366F1"],$c=()=>A.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[A.jsx("path",{d:"M5 3l14 8-6 2-4 6z"}),A.jsx("path",{d:"M13 13l6 6"})]}),Jc=()=>A.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[A.jsx("path",{d:"m7 21-4-4 9.5-9.5 5.5 5.5L7 21Z"}),A.jsx("path",{d:"M22 21H7"}),A.jsx("path",{d:"m11.5 12.5 5.5 5.5"})]}),Zc=()=>A.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[A.jsx("polyline",{points:"3 6 5 6 21 6"}),A.jsx("path",{d:"M19 6l-1 14H6L5 6"}),A.jsx("path",{d:"M10 11v6M14 11v6"}),A.jsx("path",{d:"M9 6V4h6v2"})]}),Qc=[{id:"select",label:"Select",icon:A.jsx($c,{})},{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:A.jsx(Jc,{})}];function tl({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,x]=F.useState(!1),b=F.useRef(null),w=F.useRef(null);return F.useEffect(()=>{const C=O=>{g&&b.current&&!b.current.contains(O.target)&&f(!1),v&&w.current&&!w.current.contains(O.target)&&x(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[g,v]),A.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:[Qc.map(C=>A.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
- ${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)),A.jsx("div",{className:"w-px h-[18px] bg-bv-border mx-1"}),A.jsxs("div",{ref:b,className:"relative",children:[A.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),x(!1)},children:A.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"currentColor",className:"text-bv-text-mid",children:[A.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"}),A.jsx("path",{d:"M0 20h24v4H0z",style:{fill:e==="transparent"?"none":e,stroke:e==="transparent"?"#aaa":"none",strokeWidth:e==="transparent"?1:0}})]})}),g&&A.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:[A.jsx("div",{className:"text-[9px] font-semibold uppercase tracking-wider text-bv-muted mb-1.5",children:"Fill Color"}),A.jsx("div",{className:"grid grid-cols-6 gap-1 mb-2",children:Ui.map(C=>A.jsx("button",{className:`w-[22px] h-[22px] rounded cursor-pointer transition-all hover:scale-110
507
- ${e===C?"ring-2 ring-bv-teal ring-offset-1":"border border-black/10"}`,style:{background:C},onClick:()=>{s(C),f(!1)}},C))}),A.jsxs("div",{className:"pt-1 border-t border-bv-border flex items-center gap-1.5",children:[A.jsx("button",{className:`w-[22px] h-[22px] rounded cursor-pointer border border-bv-border
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)}}),A.jsx("span",{className:"text-[9px] text-bv-muted",children:"None"})]})]})]}),A.jsxs("div",{ref:w,className:"relative",children:[A.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:()=>{x(!v),f(!1)},children:A.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"currentColor",className:"text-bv-text-mid",children:[A.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"}),A.jsx("rect",{x:"0",y:"21",width:"24",height:"3",style:{fill:r}})]})}),v&&A.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:[A.jsx("div",{className:"text-[9px] font-semibold uppercase tracking-wider text-bv-muted mb-1.5",children:"Stroke Color"}),A.jsx("div",{className:"grid grid-cols-6 gap-1",children:Ui.map(C=>A.jsx("button",{className:`w-[22px] h-[22px] rounded cursor-pointer transition-all hover:scale-110
509
- ${r===C?"ring-2 ring-bv-teal ring-offset-1":"border border-black/10"}`,style:{background:C},onClick:()=>{i(C),x(!1)}},C))})]})]}),A.jsx("div",{className:"w-px h-[18px] bg-bv-border mx-1"}),A.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
- ${n?"text-bv-text-mid hover:bg-bv-surface hover:border-bv-border hover:text-bv-text":"opacity-35 cursor-default"}`,children:"↶"}),A.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:"↷"}),A.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:A.jsx(Zc,{})}),d&&A.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&&A.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 el({onSubmit:o,onClose:t,backgroundImage:e,armedComponent:s,onComponentPlaced:r}){const{canvasElRef:i,containerRef:n,lockedHeight:a,activeTool:h,setActiveTool:c,fillColor:l,setFillColor:u,strokeColor:d,setStrokeColor:g,canUndo:f,canRedo:v,handleUndo:x,handleRedo:b,handleClear:w,handleSubmit:C,ghostPos:O,ghostSize:k}=Kc({onSubmit:o,backgroundImage:e,armedComponent:s,onComponentPlaced:r}),E=!!s;return A.jsxs("div",{className:"flex flex-col h-full","data-testid":"design-canvas",children:[A.jsx(tl,{activeTool:h,onToolChange:c,fillColor:l,onFillChange:u,strokeColor:d,onStrokeChange:g,canUndo:f,canRedo:v,onUndo:x,onRedo:b,onClear:w,onSubmit:C,onClose:t}),A.jsxs("div",{ref:n,className:"bg-white overflow-hidden relative cursor-crosshair",style:a!==null?{height:a}:{flex:1},children:[A.jsx("canvas",{ref:i}),E&&O&&(s==null?void 0:s.ghostHtml)&&A.jsx("div",{style:{position:"absolute",left:O.x-((k==null?void 0:k.width)??0)/2,top:O.y-((k==null?void 0:k.height)??0)/2,pointerEvents:"none",opacity:.6,outline:"2px dashed #00848B",outlineOffset:2,zIndex:10},dangerouslySetInnerHTML:{__html:s.ghostHtml}}),E&&A.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 rl(){const[o,t]=F.useState(null),[e,s]=F.useState(null);F.useEffect(()=>{lo(()=>{Be({type:"REGISTER",role:"design"})}),uo(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)}),co()},[]);const r=F.useCallback((a,h,c,l)=>{Be({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=()=>{Be({type:"DESIGN_CLOSE"})},n=F.useCallback(()=>{s(null),Be({type:"COMPONENT_DISARMED",to:"panel"}),Be({type:"COMPONENT_DISARM",to:"overlay"})},[]);return A.jsx("div",{className:"h-screen w-screen flex flex-col",children:A.jsx("div",{className:"flex-1 overflow-hidden",children:A.jsx(el,{onSubmit:r,onClose:i,backgroundImage:o==null?void 0:o.screenshot,armedComponent:e,onComponentPlaced:n})})})}export{rl as DesignMode};