@jetprint/editor-sdk 1.2.1 → 1.2.2

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,504 +0,0 @@
1
- var EditorHeadless=(function(Bt){"use strict";var El=Object.defineProperty;var Pl=(Bt,y,ne)=>y in Bt?El(Bt,y,{enumerable:!0,configurable:!0,writable:!0,value:ne}):Bt[y]=ne;var gr=(Bt,y,ne)=>Pl(Bt,typeof y!="symbol"?y+"":y,ne);function y(n,t,e){return(t=(function(s){var r=(function(i,o){if(typeof i!="object"||!i)return i;var a=i[Symbol.toPrimitive];if(a!==void 0){var h=a.call(i,o);if(typeof h!="object")return h;throw new TypeError("@@toPrimitive must return a primitive value.")}return(o==="string"?String:Number)(i)})(s,"string");return typeof r=="symbol"?r:r+""})(t))in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}class ne{constructor(){y(this,"browserShadowBlurConstant",1),y(this,"DPI",96),y(this,"devicePixelRatio",typeof window!="undefined"?window.devicePixelRatio:1),y(this,"perfLimitSizeTotal",2097152),y(this,"maxCacheSideLimit",4096),y(this,"minCacheSideLimit",256),y(this,"disableStyleCopyPaste",!1),y(this,"enableGLFiltering",!0),y(this,"textureSize",4096),y(this,"forceGLPutImageData",!1),y(this,"cachesBoundsOfCurve",!1),y(this,"fontPaths",{}),y(this,"NUM_FRACTION_DIGITS",4)}}const B=new class extends ne{constructor(n){super(),this.configure(n)}configure(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,n)}addFonts(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};this.fontPaths={...this.fontPaths,...n}}removeFonts(){(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).forEach(n=>{delete this.fontPaths[n]})}clearFonts(){this.fontPaths={}}restoreDefaults(n){const t=new ne,e=(n==null?void 0:n.reduce((s,r)=>(s[r]=t[r],s),{}))||t;this.configure(e)}},Qt=function(n){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[n]("fabric",...e)};class Pt extends Error{constructor(t,e){super(`fabric: ${t}`,e)}}class Xo extends Pt{constructor(t){super(`${t} 'options.signal' is in 'aborted' state`)}}class Wo{}class Yo extends Wo{testPrecision(t,e){const s=`precision ${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(),Qt("log",`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const Ho={};let Ci;const At=()=>Ci||(Ci={document,window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new Yo,dispose(){},copyPasteData:Ho}),Te=()=>At().document,ns=()=>At().window,bi=()=>{var n;return Math.max((n=B.devicePixelRatio)!==null&&n!==void 0?n:ns().devicePixelRatio,1)},He=new class{constructor(){y(this,"boundsOfCurveCache",{}),this.charWidthsCache=new Map}getFontCache(n){let{fontFamily:t,fontStyle:e,fontWeight:s}=n;t=t.toLowerCase();const r=this.charWidthsCache;r.has(t)||r.set(t,new Map);const i=r.get(t),o=`${e.toLowerCase()}_${(s+"").toLowerCase()}`;return i.has(o)||i.set(o,new Map),i.get(o)}clearFontCache(n){n?this.charWidthsCache.delete((n||"").toLowerCase()):this.charWidthsCache=new Map}limitDimsByArea(n){const{perfLimitSizeTotal:t}=B,e=Math.sqrt(t*n);return[Math.floor(e),Math.floor(t/e)]}},fr="7.1.0";function os(){}const Zt=Math.PI/2,No=Math.PI/4,wt=2*Math.PI,pr=Math.PI/180,nt=Object.freeze([1,0,0,1,0,0]),mr=16,Jt=.4477152502,A="center",$="left",ut="top",yr="bottom",q="right",gt="none",vr=/\r?\n/,Ti="moving",as="scaling",Oi="rotating",xr="rotate",Mi="skewing",Ne="resizing",Vo="modifyPoly",Go="modifyPath",hs="changed",ls="scale",ot="scaleX",dt="scaleY",Oe="skewX",Me="skewY",J="fill",ft="stroke",cs="modified",oe="ltr",$t="rtl",_r="normal",ke="json",wr="svg",O=new class{constructor(){this[ke]=new Map,this[wr]=new Map}has(n){return this[ke].has(n)}getClass(n){const t=this[ke].get(n);if(!t)throw new Pt(`No class registered for ${n}`);return t}setClass(n,t){t?this[ke].set(t,n):(this[ke].set(n.type,n),this[ke].set(n.type.toLowerCase(),n))}getSVGClass(n){return this[wr].get(n)}setSVGClass(n,t){this[wr].set(t!=null?t:n.type.toLowerCase(),n)}},us=new class extends Array{remove(n){const t=this.indexOf(n);t>-1&&this.splice(t,1)}cancelAll(){const n=this.splice(0);return n.forEach(t=>t.abort()),n}cancelByCanvas(n){if(!n)return[];const t=this.filter(e=>{var s;return e.target===n||typeof e.target=="object"&&((s=e.target)===null||s===void 0?void 0:s.canvas)===n});return t.forEach(e=>e.abort()),t}cancelByTarget(n){if(!n)return[];const t=this.filter(e=>e.target===n);return t.forEach(e=>e.abort()),t}};class zo{constructor(){y(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,o]=r;s.push(this.once(i,o))}),()=>s.forEach(r=>r())}if(e){const s=this.on(t,function(){for(var r=arguments.length,i=new Array(r),o=0;o<r;o++)i[o]=arguments[o];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 ae=(n,t)=>{const e=n.indexOf(t);return e!==-1&&n.splice(e,1),n},St=n=>{if(n===0)return 1;switch(Math.abs(n)/Zt){case 1:case 3:return 0;case 2:return-1}return Math.cos(n)},Ct=n=>{if(n===0)return 0;const t=n/Zt,e=Math.sign(n);switch(t){case 1:return e;case 2:return 0;case 3:return-e}return Math.sin(n)};class _{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 _(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new _(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new _(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new _(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new _(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new _(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new _(this.x/t.x,this.y/t.y)}scalarDivide(t){return new _(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 _(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 _(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new _(Math.max(this.x,t.x),Math.max(this.y,t.y))}toString(){return`${this.x},${this.y}`}setXY(t,e){return this.x=t,this.y=e,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setFromPoint(t){return this.x=t.x,this.y=t.y,this}swap(t){const e=this.x,s=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=s}clone(){return new _(this.x,this.y)}rotate(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:Sr;const s=Ct(t),r=St(t),i=this.subtract(e);return new _(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 _(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 Sr=new _(0,0),gs=n=>!!n&&Array.isArray(n._objects);function ki(n){class t extends n{constructor(){super(...arguments),y(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 o=this._objects.push(...r);return r.forEach(a=>this._onObjectAdded(a)),o}insertAt(s){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];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,o=new Array(i),a=0;a<i;a++)o[a]=arguments[a];return o.forEach(h=>{const l=s.indexOf(h);l!==-1&&(s.splice(l,1),r.push(h),this._onObjectRemoved(h))}),r}forEachObject(s){this.getObjects().forEach((r,i,o)=>s(r,i,o))}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(o=>o.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])&&(ae(this._objects,s),this._objects.unshift(s),this._onStackOrderChanged(s),!0)}bringObjectToFront(s){return!(!s||s===this._objects[this._objects.length-1])&&(ae(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 o=this.findNewLowerIndex(s,i,r);return ae(this._objects,s),this._objects.splice(o,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 o=this.findNewUpperIndex(s,i,r);return ae(this._objects,s),this._objects.splice(o,0,s),this._onStackOrderChanged(s),!0}return!1}moveObjectTo(s,r){return s!==this._objects[r]&&(ae(this._objects,s),this._objects.splice(r,0,s),this._onStackOrderChanged(s),!0)}findNewLowerIndex(s,r,i){let o;if(i){o=r;for(let a=r-1;a>=0;--a)if(s.isOverlapping(this._objects[a])){o=a;break}}else o=r-1;return o}findNewUpperIndex(s,r,i){let o;if(i){o=r;for(let a=r+1;a<this._objects.length;++a)if(s.isOverlapping(this._objects[a])){o=a;break}}else o=r+1;return o}collectObjects(s){let{left:r,top:i,width:o,height:a}=s,{includeIntersecting:h=!0}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const l=[],c=new _(r,i),u=c.add(new _(o,a));for(let g=this._objects.length-1;g>=0;g--){const d=this._objects[g];d.selectable&&d.visible&&(h&&d.intersectsWithRect(c,u)||d.isContainedWithinRect(c,u)||h&&d.containsPoint(c)||h&&d.containsPoint(u))&&l.push(d)}return l}}return t}class Di extends zo{_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 Ve(n){return ns().requestAnimationFrame(n)}function Ei(n){return ns().cancelAnimationFrame(n)}let Uo=0;const te=()=>Uo++,Ft=()=>{const n=Te().createElement("canvas");if(!n||n.getContext===void 0)throw new Pt("Failed to create `canvas` element");return n},Pi=()=>Te().createElement("img"),pt=n=>{const t=Ft();return t.width=n.width,t.height=n.height,t},Cr=(n,t,e)=>n.toDataURL(`image/${t}`,e),br=(n,t,e)=>new Promise((s,r)=>{n.toBlob(s,`image/${t}`,e)}),U=n=>n*pr,Xt=n=>n/pr,Ai=n=>n.every((t,e)=>t===nt[e]),et=(n,t,e)=>new _(n).transform(t,e),mt=n=>{const t=1/(n[0]*n[3]-n[1]*n[2]),e=[t*n[3],-t*n[1],-t*n[2],t*n[0],0,0],{x:s,y:r}=new _(n[4],n[5]).transform(e,!0);return e[4]=-s,e[5]=-r,e},K=(n,t,e)=>[n[0]*t[0]+n[2]*t[1],n[1]*t[0]+n[3]*t[1],n[0]*t[2]+n[2]*t[3],n[1]*t[2]+n[3]*t[3],e?0:n[0]*t[4]+n[2]*t[5]+n[4],e?0:n[1]*t[4]+n[3]*t[5]+n[5]],ds=(n,t)=>n.reduceRight((e,s)=>s&&e?K(s,e,t):s||e,void 0)||nt.concat(),Fi=n=>{let[t,e]=n;return Math.atan2(e,t)},De=n=>{const t=Fi(n),e=Math.pow(n[0],2)+Math.pow(n[1],2),s=Math.sqrt(e),r=(n[0]*n[3]-n[2]*n[1])/s,i=Math.atan2(n[0]*n[2]+n[1]*n[3],e);return{angle:Xt(t),scaleX:s,scaleY:r,skewX:Xt(i),skewY:0,translateX:n[4]||0,translateY:n[5]||0}},Ee=function(n){return[1,0,0,1,n,arguments.length>1&&arguments[1]!==void 0?arguments[1]:0]};function he(){let{angle:n=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=U(n),r=St(s),i=Ct(s);return[r,i,-i,r,t?t-(r*t-i*e):0,e?e-(i*t+r*e):0]}const fs=function(n){return[n,0,0,arguments.length>1&&arguments[1]!==void 0?arguments[1]:n,0,0]},Li=n=>Math.tan(U(n)),Tr=n=>[1,0,Li(n),1,0,0],Or=n=>[1,Li(n),0,1,0,0],Ge=n=>{let{scaleX:t=1,scaleY:e=1,flipX:s=!1,flipY:r=!1,skewX:i=0,skewY:o=0}=n,a=fs(s?-t:t,r?-e:e);return i&&(a=K(a,Tr(i),!0)),o&&(a=K(a,Or(o),!0)),a},ji=n=>{const{translateX:t=0,translateY:e=0,angle:s=0}=n;let r=Ee(t,e);s&&(r=K(r,he({angle:s})));const i=Ge(n);return Ai(i)||(r=K(r,i)),r},ze=function(n){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 Xo("loadImage"));const i=Pi();let o;t&&(o=function(h){i.src="",r(h)},t.addEventListener("abort",o,{once:!0}));const a=function(){i.onload=i.onerror=null,o&&(t==null||t.removeEventListener("abort",o)),s(i)};n?(i.onload=a,i.onerror=function(){o&&(t==null||t.removeEventListener("abort",o)),r(new Pt(`Error loading ${i.src}`))},e&&(i.crossOrigin=e),i.src=n):a()})},Pe=function(n){let{signal:t,reviver:e=os}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise((s,r)=>{const i=[];t&&t.addEventListener("abort",r,{once:!0}),Promise.all(n.map(o=>O.getClass(o.type).fromObject(o,{signal:t}).then(a=>(e(o,a),i.push(a),a)))).then(s).catch(o=>{i.forEach(a=>{a.dispose&&a.dispose()}),r(o)}).finally(()=>{t&&t.removeEventListener("abort",r)})})},Ue=function(n){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(n).map(a=>a&&a.type&&O.has(a.type)?Pe([a],{signal:t}).then(h=>{let[l]=h;return r.push(l),l}):a),o=Object.keys(n);Promise.all(i).then(a=>a.reduce((h,l,c)=>(h[o[c]]=l,h),{})).then(e).catch(a=>{r.forEach(h=>{h.dispose&&h.dispose()}),s(a)}).finally(()=>{t&&t.removeEventListener("abort",s)})})},le=function(n){return(arguments.length>1&&arguments[1]!==void 0?arguments[1]:[]).reduce((t,e)=>(e in n&&(t[e]=n[e]),t),{})},Mr=(n,t)=>Object.keys(n).reduce((e,s)=>(t(n[s],s,n)&&(e[s]=n[s]),e),{}),X=(n,t)=>parseFloat(Number(n).toFixed(t)),Ae=n=>"matrix("+n.map(t=>X(t,B.NUM_FRACTION_DIGITS)).join(" ")+")",vt=n=>!!n&&n.toLive!==void 0,Ii=n=>!!n&&typeof n.toObject=="function",Ri=n=>!!n&&n.offsetX!==void 0&&"source"in n,ce=n=>!!n&&"multiSelectionStacking"in n;function Bi(n){const t=n&&bt(n);let e=0,s=0;if(!n||!t)return{left:e,top:s};let r=n;const i=t.documentElement,o=t.body||{scrollLeft:0,scrollTop:0};for(;r&&(r.parentNode||r.host)&&(r=r.parentNode||r.host,r===t?(e=o.scrollLeft||i.scrollLeft||0,s=o.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 bt=n=>n.ownerDocument||null,$i=n=>{var t;return((t=n.ownerDocument)===null||t===void 0?void 0:t.defaultView)||null},Xi=function(n,t,e){let{width:s,height:r}=e,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:1;n.width=s,n.height=r,i>1&&(n.setAttribute("width",(s*i).toString()),n.setAttribute("height",(r*i).toString()),t.scale(i,i))},kr=(n,t)=>{let{width:e,height:s}=t;e&&(n.style.width=typeof e=="number"?`${e}px`:e),s&&(n.style.height=typeof s=="number"?`${s}px`:s)};function Wi(n){return n.onselectstart!==void 0&&(n.onselectstart=()=>!1),n.style.userSelect=gt,n}class Yi{constructor(t){y(this,"_originalCanvasStyle",void 0),y(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&&Te().getElementById(t)||Ft();var s;if(e.hasAttribute("data-fabric"))throw new Pt("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",`${e}`),r.setAttribute("height",`${s}`),r.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:s,ctx:r}=this.lower;Xi(s,r,t,e)}setCSSDimensions(t){kr(this.lower.el,t)}calcOffset(){return(function(t){var e;const s=t&&bt(t),r={left:0,top:0};if(!s)return r;const i=((e=$i(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 o={left:0,top:0};const a=s.documentElement;t.getBoundingClientRect!==void 0&&(o=t.getBoundingClientRect());const h=Bi(t);return{left:o.left+h.left-(a.clientLeft||0)+r.left,top:o.top+h.top-(a.clientTop||0)+r.top}})(this.lower.el)}dispose(){At().dispose(this.lower.el),delete this.lower}}const qo={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...nt],patternQuality:"best"};class Fe extends ki(Di){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 Fe.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 Yi(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&&(Qt("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?bi():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:s=!1}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(!e){const r={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=et(t,mt(r));r[0]=e,r[3]=e;const o=et(i,r);r[4]+=s.x-o.x,r[5]+=s.y-o.y,this.setViewportTransform(r)}setZoom(t){this.zoomToPoint(new _(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 _(-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=Ve(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,s=mt(this.viewportTransform),r=et({x:0,y:0},s),i=et({x:t,y:e},s),o=r.min(i),a=r.max(i);return this.vptCoords={tl:o,tr:new _(a.x,o.y),bl:new _(o.x,a.y),br:a}}cancelRequestedRender(){this.nextRenderHandle&&(Ei(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=this.patternQuality,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[`${e}Color`],r=this[`${e}Image`],i=this.viewportTransform,o=this[`${e}Vpt`];if(!s&&!r)return;const a=vt(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,o&&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=o,o&&t.transform(...i),r.render(t),this.skipOffscreen=h,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenterPoint(){return new _(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new _(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new _(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 _(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new _(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return et(this.getCenterPoint(),mt(this.viewportTransform))}_centerObject(t,e){t.setXY(e,A,A),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{version:fr,...le(this,e),objects:this._objects.filter(i=>!i.excludeFromExport).map(i=>this._toObject(i,t,e)),...this.__serializeBgOverlay(t,e),...r?{clipPath:r}:null}}_toObject(t,e,s){let r;this.includeDefaultValues||(r=t.includeDefaultValues,t.includeDefaultValues=!1);const i=t[e](s);return this.includeDefaultValues||(t.includeDefaultValues=!!r),i}__serializeBgOverlay(t,e){const s={},r=this.backgroundImage,i=this.overlayImage,o=this.backgroundColor,a=this.overlayColor;return vt(o)?o.excludeFromExport||(s.background=o.toObject(e)):o&&(s.background=o),vt(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(#${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||`${this.width}`,r=e.height||`${this.height}`,i=B.NUM_FRACTION_DIGITS,o=e.viewBox;let a;if(o)a=`viewBox="${o.x} ${o.y} ${o.width} ${o.height}" `;else if(this.svgViewportTransformation){const h=this.viewportTransform;a=`viewBox="${X(-h[4]/h[0],i)} ${X(-h[5]/h[3],i)} ${X(this.width/h[0],i)} ${X(this.height/h[3],i)}" `}else a=`viewBox="0 0 ${this.width} ${this.height}" `;t.push("<svg ",'xmlns="http://www.w3.org/2000/svg" ','xmlns:xlink="http://www.w3.org/1999/xlink" ','version="1.1" ','width="',s,'" ','height="',r,'" ',a,`xml:space="preserve">
8
- `,"<desc>Created with Fabric.js ",fr,`</desc>
9
- `,`<defs>
10
- `,this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(e),`</defs>
11
- `)}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId=`CLIPPATH_${te()}`,`<clipPath id="${e.clipPathId}" >
12
- ${e.toClipPathSVG(t.reviver)}</clipPath>
13
- `):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this[`${t}Color`];if(vt(e)){const s=this[`${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?Ae(r):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],e={},s=B.fontPaths;this._objects.forEach(function i(o){t.push(o),gs(o)&&o._objects.forEach(i)}),t.forEach(i=>{if(!(o=i)||typeof o._renderText!="function")return;var o;const{styles:a,fontFamily:h}=i;!e[h]&&s[h]&&(e[h]=!0,a&&Object.values(a).forEach(l=>{Object.values(l).forEach(c=>{let{fontFamily:u=""}=c;!e[u]&&s[u]&&(e[u]=!0)})}))});const r=Object.keys(e).map(i=>` @font-face {
14
- font-family: '${i}';
15
- src: url('${s[i]}');
16
- }
17
- `).join("");return r?` <style type="text/css"><![CDATA[
18
- ${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[`${e}Color`];if(s)if(vt(s)){const r=s.repeat||"",i=this.width,o=this.height,a=this[`${e}Vpt`]?Ae(mt(this.viewportTransform)):"";t.push(`<rect transform="${a} translate(${i/2},${o/2})" x="${s.offsetX-i/2}" y="${s.offsetY-o/2}" width="${r!=="repeat-y"&&r!=="no-repeat"||!Ri(s)?i:s.source.width}" height="${r!=="repeat-x"&&r!=="no-repeat"||!Ri(s)?o:s.source.height}" fill="url(#SVGID_${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 Pt("`json` is undefined"));const{objects:r=[],...i}=typeof t=="string"?JSON.parse(t):t,{backgroundImage:o,background:a,overlayImage:h,overlay:l,clipPath:c}=i,u=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([Pe(r,{reviver:e,signal:s}),Ue({backgroundImage:o,backgroundColor:a,overlayImage:h,overlayColor:l,clipPath:c},{signal:s})]).then(g=>{let[d,f]=g;return this.clear(),this.add(...d),this.set(i),this.set(f),this.renderOnAddRemove=u,this})}clone(t){const e=this.toObject(t);return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=pt(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,o=r*(i?this.getRetinaScaling():1);return Cr(this.toCanvasElement(o,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,o=r*(i?this.getRetinaScaling():1);return br(this.toCanvasElement(o,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:o}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const a=(e||this.width)*t,h=(s||this.height)*t,l=this.getZoom(),c=this.width,u=this.height,g=this.skipControlsDrawing,d=l*t,f=this.viewportTransform,p=[d,0,0,d,(f[4]-(r||0))*t,(f[5]-(i||0))*t],m=this.enableRetinaScaling,v=pt({width:a,height:h}),x=o?this._objects.filter(S=>o(S)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=p,this.width=a,this.height=h,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(v.getContext("2d"),x),this.viewportTransform=f,this.width=c,this.height=u,this.calcViewportBoundaries(),this.enableRetinaScaling=m,this.skipControlsDrawing=g,v}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),us.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 (${this.complexity()}): { objects: ${this._objects.length} }>`}}y(Fe,"ownDefaults",qo);const Ko=["touchstart","touchmove","touchend"],Hi=n=>{const t=Bi(n.target),e=(function(s){const r=s.changedTouches;return r&&r[0]?r[0]:s})(n);return new _(e.clientX+t.left,e.clientY+t.top)},ps=n=>Ko.includes(n.type)||n.pointerType==="touch",Ni=n=>{n.preventDefault(),n.stopPropagation()},Lt=n=>{let t=0,e=0,s=0,r=0;for(let i=0,o=n.length;i<o;i++){const{x:a,y:h}=n[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}},Vi=(n,t)=>Le(n,K(t,n.calcOwnMatrix())),Le=(n,t)=>{const{translateX:e,translateY:s,scaleX:r,scaleY:i,...o}=De(t),a=new _(e,s);n.flipX=!1,n.flipY=!1,Object.assign(n,o),n.set({scaleX:r,scaleY:i}),n.setPositionByOrigin(a,A,A)},Gi=n=>{n.scaleX=1,n.scaleY=1,n.skewX=0,n.skewY=0,n.flipX=!1,n.flipY=!1,n.rotate(0)},Dr=n=>({scaleX:n.scaleX,scaleY:n.scaleY,skewX:n.skewX,skewY:n.skewY,angle:n.angle,left:n.left,flipX:n.flipX,flipY:n.flipY,top:n.top}),ms=(n,t,e)=>{const s=n/2,r=t/2,i=[new _(-s,-r),new _(s,-r),new _(-s,r),new _(s,r)].map(a=>a.transform(e)),o=Lt(i);return new _(o.width,o.height)},qe=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:nt;return K(mt(arguments.length>1&&arguments[1]!==void 0?arguments[1]:nt),n)},ue=function(n){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:nt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nt;return n.transform(qe(t,e))},zi=function(n){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:nt,e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:nt;return n.transform(qe(t,e),!0)},Er=(n,t,e)=>{const s=qe(t,e);return Le(n,K(s,n.calcOwnMatrix())),s},Qo={left:-.5,top:-.5,center:0,bottom:.5,right:.5},at=n=>typeof n=="string"?Qo[n]:n-.5,Zo=new _(1,0),Ui=new _,Pr=(n,t)=>n.rotate(t),Ke=(n,t)=>new _(t).subtract(n),ys=n=>n.distanceFrom(Ui),vs=(n,t)=>Math.atan2(je(n,t),qi(n,t)),Ar=n=>vs(Zo,n),xs=n=>n.eq(Ui)?n:n.scalarDivide(ys(n)),Fr=function(n){let t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];return xs(new _(-n.y,n.x).scalarMultiply(t?1:-1))},je=(n,t)=>n.x*t.y-n.y*t.x,qi=(n,t)=>n.x*t.x+n.y*t.y,Lr=(n,t,e)=>{if(n.eq(t)||n.eq(e))return!0;const s=je(t,e),r=je(t,n),i=je(e,n);return s>=0?r>=0&&i<=0:!(r<=0&&i>=0)},_s="not-allowed";function Ki(n){return at(n.originX)===at(A)&&at(n.originY)===at(A)}function Qi(n){return .5-at(n)}const Tt=(n,t)=>n[t],Zi=(n,t,e,s)=>({e:n,transform:t,pointer:new _(e,s)});function Ji(n,t,e){const s=e,r=ue(n.getCenterPoint(),n.canvas.viewportTransform,void 0),i=Ar(Ke(r,s))+wt;return Math.round(i%wt/No)}function jr(n,t,e,s,r){var i;let{target:o,corner:a}=n;const h=o.controls[a],l=((i=o.canvas)===null||i===void 0?void 0:i.getZoom())||1,c=o.padding/l,u=(function(g,d,f,p){const m=g.getRelativeCenterPoint(),v=f!==void 0&&p!==void 0?g.translateToGivenOrigin(m,A,A,f,p):new _(g.left,g.top);return(g.angle?d.rotate(-U(g.angle),m):d).subtract(v)})(o,new _(s,r),t,e);return u.x>=c&&(u.x-=c),u.x<=-c&&(u.x+=c),u.y>=c&&(u.y-=c),u.y<=c&&(u.y+=c),u.x-=h.offsetX,u.y-=h.offsetY,u}const ws=n=>n.replace(/\s+/g," "),tn={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=(n,t,e)=>(e<0&&(e+=1),e>1&&(e-=1),e<1/6?n+6*(t-n)*e:e<.5?t:e<2/3?n+(t-n)*(2/3-e)*6:n),en=(n,t,e,s)=>{n/=255,t/=255,e/=255;const r=Math.max(n,t,e),i=Math.min(n,t,e);let o,a;const h=(r+i)/2;if(r===i)o=a=0;else{const l=r-i;switch(a=h>.5?l/(2-r-i):l/(r+i),r){case n:o=(t-e)/l+(t<e?6:0);break;case t:o=(e-n)/l+2;break;case e:o=(n-t)/l+4}o/=6}return[Math.round(360*o),Math.round(100*a),Math.round(100*h),s]},sn=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"1";return parseFloat(n)/(n.endsWith("%")?100:1)},Ss=n=>Math.min(Math.round(n),255).toString(16).toUpperCase().padStart(2,"0"),rn=n=>{let[t,e,s,r=1]=n;const i=Math.round(.3*t+.59*e+.11*s);return[i,i,i,r]};class W{constructor(t){if(y(this,"isUnrecognised",!1),t)if(t instanceof W)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 tn&&(t=tn[t]),t==="transparent"?[255,255,255,0]:W.sourceFromHex(t)||W.sourceFromRgb(t)||W.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(${t},${e},${s})`}toRgba(){return`rgba(${this.getSource().join(",")})`}toHsl(){const[t,e,s]=en(...this.getSource());return`hsl(${t},${e}%,${s}%)`}toHsla(){const[t,e,s,r]=en(...this.getSource());return`hsla(${t},${e}%,${s}%,${r})`}toHex(){return this.toHexa().slice(0,6)}toHexa(){const[t,e,s,r]=this.getSource();return`${Ss(t)}${Ss(e)}${Ss(s)}${Ss(Math.round(255*r))}`}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(rn(this.getSource())),this}toBlackWhite(t){const[e,,,s]=rn(this.getSource()),r=e<(t||127)?0:255;return this.setSource([r,r,r,s]),this}overlayWith(t){t instanceof W||(t=new W(t));const e=this.getSource(),s=t.getSource(),[r,i,o]=e.map((a,h)=>Math.round(.5*a+.5*s[h]));return this.setSource([r,i,o,e[3]]),this}static fromRgb(t){return W.fromRgba(t)}static fromRgba(t){return new W(W.sourceFromRgb(t))}static sourceFromRgb(t){const e=ws(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(o=>{const a=parseFloat(o);return o.endsWith("%")?Math.round(2.55*a):a});return[s,r,i,sn(e[4])]}}static fromHsl(t){return W.fromHsla(t)}static fromHsla(t){return new W(W.sourceFromHsl(t))}static sourceFromHsl(t){const e=ws(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=(W.parseAngletoDegrees(e[1])%360+360)%360/360,r=parseFloat(e[2])/100,i=parseFloat(e[3])/100;let o,a,h;if(r===0)o=a=h=i;else{const l=i<=.5?i*(r+1):i+r-i*r,c=2*i-l;o=Ir(c,l,s+.3333333333333333),a=Ir(c,l,s),h=Ir(c,l,s-.3333333333333333)}return[Math.round(255*o),Math.round(255*a),Math.round(255*h),sn(e[4])]}static fromHex(t){return new W(W.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,o,a=255]=s.map(h=>parseInt(h,16));return[r,i,o,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),s=parseFloat(e);return e.includes("rad")?Xt(s):e.includes("turn")?360*s:s}}const ge=function(n){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:mr;const e=/\D{0,2}$/.exec(n),s=parseFloat(n),r=B.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}},nn=n=>{const[t,e]=n.trim().split(" "),[s,r]=(i=t)&&i!==gt?[i.slice(1,4),i.slice(5,8)]:i===gt?[i,i]:["Mid","Mid"];var i;return{meetOrSlice:e||"meet",alignX:s,alignY:r}},Qe=function(n,t){let e,s,r=!(arguments.length>2&&arguments[2]!==void 0)||arguments[2];if(t)if(t.toLive)e=`url(#SVGID_${t.id})`;else{const i=new W(t),o=i.getAlpha();e=i.toRgb(),o!==1&&(s=o.toString())}else e="none";return r?`${n}: ${e}; ${s?`${n}-opacity: ${s}; `:""}`:`${n}="${e}" ${s?`${n}-opacity="${s}" `:""}`};class on{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",s=this.strokeWidth?this.strokeWidth:"0",r=this.strokeDashArray?this.strokeDashArray.join(" "):gt,i=this.strokeDashOffset?this.strokeDashOffset:"0",o=this.strokeLineCap?this.strokeLineCap:"butt",a=this.strokeLineJoin?this.strokeLineJoin:"miter",h=this.strokeMiterLimit?this.strokeMiterLimit:"4",l=this.opacity!==void 0?this.opacity:"1",c=this.visible?"":" visibility: hidden;",u=t?"":this.getSvgFilter(),g=Qe(J,this.fill);return[Qe(ft,this.stroke),"stroke-width: ",s,"; ","stroke-dasharray: ",r,"; ","stroke-linecap: ",o,"; ","stroke-dashoffset: ",i,"; ","stroke-linejoin: ",a,"; ","stroke-miterlimit: ",h,"; ",g,"fill-rule: ",e,"; ","opacity: ",l,";",u,c].join("")}getSvgFilter(){return this.shadow?`filter: url(#SVGID_${this.shadow.id});`:""}getSvgCommons(){return[this.id?`id="${this.id}" `:"",this.clipPath?`clip-path="url(#${this.clipPath.clipPathId})" `:""].join("")}getSvgTransform(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";const s=t?this.calcTransformMatrix():this.calcOwnMatrix();return`${`transform="${Ae(s)}`}${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 o=e?"":`style="${this.getSvgStyles()}" `,a=r?`style="${this.getSvgFilter()}" `:"",h=this.clipPath,l=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",c=h&&h.absolutePositioned,u=this.stroke,g=this.fill,d=this.shadow,f=[],p=t.indexOf("COMMON_PARTS");let m;h&&(h.clipPathId=`CLIPPATH_${te()}`,m=`<clipPath id="${h.clipPathId}" >
22
- ${h.toClipPathSVG(s)}</clipPath>
23
- `),c&&f.push("<g ",a,this.getSvgCommons(),` >
24
- `),f.push("<g ",this.getSvgTransform(!1),c?"":a+this.getSvgCommons(),` >
25
- `);const v=[o,l,e?"":this.addPaintOrder()," ",i?`transform="${i}" `:""].join("");return t[p]=v,vt(g)&&f.push(g.toSVG(this)),vt(u)&&f.push(u.toSVG(this)),d&&f.push(d.toSVG(this)),h&&f.push(m),f.push(t.join("")),f.push(`</g>
26
- `),c&&f.push(`</g>
27
- `),s?s(f.join("")):f.join("")}addPaintOrder(){return this.paintFirst!==J?` paint-order="${this.paintFirst}" `:""}}function Cs(n){return new RegExp("^("+n.join("|")+")\\b","i")}const de="textDecorationThickness",an=["fontSize","fontWeight","fontFamily","fontStyle"],hn=["underline","overline","linethrough"],ln=[...an,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign"],cn=[...ln,...hn,"textBackgroundColor","direction",de],Jo=[...an,...hn,ft,"strokeWidth",J,"deltaY","textBackgroundColor",de],ta={_reNewline:vr,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:_r,fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:$,fontStyle:_r,lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:$,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:oe,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,[de]:66.667},jt="justify",bs="justify-left",Ze="justify-right",Je="justify-center",fe=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,ea=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+fe+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+fe+"))?\\s+(.*)"),sa={cx:$,x:$,r:"radius",cy:ut,y:ut,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":de},Rr="font-size",Br="clip-path";Cs(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Cs(["symbol","image","marker","pattern","view","svg"]);const un=Cs(["symbol","g","a","svg","clipPath","defs"]),gn="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",dn=new RegExp("(?:\\s|^)"+gn+gn+"("+fe+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)");class Wt{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=typeof t=="string"?Wt.parseShadow(t):t;Object.assign(this,Wt.ownDefaults,e),this.id=te()}static parseShadow(t){const e=t.trim(),[,s=0,r=0,i=0]=(dn.exec(e)||[]).map(o=>parseFloat(o)||0);return{color:(e.replace(dn,"")||"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=Pr(new _(this.offsetX,this.offsetY),U(-t.angle)),s=new W(this.color);let r=40,i=40;return t.width&&t.height&&(r=100*X((Math.abs(e.x)+this.blur)/t.width,B.NUM_FRACTION_DIGITS)+20,i=100*X((Math.abs(e.y)+this.blur)/t.height,B.NUM_FRACTION_DIGITS)+20),t.flipX&&(e.x*=-1),t.flipY&&(e.y*=-1),`<filter id="SVGID_${this.id}" y="-${i}%" height="${100+2*i}%" x="-${r}%" width="${100+2*r}%" >
28
- <feGaussianBlur in="SourceAlpha" stdDeviation="${X(this.blur?this.blur/2:0,B.NUM_FRACTION_DIGITS)}"></feGaussianBlur>
29
- <feOffset dx="${X(e.x,B.NUM_FRACTION_DIGITS)}" dy="${X(e.y,B.NUM_FRACTION_DIGITS)}" result="oBlur" ></feOffset>
30
- <feFlood flood-color="${s.toRgb()}" flood-opacity="${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=Wt.ownDefaults;return this.includeDefaultValues?t:Mr(t,(s,r)=>s!==e[r])}static async fromObject(t){return new this(t)}}y(Wt,"ownDefaults",{color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1}),y(Wt,"type","shadow"),O.setClass(Wt,"shadow");const pe=(n,t,e)=>Math.max(n,Math.min(t,e)),ra=[ut,$,ot,dt,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",Oe,Me],Yt=[J,ft,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],ia={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:A,originY:A,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:J,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},$r=(n,t,e,s)=>(n<Math.abs(t)?(n=t,s=e/4):s=t===0&&n===0?e/wt*Math.asin(1):e/wt*Math.asin(t/n),{a:n,c:t,p:e,s}),fn=(n,t,e,s,r)=>n*Math.pow(2,10*(s-=1))*Math.sin((s*r-t)*wt/e),pn=(n,t,e,s)=>-e*Math.cos(n/s*Zt)+e+t,Xr=(n,t,e,s)=>(n/=s)<1/2.75?e*(7.5625*n*n)+t:n<2/2.75?e*(7.5625*(n-=1.5/2.75)*n+.75)+t:n<2.5/2.75?e*(7.5625*(n-=2.25/2.75)*n+.9375)+t:e*(7.5625*(n-=2.625/2.75)*n+.984375)+t,mn=(n,t,e,s)=>e-Xr(s-n,0,e,s)+t;var na=Object.freeze({__proto__:null,defaultEasing:pn,easeInBack:function(n,t,e,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*(n/=s)*n*((r+1)*n-r)+t},easeInBounce:mn,easeInCirc:(n,t,e,s)=>-e*(Math.sqrt(1-(n/=s)*n)-1)+t,easeInCubic:(n,t,e,s)=>e*(n/s)**3+t,easeInElastic:(n,t,e,s)=>{const r=e;let i=0;if(n===0)return t;if((n/=s)===1)return t+e;i||(i=.3*s);const{a:o,s:a,p:h}=$r(r,e,i,1.70158);return-fn(o,a,h,n,s)+t},easeInExpo:(n,t,e,s)=>n===0?t:e*2**(10*(n/s-1))+t,easeInOutBack:function(n,t,e,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return(n/=s/2)<1?e/2*(n*n*((1+(r*=1.525))*n-r))+t:e/2*((n-=2)*n*((1+(r*=1.525))*n+r)+2)+t},easeInOutBounce:(n,t,e,s)=>n<s/2?.5*mn(2*n,0,e,s)+t:.5*Xr(2*n-s,0,e,s)+.5*e+t,easeInOutCirc:(n,t,e,s)=>(n/=s/2)<1?-e/2*(Math.sqrt(1-n**2)-1)+t:e/2*(Math.sqrt(1-(n-=2)*n)+1)+t,easeInOutCubic:(n,t,e,s)=>(n/=s/2)<1?e/2*n**3+t:e/2*((n-2)**3+2)+t,easeInOutElastic:(n,t,e,s)=>{const r=e;let i=0;if(n===0)return t;if((n/=s/2)===2)return t+e;i||(i=s*(.3*1.5));const{a:o,s:a,p:h,c:l}=$r(r,e,i,1.70158);return n<1?-.5*fn(o,a,h,n,s)+t:o*Math.pow(2,-10*(n-=1))*Math.sin((n*s-a)*wt/h)*.5+l+t},easeInOutExpo:(n,t,e,s)=>n===0?t:n===s?t+e:(n/=s/2)<1?e/2*2**(10*(n-1))+t:e/2*-(2**(-10*--n)+2)+t,easeInOutQuad:(n,t,e,s)=>(n/=s/2)<1?e/2*n**2+t:-e/2*(--n*(n-2)-1)+t,easeInOutQuart:(n,t,e,s)=>(n/=s/2)<1?e/2*n**4+t:-e/2*((n-=2)*n**3-2)+t,easeInOutQuint:(n,t,e,s)=>(n/=s/2)<1?e/2*n**5+t:e/2*((n-2)**5+2)+t,easeInOutSine:(n,t,e,s)=>-e/2*(Math.cos(Math.PI*n/s)-1)+t,easeInQuad:(n,t,e,s)=>e*(n/=s)*n+t,easeInQuart:(n,t,e,s)=>e*(n/=s)*n**3+t,easeInQuint:(n,t,e,s)=>e*(n/s)**5+t,easeInSine:(n,t,e,s)=>-e*Math.cos(n/s*Zt)+e+t,easeOutBack:function(n,t,e,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1.70158;return e*((n=n/s-1)*n*((r+1)*n+r)+1)+t},easeOutBounce:Xr,easeOutCirc:(n,t,e,s)=>e*Math.sqrt(1-(n=n/s-1)*n)+t,easeOutCubic:(n,t,e,s)=>e*((n/s-1)**3+1)+t,easeOutElastic:(n,t,e,s)=>{const r=e;let i=0;if(n===0)return t;if((n/=s)===1)return t+e;i||(i=.3*s);const{a:o,s:a,p:h,c:l}=$r(r,e,i,1.70158);return o*2**(-10*n)*Math.sin((n*s-a)*wt/h)+l+t},easeOutExpo:(n,t,e,s)=>n===s?t+e:e*-(2**(-10*n/s)+1)+t,easeOutQuad:(n,t,e,s)=>-e*(n/=s)*(n-2)+t,easeOutQuart:(n,t,e,s)=>-e*((n=n/s-1)*n**3-1)+t,easeOutQuint:(n,t,e,s)=>e*((n/s-1)**5+1)+t,easeOutSine:(n,t,e,s)=>e*Math.sin(n/s*Zt)+t});const oa=()=>!1;class Wr{constructor(t){let{startValue:e,byValue:s,duration:r=500,delay:i=0,easing:o=pn,onStart:a=os,onChange:h=os,onComplete:l=os,abort:c=oa,target:u}=t;y(this,"_state","pending"),y(this,"durationProgress",0),y(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=r,this.delay=i,this.easing=o,this._onStart=a,this._onChange=h,this._onComplete=l,this._abort=c,this.target=u,this.startValue=e,this.byValue=s,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return this._state==="aborted"||this._state==="completed"}start(){const t=e=>{this._state==="pending"&&(this.startTime=e||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>Ve(t),this.delay):Ve(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),Ve(this.tick)))}register(){us.push(this)}unregister(){us.remove(this)}abort(){this._state="aborted",this.unregister()}}class aa extends Wr{constructor(t){let{startValue:e=0,endValue:s=100,...r}=t;super({...r,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)}}}class ha extends Wr{constructor(t){let{startValue:e=[0],endValue:s=[100],...r}=t;super({...r,startValue:e,byValue:s.map((i,o)=>i-e[o])})}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 la=(n,t,e,s)=>t+e*(1-Math.cos(n/s*Zt)),Yr=n=>n&&((t,e,s)=>n(new W(t).toRgba(),e,s));class ca extends Wr{constructor(t){let{startValue:e,endValue:s,easing:r=la,onChange:i,onComplete:o,abort:a,...h}=t;const l=new W(e).getSource(),c=new W(s).getSource();super({...h,startValue:l,byValue:c.map((u,g)=>u-l[g]),easing:r,onChange:Yr(i),onComplete:Yr(o),abort:Yr(a)})}calculate(t){const[e,s,r,i]=this.startValue.map((a,h)=>this.easing(t,a,this.byValue[h],this.duration,h)),o=[...[e,s,r].map(Math.round),pe(0,i,1)];return{value:o,valueProgress:o.map((a,h)=>this.byValue[h]!==0?Math.abs((a-this.startValue[h])/this.byValue[h]):0).find(a=>a!==0)||0}}}function Hr(n){const t=(e=>Array.isArray(e.startValue)||Array.isArray(e.endValue))(n)?new ha(n):new aa(n);return t.start(),t}function yn(n){const t=new ca(n);return t.start(),t}class z{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=Ke(e,s),o=Ke(e,t).divide(i);return r?Math.abs(o.x)===Math.abs(o.y):o.x===o.y&&o.x>=0&&o.x<=1}}static isPointInPolygon(t,e){const s=new _(t).setX(Math.min(t.x-1,...e.map(i=>i.x)));let r=0;for(let i=0;i<e.length;i++){const o=this.intersectSegmentSegment(e[i],e[(i+1)%e.length],t,s);if(o.includes(t))return!0;r+=+(o.status==="Intersection")}return r%2==1}static intersectLineLine(t,e,s,r){let i=!(arguments.length>4&&arguments[4]!==void 0)||arguments[4],o=!(arguments.length>5&&arguments[5]!==void 0)||arguments[5];const a=e.x-t.x,h=e.y-t.y,l=r.x-s.x,c=r.y-s.y,u=t.x-s.x,g=t.y-s.y,d=l*g-c*u,f=a*g-h*u,p=c*a-l*h;if(p!==0){const m=d/p,v=f/p;return(i||0<=m&&m<=1)&&(o||0<=v&&v<=1)?new z("Intersection").append(new _(t.x+m*a,t.y+m*h)):new z}if(d===0||f===0){const m=i||o||z.isPointContained(t,s,r)||z.isPointContained(e,s,r)||z.isPointContained(s,t,e)||z.isPointContained(r,t,e);return new z(m?"Coincident":void 0)}return new z("Parallel")}static intersectSegmentLine(t,e,s,r){return z.intersectLineLine(t,e,s,r,!1,!0)}static intersectSegmentSegment(t,e,s,r){return z.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 z,o=s.length;for(let a,h,l,c=0;c<o;c++){if(a=s[c],h=s[(c+1)%o],l=z.intersectLineLine(t,e,a,h,r,!1),l.status==="Coincident")return l;i.append(...l.points)}return i.points.length>0&&(i.status="Intersection"),i}static intersectSegmentPolygon(t,e,s){return z.intersectLinePolygon(t,e,s,!1)}static intersectPolygonPolygon(t,e){const s=new z,r=t.length,i=[];for(let o=0;o<r;o++){const a=t[o],h=t[(o+1)%r],l=z.intersectSegmentPolygon(a,h,e);l.status==="Coincident"?(i.push(l),s.append(a,h)):s.append(...l.points)}return i.length>0&&i.length===t.length?new z("Coincident"):(s.points.length>0&&(s.status="Intersection"),s)}static intersectPolygonRectangle(t,e,s){const r=e.min(s),i=e.max(s),o=new _(i.x,r.y),a=new _(r.x,i.y);return z.intersectPolygonPolygon(t,[r,o,i,a])}}class ua extends Di{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?et(t,this.group.calcTransformMatrix()):t}setXY(t,e,s){this.group&&(t=et(t,mt(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,s)}getRelativeXY(){return new _(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 o=this.group.calcTransformMatrix();return i.map(a=>et(a,o))}return i}intersectsWithRect(t,e){return z.intersectPolygonRectangle(this.getCoords(),t,e).status==="Intersection"}intersectsWithObject(t){const e=z.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:o}=this.getBoundingRect();return s>=t.x&&s+i<=e.x&&r>=t.y&&r+o<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return z.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 Lt(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(ot,t),this._set(dt,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?Xt(Fi(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return((t=this.canvas)===null||t===void 0?void 0:t.viewportTransform)||nt.concat()}calcACoords(){const t=he({angle:this.angle}),{x:e,y:s}=this.getRelativeCenterPoint(),r=Ee(e,s),i=K(r,t),o=this._getTransformedDimensions(),a=o.x/2,h=o.y/2;return{tl:et({x:-a,y:-h},i),tr:et({x:a,y:-h},i),bl:et({x:-a,y:h},i),br:et({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,at(this.originX),at(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,o)=>i===s[o])?r.value:(this.group&&(e=K(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.every((o,a)=>o===t[a]))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=ji(r);return this.ownMatrixCache={key:t,value:i},i}_getNonTransformedDimensions(){return new _(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={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 o=e.width+r,a=e.height+r;let h;return h=e.skewX===0&&e.skewY===0?new _(o*e.scaleX,a*e.scaleY):ms(o,a,Ge(e)),h.scalarAdd(i)}translateToGivenOrigin(t,e,s,r,i){let o=t.x,a=t.y;const h=at(r)-at(e),l=at(i)-at(s);if(h||l){const c=this._getTransformedDimensions();o+=h*c.x,a+=l*c.y}return new _(o,a)}translateToCenterPoint(t,e,s){if(e===A&&s===A)return t;const r=this.translateToGivenOrigin(t,e,s,A,A);return this.angle?r.rotate(U(this.angle),t):r}translateToOriginPoint(t,e,s){const r=this.translateToGivenOrigin(t,A,A,e,s);return this.angle?r.rotate(U(this.angle),t):r}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?et(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new _(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.getPositionByOrigin(t,e)}getPositionByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,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.getPositionByOrigin($,ut)}positionByLeftTop(t){return this.setPositionByOrigin(t,$,ut)}}let Ht=class dr extends ua{static getDefaults(){return dr.ownDefaults}get type(){const t=this.constructor.type;return t==="FabricObject"?"object":t.toLowerCase()}set type(t){Qt("warn","Setting type has no effect",t)}constructor(t){super(),y(this,"_cacheContext",null),Object.assign(this,dr.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=Ft(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const e=t.width,s=t.height,r=B.maxCacheSideLimit,i=B.minCacheSideLimit;if(e<=r&&s<=r&&e*s<=B.perfLimitSizeTotal)return e<i&&(t.width=i),s<i&&(t.height=i),t;const o=e/s,[a,h]=He.limitDimsByArea(o),l=pe(i,a,r),c=pe(i,h,r);return e>l&&(t.zoomX/=e/l,t.width=l,t.capped=!0),s>c&&(t.zoomY/=s/c,t.height=c,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),s=e.x*t.x/this.scaleX,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:o,x:a,y:h}=this._limitCacheSize(this._getCacheCanvasDimensions()),l=s!==t.width||r!==t.height,c=this.zoomX!==i||this.zoomY!==o;if(!t||!e)return!1;if(l||c){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,g=h/2;return this.cacheTranslationX=Math.round(t.width/2-u)+u,this.cacheTranslationY=Math.round(t.height/2-g)+g,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(i,o),this.zoomX=i,this.zoomY=o,!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 _(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=De(this.calcTransformMatrix());return new _(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!==ot&&t!==dt||(e=this._constrainScale(e)),t===ot&&e<0?(this.flipX=!this.flipX,e*=-1):t==="scaleY"&&e<0?(this.flipY=!this.flipY,e*=-1):t!=="shadow"||!e||e instanceof Wt||(e=new Wt(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:o,height:a}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:s,cacheTranslationX:r,cacheTranslationY:i,width:o,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===ft&&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=pt(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=mt(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,vt(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&&(vt(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,,,o]=(s==null?void 0:s.viewportTransform)||nt,a=i*r,h=o*r,l=e.nonScaling?new _(1,1):this.getObjectScaling();t.shadowColor=e.color,t.shadowBlur=e.blur*B.browserShadowBlurConstant*(a+h)*(l.x+l.y)/4,t.shadowOffsetX=e.offsetX*a*l.x,t.shadowOffsetY=e.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!vt(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===ft?(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(),o=r.x/this.scaleX/i,a=r.y/this.scaleY/i,h=pt({width:Math.ceil(o),height:Math.ceil(a)}),l=h.getContext("2d");l&&(l.beginPath(),l.moveTo(0,0),l.lineTo(o,0),l.lineTo(o,a),l.lineTo(0,a),l.closePath(),l.translate(o/2,a/2),l.scale(r.zoomX/this.scaleX/i,r.zoomY/this.scaleY/i),this._applyPatternGradientTransform(l,e),l.fillStyle=e.toLive(t),l.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=l.createPattern(h,"no-repeat"))!==null&&s!==void 0?s:"")}_findCenterFromElement(){return new _(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(O.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const e=Dr(this),s=this.group,r=this.shadow,i=Math.abs,o=t.enableRetinaScaling?bi():1,a=(t.multiplier||1)*o,h=t.canvasProvider||(x=>new Fe(x,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&Gi(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&Er(this,this.getViewportTransform()),this.setCoords();const l=Ft(),c=this.getBoundingRect(),u=this.shadow,g=new _;if(u){const x=u.blur,S=u.nonScaling?new _(1,1):this.getObjectScaling();g.x=2*Math.round(i(u.offsetX)+x)*i(S.x),g.y=2*Math.round(i(u.offsetY)+x)*i(S.y)}const d=c.width+g.x,f=c.height+g.y;l.width=Math.ceil(d),l.height=Math.ceil(f);const p=h(l);t.format==="jpeg"&&(p.backgroundColor="#fff"),this.setPositionByOrigin(new _(p.width/2,p.height/2),A,A);const m=this.canvas;p._objects=[this],this.set("canvas",p),this.setCoords();const v=p.toCanvasElement(a||1,t);return this.set("canvas",m),this.shadow=r,s&&(this.group=s),this.set(e),this.setCoords(),p._objects=[],p.destroy(),v}toDataURL(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return Cr(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return br(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:o}=this.getRelativeCenterPoint();this.originX=A,this.originY=A,this.left=i,this.top=o}if(this.set("angle",t),e){const{x:i,y:o}=this.getPositionByOrigin(s,r);this.left=i,this.top=o,this.originX=s,this.originY=r}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){us.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&At().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((s,r)=>{let[i,o]=r;return s[i]=this._animate(i,o,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:o,startValue:a,onChange:h,onComplete:l}=s,c={...s,target:this,startValue:a!=null?a:r.reduce((u,g)=>u[g],this),endValue:e,abort:o==null?void 0:o.bind(this),onChange:(u,g,d)=>{r.reduce((f,p,m)=>(m===r.length-1&&(f[p]=u),f[p]),this),h&&h(u,g,d)},onComplete:(u,g,d)=>{this.setCoords(),l&&l(u,g,d)}};return i?yn(c):Hr(c)}isDescendantOf(t){const{parent:e,group:s}=this;return e===t||s===t||!!e&&e.isDescendantOf(t)||!!s&&s!==e&&s.isDescendantOf(t)}getAncestors(){const t=[];let e=this;do e=e.parent,e&&t.push(e);while(e);return t}findCommonAncestors(t){if(this===t)return{fork:[],otherFork:[],common:[this,...this.getAncestors()]};const e=this.getAncestors(),s=t.getAncestors();if(e.length===0&&s.length>0&&this===s[s.length-1])return{fork:[],otherFork:[t,...s.slice(0,s.length-1)],common:[this]};for(let 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 o=0;o<s.length;o++){if(this===s[o])return{fork:[],otherFork:[t,...s.slice(0,o)],common:[this,...e]};if(r===s[o])return{fork:[this,...e.slice(0,i)],otherFork:[t,...s.slice(0,o)],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(),o=s._objects.indexOf(r),a=s._objects.indexOf(i);return o>-1&&o>a}toObject(){const t=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:[]).concat(dr.customProperties,this.constructor.customProperties||[]);let e;const s=B.NUM_FRACTION_DIGITS,{clipPath:r,fill:i,stroke:o,shadow:a,strokeDashArray:h,left:l,top:c,originX:u,originY:g,width:d,height:f,strokeWidth:p,strokeLineCap:m,strokeDashOffset:v,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:w,scaleX:C,scaleY:b,angle:M,flipX:T,flipY:k,opacity:P,visible:F,backgroundColor:D,fillRule:L,paintFirst:I,globalCompositeOperation:Q,skewX:Y,skewY:H}=this;r&&!r.excludeFromExport&&(e=r.toObject(t.concat("inverted","absolutePositioned")));const R=rt=>X(rt,s),ct={...le(this,t),type:this.constructor.type,version:fr,originX:u,originY:g,left:R(l),top:R(c),width:R(d),height:R(f),fill:Ii(i)?i.toObject():i,stroke:Ii(o)?o.toObject():o,strokeWidth:R(p),strokeDashArray:h&&h.concat(),strokeLineCap:m,strokeDashOffset:v,strokeLineJoin:x,strokeUniform:S,strokeMiterLimit:R(w),scaleX:R(C),scaleY:R(b),angle:R(M),flipX:T,flipY:k,opacity:R(P),shadow:a&&a.toObject(),visible:F,backgroundColor:D,fillRule:L,paintFirst:I,globalCompositeOperation:Q,skewX:R(Y),skewY:R(H),...e?{clipPath:e}:null};return this.includeDefaultValues?ct:this._removeDefaultValues(ct)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return Mr(t,(r,i)=>{if(i===$||i===ut||i==="type")return!0;const o=s[i];return r!==o&&!(Array.isArray(r)&&Array.isArray(o)&&r.length===0&&o.length===0)})}toString(){return`#<${this.constructor.type}>`}static _fromObject(t){let{type:e,...s}=t,{extraParam:r,...i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return Ue(s,i).then(o=>r?(delete o[r],new this(s[r],o)):new this(o))}static fromObject(t,e){return this._fromObject(t,e)}};y(Ht,"stateProperties",ra),y(Ht,"cacheProperties",Yt),y(Ht,"ownDefaults",ia),y(Ht,"type","FabricObject"),y(Ht,"colorProperties",[J,ft,"backgroundColor"]),y(Ht,"customProperties",[]),O.setClass(Ht),O.setClass(Ht,"object");const vn=(n,t)=>{var e;const{transform:{target:s}}=t;(e=s.canvas)===null||e===void 0||e.fire(`object:${n}`,{...t,target:s}),s.fire(n,t)},Ie=(n,t,e)=>(s,r,i,o)=>{const a=t(s,r,i,o);return a&&vn(n,{...Zi(s,r,i,o),...e}),a};function Re(n){return(t,e,s,r)=>{const{target:i,originX:o,originY:a}=e,h=i.getPositionByOrigin(o,a),l=n(t,e,s,r);return i.setPositionByOrigin(h,e.originX,e.originY),l}}const ga=(n,t,e,s)=>(r,i,o,a)=>{const h=jr(i,i.originX,i.originY,o,a)[e],l=at(i[t]);if(l===0||l>0&&h<0||l<0&&h>0){const{target:c}=i,u=c.strokeWidth/(c.strokeUniform?c[s]:1),g=Ki(i)?2:1,d=c[n],f=Math.abs(h*g/c[s])-u;return c.set(n,Math.max(f,1)),d!==c[n]}return!1},da=ga("width","originX","x","scaleX"),xn=Ie(Ne,Re(da));function fa(n,t,e,s,r){n.save();const{stroke:i,xSize:o,ySize:a,opName:h}=this.commonRenderProps(n,t,e,r,s);let l=o;o>a?n.scale(1,a/o):a>o&&(l=a,n.scale(o/a,1)),n.beginPath(),n.arc(0,0,l/2,0,wt,!1),n[h](),i&&n.stroke(),n.restore()}function pa(n,t,e,s,r){n.save();const{stroke:i,xSize:o,ySize:a,opName:h}=this.commonRenderProps(n,t,e,r,s),l=o/2,c=a/2;n[`${h}Rect`](-l,-c,o,a),i&&n.strokeRect(-l,-c,o,a),n.restore()}class Ot{constructor(t){y(this,"visible",!0),y(this,"actionName",ls),y(this,"angle",0),y(this,"x",0),y(this,"y",0),y(this,"offsetX",0),y(this,"offsetY",0),y(this,"sizeX",0),y(this,"sizeY",0),y(this,"touchSizeX",0),y(this,"touchSizeY",0),y(this,"cursorStyle","crosshair"),y(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,s,r){var i;let{tl:o,tr:a,br:h,bl:l}=r;return((i=e.canvas)===null||i===void 0?void 0:i.getActiveObject())===e&&e.isControlVisible(t)&&z.isPointInPolygon(s,[o,a,h,l])}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,r){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 _(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,s,r,i,o){const a=ds([Ee(s,r),he({angle:t}),fs((i?this.touchSizeX:this.sizeX)||e,(i?this.touchSizeY:this.sizeY)||e)]);return{tl:new _(-.5,-.5).transform(a),tr:new _(.5,-.5).transform(a),br:new _(.5,.5).transform(a),bl:new _(-.5,.5).transform(a)}}commonRenderProps(t,e,s,r){let i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const{cornerSize:o,cornerColor:a,transparentCorners:h,cornerStrokeColor:l}=i,c=o||r.cornerSize,u=this.sizeX||c,g=this.sizeY||c,d=h!==void 0?h:r.transparentCorners,f=d?ft:J,p=l||r.cornerStrokeColor,m=!d&&!!p;return t.fillStyle=a||r.cornerColor||"",t.strokeStyle=p||"",t.translate(e,s),t.rotate(U(r.getTotalAngle())),{stroke:m,xSize:u,ySize:g,transparentCorners:d,opName:f}}render(t,e,s,r,i){((r=r||{}).cornerStyle||i.cornerStyle)==="circle"?fa.call(this,t,e,s,r,i):pa.call(this,t,e,s,r,i)}}const ma=(n,t,e)=>e.lockRotation?_s:t.cursorStyle,ya=Ie(Oi,Re((n,t,e,s)=>{let{target:r,ex:i,ey:o,theta:a,originX:h,originY:l}=t;const c=r.getPositionByOrigin(h,l);if(Tt(r,"lockRotation"))return!1;const u=Math.atan2(o-c.y,i-c.x),g=Math.atan2(s-c.y,e-c.x);let d=Xt(g-u+a);if(r.snapAngle&&r.snapAngle>0){const p=r.snapAngle,m=r.snapThreshold||p,v=Math.ceil(d/p)*p,x=Math.floor(d/p)*p;Math.abs(d-x)<m?d=x:Math.abs(d-v)<m&&(d=v)}d<0&&(d=360+d),d%=360;const f=r.angle!==d;return r.angle=d,f}));function _n(n,t){const e=t.canvas,s=n[e.uniScaleKey];return e.uniformScaling&&!s||!e.uniformScaling&&s}function wn(n,t,e){const s=Tt(n,"lockScalingX"),r=Tt(n,"lockScalingY");if(s&&r||!t&&(s||r)&&e||s&&t==="x"||r&&t==="y")return!0;const{width:i,height:o,strokeWidth:a}=n;return i===0&&a===0&&t!=="y"||o===0&&a===0&&t!=="x"}const va=["e","se","s","sw","w","nw","n","ne","e"],ts=(n,t,e,s)=>{const r=_n(n,e);if(wn(e,t.x!==0&&t.y===0?"x":t.x===0&&t.y!==0?"y":"",r))return _s;const i=Ji(e,0,s);return`${va[i]}-resize`};function Nr(n,t,e,s){let r=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{};const i=t.target,o=r.by,a=_n(n,i);let h,l,c,u,g,d;if(wn(i,o,a))return!1;if(t.gestureScale)l=t.scaleX*t.gestureScale,c=t.scaleY*t.gestureScale;else{if(h=jr(t,t.originX,t.originY,e,s),g=o!=="y"?Math.sign(h.x||t.signX||1):1,d=o!=="x"?Math.sign(h.y||t.signY||1):1,t.signX||(t.signX=g),t.signY||(t.signY=d),Tt(i,"lockScalingFlip")&&(t.signX!==g||t.signY!==d))return!1;if(u=i._getTransformedDimensions(),a&&!o){const m=Math.abs(h.x)+Math.abs(h.y),{original:v}=t,x=m/(Math.abs(u.x*v.scaleX/i.scaleX)+Math.abs(u.y*v.scaleY/i.scaleY));l=v.scaleX*x,c=v.scaleY*x}else l=Math.abs(h.x*i.scaleX/u.x),c=Math.abs(h.y*i.scaleY/u.y);Ki(t)&&(l*=2,c*=2),t.signX!==g&&o!=="y"&&(t.originX=Qi(t.originX),l*=-1,t.signX=g),t.signY!==d&&o!=="x"&&(t.originY=Qi(t.originY),c*=-1,t.signY=d)}const f=i.scaleX,p=i.scaleY;return o?(o==="x"&&i.set(ot,l),o==="y"&&i.set(dt,c)):(!Tt(i,"lockScalingX")&&i.set(ot,l),!Tt(i,"lockScalingY")&&i.set(dt,c)),f!==i.scaleX||p!==i.scaleY}const Ts=Ie(as,Re((n,t,e,s)=>Nr(n,t,e,s))),xa=Ie(as,Re((n,t,e,s)=>Nr(n,t,e,s,{by:"x"}))),_a=Ie(as,Re((n,t,e,s)=>Nr(n,t,e,s,{by:"y"}))),Vr={x:{counterAxis:"y",scale:ot,skew:Oe,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:dt,skew:Me,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},wa=["ns","nesw","ew","nwse"],Sa=(n,t,e,s)=>{if(t.x!==0&&Tt(e,"lockSkewingY")||t.y!==0&&Tt(e,"lockSkewingX"))return _s;const r=Ji(e,0,s)%4;return`${wa[r]}-resize`};function Sn(n,t,e,s,r){const{target:i}=e,{counterAxis:o,origin:a,lockSkewing:h,skew:l,flip:c}=Vr[n];if(Tt(i,h))return!1;const{origin:u,flip:g}=Vr[o],d=at(e[u])*(i[g]?-1:1),f=-Math.sign(d)*(i[c]?-1:1),p=.5*-((i[l]===0&&jr(e,A,A,s,r)[n]>0||i[l]>0?1:-1)*f)+.5;return Ie(Mi,Re((v,x,S,w)=>(function(C,b,M){let{target:T,ex:k,ey:P,skewingSide:F,...D}=b;const{skew:L}=Vr[C],I=M.subtract(new _(k,P)).divide(new _(T.scaleX,T.scaleY))[C],Q=T[L],Y=D[L],H=Math.tan(U(Y)),R=C==="y"?T._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:T._getTransformedDimensions({scaleX:1,scaleY:1}).y,ct=2*I*F/Math.max(R,1)+H,rt=Xt(Math.atan(ct));T.set(L,rt);const Kt=Q!==T[L];if(Kt&&C==="y"){const{skewX:re,scaleX:ie}=T,E=T._getTransformedDimensions({skewY:Q}),j=T._getTransformedDimensions(),N=re!==0?E.x/j.x:1;N!==1&&T.set(ot,N*ie)}return Kt})(n,x,new _(S,w))))(t,{...e,[a]:p,skewingSide:f},s,r)}const Ca=(n,t,e,s)=>Sn("x",n,t,e,s),ba=(n,t,e,s)=>Sn("y",n,t,e,s);function Os(n,t){return n[t.canvas.altActionKey]}const Ms=(n,t,e)=>{const s=Os(n,e);return t.x===0?s?Oe:dt:t.y===0?s?Me:ot:""},Be=(n,t,e,s)=>Os(n,e)?Sa(0,t,e,s):ts(n,t,e,s),Cn=(n,t,e,s)=>Os(n,t.target)?ba(n,t,e,s):xa(n,t,e,s),bn=(n,t,e,s)=>Os(n,t.target)?Ca(n,t,e,s):_a(n,t,e,s),Tn=()=>({ml:new Ot({x:-.5,y:0,cursorStyleHandler:Be,actionHandler:Cn,getActionName:Ms}),mr:new Ot({x:.5,y:0,cursorStyleHandler:Be,actionHandler:Cn,getActionName:Ms}),mb:new Ot({x:0,y:.5,cursorStyleHandler:Be,actionHandler:bn,getActionName:Ms}),mt:new Ot({x:0,y:-.5,cursorStyleHandler:Be,actionHandler:bn,getActionName:Ms}),tl:new Ot({x:-.5,y:-.5,cursorStyleHandler:ts,actionHandler:Ts}),tr:new Ot({x:.5,y:-.5,cursorStyleHandler:ts,actionHandler:Ts}),bl:new Ot({x:-.5,y:.5,cursorStyleHandler:ts,actionHandler:Ts}),br:new Ot({x:.5,y:.5,cursorStyleHandler:ts,actionHandler:Ts}),mtr:new Ot({x:0,y:-.5,actionHandler:ya,cursorStyleHandler:ma,offsetY:-40,withConnection:!0,actionName:xr})}),Ta=()=>({mr:new Ot({x:.5,y:0,actionHandler:xn,cursorStyleHandler:Be,actionName:Ne}),ml:new Ot({x:-.5,y:0,actionHandler:xn,cursorStyleHandler:Be,actionName:Ne})}),Oa=()=>({...Tn(),...Ta()});class es extends Ht{static getDefaults(){return{...super.getDefaults(),...es.ownDefaults}}constructor(t){super(),Object.assign(this,this.constructor.createControls(),es.ownDefaults),this.setOptions(t)}static createControls(){return{controls:Tn()}}_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(ls))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,o]=s[r],a=this.controls[i];if(a.shouldActivate(i,this,t,e?o.touchCorner:o.corner))return this.__corner=i,{key:i,control:a,coord:this.oCoords[i]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),s=Ee(e.x,e.y),r=he({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),i=K(s,r),o=K(t,i),a=K(o,[1/t[0],0,0,1/t[3],0,0]),h=this.group?De(this.calcTransformMatrix()):void 0;h&&(h.scaleX=Math.abs(h.scaleX),h.scaleY=Math.abs(h.scaleY));const l=this._calculateCurrentDimensions(h),c={};return this.forEachControl((u,g)=>{const d=u.positionHandler(l,a,this,u);c[g]=Object.assign(d,this._calcCornerCoords(u,d))}),c}_calcCornerCoords(t,e){const s=this.getTotalAngle();return{corner:t.calcCornerCoords(s,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(s,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(const e in this.controls)t(this.controls[e],e,this)}drawSelectionBackground(t){if(!this.selectionBackgroundColor||this.canvas&&this.canvas._activeObject!==this)return;t.save();const e=this.getRelativeCenterPoint(),s=this._calculateCurrentDimensions(),r=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/r[0],1/r[3]),t.rotate(U(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={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={hasBorders:s,hasControls:r,...e},o=this.getViewportTransform(),a=i.hasBorders,h=i.hasControls,l=K(o,this.calcTransformMatrix()),c=De(l);t.save(),t.translate(c.translateX,c.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(c.angle-=180),t.rotate(U(this.group?c.angle:this.angle)),a&&this.drawBorders(t,c,e),h&&this.drawControls(t,e),t.restore()}drawBorders(t,e,s){let r;if(s&&s.forActiveSelection||this.group){const i=ms(this.width,this.height,Ge(e)),o=this.isStrokeAccountedForInDimensions()?Sr:(this.strokeUniform?new _().scalarAdd(this.canvas?this.canvas.getZoom():1):new _(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);r=i.add(o).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:o}=this,a={cornerStrokeColor:r,cornerDashArray:i,cornerColor:o,...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,l)=>{if(h.getVisibility(this,l)){const c=this.oCoords[l];h.render(t,c.x,c.y,a,this)}}),t.restore()}isControlVisible(t){return this.controls[t]&&this.controls[t].getVisibility(this,t)}setControlVisible(t,e){this._controlsVisibility||(this._controlsVisibility={}),this._controlsVisibility[t]=e}setControlsVisibility(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.entries(t).forEach(e=>{let[s,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 On(n,t){return t.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(s=>{s!=="constructor"&&Object.defineProperty(n.prototype,s,Object.getOwnPropertyDescriptor(e.prototype,s)||Object.create(null))})}),n}y(es,"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 st extends es{}On(st,[on]),O.setClass(st),O.setClass(st,"object");const Mn=(n,t,e,s)=>{const r=2*(s=Math.round(s))+1,{data:i}=n.getImageData(t-s,e-s,r,r);for(let o=3;o<i.length;o+=4)if(i[o]>0)return!1;return!0};class kn{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new _(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new _(1/this.options.scaleX,1/this.options.scaleY):new _(1,1)}createSideVector(t,e){const s=Ke(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 _(t);return e.y+=e.x*Math.tan(U(this.options.skewY)),e.x+=e.y*Math.tan(U(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const Ma=new _;class $e extends kn{static getOrthogonalRotationFactor(t,e){const s=e?vs(t,e):Ar(t);return Math.abs(s)<Zt?-1:1}constructor(t,e,s,r){super(r),y(this,"AB",void 0),y(this,"AC",void 0),y(this,"alpha",void 0),y(this,"bisector",void 0),this.A=new _(t),this.B=new _(e),this.C=new _(s),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=vs(this.AB,this.AC),this.bisector=xs(Pr(this.AB.eq(Ma)?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=Fr(r),o=$e.getOrthogonalRotationFactor(i,this.bisector);return this.scaleUnitVector(i,s*o)}projectBevel(){const t=[];return(this.alpha%wt===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?ys(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return ys(r)/this.strokeProjectionMagnitude<=i&&t.push(this.applySkew(this.A.add(r))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const s=[],r=new _($e.getOrthogonalRotationFactor(this.bisector),$e.getOrthogonalRotationFactor(new _(this.bisector.y,this.bisector.x)));return[new _(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r),new _(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(r)].forEach(i=>{Lr(i,t,e)&&s.push(this.A.add(i))}),s}projectRoundWithSkew(t,e){const s=[],{skewX:r,skewY:i,scaleX:o,scaleY:a,strokeUniform:h}=this.options,l=new _(Math.tan(U(r)),Math.tan(U(i))),c=this.strokeProjectionMagnitude,u=h?c/a/Math.sqrt(1/a**2+1/o**2*l.y**2):c/Math.sqrt(1+l.y**2),g=new _(Math.sqrt(Math.max(c**2-u**2,0)),u),d=h?c/Math.sqrt(1+l.x**2*(1/a)**2/(1/o+1/o*l.x*l.y)**2):c/Math.sqrt(1+l.x**2/(1+l.x*l.y)**2),f=new _(d,Math.sqrt(Math.max(c**2-d**2,0)));return[f,f.scalarMultiply(-1),g,g.scalarMultiply(-1)].map(p=>this.applySkew(h?p.multiply(this.strokeUniformScalar):p)).forEach(p=>{Lr(p,t,e)&&s.push(this.applySkew(this.A).add(p))}),s}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%wt===0,s=this.applySkew(this.A),r=t[e?0:2].subtract(s),i=t[e?1:0].subtract(s),o=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),a=je(r,o)>0,h=a?r:i,l=a?i:r;return this.isSkewed()?t.push(...this.projectRoundWithSkew(h,l)):t.push(...this.projectRoundNoSkew(h,l)),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 Dn extends kn{constructor(t,e,s){super(s),this.A=new _(t),this.T=new _(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(Fr(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 _(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 $e(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new _(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(xs(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 En=function(n,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];const s=[];if(n.length===0)return s;const r=n.reduce((i,o)=>(i[i.length-1].eq(o)||i.push(new _(o)),i),[new _(n[0])]);if(r.length===1)e=!0;else if(!e){const i=r[0],o=((a,h)=>{for(let l=a.length-1;l>=0;l--)if(h(a[l],l,a))return l;return-1})(r,a=>!a.eq(i));r.splice(o+1)}return r.forEach((i,o,a)=>{let h,l;o===0?(l=a[1],h=e?i:a[a.length-1]):o===a.length-1?(h=a[o-1],l=e?i:a[0]):(h=a[o-1],l=a[o+1]),e&&a.length===1?s.push(...new Dn(i,i,t).project()):!e||o!==0&&o!==a.length-1?s.push(...new $e(i,h,l,t).project()):s.push(...new Dn(i,o===0?l:h,t).project())}),s},Gr=n=>{const t={};return Object.keys(n).forEach(e=>{t[e]={},Object.keys(n[e]).forEach(s=>{t[e][s]={...n[e][s]}})}),t},Pn=n=>n.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let ss;const ks=n=>{if(ss||ss||(ss="Intl"in ns()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),ss){const t=ss.segment(n);return Array.from(t).map(e=>{let{segment:s}=e;return s})}return ka(n)},ka=n=>{const t=[];for(let e,s=0;s<n.length;s++)(e=Da(n,s))!==!1&&t.push(e);return t},Da=(n,t)=>{const e=n.charCodeAt(t);if(isNaN(e))return"";if(e<55296||e>57343)return n.charAt(t);if(55296<=e&&e<=56319){if(n.length<=t+1)throw"High surrogate without following low surrogate";const r=n.charCodeAt(t+1);if(56320>r||r>57343)throw"High surrogate without following low surrogate";return n.charAt(t)+n.charAt(t+1)}if(t===0)throw"Low surrogate without preceding high surrogate";const s=n.charCodeAt(t-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var Ea=Object.freeze({__proto__:null,capitalize:function(n){let t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return`${n.charAt(0).toUpperCase()}${t?n.slice(1):n.slice(1).toLowerCase()}`},escapeXml:Pn,graphemeSplit:ks});const Ds=function(n,t){let e=arguments.length>2&&arguments[2]!==void 0&&arguments[2];return n.fill!==t.fill||n.stroke!==t.stroke||n.strokeWidth!==t.strokeWidth||n.fontSize!==t.fontSize||n.fontFamily!==t.fontFamily||n.fontWeight!==t.fontWeight||n.fontStyle!==t.fontStyle||n.textDecorationThickness!==t.textDecorationThickness||n.textBackgroundColor!==t.textBackgroundColor||n.deltaY!==t.deltaY||e&&(n.overline!==t.overline||n.underline!==t.underline||n.linethrough!==t.linethrough)},An=(n,t)=>{const e=t.split(`
38
- `),s=[];let r=-1,i={};n=Gr(n);for(let o=0;o<e.length;o++){const a=ks(e[o]);if(n[o])for(let h=0;h<a.length;h++){r++;const l=n[o][h];l&&Object.keys(l).length>0&&(Ds(i,l,!0)?s.push({start:r,end:r+1,style:l}):s[s.length-1].end++),i=l||{}}else r+=a.length,i={}}return s},Fn=(n,t)=>{if(!Array.isArray(n))return Gr(n);const e=t.split(vr),s={};let r=-1,i=0;for(let o=0;o<e.length;o++){const a=ks(e[o]);for(let h=0;h<a.length;h++)r++,n[i]&&n[i].start<=r&&r<n[i].end&&(s[o]=s[o]||{},s[o][h]={...n[i].style},r===n[i].end-1&&i++)}return s},ee=["display","transform",J,"fill-opacity","fill-rule","opacity",ft,"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 Ln(n,t){const e=n.nodeName,s=n.getAttribute("class"),r=n.getAttribute("id"),i="(?![a-zA-Z\\-]+)";let o;if(o=new RegExp("^"+e,"i"),t=t.replace(o,""),r&&t.length&&(o=new RegExp("#"+r+i,"i"),t=t.replace(o,"")),s&&t.length){const a=s.split(" ");for(let h=a.length;h--;)o=new RegExp("\\."+a[h]+i,"i"),t=t.replace(o,"")}return t.length===0}function Pa(n,t){let e=!0;const s=Ln(n,t.pop());return s&&t.length&&(e=(function(r,i){let o,a=!0;for(;r.parentElement&&r.parentElement.nodeType===1&&i.length;)a&&(o=i.pop()),a=Ln(r=r.parentElement,o);return i.length===0})(n,t)),s&&e&&t.length===0}function Aa(n){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},e={};for(const s in t)Pa(n,s.split(" "))&&(e={...e,...t[s]});return e}const Fa=n=>{var t;return(t=sa[n])!==null&&t!==void 0?t:n},La=new RegExp(`(${fe})`,"gi"),ht=`(${fe})`,ja=String.raw`(skewX)\(${ht}\)`,Ia=String.raw`(skewY)\(${ht}\)`,Ra=String.raw`(rotate)\(${ht}(?: ${ht} ${ht})?\)`,Ba=String.raw`(scale)\(${ht}(?: ${ht})?\)`,$a=String.raw`(translate)\(${ht}(?: ${ht})?\)`,zr=`(?:${String.raw`(matrix)\(${ht} ${ht} ${ht} ${ht} ${ht} ${ht}\)`}|${$a}|${Ra}|${Ba}|${ja}|${Ia})`,Xa=`(?:${zr}*)`,Wa=String.raw`^\s*(?:${Xa}?)\s*$`,Ya=new RegExp(Wa),Ha=new RegExp(zr),Na=new RegExp(zr,"g");function Ur(n){const t=[];if(!(n=(e=>ws(e.replace(La," $1 ").replace(/,/gi," ")))(n).replace(/\s*([()])\s*/gi,"$1"))||n&&!Ya.test(n))return[...nt];for(const e of n.matchAll(Na)){const s=Ha.exec(e[0]);if(!s)continue;let r=nt;const i=s.filter(f=>!!f),[,o,...a]=i,[h,l,c,u,g,d]=a.map(f=>parseFloat(f));switch(o){case"translate":r=Ee(h,l);break;case xr:r=he({angle:h},{x:l,y:c});break;case ls:r=fs(h,l);break;case Oe:r=Tr(h);break;case Me:r=Or(h);break;case"matrix":r=[h,l,c,u,g,d]}t.push(r)}return ds(t)}function Va(n,t,e,s){const r=Array.isArray(t);let i,o=t;if(n!==J&&n!==ft||t!==gt){if(n==="strokeUniform")return t==="non-scaling-stroke";if(n==="strokeDashArray")o=t===gt?null:t.replace(/,/g," ").split(/\s+/).map(parseFloat);else if(n==="transformMatrix")o=e&&e.transformMatrix?K(e.transformMatrix,Ur(t)):Ur(t);else if(n==="visible")o=t!==gt&&t!=="hidden",e&&e.visible===!1&&(o=!1);else if(n==="opacity")o=parseFloat(t),e&&e.opacity!==void 0&&(o*=e.opacity);else if(n==="textAnchor")o=t==="start"?$:t==="end"?q:A;else if(n==="charSpacing"||n===de)i=ge(t,s)/s*1e3;else if(n==="paintFirst"){const a=t.indexOf(J),h=t.indexOf(ft);o=J,(a>-1&&h>-1&&h<a||a===-1&&h>-1)&&(o=ft)}else{if(n==="href"||n==="xlink:href"||n==="font"||n==="id")return t;if(n==="imageSmoothing")return t==="optimizeQuality";i=r?t.map(ge):ge(t,s)}}else o="";return!r&&isNaN(i)?o:i}function Ga(n,t){n.replace(/;\s*$/,"").split(";").forEach(e=>{if(!e)return;const[s,r]=e.split(":");t[s.trim().toLowerCase()]=r.trim()})}function za(n){const t={},e=n.getAttribute("style");return e&&(typeof e=="string"?Ga(e,t):(function(s,r){Object.entries(s).forEach(i=>{let[o,a]=i;a!==void 0&&(r[o.toLowerCase()]=a)})})(e,t)),t}const Ua={stroke:"strokeOpacity",fill:"fillOpacity"};function Nt(n,t,e){if(!n)return{};let s,r={},i=mr;n.parentNode&&un.test(n.parentNode.nodeName)&&(r=Nt(n.parentElement,t,e),r.fontSize&&(s=i=ge(r.fontSize)));const o={...t.reduce((l,c)=>{const u=n.getAttribute(c);return u&&(l[c]=u),l},{}),...Aa(n,e),...za(n)};o[Br]&&n.setAttribute(Br,o[Br]),o[Rr]&&(s=ge(o[Rr],i),o[Rr]=`${s}`);const a={};for(const l in o){const c=Fa(l),u=Va(c,o[l],r,s);a[c]=u}a&&a.font&&(function(l,c){const u=l.match(ea);if(!u)return;const g=u[1],d=u[3],f=u[4],p=u[5],m=u[6];g&&(c.fontStyle=g),d&&(c.fontWeight=isNaN(parseFloat(d))?d:parseFloat(d)),f&&(c.fontSize=ge(f)),m&&(c.fontFamily=m),p&&(c.lineHeight=p===_r?1:p)})(a.font,a);const h={...r,...a};return un.test(n.nodeName)?h:(function(l){const c=st.getDefaults();return Object.entries(Ua).forEach(u=>{let[g,d]=u;if(l[d]===void 0||l[g]==="")return;if(l[g]===void 0){if(!c[g])return;l[g]=c[g]}if(l[g].indexOf("url(")===0)return;const f=new W(l[g]);l[g]=f.setAlpha(X(f.getAlpha()*l[d],2)).toRgba()}),l})(h)}const jn=["rx","ry"];class Mt extends st{static getDefaults(){return{...super.getDefaults(),...Mt.ownDefaults}}constructor(t){super(),Object.assign(this,Mt.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,o=this.rx?Math.min(this.rx,e/2):0,a=this.ry?Math.min(this.ry,s/2):0,h=o!==0||a!==0;t.beginPath(),t.moveTo(r+o,i),t.lineTo(r+e-o,i),h&&t.bezierCurveTo(r+e-Jt*o,i,r+e,i+Jt*a,r+e,i+a),t.lineTo(r+e,i+s-a),h&&t.bezierCurveTo(r+e,i+s-Jt*a,r+e-Jt*o,i+s,r+e-o,i+s),t.lineTo(r+o,i+s),h&&t.bezierCurveTo(r+Jt*o,i+s,r,i+s-Jt*a,r,i+s-a),t.lineTo(r,i+a),h&&t.bezierCurveTo(r,i+Jt*a,r+Jt*o,i,r+o,i),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...jn,...t])}_toSVG(){const{width:t,height:e,rx:s,ry:r}=this;return["<rect ","COMMON_PARTS",`x="${-t/2}" y="${-e/2}" rx="${s}" ry="${r}" width="${t}" height="${e}" />
39
- `]}static async fromElement(t,e,s){const{left:r=0,top:i=0,width:o=0,height:a=0,visible:h=!0,...l}=Nt(t,this.ATTRIBUTE_NAMES,s);return new this({...e,...l,left:r,top:i,width:o,height:a,visible:!!(h&&o&&a)})}}y(Mt,"type","Rect"),y(Mt,"cacheProperties",[...Yt,...jn]),y(Mt,"ownDefaults",{rx:0,ry:0}),y(Mt,"ATTRIBUTE_NAMES",[...ee,"x","y","rx","ry","width","height"]),O.setClass(Mt),O.setSVGClass(Mt);const Vt="initialization",Es="added",qr="removed",Ps="imperative",In=(n,t)=>{const{strokeUniform:e,strokeWidth:s,width:r,height:i,group:o}=t,a=o&&o!==n?qe(o.calcTransformMatrix(),n.calcTransformMatrix()):null,h=a?t.getRelativeCenterPoint().transform(a):t.getRelativeCenterPoint(),l=!t.isStrokeAccountedForInDimensions(),c=e&&l?zi(new _(s,s),void 0,n.calcTransformMatrix()):Sr,u=!e&&l?s:0,g=ms(r+u,i+u,ds([a,t.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[h.subtract(g),h.add(g)]};class As{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:s,strategy:r}=t;return e===Vt||e===Ps||!!s&&r!==s}shouldLayoutClipPath(t){let{type:e,target:{clipPath:s}}=t;return e!==Vt&&s&&!s.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:s,target:r}=e;if(s===Ps&&e.overrides)return e.overrides;if(t.length===0)return;const{left:i,top:o,width:a,height:h}=Lt(t.map(u=>In(r,u)).reduce((u,g)=>u.concat(g),[])),l=new _(a,h),c=new _(i,o).add(l.scalarDivide(2));if(s===Vt){const u=this.getInitialSize(e,{size:l,center:c});return{center:c,relativeCorrection:new _(0,0),size:u}}return{center:c.transform(r.calcOwnMatrix()),size:l}}}y(As,"type","strategy");class Kr extends As{shouldPerformLayout(t){return!0}}y(Kr,"type","fit-content"),O.setClass(Kr);const Rn="layoutManager";class rs{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:new Kr;y(this,"strategy",void 0),this.strategy=t,this._subscriptions=new Map}performLayout(t){const e={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[cs,Ti,Ne,Oi,as,Mi,hs,Vo,Go].map(r=>t.on(r,i=>this.performLayout(r===cs?{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===Vt||s===Es?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===Ps&&t.deep){const{strategy:i,...o}=t;e.forEachObject(a=>a.layoutManager&&a.layoutManager.performLayout({...o,bubbles:!1,target:a}))}}getLayoutResult(t){const{target:e,strategy:s,type:r}=t,i=s.calcLayoutResult(t,e.getObjects());if(!i)return;const o=r===Vt?new _:e.getRelativeCenterPoint(),{center:a,correction:h=new _,relativeCorrection:l=new _}=i,c=o.subtract(a).add(h).transform(r===Vt?nt:mt(e.calcOwnMatrix()),!0).add(l);return{result:i,prevCenter:o,nextCenter:a,offset:c}}commitLayout(t,e){const{target:s}=t,{result:{size:r},nextCenter:i}=e;var o,a;s.set({width:r.x,height:r.y}),this.layoutObjects(t,e),t.type===Vt?s.set({left:(o=t.x)!==null&&o!==void 0?o:i.x+r.x*at(s.originX),top:(a=t.y)!==null&&a!==void 0?a:i.y+r.y*at(s.originY)}):(s.setPositionByOrigin(i,A,A),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:o,...a}=t,{canvas:h}=s;s.fire("layout:after",{context:t,result:e}),h&&h.fire("object:layout:after",{context:t,result:e,target:s});const l=s.parent;i&&l!=null&&l.layoutManager&&((a.path||(a.path=[])).push(s),l.layoutManager.performLayout({...a,target:l})),s.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(e=>e.forEach(s=>s())),t.clear()}toObject(){return{type:Rn,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}O.setClass(rs,Rn);class qa extends rs{performLayout(){}}class Gt extends ki(st){static getDefaults(){return{...super.getDefaults(),...Gt.ownDefaults}}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),y(this,"_activeObjects",[]),y(this,"__objectSelectionTracker",void 0),y(this,"__objectSelectionDisposer",void 0),Object.assign(this,Gt.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 rs,this.layoutManager.performLayout({type:Vt,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(Qt("error","Group: circular object trees are not supported, this call has no effect"),!1):this._objects.indexOf(t)===-1||(Qt("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(Es,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),o=super.insertAt(t,...i);return this._onAfterObjectsChange(Es,i),o}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&&Le(t,K(mt(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||(Le(t,K(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=st.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 o=this._objects[i];(r=this.canvas)!==null&&r!==void 0&&r.preserveObjectStacking&&o.group!==this?(t.save(),t.transform(...mt(this.calcTransformMatrix())),o.render(t),t.restore()):o.group===this&&o.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({target:this,type:Ps,...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 o=r[t||"toObject"](e);return r.includeDefaultValues=i,o})}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];const e=this.layoutManager.toObject();return{...super.toObject(["subTargetCheck","interactive",...t]),...e.strategy!=="fit-content"||this.includeDefaultValues?{layoutManager:e}:{},objects:this.__serializeObjects("toObject",t)}}toString(){return`#<Group: (${this.complexity()})>`}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Mt.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: ${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,...o}=t;return Promise.all([Pe(r,e),Ue(o,e)]).then(a=>{let[h,l]=a;const c=new this(h,{...o,...l,layoutManager:new qa});if(i){const u=O.getClass(i.type),g=O.getClass(i.strategy);c.layoutManager=new u(new g)}else c.layoutManager=new rs;return c.layoutManager.subscribeTargets({type:Vt,target:c,targets:c.getObjects()}),c.setCoords(),c})}}y(Gt,"type","Group"),y(Gt,"ownDefaults",{strokeWidth:0,subTargetCheck:!1,interactive:!1}),O.setClass(Gt);const Bn=(n,t)=>Math.min(t.width/n.width,t.height/n.height),$n=(n,t)=>Math.max(t.width/n.width,t.height/n.height),Qr="\\s*,?\\s*",is=`${Qr}(${fe})`,Ka=`${is}${is}${is}${Qr}([01])${Qr}([01])${is}${is}`,Qa={m:"l",M:"L"},Za=(n,t,e,s,r,i,o,a,h,l,c)=>{const u=St(n),g=Ct(n),d=St(t),f=Ct(t),p=e*r*d-s*i*f+o,m=s*r*d+e*i*f+a;return["C",l+h*(-e*r*g-s*i*u),c+h*(-s*r*g+e*i*u),p+h*(e*r*f+s*i*d),m+h*(s*r*f-e*i*d),p,m]},Xn=(n,t,e,s)=>{const r=Math.atan2(t,n),i=Math.atan2(s,e);return i>=r?i-r:2*Math.PI-(r-i)};function Zr(n,t,e,s,r,i,o,a){let h;if(B.cachesBoundsOfCurve&&(h=[...arguments].join(),He.boundsOfCurveCache[h]))return He.boundsOfCurveCache[h];const l=Math.sqrt,c=Math.abs,u=[],g=[[0,0],[0,0]];let d=6*n-12*e+6*r,f=-3*n+9*e-9*r+3*o,p=3*e-3*n;for(let w=0;w<2;++w){if(w>0&&(d=6*t-12*s+6*i,f=-3*t+9*s-9*i+3*a,p=3*s-3*t),c(f)<1e-12){if(c(d)<1e-12)continue;const k=-p/d;0<k&&k<1&&u.push(k);continue}const C=d*d-4*p*f;if(C<0)continue;const b=l(C),M=(-d+b)/(2*f);0<M&&M<1&&u.push(M);const T=(-d-b)/(2*f);0<T&&T<1&&u.push(T)}let m=u.length;const v=m,x=Yn(n,t,e,s,r,i,o,a);for(;m--;){const{x:w,y:C}=x(u[m]);g[0][m]=w,g[1][m]=C}g[0][v]=n,g[1][v]=t,g[0][v+1]=o,g[1][v+1]=a;const S=[new _(Math.min(...g[0]),Math.min(...g[1])),new _(Math.max(...g[0]),Math.max(...g[1]))];return B.cachesBoundsOfCurve&&(He.boundsOfCurveCache[h]=S),S}const Ja=(n,t,e)=>{let[s,r,i,o,a,h,l,c]=e;const u=((g,d,f,p,m,v,x)=>{if(f===0||p===0)return[];let S=0,w=0,C=0;const b=Math.PI,M=x*pr,T=Ct(M),k=St(M),P=.5*(-k*g-T*d),F=.5*(-k*d+T*g),D=f**2,L=p**2,I=F**2,Q=P**2,Y=D*L-D*I-L*Q;let H=Math.abs(f),R=Math.abs(p);if(Y<0){const tt=Math.sqrt(1-Y/(D*L));H*=tt,R*=tt}else C=(m===v?-1:1)*Math.sqrt(Y/(D*I+L*Q));const ct=C*H*F/R,rt=-C*R*P/H,Kt=k*ct-T*rt+.5*g,re=T*ct+k*rt+.5*d;let ie=Xn(1,0,(P-ct)/H,(F-rt)/R),E=Xn((P-ct)/H,(F-rt)/R,(-P-ct)/H,(-F-rt)/R);v===0&&E>0?E-=2*b:v===1&&E<0&&(E+=2*b);const j=Math.ceil(Math.abs(E/b*2)),N=[],V=E/j,G=8/3*Math.sin(V/4)*Math.sin(V/4)/Math.sin(V/2);let it=ie+V;for(let tt=0;tt<j;tt++)N[tt]=Za(ie,it,k,T,H,R,Kt,re,G,S,w),S=N[tt][5],w=N[tt][6],ie=it,it+=V;return N})(l-n,c-t,r,i,a,h,o);for(let g=0,d=u.length;g<d;g++)u[g][1]+=n,u[g][2]+=t,u[g][3]+=n,u[g][4]+=t,u[g][5]+=n,u[g][6]+=t;return u},Wn=n=>{let t=0,e=0,s=0,r=0;const i=[];let o,a=0,h=0;for(const l of n){const c=[...l];let u;switch(c[0]){case"l":c[1]+=t,c[2]+=e;case"L":t=c[1],e=c[2],u=["L",t,e];break;case"h":c[1]+=t;case"H":t=c[1],u=["L",t,e];break;case"v":c[1]+=e;case"V":e=c[1],u=["L",t,e];break;case"m":c[1]+=t,c[2]+=e;case"M":t=c[1],e=c[2],s=c[1],r=c[2],u=["M",t,e];break;case"c":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e,c[5]+=t,c[6]+=e;case"C":a=c[3],h=c[4],t=c[5],e=c[6],u=["C",c[1],c[2],a,h,t,e];break;case"s":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"S":o==="C"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=c[3],e=c[4],u=["C",a,h,c[1],c[2],t,e],a=u[3],h=u[4];break;case"q":c[1]+=t,c[2]+=e,c[3]+=t,c[4]+=e;case"Q":a=c[1],h=c[2],t=c[3],e=c[4],u=["Q",a,h,t,e];break;case"t":c[1]+=t,c[2]+=e;case"T":o==="Q"?(a=2*t-a,h=2*e-h):(a=t,h=e),t=c[1],e=c[2],u=["Q",a,h,t,e];break;case"a":c[6]+=t,c[7]+=e;case"A":Ja(t,e,c).forEach(g=>i.push(g)),t=c[6],e=c[7];break;case"z":case"Z":t=s,e=r,u=["Z"]}u?(i.push(u),o=u[0]):o=""}return i},Fs=(n,t,e,s)=>Math.sqrt((e-n)**2+(s-t)**2),Yn=(n,t,e,s,r,i,o,a)=>h=>{const l=h**3,c=(d=>3*d**2*(1-d))(h),u=(d=>3*d*(1-d)**2)(h),g=(d=>(1-d)**3)(h);return new _(o*l+r*c+e*u+n*g,a*l+i*c+s*u+t*g)},Hn=n=>n**2,Nn=n=>2*n*(1-n),Vn=n=>(1-n)**2,th=(n,t,e,s,r,i,o,a)=>h=>{const l=Hn(h),c=Nn(h),u=Vn(h),g=3*(u*(e-n)+c*(r-e)+l*(o-r)),d=3*(u*(s-t)+c*(i-s)+l*(a-i));return Math.atan2(d,g)},eh=(n,t,e,s,r,i)=>o=>{const a=Hn(o),h=Nn(o),l=Vn(o);return new _(r*a+e*h+n*l,i*a+s*h+t*l)},sh=(n,t,e,s,r,i)=>o=>{const a=1-o,h=2*(a*(e-n)+o*(r-e)),l=2*(a*(s-t)+o*(i-s));return Math.atan2(l,h)},Gn=(n,t,e)=>{let s=new _(t,e),r=0;for(let i=1;i<=100;i+=1){const o=n(i/100);r+=Fs(s.x,s.y,o.x,o.y),s=o}return r},rh=(n,t)=>{let e,s=0,r=0,i={x:n.x,y:n.y},o={...i},a=.01,h=0;const l=n.iterator,c=n.angleFinder;for(;r<t&&a>1e-4;)o=l(s),h=s,e=Fs(i.x,i.y,o.x,o.y),e+r>t?(s-=a,a/=2):(i=o,s+=a,r+=e);return{...o,angle:c(h)}},Jr=n=>{let t,e,s=0,r=0,i=0,o=0,a=0;const h=[];for(const l of n){const c={x:r,y:i,command:l[0],length:0};switch(l[0]){case"M":e=c,e.x=o=r=l[1],e.y=a=i=l[2];break;case"L":e=c,e.length=Fs(r,i,l[1],l[2]),r=l[1],i=l[2];break;case"C":t=Yn(r,i,l[1],l[2],l[3],l[4],l[5],l[6]),e=c,e.iterator=t,e.angleFinder=th(r,i,l[1],l[2],l[3],l[4],l[5],l[6]),e.length=Gn(t,r,i),r=l[5],i=l[6];break;case"Q":t=eh(r,i,l[1],l[2],l[3],l[4]),e=c,e.iterator=t,e.angleFinder=sh(r,i,l[1],l[2],l[3],l[4]),e.length=Gn(t,r,i),r=l[3],i=l[4];break;case"Z":e=c,e.destX=o,e.destY=a,e.length=Fs(r,i,o,a),r=o,i=a}s+=e.length,h.push(e)}return h.push({length:s,x:r,y:i}),h},zn=function(n,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Jr(n),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,o=n[s];switch(r.command){case"M":return{x:r.x,y:r.y,angle:0};case"Z":return{...new _(r.x,r.y).lerp(new _(r.destX,r.destY),i),angle:Math.atan2(r.destY-r.y,r.destX-r.x)};case"L":return{...new _(r.x,r.y).lerp(new _(o[1],o[2]),i),angle:Math.atan2(o[2]-r.y,o[1]-r.x)};case"C":case"Q":return rh(r,t)}},ih=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),Un=new RegExp(Ka,"g"),nh=new RegExp(fe,"gi"),oh={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},qn=n=>{var t;const e=[],s=(t=n.match(ih))!==null&&t!==void 0?t:[];for(const r of s){const i=r[0];if(i==="z"||i==="Z"){e.push([i]);continue}const o=oh[i.toLowerCase()];let a=[];if(i==="a"||i==="A"){Un.lastIndex=0;for(let h=null;h=Un.exec(r);)a.push(...h.slice(1))}else a=r.match(nh)||[];for(let h=0;h<a.length;h+=o){const l=new Array(o),c=Qa[i];l[0]=h>0&&c?c:i;for(let u=0;u<o;u++)l[u+1]=parseFloat(a[h+u]);e.push(l)}}return e},ah=function(n){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=new _(n[0]),s=new _(n[1]),r=1,i=0;const o=[],a=n.length,h=a>2;let l;for(h&&(r=n[2].x<s.x?-1:n[2].x===s.x?0:1,i=n[2].y<s.y?-1:n[2].y===s.y?0:1),o.push(["M",e.x-r*t,e.y-i*t]),l=1;l<a;l++){if(!e.eq(s)){const c=e.midPointFrom(s);o.push(["Q",e.x,e.y,c.x,c.y])}e=n[l],l+1<n.length&&(s=n[l+1])}return h&&(r=e.x>n[l-2].x?1:e.x===n[l-2].x?0:-1,i=e.y>n[l-2].y?1:e.y===n[l-2].y?0:-1),o.push(["L",e.x+r*t,e.y+i*t]),o},Kn=(n,t)=>n.map(e=>e.map((s,r)=>r===0||t===void 0?s:X(s,t)).join(" ")).join(" ");var Qn=Object.freeze({__proto__:null,addTransformToObject:Vi,animate:Hr,animateColor:yn,applyTransformToObject:Le,calcAngleBetweenVectors:vs,calcDimensionsMatrix:Ge,calcPlaneChangeMatrix:qe,calcVectorRotation:Ar,cancelAnimFrame:Ei,capValue:pe,composeMatrix:ji,copyCanvasElement:n=>{var t;const e=pt(n);return(t=e.getContext("2d"))===null||t===void 0||t.drawImage(n,0,0),e},cos:St,createCanvasElement:Ft,createImage:Pi,createRotateMatrix:he,createScaleMatrix:fs,createSkewXMatrix:Tr,createSkewYMatrix:Or,createTranslateMatrix:Ee,createVector:Ke,crossProduct:je,degreesToRadians:U,dotProduct:qi,ease:na,enlivenObjectEnlivables:Ue,enlivenObjects:Pe,findScaleToCover:$n,findScaleToFit:Bn,getBoundsOfCurve:Zr,getOrthonormalVector:Fr,getPathSegmentsInfo:Jr,getPointOnPath:zn,getPointer:Hi,getRandomInt:(n,t)=>Math.floor(Math.random()*(t-n+1))+n,getRegularPolygonPath:(n,t)=>{const e=2*Math.PI/n;let s=-Zt;n%2==0&&(s+=e/2);const r=new Array(n+1);for(let i=0;i<n;i++){const o=i*e+s,{x:a,y:h}=new _(St(o),Ct(o)).scalarMultiply(t);r[i]=[i===0?"M":"L",a,h]}return r[n]=["Z"],r},getSmoothPathFromPoints:ah,getSvgAttributes:n=>{const t=["instantiated_by_use","style","id","class"];switch(n){case"linearGradient":return t.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return t.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return t.concat(["offset","stop-color","stop-opacity"])}return t},getUnitVector:xs,groupSVGElements:(n,t)=>n&&n.length===1?n[0]:new Gt(n,t),hasStyleChanged:Ds,invertTransform:mt,isBetweenVectors:Lr,isIdentityMatrix:Ai,isTouchEvent:ps,isTransparent:Mn,joinPath:Kn,loadImage:ze,magnitude:ys,makeBoundingBoxFromPoints:Lt,makePathSimpler:Wn,matrixToSVG:Ae,mergeClipPaths:(n,t)=>{var e;let s=n,r=t;s.inverted&&!r.inverted&&(s=t,r=n),Er(r,(e=r.group)===null||e===void 0?void 0:e.calcTransformMatrix(),s.calcTransformMatrix());const i=s.inverted&&r.inverted;return i&&(s.inverted=r.inverted=!1),new Gt([s],{clipPath:r,inverted:i})},multiplyTransformMatrices:K,multiplyTransformMatrixArray:ds,parsePath:qn,parsePreserveAspectRatioAttribute:nn,parseUnit:ge,pick:le,projectStrokeOnPoints:En,qrDecompose:De,radiansToDegrees:Xt,removeFromArray:ae,removeTransformFromObject:(n,t)=>{const e=mt(t),s=K(e,n.calcOwnMatrix());Le(n,s)},removeTransformMatrixForSvgParsing:(n,t)=>{let e=n._findCenterFromElement();n.transformMatrix&&((s=>{if(s.transformMatrix){const{scaleX:r,scaleY:i,angle:o,skewX:a}=De(s.transformMatrix);s.flipX=!1,s.flipY=!1,s.set(ot,r),s.set(dt,i),s.angle=o,s.skewX=a,s.skewY=0}})(n),e=e.transform(n.transformMatrix)),delete n.transformMatrix,t&&(n.scaleX*=t.scaleX,n.scaleY*=t.scaleY,n.cropX=t.cropX,n.cropY=t.cropY,e.x+=t.offsetLeft,e.y+=t.offsetTop,n.width=t.width,n.height=t.height),n.setPositionByOrigin(e,A,A)},requestAnimFrame:Ve,resetObjectTransform:Gi,rotateVector:Pr,saveObjectTransform:Dr,sendObjectToPlane:Er,sendPointToPlane:ue,sendVectorToPlane:zi,sin:Ct,sizeAfterTransform:ms,string:Ea,stylesFromArray:Fn,stylesToArray:An,toBlob:br,toDataURL:Cr,toFixed:X,transformPath:(n,t,e)=>(e&&(t=K(t,[1,0,0,1,-e.x,-e.y])),n.map(s=>{const r=[...s];for(let i=1;i<s.length-1;i+=2){const{x:o,y:a}=et({x:s[i],y:s[i+1]},t);r[i]=o,r[i+1]=a}return r})),transformPoint:et});function ti(n,t){const e=n.style;e&&Object.entries(t).forEach(s=>{let[r,i]=s;return e.setProperty(r,i)})}class hh extends Yi{constructor(t){let{allowTouchScrolling:e=!1,containerClass:s=""}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(t),y(this,"upper",void 0),y(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 o=this.createContainerElement();o.classList.add(s),r.parentNode&&r.parentNode.replaceChild(o,r),o.append(r,i),this.container=o}createUpperCanvas(){const{el:t}=this.lower,e=Ft();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=Te().createElement("div");return t.setAttribute("data-fabric","wrapper"),ti(t,{position:"relative"}),Wi(t),t}applyCanvasStyle(t,e){const{styles:s,allowTouchScrolling:r}=e;ti(t,{...s,"touch-action":r?"manipulation":gt}),Wi(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:s,ctx:r}=this.upper;Xi(s,r,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),kr(this.upper.el,t),kr(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(),At().dispose(this.upper.el),delete this.upper,delete this.container}}const lh=(n,t,e,s)=>{const{target:r,offsetX:i,offsetY:o}=t,a=e-i,h=s-o,l=!Tt(r,"lockMovementX")&&r.left!==a,c=!Tt(r,"lockMovementY")&&r.top!==h;return l&&r.set($,a),c&&r.set(ut,h),(l||c)&&vn(Ti,Zi(n,t,e,s)),l||c};class Ls extends Fe{constructor(){super(...arguments),y(this,"_hoveredTargets",[]),y(this,"_currentTransform",null),y(this,"_groupSelector",null),y(this,"contextTopDirty",!1)}static getDefaults(){return{...super.getDefaults(),...Ls.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 hh(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 o=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(i),t.selectionBackgroundColor=o,i.restore();const a=Math.round(r*this.getRetinaScaling());return Mn(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===ls||e===ot||e===dt||e===Ne?r=this.centeredScaling||t.centeredScaling:e===xr&&(r=this.centeredRotation||t.centeredRotation),r?!s:s}_getOriginFromCorner(t,e){const s={x:t.originX,y:t.originY};return e&&(["ml","tl","bl"].includes(e)?s.x=q:["mr","tr","br"].includes(e)&&(s.x=$),["tl","mt","tr"].includes(e)?s.y=yr:["bl","mb","br"].includes(e)&&(s.y=ut)),s}_setupCurrentTransform(t,e,s){var r;const i=e.group?ue(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:o="",control:a}=e.getActiveControl()||{},h=s&&a?(r=a.getActionHandler(t,e,a))===null||r===void 0?void 0:r.bind(a):lh,l=((T,k,P,F)=>{if(!k||!T)return"drag";const D=F.controls[k];return D.getActionName(P,D,F)})(s,o,t,e),c=t[this.centeredKey],u=this._shouldCenterTransform(e,l,c)?{x:A,y:A}:this._getOriginFromCorner(e,o),{scaleX:g,scaleY:d,skewX:f,skewY:p,left:m,top:v,angle:x,width:S,height:w,cropX:C,cropY:b}=e,M={target:e,action:l,actionHandler:h,actionPerformed:!1,corner:o,scaleX:g,scaleY:d,skewX:f,skewY:p,offsetX:i.x-m,offsetY:i.y-v,originX:u.x,originY:u.y,ex:i.x,ey:i.y,lastX:i.x,lastY:i.y,theta:U(x),width:S,height:w,shiftKey:t.shiftKey,altKey:c,original:{...Dr(e),originX:u.x,originY:u.y,cropX:C,cropY:b}};this._currentTransform=M,this.fire("before:transform",{e:t,transform:M})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:s,deltaX:r,deltaY:i}=this._groupSelector,o=new _(e,s).transform(this.viewportTransform),a=new _(e+r,s+i).transform(this.viewportTransform),h=this.selectionLineWidth/2;let l=Math.min(o.x,a.x),c=Math.min(o.y,a.y),u=Math.max(o.x,a.x),g=Math.max(o.y,a.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(l,c,u-l,g-c)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,l+=h,c+=h,u-=h,g-=h,st.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(l,c,u-l,g-c))}findTarget(t){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};const e=this.getScenePoint(t),s=this._activeObject,r=this.getActiveObjects(),i=this.searchPossibleTargets(this._objects,e),{subTargets:o,container:a,target:h}=i,l={...i,currentSubTargets:o,currentContainer:a,currentTarget:h};if(!s)return l;const c={...this.searchPossibleTargets([s],e),currentSubTargets:o,currentContainer:a,currentTarget:h};return s.findControl(this.getViewportPoint(t),ps(t))?{...c,target:s}:c.target&&(r.length>1||!this.preserveObjectStacking||this.preserveObjectStacking&&t[this.altSelectionKey])?c:l}_pointIsInObjectSelectionArea(t,e){let s=t.getCoords();const r=this.getZoom(),i=t.padding/r;if(i){const[o,a,h,l]=s,c=Math.atan2(a.y-o.y,a.x-o.x),u=St(c)*i,g=Ct(c)*i,d=u+g,f=u-g;s=[new _(o.x-f,o.y-d),new _(a.x+d,a.y-f),new _(h.x+f,h.y+d),new _(l.x-d,l.y+f)]}return z.isPointInPolygon(e,s)}_checkTarget(t,e){if(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;{const s=e.transform(this.viewportTransform);if(!this.isTargetTransparent(t,s.x,s.y))return!0}}return!1}_searchPossibleTargets(t,e,s){let r=t.length;for(;r--;){const i=t[r];if(this._checkTarget(i,e)){if(gs(i)&&i.subTargetCheck){const{target:o}=this._searchPossibleTargets(i._objects,e,s);o&&s.push(o)}return{target:i,subTargets:s}}}return{subTargets:[]}}searchPossibleTargets(t,e){const s=this._searchPossibleTargets(t,e,[]);s.container=s.target;const{container:r,subTargets:i}=s;if(r&&gs(r)&&r.interactive&&i[0]){for(let o=i.length-1;o>0;o--){const a=i[o];if(!gs(a)||!a.interactive)return s.target=a,s}return s.target=i[0],s}return s}getViewportPoint(t){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(t,!0)}getScenePoint(t){return this._scenePoint?this._scenePoint:this._getPointerImpl(t)}_getPointerImpl(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,r=s.getBoundingClientRect();let i=Hi(t),o=r.width||0,a=r.height||0;o&&a||(ut in r&&yr in r&&(a=Math.abs(r.top-r.bottom)),q in r&&$ in r&&(o=Math.abs(r.right-r.left))),this.calcOffset(),i.x=i.x-this._offset.left,i.y=i.y-this._offset.top,e||(i=ue(i,void 0,this.viewportTransform));const h=this.getRetinaScaling();h!==1&&(i.x/=h,i.y/=h);const l=o===0||a===0?new _(1,1):new _(s.width/o,s.height/a);return i.multiply(l)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=Ft(),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 ce(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let s=!1,r=!1;const i=this.getActiveObjects(),o=[],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}),o.push(h))}),t.length>0&&i.length>0?(r=!0,s&&this.fire("selection:updated",{e,selected:o,deselected:a})):i.length>0?(r=!0,this.fire("selection:created",{e,selected:o})):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,ce(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),ce(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(cs,r))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;ce(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&&ce(e)&&this._activeObject===e){const s=le(t,["angle","flipX","flipY",$,ot,dt,Oe,Me,ut]);return Vi(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,s){const r=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,s),e.set(r)}}y(Ls,"ownDefaults",{uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!0,fireRightClick:!0,fireMiddleClick:!0,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!0});class ch{constructor(t){y(this,"targets",[]),y(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),ae(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 yt={passive:!1},me=(n,t)=>({viewportPoint:n.getViewportPoint(t),scenePoint:n.getScenePoint(t)}),se=function(n){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return n.addEventListener(...e)},xt=function(n){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s<t;s++)e[s-1]=arguments[s];return n.removeEventListener(...e)},uh={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 ei extends Ls{constructor(t){super(t,arguments.length>1&&arguments[1]!==void 0?arguments[1]:{}),y(this,"_isClick",void 0),y(this,"textEditingManager",new ch(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(se)}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t){let e=arguments.length>1&&arguments[1]!==void 0&&arguments[1];const s=this.upperCanvasEl,r=this._getEventPrefix();t($i(s),"resize",this._onResize),t(s,r+"down",this._onMouseDown),t(s,`${r}move`,this._onMouseMove,yt),t(s,`${r}out`,this._onMouseOut),t(s,`${r}enter`,this._onMouseEnter),t(s,"wheel",this._onMouseWheel,{passive:!1}),t(s,"contextmenu",this._onContextMenu),e||(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,yt)}removeListeners(){this.addOrRemove(xt);const t=this._getEventPrefix(),e=bt(this.upperCanvasEl);xt(e,`${t}up`,this._onMouseUp),xt(e,"touchend",this._onTouchEnd,yt),xt(e,`${t}move`,this._onMouseMove,yt),xt(e,"touchmove",this._onMouseMove,yt),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_onMouseOut(t){const e=this._hoveredTarget,s={e:t,...me(this,t)};this.fire("mouse:out",{...s,target:e}),this._hoveredTarget=void 0,e&&e.fire("mouseout",{...s}),this._hoveredTargets.forEach(r=>{this.fire("mouse:out",{...s,target:r}),r&&r.fire("mouseout",{...s})}),this._hoveredTargets=[]}_onMouseEnter(t){const{target:e}=this.findTarget(t);this._currentTransform||e||(this.fire("mouse:over",{e:t,...me(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 se(this.upperCanvasEl,"drag",this._onDragProgress)}Ni(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 o=this.contextTop;o.save(),o.transform(...this.viewportTransform),e&&(o.save(),e.transform(o),e.renderDragSourceEffect(t),o.restore(),r=!0),s&&(o.save(),s.transform(o),s.renderDropTargetEffect(t),o.restore(),r=!0),o.restore(),r&&(this.contextTopDirty=!0)}_onDragEnd(t){const{currentSubTargets:e}=this.findTarget(t),s=!!t.dataTransfer&&t.dataTransfer.dropEffect!==gt,r=s?this._activeObject:void 0,i={e:t,target:this._dragSource,subTargets:e,dragSource:this._dragSource,didDrop:s,dropTarget:r};xt(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",i),this._dragSource&&this._dragSource.fire("dragend",i),delete this._dragSource,this._onMouseUp(t)}_onDragProgress(t){const e={e:t,target:this._dragSource,dragSource:this._dragSource,dropTarget:this._draggedoverTarget};this.fire("drag",e),this._dragSource&&this._dragSource.fire("drag",e)}_onDragOver(t){const e="dragover",{currentContainer:s,currentSubTargets:r}=this.findTarget(t),i=this._dragSource,o={e:t,target:s,subTargets:r,dragSource:i,canDrop:!1,dropTarget:void 0};let a;this.fire(e,o),this._fireEnterLeaveEvents(t,s,o),s&&(s.canDrop(t)&&(a=s),s.fire(e,o));for(let h=0;h<r.length;h++){const l=r[h];l.canDrop(t)&&(a=l),l.fire(e,o)}this._renderDragEffects(t,i,a),this._dropTarget=a}_onDragEnter(t){const{currentContainer:e,currentSubTargets:s}=this.findTarget(t),r={e:t,target:e,subTargets:s,dragSource:this._dragSource};this.fire("dragenter",r),this._fireEnterLeaveEvents(t,e,r)}_onDragLeave(t){const{currentSubTargets:e}=this.findTarget(t),s={e:t,target:this._draggedoverTarget,subTargets:e,dragSource:this._dragSource};this.fire("dragleave",s),this._fireEnterLeaveEvents(t,void 0,s),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(t){const{currentContainer:e,currentSubTargets:s}=this.findTarget(t),r=this._basicEventHandler("drop:before",{e:t,target:e,subTargets:s,dragSource:this._dragSource,...me(this,t)});r.didDrop=!1,r.dropTarget=void 0,this._basicEventHandler("drop",r),this.fire("drop:after",r)}_onContextMenu(t){const{target:e,subTargets:s}=this.findTarget(t),r=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:s});return this.stopContextMenu&&Ni(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())}fireEventFromPointerEvent(t,e,s){let r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{};this._cacheTransformEventData(t);const{target:i,subTargets:o}=this.findTarget(t),a={e:t,target:i,subTargets:o,...me(this,t),transform:this._currentTransform,...r};this.fire(e,a),i&&i.fire(s,a);for(let h=0;h<o.length;h++)o[h]!==i&&o[h].fire(s,a);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){this._cacheTransformEventData(t);let e=!this.allowTouchScrolling;const s=this._activeObject;this.mainTouchId===void 0&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t);const{target:r}=this.findTarget(t);(this.isDrawingMode||s&&r===s)&&(e=!0),e&&t.preventDefault();const i=this.upperCanvasEl,o=this._getEventPrefix(),a=bt(i);se(a,"touchend",this._onTouchEnd,yt),e&&se(a,"touchmove",this._onMouseMove,yt),xt(i,`${o}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(t){this._cacheTransformEventData(t),this.__onMouseDown(t);const e=this.upperCanvasEl,s=this._getEventPrefix();xt(e,`${s}move`,this._onMouseMove,yt);const r=bt(e);se(r,`${s}up`,this._onMouseUp),se(r,`${s}move`,this._onMouseMove,yt),this._resetTransformEventData()}_onTouchEnd(t){if(t.touches.length>0)return;this._cacheTransformEventData(t),this.__onMouseUp(t),this._resetTransformEventData(),delete this.mainTouchId;const e=this._getEventPrefix(),s=bt(this.upperCanvasEl);xt(s,"touchend",this._onTouchEnd,yt),xt(s,"touchmove",this._onMouseMove,yt),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{se(this.upperCanvasEl,`${e}down`,this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this._cacheTransformEventData(t),this.__onMouseUp(t);const e=this.upperCanvasEl,s=this._getEventPrefix();if(this._isMainEvent(t)){const r=bt(this.upperCanvasEl);xt(r,`${s}up`,this._onMouseUp),xt(r,`${s}move`,this._onMouseMove,yt),se(e,`${s}move`,this._onMouseMove,yt)}this._resetTransformEventData()}_onMouseMove(t){this._cacheTransformEventData(t);const e=this.getActiveObject();!this.allowTouchScrolling&&(!e||!e.shouldStartDragging(t))&&t.preventDefault&&t.preventDefault(),this.__onMouseMove(t),this._resetTransformEventData()}_onResize(){this.calcOffset(),this._resetTransformEventData()}_shouldRender(t){const e=this.getActiveObject();return!!e!=!!t||e&&t&&e!==t}__onMouseUp(t){var e;this._handleEvent(t,"up:before");const s=this._currentTransform,r=this._isClick,{target:i}=this.findTarget(t),{button:o}=t;if(o)return void((this.fireMiddleClick&&o===1||this.fireRightClick&&o===2)&&this._handleEvent(t,"up"));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let a,h,l=!1;if(s&&(this._finalizeCurrentTransform(t),l=s.actionPerformed),!r){const c=i===this._activeObject;this.handleSelection(t),l||(l=this._shouldRender(i)||!c&&i===this._activeObject)}if(i){const c=i.findControl(this.getViewportPoint(t),ps(t)),{key:u,control:g}=c||{};if(h=u,i.selectable&&i!==this._activeObject&&i.activeOn==="up")this.setActiveObject(i,t),l=!0;else if(g){const d=g.getMouseUpHandler(t,i,g);d&&(a=this.getScenePoint(t),d.call(g,t,s,a.x,a.y))}i.isMoving=!1}if(s&&(s.target!==i||s.corner!==h)){const c=s.target&&s.target.controls[s.corner],u=c&&c.getMouseUpHandler(t,s.target,c);a=a||this.getScenePoint(t),u&&u.call(c,t,s,a.x,a.y)}this._setCursorFromEvent(t,i),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,i&&(i.__corner=void 0),l?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{target:r,subTargets:i}=this.findTarget(t),o={e:t,target:r,subTargets:i,...me(this,t),transform:this._currentTransform,...e==="down:before"||e==="down"?s:{}};e!=="up:before"&&e!=="up"||(o.isClick=this._isClick),this.fire(`mouse:${e}`,o),r&&r.fire(`mouse${e}`,o);for(let a=0;a<i.length;a++)i[a]!==r&&i[a].fire(`mouse${e}`,o)}_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._handleEvent(t,"down:before");let{target:e}=this.findTarget(t),s=!!e&&e===this._activeObject;const{button:r}=t;if(r)return void((this.fireMiddleClick&&r===1||this.fireRightClick&&r===2)&&this._handleEvent(t,"down",{alreadySelected:s}));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t)||this._currentTransform)return;let i=this._shouldRender(e),o=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,o=!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),ps(t));if(e===this._activeObject&&(a||!o)){this._setupCurrentTransform(t,e,s);const h=a?a.control:void 0,l=this.getScenePoint(t),c=h&&h.getMouseDownHandler(t,e,h);c&&c.call(h,t,this._currentTransform,l.x,l.y)}}i&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:s}),i&&this.requestRenderAll()}_resetTransformEventData(){this._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(t),this._scenePoint=ue(this._viewportPoint,void 0,this.viewportTransform),this._targetInfo=this.findTarget(t),this._currentTransform&&(this._targetInfo.target=this._currentTransform.target)}__onMouseMove(t){if(this._isClick=!1,this._handleEvent(t,"move:before"),this.isDrawingMode)return void this._onMouseMoveInDrawingMode(t);if(!this._isMainEvent(t))return;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{target:s}=this.findTarget(t);this._setCursorFromEvent(t,s),this._fireOverOutEvents(t,s)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move")}_fireOverOutEvents(t,e){const{_hoveredTarget:s,_hoveredTargets:r}=this,{subTargets:i}=this.findTarget(t),o=Math.max(r.length,i.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:s,fireCanvas:!0});for(let a=0;a<o;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=i}_fireEnterLeaveEvents(t,e,s){const r=this._draggedoverTarget,i=this._hoveredTargets,{subTargets:o}=this.findTarget(t),a=Math.max(i.length,o.length);this.fireSyntheticInOutEvents("drag",{...s,target:e,oldTarget:r,fireCanvas:!0});for(let h=0;h<a;h++)this.fireSyntheticInOutEvents("drag",{...s,target:o[h],oldTarget:i[h]});this._draggedoverTarget=e}fireSyntheticInOutEvents(t,e){let{target:s,oldTarget:r,fireCanvas:i,e:o,...a}=e;const{targetIn:h,targetOut:l,canvasIn:c,canvasOut:u}=uh[t],g=r!==s;if(r&&g){const d={...a,e:o,target:r,nextTarget:s,...me(this,o)};i&&this.fire(u,d),r.fire(l,d)}if(s&&g){const d={...a,e:o,target:s,previousTarget:r,...me(this,o)};i&&this.fire(c,d),s.fire(h,d)}}_transformObject(t){const e=this.getScenePoint(t),s=this._currentTransform,r=s.target,i=r.group?ue(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:o}=e,a=!!i&&i(t,e,s.x,s.y);a&&o.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=ce(this._activeObject)?this._activeObject:null,i=(!r||e.group!==r)&&e.findControl(this.getViewportPoint(t));if(i){const{control:o,coord:a}=i;this.setCursor(o.cursorStyleHandler(t,o,e,a))}else{if(e.subTargetCheck){const{subTargets:o}=this.findTarget(t);o.concat().reverse().forEach(a=>{s=a.hoverCursor||s})}this.setCursor(s)}}handleMultiSelection(t,e){const s=this._activeObject,r=ce(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();let o=[];if(e===s){const a=this.getScenePoint(t);let h=this.searchPossibleTargets(i,a);if(h.target?(e=h.target,o=h.subTargets):(h=this.searchPossibleTargets(this._objects,a),e=h.target,o=h.subTargets),!e||!e.selectable)return!1}e.group===s?(s.remove(e),this._hoveredTarget=e,this._hoveredTargets=o,s.size()===1&&this._setActiveObject(s.item(0),t)):(s.multiSelectAdd(e),this._hoveredTarget=s,this._hoveredTargets=o),this._fireSelectionEvents(i,t)}else{s.isEditing&&s.exitEditing();const i=new(O.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,o=new _(e,s),a=o.add(new _(r,i)),h=o.min(a),l=o.max(a).subtract(h),c=this.collectObjects({left:h.x,top:h.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),u=o.eq(a)?c[0]?[c[0]]:[]:c.length>1?c.filter(g=>!g.onSelect({e:t})).reverse():c;if(u.length===1)this.setActiveObject(u[0],t);else if(u.length>1){const g=O.getClass("ActiveSelection");this.setActiveObject(new g(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 Zn={x1:0,y1:0,x2:0,y2:0},gh={...Zn,r1:0,r2:0},Xe=(n,t)=>isNaN(n)&&typeof t=="number"?t:n;function Jn(n){return n&&/%$/.test(n)&&Number.isFinite(parseFloat(n))}function to(n,t){const e=typeof n=="number"?n:typeof n=="string"?parseFloat(n)/(Jn(n)?100:1):NaN;return pe(0,Xe(e,t),1)}const dh=/\s*;\s*/,fh=/\s*:\s*/;function ph(n,t){let e,s;const r=n.getAttribute("style");if(r){const o=r.split(dh);o[o.length-1]===""&&o.pop();for(let a=o.length;a--;){const[h,l]=o[a].split(fh).map(c=>c.trim());h==="stop-color"?e=l:h==="stop-opacity"&&(s=l)}}e=e||n.getAttribute("stop-color")||"rgb(0,0,0)",s=Xe(parseFloat(s||n.getAttribute("stop-opacity")||""),1);const i=new W(e);return i.setAlpha(i.getAlpha()*s*t),{offset:to(n.getAttribute("offset"),0),color:i.toRgba()}}function mh(n,t){const e=[],s=n.getElementsByTagName("stop"),r=to(t,1);for(let i=s.length;i--;)e.push(ph(s[i],r));return e}function eo(n){return n.nodeName==="linearGradient"||n.nodeName==="LINEARGRADIENT"?"linear":"radial"}function so(n){return n.getAttribute("gradientUnits")==="userSpaceOnUse"?"pixels":"percentage"}function kt(n,t){return n.getAttribute(t)}function yh(n,t){return(function(e,s){let r,{width:i,height:o,gradientUnits:a}=s;return Object.entries(e).reduce((h,l)=>{let[c,u]=l;if(u==="Infinity")r=1;else if(u==="-Infinity")r=0;else{const g=typeof u=="string";r=g?parseFloat(u):u,g&&Jn(u)&&(r*=.01,a==="pixels"&&(c!=="x1"&&c!=="x2"&&c!=="r2"||(r*=i),c!=="y1"&&c!=="y2"||(r*=o)))}return h[c]=r,h},{})})(eo(n)==="linear"?(function(e){return{x1:kt(e,"x1")||0,y1:kt(e,"y1")||0,x2:kt(e,"x2")||"100%",y2:kt(e,"y2")||0}})(n):(function(e){return{x1:kt(e,"fx")||kt(e,"cx")||"50%",y1:kt(e,"fy")||kt(e,"cy")||"50%",r1:0,x2:kt(e,"cx")||"50%",y2:kt(e,"cy")||"50%",r2:kt(e,"r")||"50%"}})(n),{...t,gradientUnits:so(n)})}class js{constructor(t){const{type:e="linear",gradientUnits:s="pixels",coords:r={},colorStops:i=[],offsetX:o=0,offsetY:a=0,gradientTransform:h,id:l}=t||{};Object.assign(this,{type:e,gradientUnits:s,coords:{...e==="radial"?gh:Zn,...r},colorStops:i,offsetX:o,offsetY:a,gradientTransform:h,id:l?`${l}_${te()}`:te()})}addColorStop(t){for(const e in t)this.colorStops.push({offset:parseFloat(e),color:t[e]});return this}toObject(t){return{...le(this,t),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map(e=>({...e})),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0}}toSVG(t){let{additionalTransform:e}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};const s=[],r=this.gradientTransform?this.gradientTransform.concat():nt.concat(),i=this.gradientUnits==="pixels"?"userSpaceOnUse":"objectBoundingBox",o=this.colorStops.map(u=>({...u})).sort((u,g)=>u.offset-g.offset);let a=-this.offsetX,h=-this.offsetY;var l;i==="objectBoundingBox"?(a/=t.width,h/=t.height):(a+=t.width/2,h+=t.height/2),(l=t)&&typeof l._renderPathCommands=="function"&&this.gradientUnits!=="percentage"&&(a-=t.pathOffset.x,h-=t.pathOffset.y),r[4]-=a,r[5]-=h;const c=[`id="SVGID_${this.id}"`,`gradientUnits="${i}"`,`gradientTransform="${e?e+" ":""}${Ae(r)}"`,""].join(" ");if(this.type==="linear"){const{x1:u,y1:g,x2:d,y2:f}=this.coords;s.push("<linearGradient ",c,' x1="',u,'" y1="',g,'" x2="',d,'" y2="',f,`">
42
- `)}else if(this.type==="radial"){const{x1:u,y1:g,x2:d,y2:f,r1:p,r2:m}=this.coords,v=p>m;s.push("<radialGradient ",c,' cx="',v?u:d,'" cy="',v?g:f,'" r="',v?p:m,'" fx="',v?d:u,'" fy="',v?f:g,`">
43
- `),v&&(o.reverse(),o.forEach(S=>{S.offset=1-S.offset}));const x=Math.min(p,m);if(x>0){const S=x/Math.max(p,m);o.forEach(w=>{w.offset+=S*(1-w.offset)})}}return o.forEach(u=>{let{color:g,offset:d}=u;s.push(`<stop offset="${100*d}%" style="stop-color:${g};"/>
44
- `)}),s.push(this.type==="linear"?"</linearGradient>":"</radialGradient>",`
45
- `),s.join("")}toLive(t){const{x1:e,y1:s,x2:r,y2:i,r1:o,r2:a}=this.coords,h=this.type==="linear"?t.createLinearGradient(e,s,r,i):t.createRadialGradient(e,s,o,r,i,a);return this.colorStops.forEach(l=>{let{color:c,offset:u}=l;h.addColorStop(u,c)}),h}static async fromObject(t){const{colorStops:e,gradientTransform:s}=t;return new this({...t,colorStops:e?e.map(r=>({...r})):void 0,gradientTransform:s?[...s]:void 0})}static fromElement(t,e,s){const r=so(t),i=e._findCenterFromElement();return new this({id:t.getAttribute("id")||void 0,type:eo(t),coords:yh(t,{width:s.viewBoxWidth||s.width,height:s.viewBoxHeight||s.height}),colorStops:mh(t,s.opacity),gradientUnits:r,gradientTransform:Ur(t.getAttribute("gradientTransform")||""),...r==="pixels"?{offsetX:e.width/2-i.x,offsetY:e.height/2-i.y}:{offsetX:0,offsetY:0}})}}y(js,"type","Gradient"),O.setClass(js,"gradient"),O.setClass(js,"linear"),O.setClass(js,"radial");class si{get type(){return"pattern"}set type(t){Qt("warn","Setting type has no effect",t)}constructor(t){y(this,"repeat","repeat"),y(this,"offsetX",0),y(this,"offsetY",0),y(this,"crossOrigin",""),this.id=te(),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{...le(this,t),type:"pattern",source:this.sourceToString(),repeat:e,crossOrigin:s,offsetX:X(this.offsetX,B.NUM_FRACTION_DIGITS),offsetY:X(this.offsetY,B.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null}}toSVG(t){let{width:e,height:s}=t;const{source:r,repeat:i,id:o}=this,a=Xe(this.offsetX/e,0),h=Xe(this.offsetY/s,0);return[`<pattern id="SVGID_${o}" x="${a}" y="${h}" width="${i==="repeat-y"||i==="no-repeat"?1+Math.abs(a||0):Xe(r.width/e,0)}" height="${i==="repeat-x"||i==="no-repeat"?1+Math.abs(h||0):Xe(r.height/s,0)}">`,`<image x="0" y="0" width="${r.width}" height="${r.height}" xlink:href="${this.sourceToString()}"></image>`,"</pattern>",""].join(`
46
- `)}static async fromObject(t,e){let{type:s,source:r,patternTransform:i,...o}=t;const a=await ze(r,{...e,crossOrigin:o.crossOrigin});return new this({...o,patternTransform:i&&i.slice(0),source:a})}}y(si,"type","Pattern"),O.setClass(si),O.setClass(si,"pattern");class ye extends st{constructor(t){let{path:e,left:s,top:r,...i}=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),Object.assign(this,ye.ownDefaults),this.setOptions(i),this._setPath(t||[],!0),typeof s=="number"&&this.set($,s),typeof r=="number"&&this.set(ut,r)}_setPath(t,e){this.path=Wn(Array.isArray(t)?t:qn(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new _(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 (${this.complexity()}): { "top": ${this.top}, "left": ${this.left} }>`}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return{...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(){return["<path ","COMMON_PARTS",`d="${Kn(this.path,B.NUM_FRACTION_DIGITS)}" stroke-linecap="round" />
47
- `]}_getOffsetTransform(){const t=B.NUM_FRACTION_DIGITS;return` translate(${X(-this.pathOffset.x,t)}, ${X(-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,A,A)}_calcBoundsFromPath(){const t=[];let e=0,s=0,r=0,i=0;for(const o of this.path)switch(o[0]){case"L":r=o[1],i=o[2],t.push({x:e,y:s},{x:r,y:i});break;case"M":r=o[1],i=o[2],e=r,s=i;break;case"C":t.push(...Zr(r,i,o[1],o[2],o[3],o[4],o[5],o[6])),r=o[5],i=o[6];break;case"Q":t.push(...Zr(r,i,o[1],o[2],o[1],o[2],o[3],o[4])),r=o[3],i=o[4];break;case"Z":r=e,i=s}return Lt(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return{...t,pathOffset:new _(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{d:r,...i}=Nt(t,this.ATTRIBUTE_NAMES,s);return new this(r,{...i,...e,left:void 0,top:void 0})}}y(ye,"type","Path"),y(ye,"cacheProperties",[...Yt,"path","fillRule"]),y(ye,"ATTRIBUTE_NAMES",[...ee,"d"]),O.setClass(ye),O.setSVGClass(ye);const ro=["radius","startAngle","endAngle","counterClockwise"];class zt extends st{static getDefaults(){return{...super.getDefaults(),...zt.ownDefaults}}constructor(t){super(),Object.assign(this,zt.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,U(this.startAngle),U(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(ot)}getRadiusY(){return this.get("radius")*this.get(dt)}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([...ro,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(t===0)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',`${this.radius}`,`" />
48
- `];{const{radius:e}=this,s=U(this.startAngle),r=U(this.endAngle),i=St(s)*e,o=Ct(s)*e,a=St(r)*e,h=Ct(r)*e;return[`<path d="M ${i} ${o} A ${e} ${e} 0 ${t>180?1:0} ${this.counterClockwise?0:1} ${a} ${h}" `,"COMMON_PARTS",` />
49
- `]}}static async fromElement(t,e,s){const{left:r=0,top:i=0,radius:o=0,...a}=Nt(t,this.ATTRIBUTE_NAMES,s);return new this({...a,radius:o,left:r-o,top:i-o})}static fromObject(t){return super._fromObject(t)}}y(zt,"type","Circle"),y(zt,"cacheProperties",[...Yt,...ro]),y(zt,"ownDefaults",{radius:0,startAngle:0,endAngle:360,counterClockwise:!1}),y(zt,"ATTRIBUTE_NAMES",["cx","cy","r",...ee]),O.setClass(zt),O.setSVGClass(zt);const ri=["x1","x2","y1","y2"];class ve extends st{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,ve.ownDefaults),this.setOptions(i),this.x1=t,this.x2=s,this.y1=e,this.y2=r,this._setWidthHeight();const{left:o,top:a}=i;typeof o=="number"&&this.set($,o),typeof a=="number"&&this.set(ut,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:o,width:a,height:h}=Lt([{x:t,y:e},{x:s,y:r}]),l=new _(i+a/2,o+h/2);this.setPositionByOrigin(l,A,A)}_set(t,e){return super._set(t,e),ri.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;vt(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 _((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return{...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:o}=this,a=t<=e?-1:1,h=s<=r?-1:1;return{x1:a*i/2,x2:a*-i/2,y1:h*o/2,y2:h*-o/2}}_toSVG(){const{x1:t,x2:e,y1:s,y2:r}=this.calcLinePoints();return["<line ","COMMON_PARTS",`x1="${t}" y1="${s}" x2="${e}" y2="${r}" />
50
- `]}static async fromElement(t,e,s){const{x1:r=0,y1:i=0,x2:o=0,y2:a=0,...h}=Nt(t,this.ATTRIBUTE_NAMES,s);return new this([r,i,o,a],h)}static fromObject(t){let{x1:e,y1:s,x2:r,y2:i,...o}=t;return this._fromObject({...o,points:[e,s,r,i]},{extraParam:"points"})}}y(ve,"type","Line"),y(ve,"cacheProperties",[...Yt,...ri]),y(ve,"ATTRIBUTE_NAMES",ee.concat(ri)),O.setClass(ve),O.setSVGClass(ve);class xe extends st{static getDefaults(){return{...super.getDefaults(),...xe.ownDefaults}}constructor(t){super(),Object.assign(this,xe.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="',`${-t} ${e},0 ${-e},${t} ${e}`,'" />']}}y(xe,"type","Triangle"),y(xe,"ownDefaults",{width:100,height:100}),O.setClass(xe),O.setSVGClass(xe);const io=["rx","ry"];class Ut extends st{static getDefaults(){return{...super.getDefaults(),...Ut.ownDefaults}}constructor(t){super(),Object.assign(this,Ut.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(ot)}getRy(){return this.get("ry")*this.get(dt)}toObject(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[];return super.toObject([...io,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",`cx="0" cy="0" rx="${this.rx}" ry="${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,wt,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,s){const r=Nt(t,this.ATTRIBUTE_NAMES,s);return r.left=(r.left||0)-r.rx,r.top=(r.top||0)-r.ry,new this(r)}}y(Ut,"type","Ellipse"),y(Ut,"cacheProperties",[...Yt,...io]),y(Ut,"ownDefaults",{rx:0,ry:0}),y(Ut,"ATTRIBUTE_NAMES",[...ee,"cx","cy","rx","ry"]),O.setClass(Ut),O.setSVGClass(Ut);const no={exactBoundingBox:!1};class Dt extends st{static getDefaults(){return{...super.getDefaults(),...Dt.ownDefaults}}constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),y(this,"strokeDiff",void 0),Object.assign(this,Dt.ownDefaults),this.setOptions(e),this.points=t;const{left:s,top:r}=e;this.initialized=!0,this.setBoundingBox(!0),typeof s=="number"&&this.set($,s),typeof r=="number"&&this.set(ut,r)}isOpen(){return!0}_projectStrokeOnPoints(t){return En(this.points,t,this.isOpen())}_calcDimensions(t){t={scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,strokeLineCap:this.strokeLineCap,strokeLineJoin:this.strokeLineJoin,strokeMiterLimit:this.strokeMiterLimit,strokeUniform:this.strokeUniform,strokeWidth:this.strokeWidth,...t||{}};const e=this.exactBoundingBox?this._projectStrokeOnPoints(t).map(l=>l.projectedPoint):this.points;if(e.length===0)return{left:0,top:0,width:0,height:0,pathOffset:new _,strokeOffset:new _,strokeDiff:new _};const s=Lt(e),r=Ge({...t,scaleX:1,scaleY:1}),i=Lt(this.points.map(l=>et(l,r,!0))),o=new _(this.scaleX,this.scaleY);let a=s.left+s.width/2,h=s.top+s.height/2;return this.exactBoundingBox&&(a-=h*Math.tan(U(this.skewX)),h-=a*Math.tan(U(this.skewY))),{...s,pathOffset:new _(a,h),strokeOffset:new _(i.left,i.top).subtract(new _(s.left,s.top)).multiply(o),strokeDiff:new _(s.width,s.height).subtract(new _(i.width,i.height)).multiply(o)}}_findCenterFromElement(){const t=Lt(this.points);return new _(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:o,strokeOffset:a,strokeDiff:h}=this._calcDimensions();this.set({width:r,height:i,pathOffset:o,strokeOffset:a,strokeDiff:h}),t&&this.setPositionByOrigin(new _(e+r/2,s+i/2),A,A)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new _(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(this.exactBoundingBox){let o;if(Object.keys(t).some(a=>this.strokeUniform||this.constructor.layoutProperties.includes(a))){var e,s;const{width:a,height:h}=this._calcDimensions(t);o=new _((e=t.width)!==null&&e!==void 0?e:a,(s=t.height)!==null&&s!==void 0?s:h)}else{var r,i;o=new _((r=t.width)!==null&&r!==void 0?r:this.width,(i=t.height)!==null&&i!==void 0?i:this.height)}return o.multiply(new _(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===ot||t===dt)&&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{...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=B.NUM_FRACTION_DIGITS;for(let i=0,o=this.points.length;i<o;i++)t.push(X(this.points[i].x-e,r),",",X(this.points[i].y-s,r)," ");return[`<${this.constructor.type.toLowerCase()} `,"COMMON_PARTS",`points="${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 o=this.points[i];t.lineTo(o.x-s,o.y-r)}!this.isOpen()&&t.closePath(),this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,s){const r=(function(h){if(!h)return[];const l=h.replace(/,/g," ").trim().split(/\s+/),c=[];for(let u=0;u<l.length;u+=2)c.push({x:parseFloat(l[u]),y:parseFloat(l[u+1])});return c})(t.getAttribute("points")),{left:i,top:o,...a}=Nt(t,this.ATTRIBUTE_NAMES,s);return new this(r,{...a,...e})}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}y(Dt,"ownDefaults",no),y(Dt,"type","Polyline"),y(Dt,"layoutProperties",[Oe,Me,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),y(Dt,"cacheProperties",[...Yt,"points"]),y(Dt,"ATTRIBUTE_NAMES",[...ee]),O.setClass(Dt),O.setSVGClass(Dt);class Is extends Dt{isOpen(){return!1}}y(Is,"ownDefaults",no),y(Is,"type","Polygon"),O.setClass(Is),O.setSVGClass(Is);class oo extends st{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,o=!0,a=0;for(const h in e){s=0;for(const l in e[h]){const c=e[h][l]||{};i++,c[t]!==void 0?(r?c[t]!==r&&(o=!1):r=c[t],c[t]===this[t]&&delete c[t]):o=!1,Object.keys(c).length!==0?s++:delete e[h][l]}s===0&&delete e[h]}for(let h=0;h<this._textLines.length;h++)a+=this._textLines[h].length;o&&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=Mr({...this._getStyleDeclaration(s,r),...e},o=>o!==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{...le(this,this.constructor._styleProperties),...this._getStyleDeclaration(t,e)}}_setStyleDeclaration(t,e,s){this.styles[t][e]=s}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}y(oo,"_styleProperties",Jo);const vh=/ +/g,xh=/"/g;function ii(n,t,e,s,r){return` ${(function(i,o){let{left:a,top:h,width:l,height:c}=o,u=arguments.length>2&&arguments[2]!==void 0?arguments[2]:B.NUM_FRACTION_DIGITS;const g=Qe(J,i,!1),[d,f,p,m]=[a,h,l,c].map(v=>X(v,u));return`<rect ${g} x="${d}" y="${f}" width="${p}" height="${m}"></rect>`})(n,{left:t,top:e,width:s,height:r})}
53
- `}let ni;class lt extends oo{static getDefaults(){return{...super.getDefaults(),...lt.ownDefaults}}constructor(t,e){super(),y(this,"__charBounds",[]),Object.assign(this,lt.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=Jr(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(jt)&&this.enlargeSpaces()}enlargeSpaces(){let t,e,s,r,i,o,a;for(let h=0,l=this._textLines.length;h<l;h++)if((this.textAlign===jt||h!==l-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 c=0;c<=i.length;c++)o=this.__charBounds[h][c],this._reSpaceAndTab.test(i[c])?(o.width+=t,o.kernedWidth+=t,o.left+=r,r+=t):o.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 (${this.complexity()}): { "text": "${this.text}", "fontFamily": "${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===ft?(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 A:t.textBaseline="middle";break;case"ascender":t.textBaseline=ut;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,o){this._renderChars(t,e,s,r,i,o)}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,s=this._getLeftOffset();let r=this._getTopOffset();for(let i=0,o=this._textLines.length;i<o;i++){const a=this.getHeightOfLine(i);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",i)){r+=a;continue}const h=this._textLines[i].length,l=this._getLineLeftOffset(i);let c,u,g=0,d=0,f=this.getValueOfPropertyAt(i,0,"textBackgroundColor");const p=this.getHeightOfLineImpl(i);for(let m=0;m<h;m++){const v=this.__charBounds[i][m];u=this.getValueOfPropertyAt(i,m,"textBackgroundColor"),this.path?(t.save(),t.translate(v.renderLeft,v.renderTop),t.rotate(v.angle),t.fillStyle=u,u&&t.fillRect(-v.width/2,-p*(1-this._fontSizeFraction),v.width,p),t.restore()):u!==f?(c=s+l+d,this.direction===$t&&(c=this.width-c-g),t.fillStyle=f,f&&t.fillRect(c,r,g,p),d=v.left,g=v.width,f=u):g+=v.kernedWidth}u&&!this.path&&(c=s+l+d,this.direction===$t&&(c=this.width-c-g),t.fillStyle=u,t.fillRect(c,r,g,p)),r+=a}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,s,r){const i=He.getFontCache(e),o=this._getFontDeclaration(e),a=s?s+t:t,h=s&&o===this._getFontDeclaration(r),l=e.fontSize/this.CACHE_FONT_SIZE;let c,u,g,d;if(s&&i.has(s)&&(g=i.get(s)),i.has(t)&&(d=c=i.get(t)),h&&i.has(a)&&(u=i.get(a),d=u-g),c===void 0||g===void 0||u===void 0){const f=(function(){return ni||(ni=pt({width:0,height:0}).getContext("2d")),ni})();this._setTextStyles(f,e,!0),c===void 0&&(d=c=f.measureText(t).width,i.set(t,c)),g===void 0&&h&&s&&(g=f.measureText(s).width,i.set(s,g)),h&&u===void 0&&(u=f.measureText(a).width,i.set(a,u),d=u-g)}return{width:c*l,kernedWidth:d*l}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return this.charSpacing!==0&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){let e,s,r=0;const i=this.pathSide===q,o=this.path,a=this._textLines[t],h=a.length,l=new Array(h);this.__charBounds[t]=l;for(let c=0;c<h;c++){const u=a[c];s=this._getGraphemeBox(u,t,c,e),l[c]=s,r+=s.kernedWidth,e=u}if(l[h]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},o&&o.segmentsInfo){let c=0;const u=o.segmentsInfo[o.segmentsInfo.length-1].length;switch(this.textAlign){case $:c=i?u-r:0;break;case A:c=(u-r)/2;break;case q:c=i?0:u-r}c+=this.pathStartOffset*(i?-1:1);for(let g=i?h-1:0;i?g>=0:g<h;i?g--:g++)s=l[g],c>u?c%=u:c<0&&(c+=u),this._setGraphemeOnPath(c,s),c+=s.kernedWidth}return{width:r,numOfSpaces:0}}_setGraphemeOnPath(t,e){const s=t+e.kernedWidth/2,r=this.path,i=zn(r.path,s,r.segmentsInfo);e.renderLeft=i.x-r.pathOffset.x,e.renderTop=i.y-r.pathOffset.y,e.angle=i.angle+(this.pathSide===q?Math.PI:0)}_getGraphemeBox(t,e,s,r,i){const o=this.getCompleteStyleDeclaration(e,s),a=r?this.getCompleteStyleDeclaration(e,s-1):{},h=this._measureChar(t,o,r,a);let l,c=h.kernedWidth,u=h.width;this.charSpacing!==0&&(l=this._getWidthOfCharSpacing(),u+=l,c+=l);const g={width:u,left:0,height:o.fontSize,kernedWidth:c,deltaY:o.deltaY};if(s>0&&!i){const d=this.__charBounds[e][s-1];g.left=d.left+d.width+h.kernedWidth-h.width}return g}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===oe?-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 o=0,a=this._textLines.length;o<a;o++)this._renderTextLine(e,t,this._textLines[o],r+this._getLineLeftOffset(o),i+s+this.getHeightOfLineImpl(o),o),s+=this.getHeightOfLine(o);t.restore()}_renderTextFill(t){(this.fill||this.styleHas(J))&&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,o){const a=this.textAlign.includes(jt),h=this.path,l=!a&&this.charSpacing===0&&this.isEmptyStyles(o)&&!h,c=this.direction===oe,u=this.direction===oe?1:-1,g=e.direction;let d,f,p,m,v,x="",S=0;if(e.save(),g!==this.direction&&(e.canvas.setAttribute("dir",c?oe:$t),e.direction=c?oe:$t,e.textAlign=c?$:q),i-=this.getHeightOfLineImpl(o)*this._fontSizeFraction,l)return this._renderChar(t,e,o,0,s.join(""),r,i),void e.restore();for(let w=0,C=s.length-1;w<=C;w++)m=w===C||this.charSpacing||h,x+=s[w],p=this.__charBounds[o][w],S===0?(r+=u*(p.kernedWidth-p.width),S+=p.width):S+=p.kernedWidth,a&&!m&&this._reSpaceAndTab.test(s[w])&&(m=!0),m||(d=d||this.getCompleteStyleDeclaration(o,w),f=this.getCompleteStyleDeclaration(o,w+1),m=Ds(d,f,!1)),m&&(h?(e.save(),e.translate(p.renderLeft,p.renderTop),e.rotate(p.angle),this._renderChar(t,e,o,w,x,-S/2,0),e.restore()):(v=r,this._renderChar(t,e,o,w,x,v,i)),x="",d=f,r+=u*S,S=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,s=this.height+this.strokeWidth,r=pt({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 vt(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,o,a){const h=this._getStyleDeclaration(s,r),l=this.getCompleteStyleDeclaration(s,r),c=t==="fillText"&&l.fill,u=t==="strokeText"&&l.stroke&&l.strokeWidth;if(u||c){if(e.save(),e.font=this._getFontDeclaration(l),h.textBackgroundColor&&this._removeShadow(e),h.deltaY&&(a+=h.deltaY),c){const g=this._setFillStyles(e,l);e.fillText(i,o-g.offsetX,a-g.offsetY)}if(u){const g=this._setStrokeStyles(e,l);e.strokeText(i,o-g.offsetX,a-g.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"),o=this.getValueOfPropertyAt(r.lineIndex,r.charIndex,"deltaY"),a={fontSize:i*s.size,deltaY:o+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,o=this.isEndOfWrapping(t);let a=0;return r===jt||r===Je&&!o||r===Ze&&!o||r===bs&&!o?0:(r===A&&(a=s/2),r===q&&(a=s),r===Je&&(a=s/2),r===Ze&&(a=s),i===$t&&(r===q||r===Ze?a=0:r===$||r===bs?a=-s:r!==A&&r!==Je||(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,o=this._getWidthOfCharSpacing(),a=e==="linethrough"?.5:e==="overline"?1:0,h=this.offsets[e];for(let l=0,c=this._textLines.length;l<c;l++){const u=this.getHeightOfLine(l);if(!this[e]&&!this.styleHas(e,l)){s+=u;continue}const g=this._textLines[l],d=u/this.lineHeight,f=this._getLineLeftOffset(l);let p=0,m=0,v=this.getValueOfPropertyAt(l,0,e),x=this.getValueOfPropertyAt(l,0,J),S=this.getValueOfPropertyAt(l,0,de),w=v,C=x,b=S;const M=s+d*(1-this._fontSizeFraction);let T=this.getHeightOfChar(l,0),k=this.getValueOfPropertyAt(l,0,"deltaY");for(let D=0,L=g.length;D<L;D++){const I=this.__charBounds[l][D];w=this.getValueOfPropertyAt(l,D,e),C=this.getValueOfPropertyAt(l,D,J),b=this.getValueOfPropertyAt(l,D,de);const Q=this.getHeightOfChar(l,D),Y=this.getValueOfPropertyAt(l,D,"deltaY");if(i&&w&&C){const H=this.fontSize*b/1e3;t.save(),t.fillStyle=x,t.translate(I.renderLeft,I.renderTop),t.rotate(I.angle),t.fillRect(-I.kernedWidth/2,h*Q+Y-a*H,I.kernedWidth,H),t.restore()}else if((w!==v||C!==x||Q!==T||b!==S||Y!==k)&&m>0){const H=this.fontSize*S/1e3;let R=r+f+p;this.direction===$t&&(R=this.width-R-m),v&&x&&S&&(t.fillStyle=x,t.fillRect(R,M+h*T+k-a*H,m,H)),p=I.left,m=I.width,v=w,S=b,x=C,T=Q,k=Y}else m+=I.kernedWidth}let P=r+f+p;this.direction===$t&&(P=this.width-P-m),t.fillStyle=C;const F=this.fontSize*b/1e3;w&&C&&b&&t.fillRect(P,M+h*T+k-a*F,m-o,F),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 o=t.includes("'")||t.includes('"')||t.includes(",")||lt.genericFonts.includes(t.toLowerCase())?t:`"${t}"`;return[e,s,`${i?this.CACHE_FONT_SIZE:r}px`,o].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return ks(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),s=new Array(e.length),r=[`
54
- `];let i=[];for(let o=0;o<e.length;o++)s[o]=this.graphemeSplit(e[o]),i=i.concat(s[o],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{...super.toObject([...cn,...t]),styles:An(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 o in t)o==="path"&&this.setPathInfo(),r=r||s.includes(o),i=i||o==="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=Nt(t,lt.ATTRIBUTE_NAMES,s),{textAnchor:i=$,textDecoration:o="",dx:a=0,dy:h=0,top:l=0,left:c=0,fontSize:u=mr,strokeWidth:g=1,...d}={...e,...r},f=new this(ws(t.textContent||"").trim(),{left:c+a,top:l+h,underline:o.includes("underline"),overline:o.includes("overline"),linethrough:o.includes("line-through"),strokeWidth:0,fontSize:u,...d}),p=f.getScaledHeight()/f.height,m=((f.height+f.strokeWidth)*f.lineHeight-f.height)*p,v=f.getScaledHeight()+m;let x=0;return i===A&&(x=f.getScaledWidth()/2),i===q&&(x=f.getScaledWidth()),f.set({left:f.left-x,top:f.top-(v-f.fontSize*(.07+f._fontSizeFraction))/f.lineHeight,strokeWidth:g}),f}static fromObject(t){return this._fromObject({...t,styles:Fn(t.styles||{},t.text)},{extraParam:"text"})}}y(lt,"textLayoutProperties",ln),y(lt,"cacheProperties",[...Yt,...cn]),y(lt,"ownDefaults",ta),y(lt,"type","Text"),y(lt,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),y(lt,"ATTRIBUTE_NAMES",ee.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),On(lt,[class extends on{_toSVG(){const n=this._getSVGLeftTopOffsets(),t=this._getSVGTextAndBg(n.textTop,n.textLeft);return this._wrapSVGTextAndBg(t)}toSVG(n){const t=this._createBaseSVGMarkup(this._toSVG(),{reviver:n,noStyle:!0,withShadow:!0}),e=this.path;return e?t+e._createBaseSVGMarkup(e._toSVG(),{reviver:n,withShadow:!0,additionalTransform:Ae(this.calcOwnMatrix())}):t}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(n){let{textBgRects:t,textSpans:e}=n;const s=this.getSvgTextDecoration(this);return[t.join(""),' <text xml:space="preserve" ',`font-family="${this.fontFamily.replace(xh,"'")}" `,`font-size="${this.fontSize}" `,this.fontStyle?`font-style="${this.fontStyle}" `:"",this.fontWeight?`font-weight="${this.fontWeight}" `:"",s?`text-decoration="${s}" `:"",this.direction==="rtl"?`direction="${this.direction}" `:"",'style="',this.getSvgStyles(!0),'"',this.addPaintOrder()," >",e.join(""),`</text>
55
- `]}_getSVGTextAndBg(n,t){const e=[],s=[];let r,i=n;this.backgroundColor&&s.push(...ii(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let o=0,a=this._textLines.length;o<a;o++)r=this._getLineLeftOffset(o),this.direction==="rtl"&&(r+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",o))&&this._setSVGTextLineBg(s,o,t+r,i),this._setSVGTextLineText(e,o,t+r,i),i+=this.getHeightOfLine(o);return{textSpans:e,textBgRects:s}}_createTextCharSpan(n,t,e,s,r){const i=B.NUM_FRACTION_DIGITS,o=this.getSvgSpanStyles(t,n!==n.trim()||!!n.match(vh)),a=o?`style="${o}"`:"",h=t.deltaY,l=h?` dy="${X(h,i)}" `:"",{angle:c,renderLeft:u,renderTop:g,width:d}=r;let f="";if(u!==void 0){const p=d/2;c&&(f=` rotate="${X(Xt(c),i)}"`);const m=he({angle:Xt(c)});m[4]=u,m[5]=g;const v=new _(-p,0).transform(m);e=v.x,s=v.y}return`<tspan x="${X(e,i)}" y="${X(s,i)}" ${l}${f}${a}>${Pn(n)}</tspan>`}_setSVGTextLineText(n,t,e,s){const r=this.getHeightOfLine(t),i=this.textAlign.includes(jt),o=this._textLines[t];let a,h,l,c,u,g="",d=0;s+=r*(1-this._fontSizeFraction)/this.lineHeight;for(let f=0,p=o.length-1;f<=p;f++)u=f===p||this.charSpacing||this.path,g+=o[f],l=this.__charBounds[t][f],d===0?(e+=l.kernedWidth-l.width,d+=l.width):d+=l.kernedWidth,i&&!u&&this._reSpaceAndTab.test(o[f])&&(u=!0),u||(a=a||this.getCompleteStyleDeclaration(t,f),h=this.getCompleteStyleDeclaration(t,f+1),u=Ds(a,h,!0)),u&&(c=this._getStyleDeclaration(t,f),n.push(this._createTextCharSpan(g,c,e,s,l)),g="",a=h,this.direction==="rtl"?e-=d:e+=d,d=0)}_setSVGTextLineBg(n,t,e,s){const r=this._textLines[t],i=this.getHeightOfLine(t)/this.lineHeight;let o,a=0,h=0,l=this.getValueOfPropertyAt(t,0,"textBackgroundColor");for(let c=0;c<r.length;c++){const{left:u,width:g,kernedWidth:d}=this.__charBounds[t][c];o=this.getValueOfPropertyAt(t,c,"textBackgroundColor"),o!==l?(l&&n.push(...ii(l,e+h,s,a,i)),h=u,a=g,l=o):a+=d}o&&n.push(...ii(l,e+h,s,a,i))}getSvgStyles(n){return`${super.getSvgStyles(n)} text-decoration-thickness: ${X(this.textDecorationThickness*this.getObjectScaling().y/10,B.NUM_FRACTION_DIGITS)}%; white-space: pre;`}getSvgSpanStyles(n,t){const{fontFamily:e,strokeWidth:s,stroke:r,fill:i,fontSize:o,fontStyle:a,fontWeight:h,textDecorationThickness:l,linethrough:c,overline:u,underline:g}=n,d=this.getSvgTextDecoration({underline:g!=null?g:this.underline,overline:u!=null?u:this.overline,linethrough:c!=null?c:this.linethrough}),f=l||this.textDecorationThickness;return[r?Qe(ft,r):"",s?`stroke-width: ${s}; `:"",e?`font-family: ${e.includes("'")||e.includes('"')?e:`'${e}'`}; `:"",o?`font-size: ${o}px; `:"",a?`font-style: ${a}; `:"",h?`font-weight: ${h}; `:"",d?`text-decoration: ${d}; text-decoration-thickness: ${X(f*this.getObjectScaling().y/10,B.NUM_FRACTION_DIGITS)}%; `:"",i?Qe(J,i):"",t?"white-space: pre; ":""].join("")}getSvgTextDecoration(n){return["overline","underline","line-through"].filter(t=>n[t.replace("-","")]).join(" ")}}]),O.setClass(lt),O.setSVGClass(lt);class _h{constructor(t){y(this,"target",void 0),y(this,"__mouseDownInPlace",!1),y(this,"__dragStartFired",!1),y(this,"__isDraggingOver",!1),y(this,"__dragStartSelection",void 0),y(this,"__dragImageDisposer",void 0),y(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 o=this.target,a=o.canvas,h=new _(o.flipX?-1:1,o.flipY?-1:1),l=o._getCursorBoundaries(r),c=new _(l.left+l.leftOffset,l.top+l.topOffset).multiply(h).transform(o.calcTransformMatrix()),u=a.getScenePoint(t).subtract(c),g=o.getCanvasRetinaScaling(),d=o.getBoundingRect(),f=c.subtract(new _(d.left,d.top)),p=a.viewportTransform,m=f.add(u).transform(p,!0),v=o.backgroundColor,x=Gr(o.styles);o.backgroundColor="";const S={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};o.setSelectionStyles(S,0,r),o.setSelectionStyles(S,i,o.text.length),o.dirty=!0;const w=o.toCanvasElement({enableRetinaScaling:a.enableRetinaScaling,viewportTransform:!0});o.backgroundColor=v,o.styles=x,o.dirty=!0,ti(w,{position:"fixed",left:-w.width+"px",border:gt,width:w.width/g+"px",height:w.height/g+"px"}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{w.remove()},bt(t.target||this.target.hiddenTextarea).body.appendChild(w),(s=t.dataTransfer)===null||s===void 0||s.setDragImage(w,m.x,m.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(""),o={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,o)}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 o=this.target,a=o.canvas;let h=o.getSelectionStartFromPointer(s);const{styles:l}=s.dataTransfer.types.includes("application/fabric")?JSON.parse(s.dataTransfer.getData("application/fabric")):{},c=i[Math.max(0,i.length-1)],u=0;if(this.__dragStartSelection){const g=this.__dragStartSelection.selectionStart,d=this.__dragStartSelection.selectionEnd;h>g&&h<=d?h=g:h>d&&(h-=d-g),o.removeChars(g,d),delete this.__dragStartSelection}o._reNewline.test(c)&&(o._reNewline.test(o._text[h])||h===o._text.length)&&(i=i.trimEnd()),t.didDrop=!0,t.dropTarget=o,o.insertChars(i,l,h),a.setActiveObject(o),o.enterEditing(s),o.selectionStart=Math.min(h+u,o._text.length),o.selectionEnd=Math.min(o.selectionStart+i.length,o._text.length),o.hiddenTextarea.value=o.text,o._updateTextarea(),o.hiddenTextarea.focus(),o.fire(hs,{index:h+u,action:"drop"}),a.fire("text:changed",{target:o}),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:o,selectionEnd:a}=this.__dragStartSelection,h=((s=e.dataTransfer)===null||s===void 0?void 0:s.dropEffect)||gt;h===gt?(r.selectionStart=o,r.selectionEnd=a,r._updateTextarea(),r.hiddenTextarea.focus()):(r.clearContextTop(),h==="move"&&(r.removeChars(o,a),r.selectionStart=r.selectionEnd=o,r.hiddenTextarea&&(r.hiddenTextarea.value=r.text),r._updateTextarea(),r.fire(hs,{index:o,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 ao=/[ \n\.,;!\?\-]/;class wh extends lt{constructor(){super(...arguments),y(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 Hr({startValue:this._currentCursorOpacity,endValue:e,duration:s,delay:r,onComplete:i,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:o=>{this._currentCursorOpacity=o,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||!vr.test(s[t-1]))?t-1:t,i=s[r];for(;r>0&&r<s.length&&!ao.test(i);)r+=e,i=s[r];return e===-1&&ao.test(i)&&r++,r}selectWord(t){t=t!=null?t:this.selectionStart;const e=this.searchWordBoundary(t,-1),s=Math.max(e,this.searchWordBoundary(t,1));this.selectionStart=e,this.selectionEnd=s,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){t=t!=null?t:this.selectionStart;const e=this.findLineBoundaryLeft(t),s=this.findLineBoundaryRight(t);this.selectionStart=e,this.selectionEnd=s,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;bt(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 o=s.slice(t,e);return{selectionStart:i,selectionEnd:i+this.graphemeSplit(o).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(){const{hiddenTextarea:t,direction:e,textAlign:s,inCompositionMode:r}=this;if(!t)return;const i=s!==jt?s.replace("justify-",""):e===oe?$:q,o=this.getPositionByOrigin(i,"top");this.cursorOffsetCache={},this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setPositionByOrigin(o,i,"top"),this.setCoords();const a=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=a.selectionEnd,r||(this.selectionStart=a.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,o=this.getValueOfPropertyAt(r,i,"fontSize")*this.lineHeight,a=e.leftOffset,h=this.getCanvasRetinaScaling(),l=this.canvas.upperCanvasEl,c=l.width/h,u=l.height/h,g=c-o,d=u-o,f=new _(e.left+a,e.top+e.topOffset+o).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new _(l.clientWidth/c,l.clientHeight/u));return f.x<0&&(f.x=0),f.x>g&&(f.x=g),f.y<0&&(f.y=0),f.y>d&&(f.y=d),f.x+=this.canvas._offset.left,f.y+=this.canvas._offset.top,{left:`${f.x}px`,top:`${f.y}px`,fontSize:`${o}px`,charHeight:o}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:this.hoverCursor,selectable:this.selectable,defaultCursor:this.canvas&&this.canvas.defaultCursor,moveCursor:this.canvas&&this.canvas.moveCursor}}_restoreEditingProps(){this._savedProps&&(this.hoverCursor=this._savedProps.hoverCursor,this.hasControls=this._savedProps.hasControls,this.borderColor=this._savedProps.borderColor,this.selectable=this._savedProps.selectable,this.lockMovementX=this._savedProps.lockMovementX,this.lockMovementY=this._savedProps.lockMovementY,this.canvas&&(this.canvas.defaultCursor=this._savedProps.defaultCursor||this.canvas.defaultCursor,this.canvas.moveCursor=this._savedProps.moveCursor||this.canvas.moveCursor),delete this._savedProps)}exitEditingImpl(){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(),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(cs),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:o}=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=o;a<this._unwrappedTextLines[i].length;a++){const h=this.styles[i][a];h&&(this.styles[s]||(this.styles[s]={}),this.styles[s][r+a-o]=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=o-r;for(let l=r;l<o;l++)delete a[l];for(const l in this.styles[s]){const c=parseInt(l,10);c>=o&&(a[c-h]=a[l],delete a[l])}}}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={},o=this._unwrappedTextLines[t].length,a=o===e;let h=!1;s||(s=1),this.shiftLineStyles(t,s);const l=this.styles[t]?this.styles[t][e===0?e:e-1]:void 0;for(const u in this.styles[t]){const g=parseInt(u,10);g>=e&&(h=!0,i[g-e]=this.styles[t][u],a&&e===0||delete this.styles[t][u])}let c=!1;for(h&&!a&&(this.styles[t+s]=i,c=!0),(c||o>e)&&s--;s>0;)r&&r[s-1]?this.styles[t+s]={0:{...r[s-1]}}:l?this.styles[t+s]={0:{...l}}:delete this.styles[t+s],s--;this._forceClearCache=!0}insertCharStyleObject(t,e,s,r){this.styles||(this.styles={});const i=this.styles[t],o=i?{...i}:{};s||(s=1);for(const h in o){const l=parseInt(h,10);l>=e&&(i[l+s]=o[l],o[l-s]||delete i[l])}if(this._forceClearCache=!0,r){for(;s--;)Object.keys(r[s]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+s]={...r[s]});return}if(!i)return;const a=i[e?e-1:1];for(;a&&s--;)this.styles[t][e+s]={...a}}insertNewStyleBlock(t,e,s){const r=this.get2DCursorLocation(e,!0),i=[0];let o,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),o=1;o<a;o++)i[o]>0?this.insertCharStyleObject(r.lineIndex+o,0,i[o],s):s&&this.styles[r.lineIndex+o]&&s[0]&&(this.styles[r.lineIndex+o][0]=s[0]),s=s&&s.slice(i[o]+1);i[o]>0&&this.insertCharStyleObject(r.lineIndex+o,0,i[o],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=$:this._selectionDirection===q&&(this._selectionDirection=$,this.selectionEnd=t),this.selectionStart=s):s>t&&s<e?this._selectionDirection===q?this.selectionEnd=s:this.selectionStart=s:(e===t?this._selectionDirection=q:this._selectionDirection===$&&(this._selectionDirection=q,this.selectionStart=e),this.selectionEnd=s)}}class Sh extends wh{initHiddenTextarea(){const t=this.canvas&&bt(this.canvas.getElement())||Te(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off",name:"fabricTextarea"}).map(o=>{let[a,h]=o;return e.setAttribute(a,h)});const{top:s,left:r,fontSize:i}=this._calcTextareaPosition();e.style.cssText=`position: absolute; top: ${s}; left: ${r}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${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(o=>{let[a,h]=o;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 o=()=>{this.updateFromTextArea(),this.fire(hs),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(this.hiddenTextarea.value==="")return this.styles={},void o();const a=this._splitTextIntoLines(s).graphemeText,h=this._text.length,l=a.length,c=this.selectionStart,u=this.selectionEnd,g=c!==u;let d,f,p,m,v=l-h;const x=this.fromStringToGraphemeSelection(r,i,s),S=c>x.selectionStart;g?(f=this._text.slice(c,u),v+=u-c):l<h&&(f=S?this._text.slice(u+v,u):this._text.slice(c,c-v));const w=a.slice(x.selectionEnd-v,x.selectionEnd);if(f&&f.length&&(w.length&&(d=this.getSelectionStyles(c,c+1,!1),d=w.map(()=>d[0])),g?(p=c,m=u):S?(p=u-f.length,m=u):(p=u,m=u+f.length),this.removeStyleFromTo(p,m)),w.length){const{copyPasteData:C}=At();e&&w.join("")===C.copiedText&&!B.disableStyleCopyPaste&&(d=C.copiedTextStyle),this.insertNewStyleBlock(w,c,d)}o()}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}=At();t.copiedText=this.getSelectedText(),B.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 o=r.charIndex,a=this._getWidthBeforeCursor(i,o),h=this._getIndexOnLine(i+1,a);return this._textLines[i].slice(o).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 o=r.charIndex,a=this._getWidthBeforeCursor(i,o),h=this._getIndexOnLine(i-1,a),l=this._textLines[i].slice(0,o),c=this.missingNewlineOffset(i-1);return-this._textLines[i-1].length+h-l.length+(1-c)}_getIndexOnLine(t,e){const s=this._textLines[t];let r,i,o=this._getLineLeftOffset(t),a=0;for(let h=0,l=s.length;h<l;h++)if(r=this.__charBounds[t][h].width,o+=r,o>e){i=!0;const c=o-r,u=o,g=Math.abs(c-e);a=Math.abs(u-e)<g?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${t}CursorOffset`](e,this._selectionDirection===q);if(e.shiftKey?this.moveCursorWithShift(s):this.moveCursorWithoutShift(s),s!==0){const r=this.text.length;this.selectionStart=pe(0,this.selectionStart,r),this.selectionEnd=pe(0,this.selectionEnd,r),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===$?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${s}`](this[e]);else{if(!t.metaKey&&t.keyCode!==35&&t.keyCode!==36)return this[e]+=s==="Left"?-1:1,!0;r=this[`findLineBoundary${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=$,this.selectionEnd===this.selectionStart&&this.selectionStart!==0&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===q&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):this.selectionStart!==0?(this._selectionDirection=$,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${t}${e.shiftKey?"WithShift":"WithoutShift"}`;this._currentCursorOpacity=1,this[s](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===$&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=q,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=q,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const ho=n=>!!n.button;class Ch extends Sh{constructor(){super(...arguments),y(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 _h(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&&!ho(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||ho(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(mt(this.calcTransformMatrix())).add(new _(-this._getLeftOffset(),-this._getTopOffset()));let s=0,r=0,i=0;for(let l=0;l<this._textLines.length&&s<=e.y;l++)s+=this.getHeightOfLine(l),i=l,l>0&&(r+=this._textLines[l-1].length+this.missingNewlineOffset(l-1));let o=Math.abs(this._getLineLeftOffset(i));const a=this._textLines[i].length,h=this.__charBounds[i];for(let l=0;l<a;l++){const c=o+h[l].kernedWidth;if(e.x<=c){Math.abs(e.x-c)<=Math.abs(e.x-o)&&r++;break}o=c,r++}return Math.min(this.flipX?a-r:r,this._text.length)}}const Rs="moveCursorUp",Bs="moveCursorDown",$s="moveCursorLeft",Xs="moveCursorRight",Ws="exitEditing",lo=(n,t)=>{const e=t.getRetinaScaling();n.setTransform(e,0,0,e,0,0);const s=t.viewportTransform;n.transform(s[0],s[1],s[2],s[3],s[4],s[5])},bh={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:Ws,27:Ws,33:Rs,34:Bs,35:Xs,36:$s,37:$s,38:Rs,39:Xs,40:Bs},keysMapRtl:{9:Ws,27:Ws,33:Rs,34:Bs,35:$s,36:Xs,37:Xs,38:Rs,39:$s,40:Bs},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"},_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1};class qt extends Ch{static getDefaults(){return{...super.getDefaults(),...qt.ownDefaults}}get type(){const t=super.type;return t==="itext"?"i-text":t}constructor(t,e){super(t,{...qt.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 ei&&this.canvas.textEditingManager.remove(this),e instanceof ei&&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,o=t;if(r){i=pt(t.canvas),o=i.getContext("2d"),lo(o,this.canvas);const a=this.calcTransformMatrix();o.transform(a[0],a[1],a[2],a[3],a[4],a[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(o,e):this.renderCursor(o,e),r)for(const a of s){const h=a.clipPath,l=pt(t.canvas),c=l.getContext("2d");if(lo(c,this.canvas),!h.absolutePositioned){const u=a.calcTransformMatrix();c.transform(u[0],u[1],u[2],u[3],u[4],u[5])}h.transform(c),h.drawObject(c,!0,{}),this.drawClipPathOnCache(o,h,l)}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),{textAlign:o,direction:a}=this;for(let u=0;u<i;u++)e+=this.getHeightOfLine(u);const h=this._getLineLeftOffset(i),l=this.__charBounds[i][r];l&&(s=l.left),this.charSpacing!==0&&r===this._textLines[i].length&&(s-=this._getWidthOfCharSpacing());let c=h+(s>0?s:0);return a===$t&&(o===q||o===jt||o===Ze?c*=-1:o===$||o===bs?c=h-(s>0?s:0):o!==A&&o!==Je||(c=h-(s>0?s:0))),{top:e,left:c}}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,o=this.getValueOfPropertyAt(r,i,"fontSize"),a=this.getObjectScaling().x*this.canvas.getZoom(),h=this.cursorWidth/a,l=this.getValueOfPropertyAt(r,i,"deltaY"),c=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(r)/this.lineHeight-o*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(r,i,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-h/2,top:c+e.top+l,width:h,height:o}}_renderCursor(t,e,s){const{color:r,opacity:i,left:o,top:a,width:h,height:l}=this.getCursorRenderingData(s,e);t.fillStyle=r,t.globalAlpha=i,t.fillRect(o,a,h,l)}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{textAlign:r,direction:i}=this,o=e.selectionStart,a=e.selectionEnd,h=r.includes(jt),l=this.get2DCursorLocation(o),c=this.get2DCursorLocation(a),u=l.lineIndex,g=c.lineIndex,d=l.charIndex<0?0:l.charIndex,f=c.charIndex<0?0:c.charIndex;for(let p=u;p<=g;p++){const m=this._getLineLeftOffset(p)||0;let v=this.getHeightOfLine(p),x=0,S=0,w=0;if(p===u&&(S=this.__charBounds[u][d].left),p>=u&&p<g)w=h&&!this.isEndOfWrapping(p)?this.width:this.getLineWidth(p)||5;else if(p===g)if(f===0)w=this.__charBounds[g][f].left;else{const k=this._getWidthOfCharSpacing();w=this.__charBounds[g][f-1].left+this.__charBounds[g][f-1].width-k}x=v,(this.lineHeight<1||p===g&&this.lineHeight>1)&&(v/=this.lineHeight);let C=s.left+m+S,b=v,M=0;const T=w-S;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",b=1,M=v):t.fillStyle=this.selectionColor,i===$t&&(r===q||r===jt||r===Ze?C=this.width-C-T:r===$||r===bs?C=s.left+m-w:r!==A&&r!==Je||(C=s.left+m-w)),t.fillRect(C,s.top+s.topOffset+M,T,b),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,J)}_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()}}y(qt,"ownDefaults",bh),y(qt,"type","IText"),O.setClass(qt),O.setClass(qt,"i-text");class _e extends qt{static getDefaults(){return{...super.getDefaults(),..._e.ownDefaults}}constructor(t,e){super(t,{..._e.ownDefaults,...e})}static createControls(){return{controls:Oa()}}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(jt)&&this.enlargeSpaces(),this.height=this.calcTextHeight())}_generateStyleMap(t){let e=0,s=0,r=0;const i={};for(let o=0;o<t.graphemeLines.length;o++)t.graphemeText[r]===`
57
- `&&o>0?(s=0,r++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[r])&&o>0&&(s++,r++),i[o]={line:e,offset:s},r+=t.graphemeLines[o].length,s+=t.graphemeLines[o].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 o=this._styleMap[t],a=this._styleMap[t+1];o&&(t=o.line,s=o.offset),a&&(r=a.line,i=r===t,e=a.offset);const h=t===void 0?this.styles:{line:this.styles[t]};for(const l in h)for(const c in h[l]){const u=parseInt(c,10);if(u>=s&&(!i||u<e))for(const g in h[l][c])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const s=this._styleMap[t];if(!s)return{};t=s.line,e=s.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,s){const 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,o)=>{let a=0;const h=e?this.graphemeSplit(i):this.wordSplit(i);return h.length===0?[{word:[],width:0}]:h.map(l=>{const c=e?[l]:this.graphemeSplit(l),u=this._measureWord(c,o,a);return r=Math.max(u,r),a+=c.length+s.length,{word:c,width:u}})}),largestWordWidth:r}}_measureWord(t,e){let s,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=0;for(let o=0,a=t.length;o<a;o++)i+=this._getGraphemeBox(t[o],e,o+r,s,!0).kernedWidth,s=t[o];return i}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,s){let{largestWordWidth:r,wordsData:i}=s,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:0;const a=this._getWidthOfCharSpacing(),h=this.splitByGrapheme,l=[],c=h?"":" ";let u=0,g=[],d=0,f=0,p=!0;e-=o;const m=Math.max(e,r,this.dynamicMinWidth),v=i[t];let x;for(d=0,x=0;x<v.length;x++){const{word:S,width:w}=v[x];d+=S.length,u+=f+w-a,u>m&&!p?(l.push(g),g=[],u=w,p=!0):u+=a,p||h||g.push(c),g=g.concat(S),f=h?0:this._measureWord([c],t,d),d++,p=!1}return x&&l.push(g),r+o>this.dynamicMinWidth&&(this.dynamicMinWidth=r-a+o),l}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(`${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])}}y(_e,"type","Textbox"),y(_e,"textLayoutProperties",[...qt.textLayoutProperties,"width"]),y(_e,"ownDefaults",{minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1}),O.setClass(_e);class co extends As{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:o,height:a}=Lt(In(s,r)),h=new _(o,a);if(r.absolutePositioned)return{center:ue(r.getRelativeCenterPoint(),void 0,i?i.calcTransformMatrix():void 0),size:h};{const l=r.getRelativeCenterPoint().transform(s.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:c=new _,correction:u=new _}=this.calcBoundingBox(e,t)||{};return{center:c.add(l),correction:u.subtract(l),size:h}}return{center:s.getRelativeCenterPoint().add(l),size:h}}}}y(co,"type","clip-path"),O.setClass(co);class uo extends As{getInitialSize(t,e){let{target:s}=t,{size:r}=e;return new _(s.width||r.x,s.height||r.y)}}y(uo,"type","fixed"),O.setClass(uo);class Th extends rs{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 we extends Gt{static getDefaults(){return{...super.getDefaults(),...we.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,we.ownDefaults),this.setOptions(e);const{left:s,top:r,layoutManager:i}=e;this.groupInit(t,{left:s,top:r,layoutManager:i!=null?i:new Th})}_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)),o=i===-1?this.size():i;this.insertAt(o,r)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(Qt("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(Es,e)}):s.forEach(r=>{r._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return`#<ActiveSelection: (${this.complexity()})>`}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,s){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const r={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()}}y(we,"type","ActiveSelection"),y(we,"ownDefaults",{multiSelectionStacking:"canvas-stacking"}),O.setClass(we),O.setClass(we,"activeSelection");class Oh{constructor(){y(this,"resources",{})}applyFilters(t,e,s,r,i){const o=i.getContext("2d",{willReadFrequently:!0,desynchronized:!0});if(!o)return;o.drawImage(e,0,0,s,r);const a={sourceWidth:s,sourceHeight:r,imageData:o.getImageData(0,0,s,r),originalEl:e,originalImageData:o.getImageData(0,0,s,r),canvasEl:i,ctx:o,filterBackend:this};t.forEach(l=>{l.applyTo(a)});const{imageData:h}=a;return h.width===s&&h.height===r||(i.width=h.width,i.height=h.height),o.putImageData(h,0,0),a}}class go{constructor(){let{tileSize:t=B.textureSize}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};y(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),y(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=pt({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,o){const a=this.gl,h=i.getContext("2d");if(!a||!h)return;let l;o&&(l=this.getCachedTexture(o,e));const c={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,l?void 0:e),targetTexture:this.createTexture(a,s,r),originalTexture:l||this.createTexture(a,s,r,l?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(g=>{g&&g.applyTo(c)}),(function(g){const d=g.targetCanvas,f=d.width,p=d.height,m=g.destinationWidth,v=g.destinationHeight;f===m&&p===v||(d.width=m,d.height=v)})(c),this.copyGLTo2D(a,c),a.bindTexture(a.TEXTURE_2D,null),a.deleteTexture(c.sourceTexture),a.deleteTexture(c.targetTexture),a.deleteFramebuffer(u),h.setTransform(1,0,0,1,0,0),c}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,s,r,i){const{NEAREST:o,TEXTURE_2D:a,RGBA:h,UNSIGNED_BYTE:l,CLAMP_TO_EDGE:c,TEXTURE_MAG_FILTER:u,TEXTURE_MIN_FILTER:g,TEXTURE_WRAP_S:d,TEXTURE_WRAP_T:f}=t,p=t.createTexture();return t.bindTexture(a,p),t.texParameteri(a,u,i||o),t.texParameteri(a,g,i||o),t.texParameteri(a,d,c),t.texParameteri(a,f,c),r?t.texImage2D(a,0,h,h,l,r):t.texImage2D(a,0,h,e,s,0,h,l,null),p}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 o=s.height-r.height;i.drawImage(s,0,o,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,o=r*i*4;if(!s)return;const a=new Uint8Array(this.imageBuffer,0,o),h=new Uint8ClampedArray(this.imageBuffer,0,o);t.readPixels(0,0,r,i,t.RGBA,t.UNSIGNED_BYTE,a);const l=new ImageData(h,r,i);s.putImageData(l,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 oi;function Mh(){const{WebGLProbe:n}=At();return n.queryWebGL(Ft()),B.enableGLFiltering&&n.isSupported(B.textureSize)?new go({tileSize:B.textureSize}):new Oh}function ai(){return!oi&&(!(arguments.length>0&&arguments[0]!==void 0)||arguments[0])&&(oi=Mh()),oi}const fo=["cropX","cropY"];class Et extends st{static getDefaults(){return{...super.getDefaults(),...Et.ownDefaults}}constructor(t,e){super(),y(this,"_lastScaleX",1),y(this,"_lastScaleY",1),y(this,"_filterScalingX",1),y(this,"_filterScalingY",1),this.filters=[],Object.assign(this,Et.ownDefaults),this.setOptions(e),this.cacheKey=`texture${te()}`,this.setElement(typeof t=="string"?(this.canvas&&bt(this.canvas.getElement())||Te()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._element=t,this._originalElement=t,this._setWidthHeight(e),this.filters.length!==0&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=ai(!1);e instanceof go&&e.evictCachesForKey(t)}dispose(){super.dispose(),this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._cacheContext=null,["_originalElement","_element","_filteredEl","_cacheCanvas"].forEach(t=>{const e=this[t];e&&At().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())}),{...super.toObject([...fo,...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=[],o=[],a="",h="";if(!e)return[];if(this.hasCrop()){const l=te();i.push('<clipPath id="imageCrop_'+l+`">
58
- `,' <rect x="'+s+'" y="'+r+'" width="'+this.width+'" height="'+this.height+`" />
59
- `,`</clipPath>
60
- `),a=' clip-path="url(#imageCrop_'+l+')" '}if(this.imageSmoothing||(h=' image-rendering="optimizeSpeed"'),t.push(" <image ","COMMON_PARTS",`xlink:href="${this.getSvgSrc(!0)}" x="${s-this.cropX}" y="${r-this.cropY}" width="${e.width||e.naturalWidth}" height="${e.height||e.naturalHeight}"${h}${a}></image>
61
- `),this.stroke||this.strokeDashArray){const l=this.fill;this.fill=null,o=[` <rect x="${s}" y="${r}" width="${this.width}" height="${this.height}" style="${this.getSvgStyles()}" />
62
- `],this.fill=l}return i=this.paintFirst!==J?i.concat(o,t):i.concat(t,o),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 ze(t,{crossOrigin:e,signal:s}).then(r=>{e!==void 0&&this.set({crossOrigin:e}),this.setElement(r)})}toString(){return`#<Image: { src: "${this.getSrc()}" }>`}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,s=this.getTotalObjectScaling(),r=s.x,i=s.y,o=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||r>e&&i>e)return this._element=o,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=r,void(this._lastScaleY=i);const a=pt(o),{width:h,height:l}=o;this._element=a,this._lastScaleX=t.scaleX=r,this._lastScaleY=t.scaleY=i,ai().applyFilters([t],o,h,l,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(`${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=pt({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);ai().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,o=this.height,a=Math.max(this.cropX,0),h=Math.max(this.cropY,0),l=e.naturalWidth||e.width,c=e.naturalHeight||e.height,u=a*s,g=h*r,d=Math.min(i*s,l-u),f=Math.min(o*r,c-g),p=-i/2,m=-o/2,v=Math.min(i,l/s-a),x=Math.min(o,c/r-h);e&&t.drawImage(e,u,g,d,f,p,m,v,x)}_needsResize(){const t=this.getTotalObjectScaling();return t.x!==this._lastScaleX||t.y!==this._lastScaleY}_resetWidthHeight(){this.set(this.getOriginalSize())}_setWidthHeight(){let{width:t,height:e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};const s=this.getOriginalSize();this.width=t||s.width,this.height=e||s.height}parsePreserveAspectRatioAttribute(){const t=nn(this.preserveAspectRatio||""),e=this.width,s=this.height,r={width:e,height:s};let i,o=this._element.width,a=this._element.height,h=1,l=1,c=0,u=0,g=0,d=0;return!t||t.alignX===gt&&t.alignY===gt?(h=e/o,l=s/a):(t.meetOrSlice==="meet"&&(h=l=Bn(this._element,r),i=(e-o*h)/2,t.alignX==="Min"&&(c=-i),t.alignX==="Max"&&(c=i),i=(s-a*l)/2,t.alignY==="Min"&&(u=-i),t.alignY==="Max"&&(u=i)),t.meetOrSlice==="slice"&&(h=l=$n(this._element,r),i=o-e/h,t.alignX==="Mid"&&(g=i/2),t.alignX==="Max"&&(g=i),i=a-s/l,t.alignY==="Mid"&&(d=i/2),t.alignY==="Max"&&(d=i),o=e/h,a=s/l)),{width:o,height:a,scaleX:h,scaleY:l,offsetLeft:c,offsetTop:u,cropX:g,cropY:d}}static fromObject(t,e){let{filters:s,resizeFilter:r,src:i,crossOrigin:o,type:a,...h}=t;return Promise.all([ze(i,{...e,crossOrigin:o}),s&&Pe(s,e),r?Pe([r],e):[],Ue(h,e)]).then(l=>{let[c,u=[],[g],d={}]=l;return new this(c,{...h,src:i,filters:u,resizeFilter:g,...d})})}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 ze(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=Nt(t,this.ATTRIBUTE_NAMES,s);return this.fromURL(r["xlink:href"]||r.href,e,r).catch(i=>(Qt("log","Unable to parse Image",i),null))}}y(Et,"type","Image"),y(Et,"cacheProperties",[...Yt,...fo]),y(Et,"ownDefaults",{strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0}),y(Et,"ATTRIBUTE_NAMES",[...ee,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),O.setClass(Et),O.setSVGClass(Et),Cs(["pattern","defs","symbol","metadata","clipPath","mask","desc"]);const Ys=n=>n.webgl!==void 0,hi="precision highp float",kh=`
63
- ${hi};
64
- varying vec2 vTexCoord;
65
- uniform sampler2D uTexture;
66
- void main() {
67
- gl_FragColor = texture2D(uTexture, vTexCoord);
68
- }`,Dh=new RegExp(hi,"g");class Z{get type(){return this.constructor.type}constructor(){let{type:t,...e}=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Object.assign(this,this.constructor.defaults,e)}getFragmentSource(){return kh}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"}}=At();r!=="highp"&&(e=e.replace(Dh,hi.replace("highp",r)));const i=t.createShader(t.VERTEX_SHADER),o=t.createShader(t.FRAGMENT_SHADER),a=t.createProgram();if(!i||!o||!a)throw new Pt("Vertex, fragment shader or program creation error");if(t.shaderSource(i,s),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Pt(`Vertex shader compile error for ${this.type}: ${t.getShaderInfoLog(i)}`);if(t.shaderSource(o,e),t.compileShader(o),!t.getShaderParameter(o,t.COMPILE_STATUS))throw new Pt(`Fragment shader compile error for ${this.type}: ${t.getShaderInfoLog(o)}`);if(t.attachShader(a,i),t.attachShader(a,o),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS))throw new Pt(`Shader link error for "${this.type}" ${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){Ys(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=pt({width:e,height:s});t.helpLayer=r}}toObject(){const t=Object.keys(this.constructor.defaults||{});return{type:this.type,...t.reduce((e,s)=>(e[s]=this[s],e),{})}}toJSON(){return this.toObject()}static async fromObject(t,e){let{type:s,...r}=t;return new this(r)}}y(Z,"type","BaseFilter"),y(Z,"uniformLocations",[]);const Eh={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 Hs extends Z{getCacheKey(){return`${this.type}_${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
- ${Eh[this.mode]}
111
- }
112
- }
113
- `}applyTo2d(t){let{imageData:{data:e}}=t;const s=new W(this.color).getSource(),r=this.alpha,i=s[0]*r,o=s[1]*r,a=s[2]*r,h=1-r;for(let l=0;l<e.length;l+=4){const c=e[l],u=e[l+1],g=e[l+2];let d,f,p;switch(this.mode){case"multiply":d=c*i/255,f=u*o/255,p=g*a/255;break;case"screen":d=255-(255-c)*(255-i)/255,f=255-(255-u)*(255-o)/255,p=255-(255-g)*(255-a)/255;break;case"add":d=c+i,f=u+o,p=g+a;break;case"difference":d=Math.abs(c-i),f=Math.abs(u-o),p=Math.abs(g-a);break;case"subtract":d=c-i,f=u-o,p=g-a;break;case"darken":d=Math.min(c,i),f=Math.min(u,o),p=Math.min(g,a);break;case"lighten":d=Math.max(c,i),f=Math.max(u,o),p=Math.max(g,a);break;case"overlay":d=i<128?2*c*i/255:255-2*(255-c)*(255-i)/255,f=o<128?2*u*o/255:255-2*(255-u)*(255-o)/255,p=a<128?2*g*a/255:255-2*(255-g)*(255-a)/255;break;case"exclusion":d=i+c-2*i*c/255,f=o+u-2*o*u/255,p=a+g-2*a*g/255;break;case"tint":d=i+c*h,f=o+u*h,p=a+g*h}e[l]=d,e[l+1]=f,e[l+2]=p}}sendUniformData(t,e){const s=new W(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)}}y(Hs,"defaults",{color:"#F95C63",mode:"multiply",alpha:1}),y(Hs,"type","BlendColor"),y(Hs,"uniformLocations",["uColor"]),O.setClass(Hs);const Ph={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
- `};class Ns extends Z{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Ph[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 o=this.image;i.blendImage||(i.blendImage=Ft());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(o.scaleX,0,0,o.scaleY,o.left,o.top),h.drawImage(o.getElement(),0,0,s,r);const l=h.getImageData(0,0,s,r).data;for(let c=0;c<e.length;c+=4){const u=e[c],g=e[c+1],d=e[c+2],f=e[c+3],p=l[c],m=l[c+1],v=l[c+2],x=l[c+3];switch(this.mode){case"multiply":e[c]=u*p/255,e[c+1]=g*m/255,e[c+2]=d*v/255,e[c+3]=f*x/255;break;case"mask":e[c+3]=x}}}sendUniformData(t,e){const s=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,s)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject(t,e){let{type:s,image:r,...i}=t;return Et.fromObject(r,e).then(o=>new this({...i,image:o}))}}y(Ns,"type","BlendImage"),y(Ns,"defaults",{mode:"multiply",alpha:1}),y(Ns,"uniformLocations",["uTransformMatrix","uImage"]),O.setClass(Ns);class Vs extends Z{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){Ys(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 o=new Uint8ClampedArray(e),a=15,h=4*s;for(let l=0;l<e.length;l+=4){let c=0,u=0,g=0,d=0,f=0;const p=l-l%h,m=p+h;for(let v=-14;v<a;v++){const x=v/a,S=4*Math.floor(i*x),w=1-Math.abs(x);let C=l+S;C<p?C=p:C>m&&(C=m);const b=e[C+3]*w;c+=e[C]*b,u+=e[C+1]*b,g+=e[C+2]*b,d+=b,f+=w}o[l]=c/d,o[l+1]=u/d,o[l+2]=g/d,o[l+3]=d/f}this.horizontal=!1,i=this.getBlurValue()*r;for(let l=0;l<o.length;l+=4){let c=0,u=0,g=0,d=0,f=0;const p=l%h,m=o.length-h+p;for(let v=-14;v<a;v++){const x=v/a,S=Math.floor(i*x)*h,w=1-Math.abs(x);let C=l+S;C<p?C=p:C>m&&(C=m);const b=o[C+3]*w;c+=o[C]*b,u+=o[C+1]*b,g+=o[C+2]*b,d+=b,f+=w}e[l]=c/d,e[l+1]=u/d,e[l+2]=g/d,e[l+3]=d/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]}}y(Vs,"type","Blur"),y(Vs,"defaults",{blur:0}),y(Vs,"uniformLocations",["uDelta"]),O.setClass(Vs);class Gs extends Z{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)}}y(Gs,"type","Brightness"),y(Gs,"defaults",{brightness:0}),y(Gs,"uniformLocations",["uBrightness"]),O.setClass(Gs);const po={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class We extends Z{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 o=e[i],a=e[i+1],h=e[i+2];if(e[i]=o*s[0]+a*s[1]+h*s[2]+255*s[4],e[i+1]=o*s[5]+a*s[6]+h*s[7]+255*s[9],e[i+2]=o*s[10]+a*s[11]+h*s[12]+255*s[14],!r){const l=e[i+3];e[i]+=l*s[3],e[i+1]+=l*s[8],e[i+2]+=l*s[13],e[i+3]=o*s[15]+a*s[16]+h*s[17]+l*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{...super.toObject(),matrix:[...this.matrix]}}}function Se(n,t){var e;const s=(y(e=class extends We{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",n),y(e,"defaults",{colorsOnly:!1,matrix:t}),e);return O.setClass(s,n),s}y(We,"type","ColorMatrix"),y(We,"defaults",po),y(We,"uniformLocations",["uColorMatrix","uConstants"]),O.setClass(We),Se("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),Se("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),Se("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),Se("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),Se("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),Se("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),Se("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 mo extends Z{constructor(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){Ys(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=>O.getClass(s.type).fromObject(s,e))).then(s=>new this({subFilters:s}))}}y(mo,"type","Composed"),O.setClass(mo);class zs extends Z{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)}}y(zs,"type","Contrast"),y(zs,"defaults",{contrast:0}),y(zs,"uniformLocations",["uContrast"]),O.setClass(zs);const Ah={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 Us extends Z{getCacheKey(){return`${this.type}_${Math.sqrt(this.matrix.length)}_${this.opaque?1:0}`}getFragmentSource(){return Ah[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,s=e.data,r=this.matrix,i=Math.round(Math.sqrt(r.length)),o=Math.floor(i/2),a=e.width,h=e.height,l=t.ctx.createImageData(a,h),c=l.data,u=this.opaque?1:0;let g,d,f,p,m,v,x,S,w,C,b,M,T;for(b=0;b<h;b++)for(C=0;C<a;C++){for(m=4*(b*a+C),g=0,d=0,f=0,p=0,T=0;T<i;T++)for(M=0;M<i;M++)x=b+T-o,v=C+M-o,x<0||x>=h||v<0||v>=a||(S=4*(x*a+v),w=r[T*i+M],g+=s[S]*w,d+=s[S+1]*w,f+=s[S+2]*w,u||(p+=s[S+3]*w));c[m]=g,c[m+1]=d,c[m+2]=f,c[m+3]=u?s[m+3]:p}t.imageData=l}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return{...super.toObject(),opaque:this.opaque,matrix:[...this.matrix]}}}y(Us,"type","Convolute"),y(Us,"defaults",{opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]}),y(Us,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),O.setClass(Us);const yo="Gamma";class qs extends Z{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],o=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,o);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:yo,gamma:this.gamma.concat()}}}y(qs,"type",yo),y(qs,"defaults",{gamma:[1,1,1]}),y(qs,"uniformLocations",["uGamma"]),O.setClass(qs);const Fh={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 Ks extends Z{applyTo2d(t){let{imageData:{data:e}}=t;for(let s,r=0;r<e.length;r+=4){const i=e[r],o=e[r+1],a=e[r+2];switch(this.mode){case"average":s=(i+o+a)/3;break;case"lightness":s=(Math.min(i,o,a)+Math.max(i,o,a))/2;break;case"luminosity":s=.21*i+.72*o+.07*a}e[r+2]=e[r+1]=e[r]=s}}getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Fh[this.mode]}sendUniformData(t,e){t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}y(Ks,"type","Grayscale"),y(Ks,"defaults",{mode:"average"}),y(Ks,"uniformLocations",["uMode"]),O.setClass(Ks);const Lh={...po,rotation:0};class li extends We{calculateMatrix(){const t=this.rotation*Math.PI,e=St(t),s=Ct(t),r=1/3,i=Math.sqrt(r)*s,o=1-e;this.matrix=[e+o/3,r*o-i,r*o+i,0,0,r*o+i,e+r*o,r*o-i,0,0,r*o-i,r*o+i,e+r*o,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}}}y(li,"type","HueRotation"),y(li,"defaults",Lh),O.setClass(li);class Qs extends Z{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))}}y(Qs,"type","Invert"),y(Qs,"defaults",{alpha:!1,invert:!0}),y(Qs,"uniformLocations",["uInvert","uAlpha"]),O.setClass(Qs);class Zs extends Z{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}}y(Zs,"type","Noise"),y(Zs,"defaults",{noise:0}),y(Zs,"uniformLocations",["uNoise","uSeed"]),O.setClass(Zs);class Js extends Z{applyTo2d(t){let{imageData:{data:e,width:s,height:r}}=t;for(let i=0;i<r;i+=this.blocksize)for(let o=0;o<s;o+=this.blocksize){const a=4*i*s+4*o,h=e[a],l=e[a+1],c=e[a+2],u=e[a+3];for(let g=i;g<Math.min(i+this.blocksize,r);g++)for(let d=o;d<Math.min(o+this.blocksize,s);d++){const f=4*g*s+4*d;e[f]=h,e[f+1]=l,e[f+2]=c,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)}}y(Js,"type","Pixelate"),y(Js,"defaults",{blocksize:4}),y(Js,"uniformLocations",["uBlocksize"]),O.setClass(Js);class tr extends Z{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 W(this.color).getSource(),i=[r[0]-s,r[1]-s,r[2]-s],o=[r[0]+s,r[1]+s,r[2]+s];for(let a=0;a<e.length;a+=4){const h=e[a],l=e[a+1],c=e[a+2];h>i[0]&&l>i[1]&&c>i[2]&&h<o[0]&&l<o[1]&&c<o[2]&&(e[a+3]=0)}}sendUniformData(t,e){const s=new W(this.color).getSource(),r=this.distance,i=[0+s[0]/255-r,0+s[1]/255-r,0+s[2]/255-r,1],o=[s[0]/255+r,s[1]/255+r,s[2]/255+r,1];t.uniform4fv(e.uLow,i),t.uniform4fv(e.uHigh,o)}}y(tr,"type","RemoveColor"),y(tr,"defaults",{color:"#FFFFFF",distance:.02,useAlpha:!1}),y(tr,"uniformLocations",["uLow","uHigh"]),O.setClass(tr);class er extends Z{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`${this.type}_${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]=`${s}.0 * uDelta`;return`
460
- precision highp float;
461
- uniform sampler2D uTexture;
462
- uniform vec2 uDelta;
463
- varying vec2 vTexCoord;
464
- uniform float uTaps[${t}];
465
- void main() {
466
- vec4 color = texture2D(uTexture, vTexCoord);
467
- float sum = 1.0;
468
- ${e.map((s,r)=>`
469
- color += texture2D(uTexture, vTexCoord + ${s}) * uTaps[${r}] + texture2D(uTexture, vTexCoord - ${s}) * uTaps[${r}];
470
- sum += 2.0 * uTaps[${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){Ys(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,o=e.height,a=Math.round(i*s),h=Math.round(o*r);let l;l=this.resizeType==="sliceHack"?this.sliceByTwo(t,i,o,a,h):this.resizeType==="hermite"?this.hermiteFastResize(t,i,o,a,h):this.resizeType==="bilinear"?this.bilinearFiltering(t,i,o,a,h):this.resizeType==="lanczos"?this.lanczosResize(t,i,o,a,h):new ImageData(a,h),t.imageData=l}sliceByTwo(t,e,s,r,i){const o=t.imageData,a=.5;let h=!1,l=!1,c=e*a,u=s*a;const g=t.filterBackend.resources;let d=0,f=0;const p=e;let m=0;g.sliceByTwo||(g.sliceByTwo=Ft());const v=g.sliceByTwo;(v.width<1.5*e||v.height<s)&&(v.width=1.5*e,v.height=s);const x=v.getContext("2d");for(x.clearRect(0,0,1.5*e,s),x.putImageData(o,0,0),r=Math.floor(r),i=Math.floor(i);!h||!l;)e=c,s=u,r<Math.floor(c*a)?c=Math.floor(c*a):(c=r,h=!0),i<Math.floor(u*a)?u=Math.floor(u*a):(u=i,l=!0),x.drawImage(v,d,f,e,s,p,m,c,u),d=p,f=m,m+=u;return x.getImageData(d,f,r,i)}lanczosResize(t,e,s,r,i){const o=t.imageData.data,a=t.ctx.createImageData(r,i),h=a.data,l=this.lanczosCreate(this.lanczosLobes),c=this.rcpScaleX,u=this.rcpScaleY,g=2/this.rcpScaleX,d=2/this.rcpScaleY,f=Math.ceil(c*this.lanczosLobes/2),p=Math.ceil(u*this.lanczosLobes/2),m={},v={x:0,y:0},x={x:0,y:0};return(function S(w){let C,b,M,T,k,P,F,D,L,I,Q;for(v.x=(w+.5)*c,x.x=Math.floor(v.x),C=0;C<i;C++){for(v.y=(C+.5)*u,x.y=Math.floor(v.y),k=0,P=0,F=0,D=0,L=0,b=x.x-f;b<=x.x+f;b++)if(!(b<0||b>=e)){I=Math.floor(1e3*Math.abs(b-v.x)),m[I]||(m[I]={});for(let Y=x.y-p;Y<=x.y+p;Y++)Y<0||Y>=s||(Q=Math.floor(1e3*Math.abs(Y-v.y)),m[I][Q]||(m[I][Q]=l(Math.sqrt(Math.pow(I*g,2)+Math.pow(Q*d,2))/1e3)),M=m[I][Q],M>0&&(T=4*(Y*e+b),k+=M,P+=M*o[T],F+=M*o[T+1],D+=M*o[T+2],L+=M*o[T+3]))}T=4*(C*r+w),h[T]=P/k,h[T+1]=F/k,h[T+2]=D/k,h[T+3]=L/k}return++w<r?S(w):a})(0)}bilinearFiltering(t,e,s,r,i){let o,a,h,l,c,u,g,d,f,p,m,v,x,S=0;const w=this.rcpScaleX,C=this.rcpScaleY,b=4*(e-1),M=t.imageData.data,T=t.ctx.createImageData(r,i),k=T.data;for(g=0;g<i;g++)for(d=0;d<r;d++)for(c=Math.floor(w*d),u=Math.floor(C*g),f=w*d-c,p=C*g-u,x=4*(u*e+c),m=0;m<4;m++)o=M[x+m],a=M[x+4+m],h=M[x+b+m],l=M[x+b+4+m],v=o*(1-f)*(1-p)+a*f*(1-p)+h*p*(1-f)+l*f*p,k[S++]=v;return T}hermiteFastResize(t,e,s,r,i){const o=this.rcpScaleX,a=this.rcpScaleY,h=Math.ceil(o/2),l=Math.ceil(a/2),c=t.imageData.data,u=t.ctx.createImageData(r,i),g=u.data;for(let d=0;d<i;d++)for(let f=0;f<r;f++){const p=4*(f+d*r);let m=0,v=0,x=0,S=0,w=0,C=0,b=0;const M=(d+.5)*a;for(let T=Math.floor(d*a);T<(d+1)*a;T++){const k=Math.abs(M-(T+.5))/l,P=(f+.5)*o,F=k*k;for(let D=Math.floor(f*o);D<(f+1)*o;D++){let L=Math.abs(P-(D+.5))/h;const I=Math.sqrt(F+L*L);I>1&&I<-1||(m=2*I*I*I-3*I*I+1,m>0&&(L=4*(D+T*e),b+=m*c[L+3],x+=m,c[L+3]<255&&(m=m*c[L+3]/250),S+=m*c[L],w+=m*c[L+1],C+=m*c[L+2],v+=m))}}g[p]=S/v,g[p+1]=w/v,g[p+2]=C/v,g[p+3]=b/x}return u}}y(er,"type","Resize"),y(er,"defaults",{resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3}),y(er,"uniformLocations",["uDelta","uTaps"]),O.setClass(er);class sr extends Z{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],o=e[r+1],a=e[r+2],h=Math.max(i,o,a);e[r]+=h!==i?(h-i)*s:0,e[r+1]+=h!==o?(h-o)*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}}y(sr,"type","Saturation"),y(sr,"defaults",{saturation:0}),y(sr,"uniformLocations",["uSaturation"]),O.setClass(sr);class rr extends Z{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],o=e[r+1],a=e[r+2],h=Math.max(i,o,a),l=(i+o+a)/3,c=2*Math.abs(h-l)/255*s;e[r]+=h!==i?(h-i)*c:0,e[r+1]+=h!==o?(h-o)*c:0,e[r+2]+=h!==a?(h-a)*c:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}}y(rr,"type","Vibrance"),y(rr,"defaults",{vibrance:0}),y(rr,"uniformLocations",["uVibrance"]),O.setClass(rr);function vo(n){const t=n&&n.bounds;if(t&&typeof t.width=="number"&&typeof t.height=="number"&&t.width>0&&t.height>0)return{left:typeof t.left=="number"?t.left:0,top:typeof t.top=="number"?t.top:0,width:t.width,height:t.height};if(Array.isArray(n==null?void 0:n.children))for(const e of n.children){const s=vo(e);if(s)return s}return null}function jh(n,t="split"){if(!Array.isArray(n))return[];const e=(o,a)=>{for(const h of o){if(h&&h.name===a&&h.type==="Group")return h;if(Array.isArray(h==null?void 0:h.children)){const l=e(h.children,a);if(l)return l}}return null},s=e(n,t),r=s&&s.children||[],i=[];for(const o of r){if(!o||o.type!=="Group"||o.id==null)continue;const a=vo(o);a&&i.push({id:Number(o.id),name:o.name||"",bounds:a})}return i}function Ih(n){return new Promise((t,e)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>t(s),s.onerror=()=>e(new Error("图片加载失败: "+n.slice(0,60))),s.src=n})}async function Rh(n,t,e="png"){const s=Number(t==null?void 0:t.canvasWidth)||0,r=(t==null?void 0:t.canvasHeight)!=null?Number(t.canvasHeight):s;if(!(s>0&&r>0))throw new Error("productJson.canvasWidth/canvasHeight 无效");const i=jh((t==null?void 0:t.layerList)||[],"split");if(!i.length)throw new Error("productJson 中未解析到 split 分片结构");const o=new Map,a=new Map;for(const p of n||[])p!=null&&p.name&&o.set(p.name,p),(p==null?void 0:p.id)!=null&&a.set(String(p.id),p);const h=document.createElement("canvas");h.width=s,h.height=r;const l=h.getContext("2d");if(!l)throw new Error("无法创建画布 2D 上下文");l.fillStyle="#ffffff",l.fillRect(0,0,s,r);const c=[],u=[],g=[];try{for(const p of i){const m=p.name&&o.get(p.name)||a.get(String(p.id));if(!(m!=null&&m.blob)){u.push(`${p.name||p.id}(无位图)`);continue}const{left:v,top:x,width:S,height:w}=p.bounds;if(S<=0||w<=0){u.push(`${p.name||p.id}(槽位无效)`);continue}const C=URL.createObjectURL(m.blob);g.push(C);const b=await Ih(C),M=b.naturalWidth||1,T=b.naturalHeight||1,k=Math.max(S/M,w/T),P=Math.round(M*k),F=Math.round(T*k),D=Math.round(v+(S-P)/2),L=Math.round(x+(w-F)/2);l.save(),l.beginPath(),l.rect(v,x,S,w),l.clip(),l.drawImage(b,0,0,M,T,D,L,P,F),l.restore(),c.push(p.name||String(p.id))}}finally{g.forEach(p=>{try{URL.revokeObjectURL(p)}catch{}})}const d=e==="jpeg"?"image/jpeg":"image/png";return{blob:await new Promise((p,m)=>{h.toBlob(v=>v?p(v):m(new Error("canvas.toBlob 返回空")),d,e==="jpeg"?1:void 0)}),canvasWidth:s,canvasHeight:r,drawn:c,skipped:u}}const Bh=0,ci="single",$h="full",xo="#1677ff";function Xh(n){var t;return((t=n==null?void 0:n.customData)==null?void 0:t.patternRenderMode)===ci?ci:$h}function Wh(n){return Xh(n)===ci}function ir(n,t){return t?(n%t+t)%t:0}function Yh(n){var l,c,u;const t=(n==null?void 0:n.customData)||{},e=Number((l=n==null?void 0:n.patternTileWidth)!=null?l:t.patternTileWidth)||100,s=Number((c=n==null?void 0:n.patternTileHeight)!=null?c:t.patternTileHeight)||100,r=n==null?void 0:n.patternScale,i=typeof r=="number"&&r>0&&r<=2?Math.max(.01,r):Math.max(.01,(Number((u=t.patternScale)!=null?u:100)||100)/100),o=Math.max(1,e*i),a=Math.max(1,s*i),h=ui(n);return{tileW:o,tileH:a,strideW:o+h.x,strideH:a+h.y,scale:i}}function _o(n){var m,v,x,S;const t=Yh(n),{strideW:e,strideH:s}=t,r=Number(n==null?void 0:n.width)||0,i=Number(n==null?void 0:n.height)||0,o=(m=n==null?void 0:n.getCenterPoint)==null?void 0:m.call(n),a=Number(o==null?void 0:o.x)||(Number(n==null?void 0:n.left)||0)+r/2,h=Number(o==null?void 0:o.y)||(Number(n==null?void 0:n.top)||0)+i/2,l=a-r/2,c=h-i/2,u=typeof(n==null?void 0:n.patternPhaseX)=="number"?n.patternPhaseX:typeof((v=n==null?void 0:n.customData)==null?void 0:v.patternPhaseX)=="number"?n.customData.patternPhaseX:0,g=typeof(n==null?void 0:n.patternPhaseY)=="number"?n.patternPhaseY:typeof((x=n==null?void 0:n.customData)==null?void 0:x.patternPhaseY)=="number"?n.customData.patternPhaseY:0,d=l-ir(l-u,e),f=c-ir(c-g,s),p=(n==null?void 0:n.patternMode)||((S=n==null?void 0:n.customData)==null?void 0:S.patternMode)||"";return{...t,centerX:a,centerY:h,sceneLeft:l,sceneTop:c,startSceneX:d,startSceneY:f,startX:d-a,startY:f-h,phaseX:u,phaseY:g,mode:p}}function Hh(n,t,e){const s=_o(n),{strideW:r,strideH:i,tileW:o,tileH:a,startSceneX:h,startSceneY:l,centerX:c,centerY:u,phaseX:g,phaseY:d,mode:f}=s,p=wo(n);if(p%360!==0){const w=p*Math.PI/180,C=Math.cos(w),b=Math.sin(w),M=t-c,T=e-u,k=M*C+T*b,P=-M*b+T*C,F=g-c,D=d-u,L=F*C+D*b,I=-F*b+D*C,Q=Math.floor((k-L)/r),Y=Math.floor((P-I)/i);let H=L+Q*r,R=I+Y*i;f==="brick-x"&&Math.round((R-I)/i)&1&&(H+=r/2),f==="brick-y"&&Math.round((H-L)/r)&1&&(R+=i/2);const ct=c+H*C-R*b,rt=u+H*b+R*C;return{left:ct,top:rt,tileW:o,tileH:a}}const m=Math.floor((t-h)/r),v=Math.floor((e-l)/i);let x=h+m*r,S=l+v*i;return f==="brick-x"&&Math.round((S-d)/i)&1&&(x+=r/2),f==="brick-y"&&Math.round((x-g)/r)&1&&(S+=i/2),{left:x,top:S,tileW:o,tileH:a}}function Ye(n,t=Bh){const e=Number(n);return Number.isFinite(e)?Math.max(0,e):t}function nr(n){const t=n,e=(t==null?void 0:t.naturalWidth)||(t==null?void 0:t.videoWidth)||(t==null?void 0:t.width)||0,s=(t==null?void 0:t.naturalHeight)||(t==null?void 0:t.videoHeight)||(t==null?void 0:t.height)||0;return{width:e,height:s}}function Nh(n,t,e){let s=e*2654435761>>>0;return s=(s<<5)-s+n|0,s=(s<<5)-s+t|0,s>>>0}function ui(n){var e,s;const t=(n==null?void 0:n.customData)||{};return{x:Ye((e=n==null?void 0:n.patternGapX)!=null?e:t.patternGapX),y:Ye((s=n==null?void 0:n.patternGapY)!=null?s:t.patternGapY)}}function or(n){const t=Number(n);return Number.isFinite(t)?(t%360+360)%360:0}function wo(n){const t=(n==null?void 0:n.customData)||{},e=[n==null?void 0:n.patternTileAngle,t.patternTileAngle,t.originalAngle];for(const s of e){const r=Number(s);if(Number.isFinite(r)&&r!==0)return or(r)}return 0}function Vh(n){var e,s,r,i;const t=(n==null?void 0:n.customData)||{};return{flipX:!!((s=(e=n==null?void 0:n.patternTileFlipX)!=null?e:t.patternTileFlipX)!=null?s:t.originalFlipX),flipY:!!((i=(r=n==null?void 0:n.patternTileFlipY)!=null?r:t.patternTileFlipY)!=null?i:t.originalFlipY),angle:wo(n)}}function Gh(n,t,e,s,r,i,o=!1,a=!1,h=0){const l=or(h),c=.75;if(!o&&!a&&l===0){n.drawImage(t,e-c,s-c,r+c*2,i+c*2);return}n.save(),n.translate(e+r/2,s+i/2),l&&n.rotate(l*Math.PI/180),n.scale(o?-1:1,a?-1:1),n.drawImage(t,-r/2-c,-i/2-c,r+c*2,i+c*2),n.restore()}class ar extends Mt{constructor(t={}){var e,s,r;super({...t,originX:"left",originY:"top",objectCaching:!1,hasControls:!1,hasBorders:!1,lockScalingX:!0,lockScalingY:!0,lockRotation:!0,fill:(e=t.fill)!=null?e:"",stroke:(s=t.stroke)!=null?s:null,borderColor:xo,cornerColor:xo,cornerStrokeColor:"#ffffff",transparentCorners:!1,borderScaleFactor:2}),this.patternElement=(r=t.patternElement)!=null?r:null,this.patternTileWidth=Number(t.patternTileWidth)||nr(this.patternElement).width||100,this.patternTileHeight=Number(t.patternTileHeight)||nr(this.patternElement).height||100,this.patternScale=Number(t.patternScale)||1,this.patternPhaseX=Number(t.patternPhaseX)||0,this.patternPhaseY=Number(t.patternPhaseY)||0,this.patternGapX=Ye(t.patternGapX),this.patternGapY=Ye(t.patternGapY),this.patternMode=t.patternMode||"",this.patternSeed=Number(t.patternSeed)||1,this.patternTileFlipX=!!t.patternTileFlipX,this.patternTileFlipY=!!t.patternTileFlipY,this.patternTileAngle=or(t.patternTileAngle),this.patternActiveTileLeft=null,this.patternActiveTileTop=null}setActiveDragTile(t,e){this.patternActiveTileLeft=t,this.patternActiveTileTop=e,this.dirty=!0}clearActiveDragTile(){this.patternActiveTileLeft==null&&this.patternActiveTileTop==null||(this.patternActiveTileLeft=null,this.patternActiveTileTop=null,this.dirty=!0)}setPatternElement(t){this.patternElement=t;const e=nr(t);!this.patternTileWidth&&e.width&&(this.patternTileWidth=e.width),!this.patternTileHeight&&e.height&&(this.patternTileHeight=e.height),this.dirty=!0}setPatternPhase(t,e){this.patternPhaseX=t,this.patternPhaseY=e,this.customData={...this.customData||{},patternPhaseX:t,patternPhaseY:e},this.dirty=!0}setPatternGap(t,e){this.patternGapX=Ye(t),this.patternGapY=Ye(e),this.customData={...this.customData||{},patternGapX:this.patternGapX,patternGapY:this.patternGapY},this.dirty=!0}toObject(t=[]){return super.toObject(["patternTileWidth","patternTileHeight","patternScale","patternPhaseX","patternPhaseY","patternGapX","patternGapY","patternMode","patternSeed","patternTileFlipX","patternTileFlipY","patternTileAngle",...t])}_render(t){var Y,H,R,ct,rt,Kt,re,ie;const e=this.patternElement;if(!e){super._render(t);return}const s=Number(this.width)||0,r=Number(this.height)||0,i=_o(this),{tileW:o,tileH:a,strideW:h,strideH:l,centerX:c,centerY:u}=i;let g=i.startX,d=i.startY,f=i.phaseX,p=i.phaseY;const m=i.mode,v=-s/2,x=-r/2;let S=s/2,w=r/2;t.save(),t.beginPath(),t.rect(v,x,s,r),t.clip(),t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high";const{flipX:C,flipY:b,angle:M}=Vh(this),T=(E,j)=>({flipX:C!==E,flipY:b!==j}),k=ui(this),P=M*Math.PI/180,F=M%360!==0;if(F){t.rotate(P);const E=Math.cos(P),j=Math.sin(P),N=f-c,V=p-u,G=N*E+V*j,it=-N*j+V*E;f=G+c,p=it+u;const tt=Math.abs(E),It=Math.abs(j),Rt=s/2*tt+r/2*It+h,be=s/2*It+r/2*tt+l;S=Rt,w=be,g=-Rt-ir(-Rt-G,h),d=-be-ir(-be-it,l)}const D=(E,j,N,V)=>{Gh(t,e,E,j,o,a,N,V,0)};if(Wh(this)){const E=f-c,j=p-u;if(D(E,j,C,b),((H=(Y=this.canvas)==null?void 0:Y.getActiveObject)==null?void 0:H.call(Y))===this){const V=Math.abs(Number((ct=(R=this.canvas)==null?void 0:R.getZoom)==null?void 0:ct.call(R))||1);t.save(),t.strokeStyle="#1677ff",t.lineWidth=10/V,t.setLineDash([18/V,15/V]),t.strokeRect(E,j,o,a),t.restore()}t.restore();return}const L=nr(e);if((m===""||m==="grid")&&k.x===0&&k.y===0&&!C&&!b&&or(M)===0&&L.width>0&&L.height>0){const E=t.createPattern(e,"repeat");if(E){const j=f-c,N=p-u;E.setTransform(new DOMMatrix([o/L.width,0,0,a/L.height,j,N])),t.fillStyle=E,t.fillRect(v,x,s,r)}}else if(m==="brick-x")for(let E=d-l;E<w;E+=l){const j=u+E,V=Math.round((j-p)/l)&1?h/2:0;for(let G=g-h;G<S;G+=h)D(G+V,E,C,b)}else if(m==="brick-y")for(let E=d-l;E<w;E+=l)for(let j=g-h;j<S;j+=h){const N=c+j,G=Math.round((N-f)/h)&1?l/2:0;D(j,E+G,C,b)}else if(m==="mirror")for(let E=d;E<w;E+=l){const j=u+E,V=!!(Math.round((j-p)/l)&1);for(let G=g;G<S;G+=h){const it=c+G,It=!!(Math.round((it-f)/h)&1),{flipX:Rt,flipY:be}=T(It,V);D(G,E,Rt,be)}}else if(m==="random"){const E=this.patternSeed||1;for(let j=d;j<w;j+=l){const N=u+j,V=Math.round((N-p)/l);for(let G=g;G<S;G+=h){const it=c+G,tt=Math.round((it-f)/h),It=Nh(V,tt,E),{flipX:Rt,flipY:be}=T(!!(It&1),!!(It&2));D(G,j,Rt,be)}}}else for(let E=d;E<w;E+=l)for(let j=g;j<S;j+=h)D(j,E,C,b);if(((Kt=(rt=this.canvas)==null?void 0:rt.getActiveObject)==null?void 0:Kt.call(rt))===this){let E,j;if(this.patternActiveTileLeft!=null&&this.patternActiveTileTop!=null)E=this.patternActiveTileLeft,j=this.patternActiveTileTop;else{const it=Hh(this,c,u);E=it.left,j=it.top}let N,V;if(F){const it=Math.cos(P),tt=Math.sin(P),It=E-c,Rt=j-u;N=It*it+Rt*tt,V=-It*tt+Rt*it}else N=E-c,V=j-u;const G=Math.abs(Number((ie=(re=this.canvas)==null?void 0:re.getZoom)==null?void 0:ie.call(re))||1);t.save(),t.strokeStyle="#1677ff",t.lineWidth=10/G,t.setLineDash([18/G,15/G]),t.strokeRect(N,V,o,a),t.restore()}t.restore()}}gr(ar,"type","pattern-layer"),O.setClass(ar);function So(n){var t;return!!((t=n==null?void 0:n.customData)!=null&&t.isPatternRect)||n instanceof ar||(n==null?void 0:n.type)===ar.type}function zh(n,t){return!(n!=null&&n.patternElement)||!t||!So(n)?!1:(typeof t.setPatternElement=="function"?t.setPatternElement(n.patternElement):t.patternElement=n.patternElement,t.patternTileWidth=n.patternTileWidth,t.patternTileHeight=n.patternTileHeight,t.patternScale=n.patternScale,t.patternPhaseX=n.patternPhaseX,t.patternPhaseY=n.patternPhaseY,t.patternGapX=n.patternGapX,t.patternGapY=n.patternGapY,t.patternMode=n.patternMode,t.patternSeed=n.patternSeed,t.patternTileFlipX=n.patternTileFlipX,t.patternTileFlipY=n.patternTileFlipY,t.patternTileAngle=n.patternTileAngle,t.dirty=!0,!0)}const Uh=n=>Number.isFinite(n)?Math.min(200,Math.max(1,Math.round(n))):100,qh=n=>{var s,r;if(!n)return null;const t=(s=n.width)!=null?s:n.naturalWidth,e=(r=n.height)!=null?r:n.naturalHeight;return!t||!e?null:{width:t,height:e}};function Kh(n,t,e){var o,a;const s=(...h)=>{for(const l of h){const c=Number(l);if(Number.isFinite(c)&&c>0)return c}return null},r=(o=s(n==null?void 0:n.patternTileWidth,n==null?void 0:n.originalWidth,e==null?void 0:e.patternTileWidth,t==null?void 0:t.width))!=null?o:100,i=(a=s(n==null?void 0:n.patternTileHeight,n==null?void 0:n.originalHeight,e==null?void 0:e.patternTileHeight,t==null?void 0:t.height))!=null?a:100;return{tw:r,th:i}}class Ce{static getItem(t){if(!this.hasStorage)return null;try{return localStorage.getItem(t)}catch(e){return console.warn(`读取 localStorage 失败 [${t}]:`,e),null}}static setItem(t,e){if(!this.hasStorage)return!1;try{return localStorage.setItem(t,e),!0}catch(s){return console.warn(`写入 localStorage 失败 [${t}]:`,s),!1}}static removeItem(t){if(!this.hasStorage)return!1;try{return localStorage.removeItem(t),!0}catch(e){return console.warn(`删除 localStorage 失败 [${t}]:`,e),!1}}static clear(){if(!this.hasStorage)return!1;try{return localStorage.clear(),!0}catch(t){return console.warn("清空 localStorage 失败:",t),!1}}static isAvailable(){return this.hasStorage}}gr(Ce,"hasStorage",typeof window!="undefined"&&typeof localStorage!="undefined");class hr{static isBrowser(){return typeof window!="undefined"}static isWorker(){return typeof WorkerGlobalScope!="undefined"}static hasLocalStorage(){return this.isBrowser()&&typeof localStorage!="undefined"}static hasCanvas(){return this.isBrowser()&&typeof HTMLCanvasElement!="undefined"}static getDomain(){return this.isBrowser()?window.location.hostname:"localhost"}static getOrigin(){return this.isBrowser()?window.location.origin:"http://localhost"}}const ur=class ur{static parse(t){try{const e=hr.getOrigin();return new URL(t,e)}catch{return null}}static addParam(t,e,s){const r=this.parse(t);return!r||r.searchParams.has(e)?t:(r.searchParams.set(e,s),this.formatUrl(t,r))}static removeParam(t,e){const s=this.parse(t);return!s||!s.searchParams.has(e)?t:(s.searchParams.delete(e),this.formatUrl(t,s))}static hasParam(t,e){var r;const s=this.parse(t);return(r=s==null?void 0:s.searchParams.has(e))!=null?r:!1}static forceHttpsAsset(t){if(typeof t!="string"||!/^http:\/\//i.test(t))return t;const e=t.slice(t.indexOf("://")+3),s=e.split(/[/?#]/)[0].split("@").pop().split(":")[0];return ur.HTTPS_ASSET_HOST_RE.test(s)?"https://"+e:t}static formatUrl(t,e){const s=/^(https?:)?\/\//i.test(t),r=t.startsWith("//");return s?e.toString():r?e.toString().replace(/^https?:/,""):`${e.pathname}${e.search}${e.hash}`}static isDataUrl(t){var e;return(e=t==null?void 0:t.startsWith("data:"))!=null?e:!1}static isBlobUrl(t){var e;return(e=t==null?void 0:t.startsWith("blob:"))!=null?e:!1}};gr(ur,"HTTPS_ASSET_HOST_RE",/(^|\.)(r480\.cn|aliyuncs\.com)$/i);let _t=ur;const Qh=new Map,Zh=new Map;function Jh(){Qh.clear(),Zh.clear()}const tl=new Map,el=new Map;function sl(){tl.clear(),el.clear()}const gi="file_token",di="file_token_expire_time",rl=60*1e3;function fi(){return Ce.getItem(gi)}function il(n=rl){if(!fi())return!0;const e=Ce.getItem(di);if(!e)return!1;const s=Number(e);return Date.now()+n>s}function Co(n,t){if(Ce.setItem(gi,n),typeof t=="number"&&t>0){const e=Date.now()+t*1e3;Ce.setItem(di,String(e))}}function nl(){Ce.removeItem(gi),Ce.removeItem(di),Jh(),sl()}async function bo(n){var s,r;const t=await n(),e=(s=t==null?void 0:t.data)==null?void 0:s.data;return((r=t==null?void 0:t.data)==null?void 0:r.code)===200&&(e!=null&&e.file_token)?(Co(e.file_token,e.expires_in),e.file_token):null}let ol=null,pi=null;function al(n){pi=n,n&&Co(n)}function To(){return hr.isBrowser()?ol:null}async function Oo(){if(pi)return pi;if(!hr.isBrowser())return fi();const n=fi();if(n&&!il())return n;try{const t=await To();if(n&&(t!=null&&t.fetchFileTokenRefresh)){const e=await bo(t.fetchFileTokenRefresh);if(e)return e}}catch{}try{const t=To();return t!=null&&t.fetchFileToken?await bo(t.fetchFileToken):null}catch{return null}}const Mo=["/files/","/pd/","/pm/","/test/","/test-local/","/wd/","/whiteboard/"];function ko(n){if(!n||_t.isDataUrl(n)||_t.isBlobUrl(n))return!1;const t=_t.parse(n);return t?Mo.some(e=>t.pathname.includes(e))&&!_t.hasParam(n,"fileToken"):Mo.some(e=>n.includes(e))&&!n.includes("fileToken=")}function mi(n,t){return n=_t.forceHttpsAsset(n),!t||!ko(n)?n:_t.addParam(n,"fileToken",t)}function hl(n){return _t.removeParam(n,"fileToken")}async function ll(n){if(!ko(n))return n;const t=await Oo();return mi(n,t)}const yi=new Map;function cl(n,t){return`${String((t==null?void 0:t.method)||"GET").toUpperCase()}\0${n}`}async function Do(n,t){if(!hr.isBrowser())return fetch(n,t);const e=_t.forceHttpsAsset(hl(n)),s=cl(e,t);let r=yi.get(s);return r||(r=(async()=>{try{const o=await ll(e),a=3;let h=null;for(let l=0;l<a;l++)try{let c;try{c=await fetch(o,t)}catch{if((t==null?void 0:t.mode)==="cors")c=await fetch(o,{...t,cache:"no-store"});else throw new Error("fetch failed")}if(c.status===401){nl();const u=await Oo(),g=mi(e,u);return await fetch(g,t)}if(c.status>=500&&l<a-1){h=new Error(`HTTP ${c.status}`),await new Promise(u=>setTimeout(u,300*Math.pow(2,l)));continue}return c}catch(c){if(h=c,l<a-1){await new Promise(u=>setTimeout(u,300*Math.pow(2,l)));continue}}throw h!=null?h:new Error("fetchWithFileToken failed")}finally{yi.delete(s)}})(),yi.set(s,r)),(await r).clone()}const vi="all";function ul(n){if(!(!n||n===vi))return n}function gl(n,t){if(n==null)return!0;if(Array.isArray(n)){if(n.length===0||n.includes(vi))return!0;const s=n.filter(r=>r!==vi);return s.length===0||t==null?!0:s.includes(t)}const e=ul(n);return!e||t==null?!0:t===e}function Eo(n){const t=n==null?void 0:n.bounds;if(t&&typeof t.width=="number"&&typeof t.height=="number"&&t.width>0&&t.height>0)return{left:typeof t.left=="number"?t.left:0,top:typeof t.top=="number"?t.top:0,width:t.width,height:t.height};if(Array.isArray(n.children))for(const e of n.children){const s=Eo(e);if(s)return s}return null}const dl=(n,t)=>{var r;const e=Math.max(1,Number(t.canvasWidth)||1);let s=Number(t.canvasHeight);if(!s||!Number.isFinite(s)){const i=Array.isArray(n)?n.find(o=>(o==null?void 0:o.name)==="bg"):null;s=Math.max(1,Number((r=i==null?void 0:i.bounds)==null?void 0:r.height)||e)}return{psdW:e,psdH:s}},fl=(n,t,e,s)=>{const r=Math.max(1,n),i=Math.max(1,t),o=Math.max(1,e),a=Math.max(1,s),h=Math.min(o/r,a/i),l=(o-r*h)/2,c=(a-i*h)/2;return{scale:h,offsetX:l,offsetY:c}},pl=(n,t,e,s,r)=>{const{scale:i,offsetX:o,offsetY:a}=fl(t,e,s,r);return{left:o+n.left*i,top:a+n.top*i,width:n.width*i,height:n.height*i}},ml=(n,t="split")=>{var o;if(!Array.isArray(n))return[];const e=(a,h="split")=>{for(const l of a){if((l==null?void 0:l.name)===h&&(l==null?void 0:l.type)==="Group")return l;if(Array.isArray(l.children)){const c=e(l.children);if(c)return c}}return null},s=e(n,t),r=(o=s==null?void 0:s.children)!=null?o:[],i=[];for(const a of r){if((a==null?void 0:a.type)!=="Group"||a.id==null)continue;const h=Eo(a);h&&i.push({id:a.id,name:a.name||"",bounds:h})}return i},yl=(n,t)=>{var a,h,l;const r=((a=n==null?void 0:n.data)!=null?a:[]).filter(c=>gl(t,c==null?void 0:c.size)).find(c=>(c==null?void 0:c.type)==="SPLIT");if(!(r!=null&&r.jsonURL))return null;const i=(h=r.resources)!=null?h:[],o=new Map;for(const c of i){if(!(c!=null&&c.groupId))continue;const u=String(c.groupId);let g=o.get(u);g||(g={groupId:u,groupName:String((l=c.groupName)!=null?l:""),maskUrl:"",maskWidth:0,maskHeight:0},o.set(u,g)),c.groupName&&(g.groupName=String(c.groupName)),c.type==="MASK"&&c.url&&(g.maskUrl=c.url,g.maskWidth=Number(c.width)||0,g.maskHeight=Number(c.height)||0),c.type==="DOTTED_LINE"&&c.url&&(g.dottedLineUrl=c.url,g.dottedLineWidth=Number(c.width)||0,g.dottedLineHeight=Number(c.height)||0)}for(const[c,u]of[...o]){const g=!!(u.maskUrl&&u.maskWidth&&u.maskHeight),d=!!(u.dottedLineUrl&&u.dottedLineWidth&&u.dottedLineHeight)||!!(u.dottedLineUrl&&g);!g&&!d&&o.delete(c)}return o.size?{jsonURL:r.jsonURL,slicesByGroupId:o}:null},lr=(n,t="image/png",e)=>new Promise((s,r)=>{n.toBlob(i=>{if(!i){r(new Error("canvas toBlob failed"));return}s(i)},t,e)});function vl(n,t){if(t)return;const e=n.backgroundColor;return e!=null&&e!==""?String(e):"#ffffff"}const Po="guide-resource",cr=(n,t)=>{var s;const e=(s=n==null?void 0:n.customData)==null?void 0:s.role;return e===t||e==="guide"||e==="grid"},xl=n=>{var e;const t=(e=n==null?void 0:n.customData)==null?void 0:e.guideKind;return t==="split-piece-mask"||t==="split-piece-dotted"};function Ao(n,t=Po){var g,d,f;const e=Math.max(1,typeof n.getWidth=="function"?n.getWidth():1),s=Math.max(1,typeof n.getHeight=="function"?n.getHeight():1);let r=0,i=0,o=e,a=s;for(const p of(d=(g=n.getObjects)==null?void 0:g.call(n))!=null?d:[])if(!(cr(p,t)&&!xl(p))&&p.type!=="activeSelection"&&!((f=p.customData)!=null&&f.isPatternRect)&&!p.group&&typeof p.getBoundingRect=="function")try{const m=p.getBoundingRect(!0,!0);if(!m||!Number.isFinite(m.width)||!Number.isFinite(m.height))continue;r=Math.min(r,m.left),i=Math.min(i,m.top),o=Math.max(o,m.left+m.width),a=Math.max(a,m.top+m.height)}catch{}const l=n.backgroundImage;if(l&&typeof l.getBoundingRect=="function")try{const p=l.getBoundingRect(!0,!0);p&&Number.isFinite(p.width)&&Number.isFinite(p.height)&&(r=Math.min(r,p.left),i=Math.min(i,p.top),o=Math.max(o,p.left+p.width),a=Math.max(a,p.top+p.height))}catch{}const c=Math.max(1,Math.ceil(o-r)),u=Math.max(1,Math.ceil(a-i));return{minL:r,minT:i,maxR:o,maxB:a,width:c,height:u}}async function _l(n,t,e,s){var c;const r=document.createElement("canvas"),i=Ao(n,t),o=i.width,a=i.height,h=n;let l=null;try{l=new Fe(r,{width:o,height:a,renderOnAddRemove:!1,enableRetinaScaling:!!h.enableRetinaScaling,backgroundColor:vl(h,s)}),l.setViewportTransform([1,0,0,1,-i.minL,-i.minT]);const u=h.backgroundImage;if(!s&&u&&typeof u.clone=="function")try{l.backgroundImage=await u.clone()}catch{}const g=performance.now();for(const m of n.getObjects())if(!cr(m,t)&&m.type!=="activeSelection")try{const v=await m.clone();So(v)&&zh(m,v);const x=m.group;if(x){const S=typeof m.calcOwnMatrix=="function"?m.calcOwnMatrix():m.calcTransformMatrix(),w=typeof x.calcTransformMatrix=="function"?x.calcTransformMatrix():null,C=w?Qn.multiplyTransformMatrices(w,S):m.calcTransformMatrix(),b=Qn.qrDecompose(C);v.set({originX:"center",originY:"center",left:b.translateX,top:b.translateY,angle:b.angle,scaleX:b.scaleX,scaleY:b.scaleY,skewX:b.skewX,skewY:b.skewY,flipX:m.flipX,flipY:m.flipY}),(c=v.setCoords)==null||c.call(v)}l.add(v)}catch(v){return console.warn("[fabricMainCanvasSnapshot] offscreen clone failed:",m.type,v),null}const d=Math.round(performance.now()-g);l.requestRenderAll(),await new Promise(m=>requestAnimationFrame(()=>requestAnimationFrame(()=>m())));const f=l;if(typeof f.toBlob=="function"){const m=await f.toBlob({format:"png",quality:1,multiplier:e,enableRetinaScaling:!!l.enableRetinaScaling});return m!=null?m:null}const p=l.lowerCanvasEl;if(!p)return null;if(e<1){const m=Math.max(1,Math.floor(p.width*e)),v=Math.max(1,Math.floor(p.height*e)),x=document.createElement("canvas");x.width=m,x.height=v;const S=x.getContext("2d");return S?(S.imageSmoothingEnabled=!0,S.imageSmoothingQuality="medium",S.drawImage(p,0,0,p.width,p.height,0,0,m,v),await lr(x,"image/png")):null}return await lr(p,"image/png")}catch(u){return console.warn("[fabricMainCanvasSnapshot] offscreen export failed:",u),null}finally{if(l)try{await l.dispose()}catch{}}}async function wl(n,t,e){var o,a,h,l;const s=n;if(typeof s.toBlob=="function"){let c;try{c=n.getActiveObject(),c&&((o=s._discardActiveObject)==null||o.call(s));const u=await s.toBlob({format:"png",quality:1,multiplier:e,enableRetinaScaling:!!s.enableRetinaScaling,filter:g=>!cr(g,t)});return u!=null?u:null}catch(u){return console.warn("[fabricMainCanvasSnapshot] toBlob(filter) 导出失败:",u),null}finally{try{c&&((a=s._setActiveObject)==null||a.call(s,c)),n.renderAll()}catch{}}}const r=[];let i;try{for(const u of n.getObjects())cr(u,t)&&(r.push({obj:u,visible:u.visible!==!1}),u.set("visible",!1));i=n.getActiveObject(),i&&((h=n._discardActiveObject)==null||h.call(n)),n.renderAll();const c=n.lowerCanvasEl;if(!c)return null;if(e<1){const u=Math.max(1,Math.floor(c.width*e)),g=Math.max(1,Math.floor(c.height*e)),d=document.createElement("canvas");d.width=u,d.height=g;const f=d.getContext("2d");return f?(f.imageSmoothingEnabled=!0,f.imageSmoothingQuality="medium",f.drawImage(c,0,0,c.width,c.height,0,0,u,g),await lr(d,"image/png")):null}return await lr(c,"image/png")}catch(c){return console.warn("[fabricMainCanvasSnapshot] 导出主画布失败:",c),null}finally{for(const{obj:c,visible:u}of r)try{c.set("visible",u)}catch{}try{i&&((l=n._setActiveObject)==null||l.call(n,i)),n.renderAll()}catch{}}}async function Fo(n,t){var h;const e=(h=t==null?void 0:t.guideResourceRole)!=null?h:Po,s=(t==null?void 0:t.multiplier)!=null&&t.multiplier>0?t.multiplier:1,r=!!(t!=null&&t.useIdentityViewport),i=(t==null?void 0:t.transparentBackground)===!0;if(r){const l=await _l(n,e,s,i);if(l)return l;if(i)return console.warn("[fabricMainCanvasSnapshot] 透明底离屏导出失败,不再回退主画布直读(会带白底)"),null;console.warn("[fabricMainCanvasSnapshot] 离屏导出失败,回退为临时单位视口")}let o=null;const a=()=>{if(!(!r||!o||o.length<6))try{n.setViewportTransform(o),n.requestRenderAll()}catch{}};try{if(r){const c=n.viewportTransform;o=Array.isArray(c)&&c.length>=6?[...c]:[1,0,0,1,0,0],n.setViewportTransform([1,0,0,1,0,0]),n.requestRenderAll(),await new Promise(u=>requestAnimationFrame(()=>requestAnimationFrame(()=>u())))}return await wl(n,e,s)}finally{a()}}const Lo=1e3,jo=1600;async function xi(n,t){if(n&&typeof n=="object")return n;if(typeof n!="string"||!n.trim())throw new Error("JSON 入参为空");let e=_t.forceHttpsAsset(n.trim());t&&(e+=(e.includes("?")?"&":"?")+"file_token="+encodeURIComponent(t));let s=null;for(let r=0;r<3;r++){try{const i=await fetch(e);if(i.ok)return await i.json();if(i.status<500)throw new Error(`加载 JSON 失败 HTTP ${i.status}: ${e.slice(0,80)}`);s=new Error(`加载 JSON 失败 HTTP ${i.status}: ${e.slice(0,80)}`)}catch(i){if(s=i,i instanceof Error&&/HTTP 4\d\d/.test(i.message))throw i}r<2&&await new Promise(i=>setTimeout(i,200*(r+1)))}throw s instanceof Error?s:new Error("加载 JSON 失败: "+e.slice(0,80))}function Sl(n,t,e){var m,v;const s=n!=null&&n.stateMap&&typeof n.stateMap=="object"?n.stateMap:{},r=Number(n==null?void 0:n.designCanvasSize)>0?Number(n.designCanvasSize):Lo,i=Number(n==null?void 0:n.designCanvasHeight)>0?Number(n.designCanvasHeight):jo,o=String((m=e!=null?e:n==null?void 0:n.selectedSize)!=null?m:"").trim(),a=x=>{const S=String(x!=null?x:"").trim().toLowerCase();return S==="default"||S==="all"||S==="common"?"":S},h=a(o),c=(Array.isArray(n==null?void 0:n.data)?n.data:[]).filter(x=>(x==null?void 0:x.type)===t),u=c.filter(x=>{var S,w;return!o||String((S=x==null?void 0:x.size)!=null?S:"")===o||String((w=x==null?void 0:x.size)!=null?w:"")==="default"}),g=u[u.length-1]||c[c.length-1]||null,d=g&&typeof g.jsonURL=="object"?g.jsonURL:null,f=Array.isArray(g==null?void 0:g.resources)?g.resources:[],p=[];for(const x of Object.keys(s)){let S="";if(x.includes("::")){const[k,P]=x.split("::");if(h&&a(P!=null?P:"")!==h)continue;S=k}else S=x;const w=s[x];if(!w||typeof w!="object")continue;const C=Number(w.designCanvasSize)>0?Number(w.designCanvasSize):r,b=Number(w.designCanvasHeight)>0?Number(w.designCanvasHeight):i,M=f.filter(k=>{var P;return String((P=k==null?void 0:k.groupId)!=null?P:"")===String(S)}),T=((v=M.find(k=>k==null?void 0:k.groupName))==null?void 0:v.groupName)||"";p.push({groupId:String(S),name:T,state:w,savedCanvasW:C,savedCanvasH:b,resources:M,guideline:d})}return p}function Cl(n,t){return!n||!t?n:mi(n,t)}function _i(n){return new Promise((t,e)=>{const s=new Image;s.crossOrigin="anonymous",s.onload=()=>t(s),s.onerror=()=>e(new Error("图片加载失败: "+n.slice(0,80))),s.src=_t.forceHttpsAsset(n)})}async function wi(n,t){if(n&&/^https?:/i.test(n)){try{const e=await Do(n,{mode:"cors"});if(e.ok)return await _i(URL.createObjectURL(await e.blob()))}catch{}return await _i(Cl(n,t))}return await _i(n)}function Si(n,t="image/png",e){return new Promise((s,r)=>{n.toBlob(i=>i?s(i):r(new Error("canvas.toBlob 返回空")),t,e)})}async function bl(n,t){var s,r,i,o,a,h,l,c,u,g;const e=(r=(s=n.getObjects)==null?void 0:s.call(n))!=null?r:[];for(const d of e){if(!((i=d==null?void 0:d.customData)!=null&&i.isPatternRect))continue;const f=d.customData.patternSource||d.customData.savedSrc;if(!(!f||typeof f!="string"))try{const p=await wi(f,t),m=(o=d.customData.patternScale)!=null?o:100,v=Math.max(.01,Uh(m)/100),x=qh(p),{tw:S,th:w}=Kh(d.customData,x,{patternTileWidth:d.patternTileWidth,patternTileHeight:d.patternTileHeight});typeof d.setPatternElement=="function"?d.setPatternElement(p):d.patternElement=p,d.patternTileWidth=S,d.patternTileHeight=w,d.patternScale=v;const C=ui(d);d.patternGapX=C.x,d.patternGapY=C.y,d.customData={...d.customData||{},patternTileWidth:S,patternTileHeight:w,patternGapX:C.x,patternGapY:C.y};const b=typeof((a=d.customData)==null?void 0:a.patternPhaseX)=="number"?d.customData.patternPhaseX:typeof((h=d.fill)==null?void 0:h.offsetX)=="number"?((l=d.left)!=null?l:0)+d.fill.offsetX:d.patternPhaseX||0,M=typeof((c=d.customData)==null?void 0:c.patternPhaseY)=="number"?d.customData.patternPhaseY:typeof((u=d.fill)==null?void 0:u.offsetY)=="number"?((g=d.top)!=null?g:0)+d.fill.offsetY:d.patternPhaseY||0;typeof d.setPatternPhase=="function"?d.setPatternPhase(b,M):(d.patternPhaseX=b,d.patternPhaseY=M),d.objectCaching=!1,d.dirty=!0}catch(p){console.warn("[productionRender] rebuildPattern 失败",p)}}}async function Io(n,t){var v;(v=n.renderAll)==null||v.call(n);const e=n.getWidth?n.getWidth():1,s=n.getHeight?n.getHeight():1,r=n.getElement?n.getElement():n.lowerCanvasEl;if(!r)throw new Error("无法取得 Fabric 画布元素");const i=await Si(r),o=await createImageBitmap(i),a=o.width/e,h=o.height/s,l=Math.max(0,Math.floor(t.left*a)),c=Math.max(0,Math.floor(t.top*h)),u=Math.max(1,Math.min(o.width-l,Math.ceil(t.width*a))),g=Math.max(1,Math.min(o.height-c,Math.ceil(t.height*h))),d=Math.max(1,Math.round(t.width)),f=Math.max(1,Math.round(t.height)),p=document.createElement("canvas");p.width=d,p.height=f;const m=p.getContext("2d");return m?(m.imageSmoothingEnabled=!0,m.imageSmoothingQuality="high",m.drawImage(o,l,c,u,g,0,0,d,f),o.close(),Si(p)):(o.close(),i)}async function Ro(n,t){const e=Math.max(1,Math.round(n.savedCanvasW)),s=Math.max(1,Math.round(n.savedCanvasH)),r=document.createElement("canvas");r.width=e,r.height=s;const i=new ei(r,{width:e,height:s,preserveObjectStacking:!0,enableRetinaScaling:!1,renderOnAddRemove:!1}),o=JSON.parse(JSON.stringify(n.state)),a=Array.isArray(o.objects)?o.objects:[];let h=0,l=0,c=0;for(const u of a)if(String(u==null?void 0:u.type).toLowerCase()==="image"&&typeof u.src=="string"&&/^https?:/i.test(u.src)){h++;try{const g=await Do(u.src,{mode:"cors"});g.ok?(u.src=URL.createObjectURL(await g.blob()),l++):(c++,console.warn(`[productionRender] 设计图 fetch !ok status=${g.status} ${String(u.src).slice(0,80)}`))}catch(g){c++,console.warn(`[productionRender] 设计图 fetch 异常 ${String(u.src).slice(0,80)}`,g)}}return await i.loadFromJSON(o,(u,g)=>{var d;String(g==null?void 0:g.type).toLowerCase()==="image"&&((d=g.set)==null||d.call(g,{crossOrigin:"anonymous"}))}),console.log(`[productionRender] loadFromJSON done piece=${n.groupId} jsonObjs=${a.length} httpImg(total/ok/fail)=${h}/${l}/${c} loadedObjs=${i.getObjects().length} loadedTypes=${JSON.stringify(i.getObjects().map(u=>u.type))}`),await bl(i,t),i.renderAll(),{canvas:i,W:e,H:s}}async function Tl(n,t,e=!1){var o;const{canvas:s,W:r,H:i}=await Ro(n,t);try{const a=(n.resources||[]).find(c=>(c==null?void 0:c.type)==="MASK");if(console.log(`[productionRender] piece=${n.groupId} name=${n.name} canvas=${r}x${i} objects=${s.getObjects().length} mask=${a!=null&&a.url?"Y":"N"} restoreOnly=${e}`),e){const c=await Fo(s,{useIdentityViewport:!0,transparentBackground:!0});return c!=null?c:await Io(s,{left:0,top:0,width:r,height:i})}const h=(n.resources||[]).find(c=>(c==null?void 0:c.type)==="MASK");let l={left:0,top:0,width:r,height:i};if(h!=null&&h.url){const c=Number(h.width)||1e3,u=Number(h.height)||1e3,g=Math.min(r/c,i/u),d=c*g,f=u*g,p=(r-d)/2,m=(i-f)/2,v=await wi(h.url,t),x=new Et(v,{left:p+d/2,top:m+f/2,originX:"center",originY:"center",scaleX:d/c,scaleY:f/u,selectable:!1,evented:!1,globalCompositeOperation:"destination-in"});s.add(x),s.renderAll(),l={left:p,top:m,width:d,height:f}}return await Io(s,l)}finally{try{(o=s.dispose)==null||o.call(s)}catch{}}}async function Ol(n,t,e=!1){const s=[];for(const r of n)try{const i=await Tl(r,t,e);i&&s.push({id:r.groupId,name:r.name,blob:i})}catch(i){console.warn("[productionRender] 分片渲染失败",r.groupId,r.name,i)}return s}function Bo(n,t,e){var a;const s=Array.isArray(n==null?void 0:n.data)?n.data:[],r=String((a=e!=null?e:n==null?void 0:n.selectedSize)!=null?a:"").trim(),i=s.filter(h=>(h==null?void 0:h.type)===t),o=i.filter(h=>{var l;return!r||String((l=h==null?void 0:h.size)!=null?l:"")===r});return o[o.length-1]||i.find(h=>{var l;return String((l=h==null?void 0:h.size)!=null?l:"")==="default"})||i[i.length-1]||null}function Ml(n,t){var d,f,p;const e=n!=null&&n.stateMap&&typeof n.stateMap=="object"?n.stateMap:{},s=Number(n==null?void 0:n.designCanvasSize)>0?Number(n.designCanvasSize):Lo,r=Number(n==null?void 0:n.designCanvasHeight)>0?Number(n.designCanvasHeight):jo,i=String((d=t!=null?t:n==null?void 0:n.selectedSize)!=null?d:"").trim(),o=Bo(n,"COMPLETE",i),a=String((p=(f=(Array.isArray(o==null?void 0:o.resources)?o.resources:[]).find(m=>(m==null?void 0:m.type)==="MASK"))==null?void 0:f.groupId)!=null?p:""),h=Object.keys(e);let l=a&&h.find(m=>m===`${a}::${i}`)||a&&h.find(m=>m===a)||i&&h.find(m=>m.endsWith(`::${i}`))||h[0];if(!l)return null;const c=e[l];if(!c||typeof c!="object")return null;const u=Number(c.designCanvasSize)>0?Number(c.designCanvasSize):s,g=Number(c.designCanvasHeight)>0?Number(c.designCanvasHeight):r;return{groupId:a||l,name:"complete",state:c,savedCanvasW:u,savedCanvasH:g,resources:[]}}function kl(n,t,e,s,r,i){const o=Math.max(0,Math.min(n,e)),a=Math.max(0,Math.min(t,s)),h=Math.max(0,Math.min(n,e+r)),l=Math.max(0,Math.min(t,s+i)),c=Math.max(0,Math.floor(h-o)),u=Math.max(0,Math.floor(l-a));return{sx:o,sy:a,sw:c,sh:u,dx:Math.round(o-e),dy:Math.round(a-s)}}async function Dl(n,t,e,s,r,i,o){var v;const a=yl(r,i);if(!((v=a==null?void 0:a.slicesByGroupId)!=null&&v.size))return console.warn("[productionRender] COMPLETE: 无 SPLIT slices 配置,无法裁切"),[];const h=Bo(r,"SPLIT",i),l=h&&typeof h.jsonURL=="object"?h.jsonURL:await xi(h==null?void 0:h.jsonURL,o),c=Array.isArray(l==null?void 0:l.layerList)?l.layerList:[],u=ml(c),{psdW:g,psdH:d}=dl(c,l),f=n.width/Math.max(1,t.width),p=n.height/Math.max(1,t.height);if(console.log(`[productionRender] COMPLETE children=${u.length} slices=${a.slicesByGroupId.size} psd=${g}x${d} canvas=${e}x${s} ext=[${Math.round(t.minL)},${Math.round(t.minT)} ${Math.round(t.width)}x${Math.round(t.height)}] base=${n.width}x${n.height}`,u.map(x=>`${x.id}/${x.name}`)),!u.length)return[];const m=[];for(const x of u){const S=a.slicesByGroupId.get(String(x.id));if(!(S!=null&&S.maskUrl))continue;const w=pl(x.bounds,g,d,e,s),C=Math.round((w.left-t.minL)*f),b=Math.round((w.top-t.minT)*p),M=Math.max(1,Math.round(w.width*f)),T=Math.max(1,Math.round(w.height*p)),k=document.createElement("canvas");k.width=M,k.height=T;const P=k.getContext("2d");if(!P)continue;P.imageSmoothingEnabled=!0,P.imageSmoothingQuality="high";const F=kl(n.width,n.height,C,b,M,T);F.sw>0&&F.sh>0&&P.drawImage(n,F.sx,F.sy,F.sw,F.sh,F.dx,F.dy,F.sw,F.sh);try{const D=await wi(S.maskUrl,o),L=D.naturalWidth||D.width,I=D.naturalHeight||D.height;P.globalCompositeOperation="destination-in",P.drawImage(D,0,0,L,I,0,0,M,T),P.globalCompositeOperation="source-over"}catch(D){console.warn("[productionRender] COMPLETE mask 加载失败",x.id,x.name,D)}m.push({id:String(x.id),name:x.name,blob:await Si(k)})}return m}async function $o(n){var c,u,g,d,f,p,m;n.fileToken&&al(n.fileToken);const t=await xi(n.fabricJson,n.fileToken),e=await xi(n.productJson,n.fileToken),s=(t==null?void 0:t.selectedMode)==="SPLIT"?"SPLIT":"COMPLETE",r=n.fabricDirect===!0,i=n.imageFormat==="jpeg"?"jpeg":"png",o=String((c=n.size)!=null?c:"").trim(),a=!o||/^(default|all|common)$/i.test(o)?String((u=t==null?void 0:t.selectedSize)!=null?u:"").trim():o;let h=[];if(s==="COMPLETE"){const v=Ml(t,a);if(!v)throw new Error(`COMPLETE:未解析到尺码「${a||(t==null?void 0:t.selectedSize)||""}」的整稿设计`);console.log(`[productionRender] mode=COMPLETE size=${a} (raw=${o}) baseGid=${v.groupId} base=${v.savedCanvasW}x${v.savedCanvasH} objs=${(f=(d=(g=v.state)==null?void 0:g.objects)==null?void 0:d.length)!=null?f:0} restoreOnly=${r}`);const{canvas:x,W:S,H:w}=await Ro(v,n.fileToken);try{const C=Ao(x),b=await Fo(x,{useIdentityViewport:!0,transparentBackground:!0});if(!b)throw new Error("COMPLETE:整稿 base 渲染失败");if(r)return b;const M=await createImageBitmap(b);try{h=await Dl(M,C,S,w,t,a,n.fileToken)}finally{(p=M.close)==null||p.call(M)}}finally{(m=x.dispose)==null||m.call(x)}}else{const v=Sl(t,s,a);if(console.log(`[productionRender] mode=${s} size=${a} (raw=${o}) tasks=${v.length} restoreOnly=${r}`,v.map(x=>{var S,w,C;return`${x.groupId}/${x.name}/${x.savedCanvasW}x${x.savedCanvasH}/objs=${(C=(w=(S=x.state)==null?void 0:S.objects)==null?void 0:w.length)!=null?C:0}/res=${x.resources.length}`})),!v.length)throw new Error(`未解析到尺码「${a||(t==null?void 0:t.selectedSize)||""}」的分片设计(检查 size 与 stateMap 键)`);h=await Ol(v,n.fileToken,r)}console.log(`[productionRender] bitmaps=${h.length}`,h.map(v=>`${v.id}/${v.name}/${Math.round(v.blob.size/1024)}KB`));const l=await Rh(h,e,i);return console.log(`[productionRender] compose drawn=[${l.drawn.join(",")}] skipped=[${l.skipped.join(",")}] out=${l.canvasWidth}x${l.canvasHeight}`),l.blob}return typeof window!="undefined"&&(window.generateProductionImage=$o),Bt.generateProductionImage=$o,Object.defineProperty(Bt,Symbol.toStringTag,{value:"Module"}),Bt})({});