@nasser-sw/fabric 7.0.1-beta42 → 7.0.1-beta43

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.min.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).fabric={})}(this,function(t){"use strict";function _defineProperty(t,e,i){return(e=_toPropertyKey(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function _toPrimitive(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var s=i.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return"symbol"==typeof e?e:e+""}class BaseConfiguration{constructor(){_defineProperty(this,"browserShadowBlurConstant",1),_defineProperty(this,"DPI",96),_defineProperty(this,"devicePixelRatio","undefined"!=typeof window?window.devicePixelRatio:1),_defineProperty(this,"perfLimitSizeTotal",2097152),_defineProperty(this,"maxCacheSideLimit",4096),_defineProperty(this,"minCacheSideLimit",256),_defineProperty(this,"disableStyleCopyPaste",!1),_defineProperty(this,"enableGLFiltering",!0),_defineProperty(this,"textureSize",4096),_defineProperty(this,"forceGLPutImageData",!1),_defineProperty(this,"cachesBoundsOfCurve",!1),_defineProperty(this,"fontPaths",{}),_defineProperty(this,"NUM_FRACTION_DIGITS",4)}}class Configuration extends BaseConfiguration{constructor(t){super(),this.configure(t)}configure(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,t)}addFonts(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.fontPaths={...this.fontPaths,...t}}removeFonts(){let t;(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).forEach(t=>{delete this.fontPaths[t]})}clearFonts(){this.fontPaths={}}restoreDefaults(t){const e=new BaseConfiguration,i=(null==t?void 0:t.reduce((t,i)=>(t[i]=e[i],t),{}))||e;this.configure(i)}}const e=new Configuration,log=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return console[t]("fabric",...i)};class FabricError extends Error{constructor(t,e){super(`fabric: ${t}`,e)}}class SignalAbortedError extends FabricError{constructor(t){super(`${t} 'options.signal' is in 'aborted' state`)}}class GLProbe{}class WebGLProbe extends GLProbe{testPrecision(t,e){const i=`precision ${e} float;\nvoid main(){}`,s=t.createShader(t.FRAGMENT_SHADER);return!!s&&(t.shaderSource(s,i),t.compileShader(s),!!t.getShaderParameter(s,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find(t=>this.testPrecision(e,t)),e.getExtension("WEBGL_lose_context").loseContext(),log("log",`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const i={},getEnv$1=()=>({document:document,window:window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new WebGLProbe,dispose(){},copyPasteData:i});let s;const setEnv=t=>{s=t},getEnv=()=>s||(s=getEnv$1()),getFabricDocument=()=>getEnv().document,getFabricWindow=()=>getEnv().window,getDevicePixelRatio=()=>{var t;return Math.max(null!==(t=e.devicePixelRatio)&&void 0!==t?t:getFabricWindow().devicePixelRatio,1)};class Cache{constructor(){_defineProperty(this,"charWidthsCache",{}),_defineProperty(this,"boundsOfCurveCache",{})}getFontCache(t){let{fontFamily:e,fontStyle:i,fontWeight:s}=t;e=e.toLowerCase(),this.charWidthsCache[e]||(this.charWidthsCache[e]={});const n=this.charWidthsCache[e],r=`${i.toLowerCase()}_${(s+"").toLowerCase()}`;return n[r]||(n[r]={}),n[r]}clearFontCache(t){(t=(t||"").toLowerCase())?this.charWidthsCache[t]&&delete this.charWidthsCache[t]:this.charWidthsCache={}}limitDimsByArea(t){const{perfLimitSizeTotal:i}=e,s=Math.sqrt(i*t);return[Math.floor(s),Math.floor(i/s)]}}const n=new Cache;var r;const o="7.0.1-beta40";function noop(){}const a=Math.PI/2,h=Math.PI/4,l=2*Math.PI,c=Math.PI/180,d=Object.freeze([1,0,0,1,0,0]),u=16,g=2,f=.4477152502,p="center",m="left",y="top",x="bottom",v="right",_="none",C=/\r?\n/,b="moving",S="scaling",w="rotating",T="rotate",P="skewing",M="resizing",O="modifyPoly",k="modifyPath",D="changed",E="scale",A="scaleX",F="scaleY",L="skewX",j="skewY",I="fill",B="stroke",R="modified",W="json",H="svg";class ClassRegistry{constructor(){this[W]=new Map,this[H]=new Map}has(t){return this[W].has(t)}getClass(t){const e=this[W].get(t);if(!e)throw new FabricError(`No class registered for ${t}`);return e}setClass(t,e){e?this[W].set(e,t):(this[W].set(t.type,t),this[W].set(t.type.toLowerCase(),t))}getSVGClass(t){return this[H].get(t)}setSVGClass(t,e){this[H].set(null!=e?e:t.type.toLowerCase(),t)}}const X=new ClassRegistry;class AnimationRegistry extends Array{remove(t){const e=this.indexOf(t);e>-1&&this.splice(e,1)}cancelAll(){const t=this.splice(0);return t.forEach(t=>t.abort()),t}cancelByCanvas(t){if(!t)return[];const e=this.filter(e=>{var i;return e.target===t||"object"==typeof e.target&&(null===(i=e.target)||void 0===i?void 0:i.canvas)===t});return e.forEach(t=>t.abort()),e}cancelByTarget(t){if(!t)return[];const e=this.filter(e=>e.target===t);return e.forEach(t=>t.abort()),e}}const $=new AnimationRegistry;class Observable{constructor(){_defineProperty(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),"object"==typeof t)return Object.entries(t).forEach(t=>{let[e,i]=t;this.on(e,i)}),()=>this.off(t);if(e){const i=t;return this.__eventListeners[i]||(this.__eventListeners[i]=[]),this.__eventListeners[i].push(e),()=>this.off(i,e)}return()=>!1}once(t,e){if("object"==typeof t){const e=[];return Object.entries(t).forEach(t=>{let[i,s]=t;e.push(this.once(i,s))}),()=>e.forEach(t=>t())}if(e){const i=this.on(t,function onceHandler(){for(var t=arguments.length,s=new Array(t),n=0;n<t;n++)s[n]=arguments[n];e.call(this,...s),i()});return i}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const i=this.__eventListeners[t],s=i.indexOf(e);s>-1&&i.splice(s,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(void 0===t)for(const t in this.__eventListeners)this._removeEventListener(t);else"object"==typeof t?Object.entries(t).forEach(t=>{let[e,i]=t;this._removeEventListener(e,i)}):this._removeEventListener(t,e)}fire(t,e){var i;if(!this.__eventListeners)return;const s=null===(i=this.__eventListeners[t])||void 0===i?void 0:i.concat();if(s)for(let t=0;t<s.length;t++)s[t].call(this,e||{})}}const removeFromArray=(t,e)=>{const i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},cos=t=>{if(0===t)return 1;const e=undefined;switch(Math.abs(t)/a){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin=t=>{if(0===t)return 0;const e=t/a,i=Math.sign(t);switch(e){case 1:return i;case 2:return 0;case 3:return-i}return Math.sin(t)};class Point{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;"object"==typeof t?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new Point(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new Point(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new Point(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new Point(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new Point(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new Point(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new Point(this.x/t.x,this.y/t.y)}scalarDivide(t){return new Point(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&&void 0!==arguments[1]?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new Point(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}midPointFrom(t){return this.lerp(t)}min(t){return new Point(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new Point(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,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i}clone(){return new Point(this.x,this.y)}rotate(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:z;const i=sin(t),s=cos(t),n=this.subtract(e),r=undefined;return new Point(n.x*s-n.y*i,n.x*i+n.y*s).add(e)}transform(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Point(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 z=new Point(0,0),isCollection=t=>!!t&&Array.isArray(t._objects);function createCollectionMixin(t){class Collection extends t{constructor(){super(...arguments),_defineProperty(this,"_objects",[])}_onObjectAdded(t){}_onObjectRemoved(t){}_onStackOrderChanged(t){}add(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const s=this._objects.push(...e);return e.forEach(t=>this._onObjectAdded(t)),s}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return this._objects.splice(t,0,...i),i.forEach(t=>this._onObjectAdded(t)),this._objects.length}remove(){const t=this._objects,e=[];for(var i=arguments.length,s=new Array(i),n=0;n<i;n++)s[n]=arguments[n];return s.forEach(i=>{const s=t.indexOf(i);-1!==s&&(t.splice(s,1),e.push(i),this._onObjectRemoved(i))}),e}forEachObject(t){this.getObjects().forEach((e,i,s)=>t(e,i,s))}getObjects(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return 0===e.length?[...this._objects]:this._objects.filter(t=>t.isType(...e))}item(t){return this._objects[t]}isEmpty(){return 0===this._objects.length}size(){return this._objects.length}contains(t,e){return!!this._objects.includes(t)||!!e&&this._objects.some(e=>e instanceof Collection&&e.contains(t,!0))}complexity(){return this._objects.reduce((t,e)=>t+=e.complexity?e.complexity():0,0)}sendObjectToBack(t){return!(!t||t===this._objects[0])&&(removeFromArray(this._objects,t),this._objects.unshift(t),this._onStackOrderChanged(t),!0)}bringObjectToFront(t){return!(!t||t===this._objects[this._objects.length-1])&&(removeFromArray(this._objects,t),this._objects.push(t),this._onStackOrderChanged(t),!0)}sendObjectBackwards(t,e){if(!t)return!1;const i=this._objects.indexOf(t);if(0!==i){const s=this.findNewLowerIndex(t,i,e);return removeFromArray(this._objects,t),this._objects.splice(s,0,t),this._onStackOrderChanged(t),!0}return!1}bringObjectForward(t,e){if(!t)return!1;const i=this._objects.indexOf(t);if(i!==this._objects.length-1){const s=this.findNewUpperIndex(t,i,e);return removeFromArray(this._objects,t),this._objects.splice(s,0,t),this._onStackOrderChanged(t),!0}return!1}moveObjectTo(t,e){return t!==this._objects[e]&&(removeFromArray(this._objects,t),this._objects.splice(e,0,t),this._onStackOrderChanged(t),!0)}findNewLowerIndex(t,e,i){let s;if(i){s=e;for(let i=e-1;i>=0;--i)if(t.isOverlapping(this._objects[i])){s=i;break}}else s=e-1;return s}findNewUpperIndex(t,e,i){let s;if(i){s=e;for(let i=e+1;i<this._objects.length;++i)if(t.isOverlapping(this._objects[i])){s=i;break}}else s=e+1;return s}collectObjects(t){let{left:e,top:i,width:s,height:n}=t,{includeIntersecting:r=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=[],a=new Point(e,i),h=a.add(new Point(s,n));for(let t=this._objects.length-1;t>=0;t--){const e=this._objects[t];e.selectable&&e.visible&&(r&&e.intersectsWithRect(a,h)||e.isContainedWithinRect(a,h)||r&&e.containsPoint(a)||r&&e.containsPoint(h))&&o.push(e)}return o}}return Collection}class CommonMethods extends Observable{_setOptions(){let t=arguments.length>0&&void 0!==arguments[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"object"==typeof t?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this}get(t){return this[t]}}function requestAnimFrame(t){return getFabricWindow().requestAnimationFrame(t)}function cancelAnimFrame(t){return getFabricWindow().cancelAnimationFrame(t)}let Y=0;const uid=()=>Y++,createCanvasElement=()=>{const t=getFabricDocument().createElement("canvas");if(!t||void 0===t.getContext)throw new FabricError("Failed to create `canvas` element");return t},createImage=()=>getFabricDocument().createElement("img"),copyCanvasElement=t=>{var e;const i=createCanvasElementFor(t);return null===(e=i.getContext("2d"))||void 0===e||e.drawImage(t,0,0),i},createCanvasElementFor=t=>{const e=createCanvasElement();return e.width=t.width,e.height=t.height,e},toDataURL=(t,e,i)=>t.toDataURL(`image/${e}`,i),isHTMLCanvas=t=>!!t&&void 0!==t.getContext,toBlob=(t,e,i)=>new Promise((s,n)=>{t.toBlob(s,`image/${e}`,i)}),degreesToRadians=t=>t*c,radiansToDegrees=t=>t/c,isIdentityMatrix=t=>t.every((t,e)=>t===d[e]),transformPoint=(t,e,i)=>new Point(t).transform(e,i),invertTransform=t=>{const e=1/(t[0]*t[3]-t[1]*t[2]),i=[e*t[3],-e*t[1],-e*t[2],e*t[0],0,0],{x:s,y:n}=new Point(t[4],t[5]).transform(i,!0);return i[4]=-s,i[5]=-n,i},multiplyTransformMatrices=(t,e,i)=>[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],i?0:t[0]*e[4]+t[2]*e[5]+t[4],i?0:t[1]*e[4]+t[3]*e[5]+t[5]],multiplyTransformMatrixArray=(t,e)=>t.reduceRight((t,i)=>i&&t?multiplyTransformMatrices(i,t,e):i||t,void 0)||d.concat(),calcPlaneRotation=t=>{let[e,i]=t;return Math.atan2(i,e)},qrDecompose=t=>{const e=calcPlaneRotation(t),i=Math.pow(t[0],2)+Math.pow(t[1],2),s=Math.sqrt(i),n=(t[0]*t[3]-t[2]*t[1])/s,r=Math.atan2(t[0]*t[2]+t[1]*t[3],i);return{angle:radiansToDegrees(e),scaleX:s,scaleY:n,skewX:radiansToDegrees(r),skewY:0,translateX:t[4]||0,translateY:t[5]||0}},createTranslateMatrix=function(t){let e;return[1,0,0,1,t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0]};function createRotateMatrix(){let{angle:t=0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{x:e=0,y:i=0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=degreesToRadians(t),n=cos(s),r=sin(s);return[n,r,-r,n,e?e-(n*e-r*i):0,i?i-(r*e+n*i):0]}const createScaleMatrix=function(t){let e;return[t,0,0,arguments.length>1&&void 0!==arguments[1]?arguments[1]:t,0,0]},angleToSkew=t=>Math.tan(degreesToRadians(t)),createSkewXMatrix=t=>[1,0,angleToSkew(t),1,0,0],createSkewYMatrix=t=>[1,angleToSkew(t),0,1,0,0],calcDimensionsMatrix=t=>{let{scaleX:e=1,scaleY:i=1,flipX:s=!1,flipY:n=!1,skewX:r=0,skewY:o=0}=t,a=createScaleMatrix(s?-e:e,n?-i:i);return r&&(a=multiplyTransformMatrices(a,createSkewXMatrix(r),!0)),o&&(a=multiplyTransformMatrices(a,createSkewYMatrix(o),!0)),a},composeMatrix=t=>{const{translateX:e=0,translateY:i=0,angle:s=0}=t;let n=createTranslateMatrix(e,i);s&&(n=multiplyTransformMatrices(n,createRotateMatrix({angle:s})));const r=calcDimensionsMatrix(t);return isIdentityMatrix(r)||(n=multiplyTransformMatrices(n,r)),n},loadImage=function(t){let{signal:e,crossOrigin:i=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise(function(s,n){if(e&&e.aborted)return n(new SignalAbortedError("loadImage"));const r=createImage();let o;e&&(o=function(t){r.src="",n(t)},e.addEventListener("abort",o,{once:!0}));const done=function(){r.onload=r.onerror=null,o&&(null==e||e.removeEventListener("abort",o)),s(r)};t?(r.onload=done,r.onerror=function(){o&&(null==e||e.removeEventListener("abort",o)),n(new FabricError(`Error loading ${r.src}`))},i&&(r.crossOrigin=i),r.src=t):done()})},enlivenObjects=function(t){let{signal:e,reviver:i=noop}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((s,n)=>{const r=[];e&&e.addEventListener("abort",n,{once:!0}),Promise.all(t.map(t=>X.getClass(t.type).fromObject(t,{signal:e}).then(e=>(i(t,e),r.push(e),e)))).then(s).catch(t=>{r.forEach(t=>{t.dispose&&t.dispose()}),n(t)}).finally(()=>{e&&e.removeEventListener("abort",n)})})},enlivenObjectEnlivables=function(t){let{signal:e}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((i,s)=>{const n=[];e&&e.addEventListener("abort",s,{once:!0});const r=Object.values(t).map(t=>t&&t.type&&X.has(t.type)?enlivenObjects([t],{signal:e}).then(t=>{let[e]=t;return n.push(e),e}):t),o=Object.keys(t);Promise.all(r).then(t=>t.reduce((t,e,i)=>(t[o[i]]=e,t),{})).then(i).catch(t=>{n.forEach(t=>{t.dispose&&t.dispose()}),s(t)}).finally(()=>{e&&e.removeEventListener("abort",s)})})},pick=function(t){let e;return(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).reduce((e,i)=>(i in t&&(e[i]=t[i]),e),{})},pickBy=(t,e)=>Object.keys(t).reduce((i,s)=>(e(t[s],s,t)&&(i[s]=t[s]),i),{}),toFixed=(t,e)=>parseFloat(Number(t).toFixed(e)),matrixToSVG=t=>"matrix("+t.map(t=>toFixed(t,e.NUM_FRACTION_DIGITS)).join(" ")+")",isFiller=t=>!!t&&void 0!==t.toLive,isSerializableFiller=t=>!!t&&"function"==typeof t.toObject,isPattern=t=>!!t&&void 0!==t.offsetX&&"source"in t,isTextObject=t=>!!t&&"function"==typeof t._renderText,isPath=t=>!!t&&"function"==typeof t._renderPathCommands,isActiveSelection=t=>!!t&&"multiSelectionStacking"in t;function getScrollLeftTop(t){const e=t&&getDocumentFromElement(t);let i=0,s=0;if(!t||!e)return{left:i,top:s};let n=t;const r=e.documentElement,o=e.body||{scrollLeft:0,scrollTop:0};for(;n&&(n.parentNode||n.host)&&(n=n.parentNode||n.host,n===e?(i=o.scrollLeft||r.scrollLeft||0,s=o.scrollTop||r.scrollTop||0):(i+=n.scrollLeft||0,s+=n.scrollTop||0),1!==n.nodeType||"fixed"!==n.style.position););return{left:i,top:s}}const getDocumentFromElement=t=>t.ownerDocument||null,getWindowFromElement=t=>{var e;return(null===(e=t.ownerDocument)||void 0===e?void 0:e.defaultView)||null},setCanvasDimensions=function(t,e,i){let{width:s,height:n}=i,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;t.width=s,t.height=n,r>1&&(t.setAttribute("width",(s*r).toString()),t.setAttribute("height",(n*r).toString()),e.scale(r,r))},setCSSDimensions=(t,e)=>{let{width:i,height:s}=e;i&&(t.style.width="number"==typeof i?`${i}px`:i),s&&(t.style.height="number"==typeof s?`${s}px`:s)};function getElementOffset(t){var e;const i=t&&getDocumentFromElement(t),s={left:0,top:0};if(!i)return s;const n=(null===(e=getWindowFromElement(t))||void 0===e?void 0:e.getComputedStyle(t,null))||{};s.left+=parseInt(n.borderLeftWidth,10)||0,s.top+=parseInt(n.borderTopWidth,10)||0,s.left+=parseInt(n.paddingLeft,10)||0,s.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const o=i.documentElement;void 0!==t.getBoundingClientRect&&(r=t.getBoundingClientRect());const a=getScrollLeftTop(t);return{left:r.left+a.left-(o.clientLeft||0)+s.left,top:r.top+a.top-(o.clientTop||0)+s.top}}function makeElementUnselectable(t){return void 0!==t.onselectstart&&(t.onselectstart=()=>!1),t.style.userSelect=_,t}class StaticCanvasDOMManager{constructor(t){_defineProperty(this,"_originalCanvasStyle",void 0),_defineProperty(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=isHTMLCanvas(t)?t:t&&getFabricDocument().getElementById(t)||createCanvasElement();if(e.hasAttribute("data-fabric"))throw new FabricError("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:i}=t;const{el:s}=this.lower;s.classList.remove("lower-canvas"),s.removeAttribute("data-fabric"),s.setAttribute("width",`${e}`),s.setAttribute("height",`${i}`),s.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:i,ctx:s}=this.lower;setCanvasDimensions(i,s,t,e)}setCSSDimensions(t){setCSSDimensions(this.lower.el,t)}calcOffset(){return getElementOffset(this.lower.el)}dispose(){getEnv().dispose(this.lower.el),delete this.lower}}const V={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...d]};class StaticCanvas extends(createCollectionMixin(CommonMethods)){get lowerCanvasEl(){var t;return null===(t=this.elements.lower)||void 0===t?void 0:t.el}get contextContainer(){var t;return null===(t=this.elements.lower)||void 0===t?void 0:t.ctx}static getDefaults(){return StaticCanvas.ownDefaults}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?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 StaticCanvasDOMManager(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];const n=super.insertAt(t,...i);return i.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(log("warn","Canvas is trying to add an object that belongs to a different canvas.\nResulting to default behavior: removing object from previous canvas and adding to new canvas"),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?getDevicePixelRatio():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:i=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e){const e={width:this.width,height:this.height,...t};this.elements.setDimensions(e,this.getRetinaScaling()),this.hasLostContext=!0,this.width=e.width,this.height=e.height}i||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const i=t,s=[...this.viewportTransform],n=transformPoint(t,invertTransform(s));s[0]=e,s[3]=e;const r=transformPoint(n,s);s[4]+=i.x-r.x,s[5]+=i.y-r.y,this.setViewportTransform(s)}setZoom(t){this.zoomToPoint(new Point(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 Point(-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=requestAnimFrame(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,i=invertTransform(this.viewportTransform),s=transformPoint({x:0,y:0},i),n=transformPoint({x:t,y:e},i),r=s.min(n),o=s.max(n);return this.vptCoords={tl:r,tr:new Point(o.x,r.y),bl:new Point(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(cancelAnimFrame(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const i=this.viewportTransform,s=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),s&&(s._set("canvas",this),s.shouldCache(),s._transformDone=!0,s.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,s)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const i=this.viewportTransform;t.save(),t.transform(...i),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let i=0,s=e.length;i<s;++i)e[i]&&e[i].render(t)}_renderBackgroundOrOverlay(t,e){const i=this[`${e}Color`],s=this[`${e}Image`],n=this.viewportTransform,r=this[`${e}Vpt`];if(!i&&!s)return;const o=isFiller(i);if(i){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=o?i.toLive(t):i,r&&t.transform(...n),o){t.transform(1,0,0,1,i.offsetX||0,i.offsetY||0);const e=i.gradientTransform||i.patternTransform;e&&t.transform(...e)}t.fill(),t.restore()}if(s){t.save();const{skipOffscreen:e}=this;this.skipOffscreen=r,r&&t.transform(...n),s.render(t),this.skipOffscreen=e,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenterPoint(){return new Point(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new Point(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new Point(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 Point(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new Point(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return transformPoint(this.getCenterPoint(),invertTransform(this.viewportTransform))}_centerObject(t,e){t.setXY(e,p,p),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 i=this.clipPath,s=i&&!i.excludeFromExport?this._toObject(i,t,e):null;return{version:o,...pick(this,e),objects:this._objects.filter(t=>!t.excludeFromExport).map(i=>this._toObject(i,t,e)),...this.__serializeBgOverlay(t,e),...s?{clipPath:s}:null}}_toObject(t,e,i){let s;this.includeDefaultValues||(s=t.includeDefaultValues,t.includeDefaultValues=!1);const n=t[e](i);return this.includeDefaultValues||(t.includeDefaultValues=!!s),n}__serializeBgOverlay(t,e){const i={},s=this.backgroundImage,n=this.overlayImage,r=this.backgroundColor,o=this.overlayColor;return isFiller(r)?r.excludeFromExport||(i.background=r.toObject(e)):r&&(i.background=r),isFiller(o)?o.excludeFromExport||(i.overlay=o.toObject(e)):o&&(i.overlay=o),s&&!s.excludeFromExport&&(i.backgroundImage=this._toObject(s,t,e)),n&&!n.excludeFromExport&&(i.overlayImage=this._toObject(n,t,e)),i}toSVG(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const i=[];return this._setSVGPreamble(i,t),this._setSVGHeader(i,t),this.clipPath&&i.push(`<g clip-path="url(#${this.clipPath.clipPathId})" >\n`),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("</g>\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push("</svg>"),i.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')}_setSVGHeader(t,i){const s=i.width||`${this.width}`,n=i.height||`${this.height}`,r=e.NUM_FRACTION_DIGITS,a=i.viewBox;let h;if(a)h=`viewBox="${a.x} ${a.y} ${a.width} ${a.height}" `;else if(this.svgViewportTransformation){const t=this.viewportTransform;h=`viewBox="${toFixed(-t[4]/t[0],r)} ${toFixed(-t[5]/t[3],r)} ${toFixed(this.width/t[0],r)} ${toFixed(this.height/t[3],r)}" `}else h=`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="',n,'" ',h,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",o,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(i),"</defs>\n")}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId=`CLIPPATH_${uid()}`,`<clipPath id="${e.clipPathId}" >\n${e.toClipPathSVG(t.reviver)}</clipPath>\n`):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this[`${t}Color`];if(isFiller(e)){const i=this[`${t}Vpt`],s=this.viewportTransform,n={isType:()=>!1,width:this.width/(i?s[0]:1),height:this.height/(i?s[3]:1)};return e.toSVG(n,{additionalTransform:i?matrixToSVG(s):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],i={},s=e.fontPaths;this._objects.forEach(function add(e){t.push(e),isCollection(e)&&e._objects.forEach(add)}),t.forEach(t=>{if(!isTextObject(t))return;const{styles:e,fontFamily:n}=t;!i[n]&&s[n]&&(i[n]=!0,e&&Object.values(e).forEach(t=>{Object.values(t).forEach(t=>{let{fontFamily:e=""}=t;!i[e]&&s[e]&&(i[e]=!0)})}))});const n=Object.keys(i).map(t=>`\t\t@font-face {\n\t\t\tfont-family: '${t}';\n\t\t\tsrc: url('${s[t]}');\n\t\t}\n`).join("");return n?`\t<style type="text/css"><![CDATA[\n${n}]]></style>\n`:""}_setSVGObjects(t,e){this.forEachObject(i=>{i.excludeFromExport||this._setSVGObject(t,i,e)})}_setSVGObject(t,e,i){t.push(e.toSVG(i))}_setSVGBgOverlayImage(t,e,i){const s=this[e];s&&!s.excludeFromExport&&s.toSVG&&t.push(s.toSVG(i))}_setSVGBgOverlayColor(t,e){const i=this[`${e}Color`];if(i)if(isFiller(i)){const s=i.repeat||"",n=this.width,r=this.height,o=undefined,a=this[`${e}Vpt`]?matrixToSVG(invertTransform(this.viewportTransform)):"";t.push(`<rect transform="${a} translate(${n/2},${r/2})" x="${i.offsetX-n/2}" y="${i.offsetY-r/2}" width="${"repeat-y"!==s&&"no-repeat"!==s||!isPattern(i)?n:i.source.width}" height="${"repeat-x"!==s&&"no-repeat"!==s||!isPattern(i)?r:i.source.height}" fill="url(#SVGID_${i.id})"></rect>\n`)}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',i,'"',"></rect>\n")}loadFromJSON(t,e){let{signal:i}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)return Promise.reject(new FabricError("`json` is undefined"));const s="string"==typeof t?JSON.parse(t):t,{objects:n=[],backgroundImage:r,background:o,overlayImage:a,overlay:h,clipPath:l}=s,c=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([enlivenObjects(n,{reviver:e,signal:i}),enlivenObjectEnlivables({backgroundImage:r,backgroundColor:o,overlayImage:a,overlayColor:h,clipPath:l},{signal:i})]).then(t=>{let[e,i]=t;return this.clear(),this.add(...e),this.set(s),this.set(i),this.renderOnAddRemove=c,this})}clone(t){const e=this.toObject(t),i=undefined;return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=createCanvasElementFor(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{format:e="png",quality:i=1,multiplier:s=1,enableRetinaScaling:n=!1}=t,r=s*(n?this.getRetinaScaling():1);return toDataURL(this.toCanvasElement(r,t),e,i)}toBlob(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{format:e="png",quality:i=1,multiplier:s=1,enableRetinaScaling:n=!1}=t,r=s*(n?this.getRetinaScaling():1);return toBlob(this.toCanvasElement(r,t),e,i)}toCanvasElement(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,{width:e,height:i,left:s,top:n,filter:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=(e||this.width)*t,a=(i||this.height)*t,h=this.getZoom(),l=this.width,c=this.height,d=this.skipControlsDrawing,u=h*t,g=this.viewportTransform,f=undefined,p=undefined,m=[u,0,0,u,(g[4]-(s||0))*t,(g[5]-(n||0))*t],y=this.enableRetinaScaling,x=createCanvasElementFor({width:o,height:a}),v=r?this._objects.filter(t=>r(t)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=a,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(x.getContext("2d"),v),this.viewportTransform=g,this.width=l,this.height=c,this.calcViewportBoundaries(),this.enableRetinaScaling=y,this.skipControlsDrawing=d,x}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),$.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const task=()=>{this.destroy(),t(!0)};task.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=task:task()})}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} }>`}}_defineProperty(StaticCanvas,"ownDefaults",V);const G=["touchstart","touchmove","touchend"];function getTouchInfo(t){const e=t.changedTouches;return e&&e[0]?e[0]:t}const getPointer=t=>{const e=undefined,i=getScrollLeftTop(t.target),s=getTouchInfo(t);return new Point(s.clientX+i.left,s.clientY+i.top)},isTouchEvent=t=>G.includes(t.type)||"touch"===t.pointerType,stopEvent=t=>{t.preventDefault(),t.stopPropagation()},makeBoundingBoxFromPoints=t=>{let e=0,i=0,s=0,n=0;for(let r=0,o=t.length;r<o;r++){const{x:o,y:a}=t[r];(o>s||!r)&&(s=o),(o<e||!r)&&(e=o),(a>n||!r)&&(n=a),(a<i||!r)&&(i=a)}return{left:e,top:i,width:s-e,height:n-i}},removeTransformFromObject=(t,e)=>{const i=invertTransform(e),s=multiplyTransformMatrices(i,t.calcOwnMatrix());applyTransformToObject(t,s)},addTransformToObject=(t,e)=>applyTransformToObject(t,multiplyTransformMatrices(e,t.calcOwnMatrix())),applyTransformToObject=(t,e)=>{const{translateX:i,translateY:s,scaleX:n,scaleY:r,...o}=qrDecompose(e),a=new Point(i,s);t.flipX=!1,t.flipY=!1,Object.assign(t,o),t.set({scaleX:n,scaleY:r}),t.setPositionByOrigin(a,p,p)},resetObjectTransform=t=>{t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.rotate(0)},saveObjectTransform=t=>({scaleX:t.scaleX,scaleY:t.scaleY,skewX:t.skewX,skewY:t.skewY,angle:t.angle,left:t.left,flipX:t.flipX,flipY:t.flipY,top:t.top}),sizeAfterTransform=(t,e,i)=>{const s=t/2,n=e/2,r=[new Point(-s,-n),new Point(s,-n),new Point(-s,n),new Point(s,n)].map(t=>t.transform(i)),o=makeBoundingBoxFromPoints(r);return new Point(o.width,o.height)},calcPlaneChangeMatrix=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:d,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d;return multiplyTransformMatrices(invertTransform(e),t)},sendPointToPlane=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d;return t.transform(calcPlaneChangeMatrix(e,i))},sendVectorToPlane=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d;return t.transform(calcPlaneChangeMatrix(e,i),!0)},sendObjectToPlane=(t,e,i)=>{const s=calcPlaneChangeMatrix(e,i);return applyTransformToObject(t,multiplyTransformMatrices(s,t.calcOwnMatrix())),s},fireEvent=(t,e)=>{var i;const{transform:{target:s}}=e;null===(i=s.canvas)||void 0===i||i.fire(`object:${t}`,{...e,target:s}),s.fire(t,e)},N={left:-.5,top:-.5,center:0,bottom:.5,right:.5},resolveOrigin=t=>"string"==typeof t?N[t]:t-.5,U=new Point(1,0),q=new Point,rotateVector=(t,e)=>t.rotate(e),createVector=(t,e)=>new Point(e).subtract(t),magnitude=t=>t.distanceFrom(q),calcAngleBetweenVectors=(t,e)=>Math.atan2(crossProduct(t,e),dotProduct(t,e)),calcVectorRotation=t=>calcAngleBetweenVectors(U,t),getUnitVector=t=>t.eq(q)?t:t.scalarDivide(magnitude(t)),getOrthonormalVector=function(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return getUnitVector(new Point(-t.y,t.x).scalarMultiply(e?1:-1))},crossProduct=(t,e)=>t.x*e.y-t.y*e.x,dotProduct=(t,e)=>t.x*e.x+t.y*e.y,isBetweenVectors=(t,e,i)=>{if(t.eq(e)||t.eq(i))return!0;const s=crossProduct(e,i),n=crossProduct(e,t),r=crossProduct(i,t);return s>=0?n>=0&&r<=0:!(n<=0&&r>=0)},K="not-allowed",getActionFromCorner=(t,e,i,s)=>{if(!e||!t)return"drag";const n=s.controls[e];return n.getActionName(i,n,s)};function isTransformCentered(t){return resolveOrigin(t.originX)===resolveOrigin(p)&&resolveOrigin(t.originY)===resolveOrigin(p)}function invertOrigin(t){return.5-resolveOrigin(t)}const isLocked=(t,e)=>t[e],commonEventInfo=(t,e,i,s)=>({e:t,transform:e,pointer:new Point(i,s)});function findCornerQuadrant(t,e,i){const s=i,n=sendPointToPlane(t.getCenterPoint(),t.canvas.viewportTransform,void 0),r=calcVectorRotation(createVector(n,s))+l;return Math.round(r%l/h)}function normalizePoint(t,e,i,s){const n=t.getRelativeCenterPoint(),r=void 0!==i&&void 0!==s?t.translateToGivenOrigin(n,p,p,i,s):new Point(t.left,t.top),o=undefined;return(t.angle?e.rotate(-degreesToRadians(t.angle),n):e).subtract(r)}function getLocalPoint(t,e,i,s,n){var r;let{target:o,corner:a}=t;const h=o.controls[a],l=(null===(r=o.canvas)||void 0===r?void 0:r.getZoom())||1,c=o.padding/l,d=normalizePoint(o,new Point(s,n),e,i);return d.x>=c&&(d.x-=c),d.x<=-c&&(d.x+=c),d.y>=c&&(d.y-=c),d.y<=c&&(d.y+=c),d.x-=h.offsetX,d.y-=h.offsetY,d}const dragHandler=(t,e,i,s)=>{const{target:n,offsetX:r,offsetY:o}=e,a=i-r,h=s-o,l=!isLocked(n,"lockMovementX")&&n.left!==a,c=!isLocked(n,"lockMovementY")&&n.top!==h;return l&&n.set(m,a),c&&n.set(y,h),(l||c)&&fireEvent(b,commonEventInfo(t,e,i,s)),l||c},J={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"},reRGBa=()=>/^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,reHSLa=()=>/^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,reHex=()=>/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i,hue2rgb=(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t),rgb2Hsl=(t,e,i,s)=>{t/=255,e/=255,i/=255;const n=Math.max(t,e,i),r=Math.min(t,e,i);let o,a;const h=(n+r)/2;if(n===r)o=a=0;else{const s=n-r;switch(a=h>.5?s/(2-n-r):s/(n+r),n){case t:o=(e-i)/s+(e<i?6:0);break;case e:o=(i-t)/s+2;break;case i:o=(t-e)/s+4;break}o/=6}return[Math.round(360*o),Math.round(100*a),Math.round(100*h),s]},fromAlphaToFloat=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"1";return parseFloat(t)/(t.endsWith("%")?100:1)},hexify=t=>Math.min(Math.round(t),255).toString(16).toUpperCase().padStart(2,"0"),greyAverage=t=>{let[e,i,s,n=1]=t;const r=Math.round(.3*e+.59*i+.11*s);return[r,r,r,n]};class Color{constructor(t){if(_defineProperty(this,"isUnrecognised",!1),t)if(t instanceof Color)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,i,s,n=1]=t;this.setSource([e,i,s,n])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in J&&(t=J[t]),"transparent"===t?[255,255,255,0]:Color.sourceFromHex(t)||Color.sourceFromRgb(t)||Color.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,i]=this.getSource();return`rgb(${t},${e},${i})`}toRgba(){return`rgba(${this.getSource().join(",")})`}toHsl(){const[t,e,i]=rgb2Hsl(...this.getSource());return`hsl(${t},${e}%,${i}%)`}toHsla(){const[t,e,i,s]=rgb2Hsl(...this.getSource());return`hsla(${t},${e}%,${i}%,${s})`}toHex(){const t=undefined;return this.toHexa().slice(0,6)}toHexa(){const[t,e,i,s]=this.getSource();return`${hexify(t)}${hexify(e)}${hexify(i)}${hexify(Math.round(255*s))}`}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(greyAverage(this.getSource())),this}toBlackWhite(t){const[e,,,i]=greyAverage(this.getSource()),s=e<(t||127)?0:255;return this.setSource([s,s,s,i]),this}overlayWith(t){t instanceof Color||(t=new Color(t));const e=this.getSource(),i=.5,s=t.getSource(),[n,r,o]=e.map((t,e)=>Math.round(.5*t+s[e]*i));return this.setSource([n,r,o,e[3]]),this}static fromRgb(t){return Color.fromRgba(t)}static fromRgba(t){return new Color(Color.sourceFromRgb(t))}static sourceFromRgb(t){const e=t.match(/^rgba?\(\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d{0,3}(?:\.\d+)?%?)\s*)?\)$/i);if(e){const[t,i,s]=e.slice(1,4).map(t=>{const e=parseFloat(t);return t.endsWith("%")?Math.round(2.55*e):e});return[t,i,s,fromAlphaToFloat(e[4])]}}static fromHsl(t){return Color.fromHsla(t)}static fromHsla(t){return new Color(Color.sourceFromHsl(t))}static sourceFromHsl(t){const e=t.match(/^hsla?\(\s*([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d*(?:\.\d+)?%?)\s*)?\)$/i);if(!e)return;const i=undefined,s=(Color.parseAngletoDegrees(e[1])%360+360)%360/360,n=parseFloat(e[2])/100,r=parseFloat(e[3])/100;let o,a,h;if(0===n)o=a=h=r;else{const t=r<=.5?r*(n+1):r+n-r*n,e=2*r-t;o=hue2rgb(e,t,s+1/3),a=hue2rgb(e,t,s),h=hue2rgb(e,t,s-1/3)}return[Math.round(255*o),Math.round(255*a),Math.round(255*h),fromAlphaToFloat(e[4])]}static fromHex(t){return new Color(Color.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),i=undefined;let s;s=e.length<=4?e.split("").map(t=>t+t):e.match(/.{2}/g);const[n,r,o,a=255]=s.map(t=>parseInt(t,16));return[n,r,o,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),i=parseFloat(e);return e.includes("rad")?radiansToDegrees(i):e.includes("turn")?360*i:i}}const getSvgAttributes=t=>{const e=["instantiated_by_use","style","id","class"];switch(t){case"linearGradient":return e.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return e.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return e.concat(["offset","stop-color","stop-opacity"])}return e},parseUnit=function(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u;const s=/\D{0,2}$/.exec(t),n=parseFloat(t),r=e.DPI;switch(null==s?void 0:s[0]){case"mm":return n*r/25.4;case"cm":return n*r/2.54;case"in":return n*r;case"pt":return n*r/72;case"pc":return n*r/72*12;case"em":return n*i;default:return n}},parseAlign=t=>t&&t!==_?[t.slice(1,4),t.slice(5,8)]:t===_?[t,t]:["Mid","Mid"],parsePreserveAspectRatioAttribute=t=>{const[e,i]=t.trim().split(" "),[s,n]=parseAlign(e);return{meetOrSlice:i||"meet",alignX:s,alignY:n}},colorPropToSVG=function(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s,n;if(e)if(e.toLive)s=`url(#SVGID_${e.id})`;else{const t=new Color(e),i=t.getAlpha();s=t.toRgb(),1!==i&&(n=i.toString())}else s="none";return i?`${t}: ${s}; ${n?`${t}-opacity: ${n}; `:""}`:`${t}="${s}" ${n?`${t}-opacity="${n}" `:""}`},createSVGRect=function(t,i){let{left:s,top:n,width:r,height:o}=i,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.NUM_FRACTION_DIGITS;const h=colorPropToSVG(I,t,!1),[l,c,d,u]=[s,n,r,o].map(t=>toFixed(t,a));return`<rect ${h} x="${l}" y="${c}" width="${d}" height="${u}"></rect>`};class FabricObjectSVGExportMixin{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",i=this.strokeWidth?this.strokeWidth:"0",s=this.strokeDashArray?this.strokeDashArray.join(" "):_,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",a=this.strokeMiterLimit?this.strokeMiterLimit:"4",h=void 0!==this.opacity?this.opacity:"1",l=this.visible?"":" visibility: hidden;",c=t?"":this.getSvgFilter(),d=colorPropToSVG(I,this.fill),u=undefined;return[colorPropToSVG(B,this.stroke),"stroke-width: ",i,"; ","stroke-dasharray: ",s,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",a,"; ",d,"fill-rule: ",e,"; ","opacity: ",h,";",c,l].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&&void 0!==arguments[1]?arguments[1]:"";const i=t?this.calcTransformMatrix():this.calcOwnMatrix(),s=undefined;return`${`transform="${matrixToSVG(i)}`}${e}" `}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:i=""}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=[this.getSvgTransform(!0,i),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=s,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:i,withShadow:s,additionalTransform:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=e?"":`style="${this.getSvgStyles()}" `,o=s?`style="${this.getSvgFilter()}" `:"",a=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",l=a&&a.absolutePositioned,c=this.stroke,d=this.fill,u=this.shadow,g=[],f=t.indexOf("COMMON_PARTS");let p;a&&(a.clipPathId=`CLIPPATH_${uid()}`,p=`<clipPath id="${a.clipPathId}" >\n${a.toClipPathSVG(i)}</clipPath>\n`),l&&g.push("<g ",o,this.getSvgCommons()," >\n"),g.push("<g ",this.getSvgTransform(!1),l?"":o+this.getSvgCommons()," >\n");const m=[r,h,e?"":this.addPaintOrder()," ",n?`transform="${n}" `:""].join("");return t[f]=m,isFiller(d)&&g.push(d.toSVG(this)),isFiller(c)&&g.push(c.toSVG(this)),u&&g.push(u.toSVG(this)),a&&g.push(p),g.push(t.join("")),g.push("</g>\n"),l&&g.push("</g>\n"),i?i(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==I?` paint-order="${this.paintFirst}" `:""}}function getSvgRegex(t){return new RegExp("^("+t.join("|")+")\\b","i")}const Z="textDecorationThickness",Q=["fontSize","fontWeight","fontFamily","fontStyle"],tt=["underline","overline","linethrough"],et=[...Q,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign","wrap","ellipsis","letterSpacing","enableAdvancedLayout","verticalAlign","kashida"],it=[...et,...tt,"textBackgroundColor","direction",Z,"useOverlayEditing"],st=[...Q,...tt,B,"strokeWidth",I,"deltaY","textBackgroundColor",Z],nt={_reNewline:C,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:m,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:m,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",wrap:"word",ellipsis:!1,letterSpacing:0,enableAdvancedLayout:!1,verticalAlign:"top",kashida:"none",useOverlayEditing:!1,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,[Z]:66.667},rt="justify",ot="justify-left",at="justify-right",ht="justify-center",lt=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,ct=String.raw`(?:\s*,?\s+|\s*,\s*)`,dt="http://www.w3.org/2000/svg",ut=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+lt+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+lt+"))?\\s+(.*)"),gt=undefined,ft=["symbol","image","marker","pattern","view","svg"],pt=["pattern","defs","symbol","metadata","clipPath","mask","desc"],mt=["symbol","g","a","svg","clipPath","defs"],yt={cx:m,x:m,r:"radius",cy:y,y:y,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":Z},xt="font-size",vt="clip-path",_t=getSvgRegex(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Ct=getSvgRegex(ft),bt=getSvgRegex(mt),St=new RegExp(String.raw`^\s*(${lt})${ct}(${lt})${ct}(${lt})${ct}(${lt})\s*$`),wt="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Tt=new RegExp("(?:\\s|^)"+wt+wt+"("+lt+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)"),Pt={color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1};class Shadow{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e="string"==typeof t?Shadow.parseShadow(t):t;Object.assign(this,Shadow.ownDefaults,e),this.id=uid()}static parseShadow(t){const e=t.trim(),[,i=0,s=0,n=0]=(Tt.exec(e)||[]).map(t=>parseFloat(t)||0),r=undefined;return{color:(e.replace(Tt,"")||"rgb(0,0,0)").trim(),offsetX:i,offsetY:s,blur:n}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const i=rotateVector(new Point(this.offsetX,this.offsetY),degreesToRadians(-t.angle)),s=20,n=new Color(this.color);let r=40,o=40;return t.width&&t.height&&(r=100*toFixed((Math.abs(i.x)+this.blur)/t.width,e.NUM_FRACTION_DIGITS)+s,o=100*toFixed((Math.abs(i.y)+this.blur)/t.height,e.NUM_FRACTION_DIGITS)+s),t.flipX&&(i.x*=-1),t.flipY&&(i.y*=-1),`<filter id="SVGID_${this.id}" y="-${o}%" height="${100+2*o}%" x="-${r}%" width="${100+2*r}%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="${toFixed(this.blur?this.blur/2:0,e.NUM_FRACTION_DIGITS)}"></feGaussianBlur>\n\t<feOffset dx="${toFixed(i.x,e.NUM_FRACTION_DIGITS)}" dy="${toFixed(i.y,e.NUM_FRACTION_DIGITS)}" result="oBlur" ></feOffset>\n\t<feFlood flood-color="${n.toRgb()}" flood-opacity="${n.getAlpha()}"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n`}toObject(){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=Shadow.ownDefaults;return this.includeDefaultValues?t:pickBy(t,(t,i)=>t!==e[i])}static async fromObject(t){return new this(t)}}_defineProperty(Shadow,"ownDefaults",Pt),_defineProperty(Shadow,"type","shadow"),X.setClass(Shadow,"shadow");const capValue=(t,e,i)=>Math.max(t,Math.min(e,i)),Mt=[y,m,A,F,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",L,j],Ot=[I,B,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],kt={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:m,originY:y,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:I,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},Dt={noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:10,touchCornerSize:24,transparentCorners:!1,cornerColor:"#ffffff",cornerStrokeColor:"#0d99ff",cornerStyle:"circle",cornerDashArray:null,hasControls:!0,borderColor:"#0d99ff",borderDashArray:null,borderOpacityWhenMoving:.6,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null},normalize=(t,e,i,s)=>(t<Math.abs(e)?(t=e,s=i/4):s=0===e&&0===t?i/l*Math.asin(1):i/l*Math.asin(e/t),{a:t,c:e,p:i,s:s}),elastic=(t,e,i,s,n)=>t*Math.pow(2,10*(s-=1))*Math.sin((s*n-e)*l/i),defaultEasing=(t,e,i,s)=>-i*Math.cos(t/s*a)+i+e,easeInCubic=(t,e,i,s)=>i*(t/s)**3+e,easeOutCubic=(t,e,i,s)=>i*((t/s-1)**3+1)+e,easeInOutCubic=(t,e,i,s)=>(t/=s/2)<1?i/2*t**3+e:i/2*((t-2)**3+2)+e,easeInQuart=(t,e,i,s)=>i*(t/=s)*t**3+e,easeOutQuart=(t,e,i,s)=>-i*((t=t/s-1)*t**3-1)+e,easeInOutQuart=(t,e,i,s)=>(t/=s/2)<1?i/2*t**4+e:-i/2*((t-=2)*t**3-2)+e,easeInQuint=(t,e,i,s)=>i*(t/s)**5+e,easeOutQuint=(t,e,i,s)=>i*((t/s-1)**5+1)+e,easeInOutQuint=(t,e,i,s)=>(t/=s/2)<1?i/2*t**5+e:i/2*((t-2)**5+2)+e,easeInSine=(t,e,i,s)=>-i*Math.cos(t/s*a)+i+e,easeOutSine=(t,e,i,s)=>i*Math.sin(t/s*a)+e,easeInOutSine=(t,e,i,s)=>-i/2*(Math.cos(Math.PI*t/s)-1)+e,easeInExpo=(t,e,i,s)=>0===t?e:i*2**(10*(t/s-1))+e,easeOutExpo=(t,e,i,s)=>t===s?e+i:i*-(2**(-10*t/s)+1)+e,easeInOutExpo=(t,e,i,s)=>0===t?e:t===s?e+i:(t/=s/2)<1?i/2*2**(10*(t-1))+e:i/2*-(2**(-10*--t)+2)+e,easeInCirc=(t,e,i,s)=>-i*(Math.sqrt(1-(t/=s)*t)-1)+e,easeOutCirc=(t,e,i,s)=>i*Math.sqrt(1-(t=t/s-1)*t)+e,easeInOutCirc=(t,e,i,s)=>(t/=s/2)<1?-i/2*(Math.sqrt(1-t**2)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e,easeInElastic=(t,e,i,s)=>{const n=1.70158,r=i;let o=0;if(0===t)return e;if(1===(t/=s))return e+i;o||(o=.3*s);const{a:a,s:h,p:l}=normalize(r,i,o,n);return-elastic(a,h,l,t,s)+e},easeOutElastic=(t,e,i,s)=>{const n=1.70158,r=i;let o=0;if(0===t)return e;if(1===(t/=s))return e+i;o||(o=.3*s);const{a:a,s:h,p:c,c:d}=normalize(r,i,o,n);return a*2**(-10*t)*Math.sin((t*s-h)*l/c)+d+e},easeInOutElastic=(t,e,i,s)=>{const n=1.70158,r=i;let o=0;if(0===t)return e;if(2===(t/=s/2))return e+i;o||(o=s*(.3*1.5));const{a:a,s:h,p:c,c:d}=normalize(r,i,o,n);return t<1?-.5*elastic(a,h,c,t,s)+e:a*Math.pow(2,-10*(t-=1))*Math.sin((t*s-h)*l/c)*.5+d+e},easeInBack=function(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return i*(t/=s)*t*((n+1)*t-n)+e},easeOutBack=function(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return i*((t=t/s-1)*t*((n+1)*t+n)+1)+e},easeInOutBack=function(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return(t/=s/2)<1?i/2*(t*t*((1+(n*=1.525))*t-n))+e:i/2*((t-=2)*t*((1+(n*=1.525))*t+n)+2)+e},easeOutBounce=(t,e,i,s)=>(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e,easeInBounce=(t,e,i,s)=>i-easeOutBounce(s-t,0,i,s)+e,easeInOutBounce=(t,e,i,s)=>t<s/2?.5*easeInBounce(2*t,0,i,s)+e:.5*easeOutBounce(2*t-s,0,i,s)+.5*i+e,easeInQuad=(t,e,i,s)=>i*(t/=s)*t+e,easeOutQuad=(t,e,i,s)=>-i*(t/=s)*(t-2)+e,easeInOutQuad=(t,e,i,s)=>(t/=s/2)<1?i/2*t**2+e:-i/2*(--t*(t-2)-1)+e;var Et=Object.freeze({__proto__:null,defaultEasing:defaultEasing,easeInBack:easeInBack,easeInBounce:easeInBounce,easeInCirc:easeInCirc,easeInCubic:easeInCubic,easeInElastic:easeInElastic,easeInExpo:easeInExpo,easeInOutBack:easeInOutBack,easeInOutBounce:easeInOutBounce,easeInOutCirc:easeInOutCirc,easeInOutCubic:easeInOutCubic,easeInOutElastic:easeInOutElastic,easeInOutExpo:easeInOutExpo,easeInOutQuad:easeInOutQuad,easeInOutQuart:easeInOutQuart,easeInOutQuint:easeInOutQuint,easeInOutSine:easeInOutSine,easeInQuad:easeInQuad,easeInQuart:easeInQuart,easeInQuint:easeInQuint,easeInSine:easeInSine,easeOutBack:easeOutBack,easeOutBounce:easeOutBounce,easeOutCirc:easeOutCirc,easeOutCubic:easeOutCubic,easeOutElastic:easeOutElastic,easeOutExpo:easeOutExpo,easeOutQuad:easeOutQuad,easeOutQuart:easeOutQuart,easeOutQuint:easeOutQuint,easeOutSine:easeOutSine});const defaultAbort=()=>!1;class AnimationBase{constructor(t){let{startValue:e,byValue:i,duration:s=500,delay:n=0,easing:r=defaultEasing,onStart:o=noop,onChange:a=noop,onComplete:h=noop,abort:l=defaultAbort,target:c}=t;_defineProperty(this,"_state","pending"),_defineProperty(this,"durationProgress",0),_defineProperty(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=s,this.delay=n,this.easing=r,this._onStart=o,this._onChange=a,this._onComplete=h,this._abort=l,this.target=c,this.startValue=e,this.byValue=i,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return"aborted"===this._state||"completed"===this._state}start(){const firstTick=t=>{"pending"===this._state&&(this.startTime=t||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>requestAnimFrame(firstTick),this.delay):requestAnimFrame(firstTick)}tick(t){const e=(t||+new Date)-this.startTime,i=Math.min(e,this.duration);this.durationProgress=i/this.duration;const{value:s,valueProgress:n}=this.calculate(i);this.value=Object.freeze(s),this.valueProgress=n,"aborted"!==this._state&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),requestAnimFrame(this.tick)))}register(){$.push(this)}unregister(){$.remove(this)}abort(){this._state="aborted",this.unregister()}}class ValueAnimation extends AnimationBase{constructor(t){let{startValue:e=0,endValue:i=100,...s}=t;super({...s,startValue:e,byValue:i-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 ArrayAnimation extends AnimationBase{constructor(t){let{startValue:e=[0],endValue:i=[100],...s}=t;super({...s,startValue:e,byValue:i.map((t,i)=>t-e[i])})}calculate(t){const e=this.startValue.map((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const defaultColorEasing=(t,e,i,s)=>{const n=undefined;return e+i*(1-Math.cos(t/s*a))},wrapColorCallback=t=>t&&((e,i,s)=>t(new Color(e).toRgba(),i,s));class ColorAnimation extends AnimationBase{constructor(t){let{startValue:e,endValue:i,easing:s=defaultColorEasing,onChange:n,onComplete:r,abort:o,...a}=t;const h=new Color(e).getSource(),l=new Color(i).getSource();super({...a,startValue:h,byValue:l.map((t,e)=>t-h[e]),easing:s,onChange:wrapColorCallback(n),onComplete:wrapColorCallback(r),abort:wrapColorCallback(o)})}calculate(t){const[e,i,s,n]=this.startValue.map((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i)),r=[...[e,i,s].map(Math.round),capValue(0,n,1)];return{value:r,valueProgress:r.map((t,e)=>0!==this.byValue[e]?Math.abs((t-this.startValue[e])/this.byValue[e]):0).find(t=>0!==t)||0}}}const isArrayAnimation=t=>Array.isArray(t.startValue)||Array.isArray(t.endValue);function animate(t){const e=isArrayAnimation(t)?new ArrayAnimation(t):new ValueAnimation(t);return e.start(),e}function animateColor(t){const e=new ColorAnimation(t);return e.start(),e}class Intersection{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),i=0;i<t;i++)e[i]=arguments[i];return this.points=this.points.concat(e.filter(t=>!this.includes(t))),this}static isPointContained(t,e,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(e.eq(i))return t.eq(e);if(e.x===i.x)return t.x===e.x&&(s||t.y>=Math.min(e.y,i.y)&&t.y<=Math.max(e.y,i.y));if(e.y===i.y)return t.y===e.y&&(s||t.x>=Math.min(e.x,i.x)&&t.x<=Math.max(e.x,i.x));{const n=createVector(e,i),r=undefined,o=createVector(e,t).divide(n);return s?Math.abs(o.x)===Math.abs(o.y):o.x===o.y&&o.x>=0&&o.x<=1}}static isPointInPolygon(t,e){const i=new Point(t).setX(Math.min(t.x-1,...e.map(t=>t.x)));let s=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,i);if(r.includes(t))return!0;s+=Number("Intersection"===r.status)}return s%2==1}static intersectLineLine(t,e,i,s){let n=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],r=!(arguments.length>5&&void 0!==arguments[5])||arguments[5];const o=e.x-t.x,a=e.y-t.y,h=s.x-i.x,l=s.y-i.y,c=t.x-i.x,d=t.y-i.y,u=h*d-l*c,g=o*d-a*c,f=l*o-h*a;if(0!==f){const e=u/f,i=g/f;return(n||0<=e&&e<=1)&&(r||0<=i&&i<=1)?new Intersection("Intersection").append(new Point(t.x+e*o,t.y+e*a)):new Intersection}if(0===u||0===g){const o=n||r||Intersection.isPointContained(t,i,s)||Intersection.isPointContained(e,i,s)||Intersection.isPointContained(i,t,e)||Intersection.isPointContained(s,t,e);return new Intersection(o?"Coincident":void 0)}return new Intersection("Parallel")}static intersectSegmentLine(t,e,i,s){return Intersection.intersectLineLine(t,e,i,s,!1,!0)}static intersectSegmentSegment(t,e,i,s){return Intersection.intersectLineLine(t,e,i,s,!1,!1)}static intersectLinePolygon(t,e,i){let s=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];const n=new Intersection,r=i.length;for(let o=0,a,h,l;o<r;o++){if(a=i[o],h=i[(o+1)%r],l=Intersection.intersectLineLine(t,e,a,h,s,!1),"Coincident"===l.status)return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,i){return Intersection.intersectLinePolygon(t,e,i,!1)}static intersectPolygonPolygon(t,e){const i=new Intersection,s=t.length,n=[];for(let r=0;r<s;r++){const o=t[r],a=t[(r+1)%s],h=Intersection.intersectSegmentPolygon(o,a,e);"Coincident"===h.status?(n.push(h),i.append(o,a)):i.append(...h.points)}return n.length>0&&n.length===t.length?new Intersection("Coincident"):(i.points.length>0&&(i.status="Intersection"),i)}static intersectPolygonRectangle(t,e,i){const s=e.min(i),n=e.max(i),r=new Point(n.x,s.y),o=new Point(s.x,n.y);return Intersection.intersectPolygonPolygon(t,[s,r,n,o])}}class ObjectGeometry extends CommonMethods{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?transformPoint(t,this.group.calcTransformMatrix()):t}setXY(t,e,i){this.group&&(t=transformPoint(t,invertTransform(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,i)}getRelativeXY(){return new Point(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.originX,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.originY;this.setPositionByOrigin(t,e,i)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:i,bl:s}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,i,s];if(this.group){const t=this.group.calcTransformMatrix();return n.map(e=>transformPoint(e,t))}return n}intersectsWithRect(t,e){const i=undefined;return"Intersection"===Intersection.intersectPolygonRectangle(this.getCoords(),t,e).status}intersectsWithObject(t){const e=Intersection.intersectPolygonPolygon(this.getCoords(),t.getCoords());return"Intersection"===e.status||"Coincident"===e.status||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){const e=undefined;return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:i,top:s,width:n,height:r}=this.getBoundingRect();return i>=t.x&&i+n<=e.x&&s>=t.y&&s+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return Intersection.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords,i=undefined;return!!this.getCoords().some(i=>i.x<=e.x&&i.x>=t.x&&i.y<=e.y&&i.y>=t.y)||(!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e)))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;if(this.intersectsWithRect(t,e))return!0;const i=undefined;return this.getCoords().every(i=>(i.x>=e.x||i.x<=t.x)&&(i.y>=e.y||i.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return makeBoundingBoxFromPoints(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(A,t),this._set(F,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(null===(t=this.canvas)||void 0===t?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?radiansToDegrees(calcPlaneRotation(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return(null===(t=this.canvas)||void 0===t?void 0:t.viewportTransform)||d.concat()}calcACoords(){const t=createRotateMatrix({angle:this.angle}),{x:e,y:i}=this.getRelativeCenterPoint(),s=createTranslateMatrix(e,i),n=multiplyTransformMatrices(s,t),r=this._getTransformedDimensions(),o=r.x/2,a=r.y/2;return{tl:transformPoint({x:-o,y:-a},n),tr:transformPoint({x:o,y:-a},n),bl:transformPoint({x:-o,y:a},n),br:transformPoint({x:o,y:a},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&void 0!==arguments[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,resolveOrigin(this.originX),resolveOrigin(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const i=this.transformMatrixKey(t),s=this.matrixCache;return s&&s.key.every((t,e)=>t===i[e])?s.value:(this.group&&(e=multiplyTransformMatrices(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:i,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const i=this.getRelativeCenterPoint(),s={angle:this.angle,translateX:i.x,translateY:i.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=composeMatrix(s);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new Point(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&&void 0!==arguments[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},i=e.strokeWidth;let s=i,n=0;this.strokeUniform&&(s=0,n=i);const r=e.width+s,o=e.height+s,a=undefined;let h;return h=0===e.skewX&&0===e.skewY?new Point(r*e.scaleX,o*e.scaleY):sizeAfterTransform(r,o,calcDimensionsMatrix(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,i,s,n){let r=t.x,o=t.y;const a=resolveOrigin(s)-resolveOrigin(e),h=resolveOrigin(n)-resolveOrigin(i);if(a||h){const t=this._getTransformedDimensions();r+=a*t.x,o+=h*t.y}return new Point(r,o)}translateToCenterPoint(t,e,i){if(e===p&&i===p)return t;const s=this.translateToGivenOrigin(t,e,i,p,p);return this.angle?s.rotate(degreesToRadians(this.angle),t):s}translateToOriginPoint(t,e,i){const s=this.translateToGivenOrigin(t,p,p,e,i);return this.angle?s.rotate(degreesToRadians(this.angle),t):s}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?transformPoint(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new Point(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,i){const s=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(s,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),m,y)}}let At=class FabricObject extends ObjectGeometry{static getDefaults(){return FabricObject.ownDefaults}get type(){const t=this.constructor.type;return"FabricObject"===t?"object":t.toLowerCase()}set type(t){log("warn","Setting type has no effect",t)}constructor(t){super(),_defineProperty(this,"_cacheContext",null),Object.assign(this,FabricObject.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const i=t.width,s=t.height,r=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(i<=r&&s<=r&&i*s<=e.perfLimitSizeTotal)return i<o&&(t.width=o),s<o&&(t.height=o),t;const a=i/s,[h,l]=n.limitDimsByArea(a),c=capValue(o,h,r),d=capValue(o,l,r);return i>c&&(t.zoomX/=i/c,t.width=c,t.capped=!0),s>d&&(t.zoomY/=s/d,t.height=d,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),i=e.x*t.x/this.scaleX,s=e.y*t.y/this.scaleY;return{width:Math.ceil(i+2),height:Math.ceil(s+2),zoomX:t.x,zoomY:t.y,x:i,y:s}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:i,height:s,zoomX:n,zoomY:r,x:o,y:a}=this._limitCacheSize(this._getCacheCanvasDimensions()),h=i!==t.width||s!==t.height,l=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;const c=undefined;if(h||l){i!==t.width||s!==t.height?(t.width=i,t.height=s):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const h=o/2,l=a/2;return this.cacheTranslationX=Math.round(t.width/2-h)+h,this.cacheTranslationY=Math.round(t.height/2-l)+l,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}setOptions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])}getObjectScaling(){if(!this.group)return new Point(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=qrDecompose(this.calcTransformMatrix());return new Point(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),i=this.getCanvasRetinaScaling();return t.scalarMultiply(e*i)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:0===t?1e-4:t}_set(t,e){t!==A&&t!==F||(e=this._constrainScale(e)),t===A&&e<0?(this.flipX=!this.flipX,e*=-1):"scaleY"===t&&e<0?(this.flipY=!this.flipY,e*=-1):"shadow"!==t||!e||e instanceof Shadow||(e=new Shadow(e));const i=this[t]!==e;return this[t]=e,i&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||i&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:i,cacheTranslationX:s,cacheTranslationY:n}=this,{width:r,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:i,cacheTranslationX:s,cacheTranslationY:n,width:r,height:o,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return!!this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth}hasFill(){return!!this.fill&&"transparent"!==this.fill}needsItsOwnCache(){return!!(this.paintFirst===B&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)}drawClipPathOnCache(t,e,i){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(i,0,0),t.restore()}drawObject(t,e,i){const s=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,i),this.fill=s,this.stroke=n}createClipPathLayer(t,e){const i=createCanvasElementFor(e),s=i.getContext("2d");if(s.translate(e.cacheTranslationX,e.cacheTranslationY),s.scale(e.zoomX,e.zoomY),t._cacheCanvas=i,e.parentClipPaths.forEach(t=>{t.transform(s)}),e.parentClipPaths.push(t),t.absolutePositioned){const t=invertTransform(this.calcTransformMatrix());s.transform(t[0],t[1],t[2],t[3],t[4],t[5])}return t.transform(s),t.drawObject(s,!0,e),i}_drawClipPath(t,e,i){if(!e)return;e._transformDone=!0;const s=this.createClipPathLayer(e,i);this.drawClipPathOnCache(t,e,s)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,i=this._cacheContext;return!(!e||!i||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&i&&!t&&(i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,e.width,e.height),i.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;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 i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,isFiller(i)?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:i}=e;i&&(isFiller(i)?(t.fillStyle=i.toLive(t),this._applyPatternGradientTransform(t,i)):t.fillStyle=i)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&0!==e.length&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const i=this.shadow,s=this.canvas,n=this.getCanvasRetinaScaling(),[r,,,o]=(null==s?void 0:s.viewportTransform)||d,a=r*n,h=o*n,l=i.nonScaling?new Point(1,1):this.getObjectScaling();t.shadowColor=i.color,t.shadowBlur=i.blur*e.browserShadowBlurConstant*(a+h)*(l.x+l.y)/4,t.shadowOffsetX=i.offsetX*a*l.x,t.shadowOffsetY=i.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!isFiller(e))return{offsetX:0,offsetY:0};const i=e.gradientTransform||e.patternTransform,s=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,s,n):t.transform(1,0,0,1,s,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:s,offsetY:n}}_renderPaintInOrder(t){this.paintFirst===B?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){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 i;const s=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=s.x/this.scaleX/n,o=s.y/this.scaleY/n,a=createCanvasElementFor({width:Math.ceil(r),height:Math.ceil(o)}),h=a.getContext("2d");h&&(h.beginPath(),h.moveTo(0,0),h.lineTo(r,0),h.lineTo(r,o),h.lineTo(0,o),h.closePath(),h.translate(r/2,o/2),h.scale(s.zoomX/this.scaleX/n,s.zoomY/this.scaleY/n),this._applyPatternGradientTransform(h,e),h.fillStyle=e.toLive(t),h.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/s.zoomX,n*this.scaleY/s.zoomY),t.strokeStyle=null!==(i=h.createPattern(a,"no-repeat"))&&void 0!==i?i:"")}_findCenterFromElement(){return new Point(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),i=undefined;return new(X.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e=saveObjectTransform(this),i=this.group,s=this.shadow,n=Math.abs,r=t.enableRetinaScaling?getDevicePixelRatio():1,o=(t.multiplier||1)*r,a=t.canvasProvider||(t=>new StaticCanvas(t,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&resetObjectTransform(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&sendObjectToPlane(this,this.getViewportTransform()),this.setCoords();const h=createCanvasElement(),l=this.getBoundingRect(),c=this.shadow,d=new Point;if(c){const t=c.blur,e=c.nonScaling?new Point(1,1):this.getObjectScaling();d.x=2*Math.round(n(c.offsetX)+t)*n(e.x),d.y=2*Math.round(n(c.offsetY)+t)*n(e.y)}const u=l.width+d.x,g=l.height+d.y;h.width=Math.ceil(u),h.height=Math.ceil(g);const f=a(h);"jpeg"===t.format&&(f.backgroundColor="#fff"),this.setPositionByOrigin(new Point(f.width/2,f.height/2),p,p);const m=this.canvas;f._objects=[this],this.set("canvas",f),this.setCoords();const y=f.toCanvasElement(o||1,t);return this.set("canvas",m),this.shadow=s,i&&(this.group=i),this.set(e),this.setCoords(),f._objects=[],f.destroy(),y}toDataURL(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return toBlob(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:i,originY:s}=this;if(e){const{x:t,y:e}=this.getRelativeCenterPoint();this.originX=p,this.originY=p,this.left=t,this.top=e}if(this.set("angle",t),e){const{x:t,y:e}=this.translateToOriginPoint(this.getRelativeCenterPoint(),i,s);this.left=t,this.top=e,this.originX=i,this.originY=s}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){$.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&getEnv().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((t,i)=>{let[s,n]=i;return t[s]=this._animate(s,n,e),t},{})}_animate(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const s=t.split("."),n=this.constructor.colorProperties.includes(s[s.length-1]),{abort:r,startValue:o,onChange:a,onComplete:h}=i,l={...i,target:this,startValue:null!=o?o:s.reduce((t,e)=>t[e],this),endValue:e,abort:null==r?void 0:r.bind(this),onChange:(t,e,i)=>{s.reduce((e,i,n)=>(n===s.length-1&&(e[i]=t),e[i]),this),a&&a(t,e,i)},onComplete:(t,e,i)=>{this.setCoords(),h&&h(t,e,i)}};return n?animateColor(l):animate(l)}isDescendantOf(t){const{parent:e,group:i}=this;return e===t||i===t||!!e&&e.isDescendantOf(t)||!!i&&i!==e&&i.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(),i=t.getAncestors();if(0===e.length&&i.length>0&&this===i[i.length-1])return{fork:[],otherFork:[t,...i.slice(0,i.length-1)],common:[this]};for(let s=0,n;s<e.length;s++){if(n=e[s],n===t)return{fork:[this,...e.slice(0,s)],otherFork:[],common:e.slice(s)};for(let r=0;r<i.length;r++){if(this===i[r])return{fork:[],otherFork:[t,...i.slice(0,r)],common:[this,...e]};if(n===i[r])return{fork:[this,...e.slice(0,s)],otherFork:[t,...i.slice(0,r)],common:e.slice(s)}}}return{fork:[this,...e],otherFork:[t,...i],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 i=e.common[0]||this.canvas;if(!i)return;const s=e.fork.pop(),n=e.otherFork.pop(),r=i._objects.indexOf(s),o=i._objects.indexOf(n);return r>-1&&r>o}toObject(){let t;const i=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).concat(FabricObject.customProperties,this.constructor.customProperties||[]);let s;const n=e.NUM_FRACTION_DIGITS,{clipPath:r,fill:a,stroke:h,shadow:l,strokeDashArray:c,left:d,top:u,originX:g,originY:f,width:p,height:m,strokeWidth:y,strokeLineCap:x,strokeDashOffset:v,strokeLineJoin:_,strokeUniform:C,strokeMiterLimit:b,scaleX:S,scaleY:w,angle:T,flipX:P,flipY:M,opacity:O,visible:k,backgroundColor:D,fillRule:E,paintFirst:A,globalCompositeOperation:F,skewX:L,skewY:j}=this;r&&!r.excludeFromExport&&(s=r.toObject(i.concat("inverted","absolutePositioned")));const toFixedBound=t=>toFixed(t,n),I={...pick(this,i),type:this.constructor.type,version:o,originX:g,originY:f,left:toFixedBound(d),top:toFixedBound(u),width:toFixedBound(p),height:toFixedBound(m),fill:isSerializableFiller(a)?a.toObject():a,stroke:isSerializableFiller(h)?h.toObject():h,strokeWidth:toFixedBound(y),strokeDashArray:c?c.concat():c,strokeLineCap:x,strokeDashOffset:v,strokeLineJoin:_,strokeUniform:C,strokeMiterLimit:toFixedBound(b),scaleX:toFixedBound(S),scaleY:toFixedBound(w),angle:toFixedBound(T),flipX:P,flipY:M,opacity:toFixedBound(O),shadow:l?l.toObject():l,visible:k,backgroundColor:D,fillRule:E,paintFirst:A,globalCompositeOperation:F,skewX:toFixedBound(L),skewY:toFixedBound(j),...s?{clipPath:s}:null};return this.includeDefaultValues?I:this._removeDefaultValues(I)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),i=undefined,s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return pickBy(t,(t,e)=>{if(e===m||e===y||"type"===e)return!0;const i=s[e];return t!==i&&!(Array.isArray(t)&&Array.isArray(i)&&0===t.length&&0===i.length)})}toString(){return`#<${this.constructor.type}>`}static _fromObject(t){let{type:e,...i}=t,{extraParam:s,...n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return enlivenObjectEnlivables(i,n).then(t=>s?(delete t[s],new this(i[s],t)):new this(t))}static fromObject(t,e){return this._fromObject(t,e)}};_defineProperty(At,"stateProperties",Mt),_defineProperty(At,"cacheProperties",Ot),_defineProperty(At,"ownDefaults",kt),_defineProperty(At,"type","FabricObject"),_defineProperty(At,"colorProperties",[I,B,"backgroundColor"]),_defineProperty(At,"customProperties",[]),X.setClass(At),X.setClass(At,"object");const wrapWithFireEvent=(t,e,i)=>(s,n,r,o)=>{const a=e(s,n,r,o);return a&&fireEvent(t,{...commonEventInfo(s,n,r,o),...i}),a};function wrapWithFixedAnchor(t){return(e,i,s,n)=>{const{target:r,originX:o,originY:a}=i,h=r.getRelativeCenterPoint(),l=r.translateToOriginPoint(h,o,a),c=t(e,i,s,n);return r.setPositionByOrigin(l,i.originX,i.originY),c}}const changeObjectWidth=(t,e,i,s)=>{const n=getLocalPoint(e,e.originX,e.originY,i,s);if(resolveOrigin(e.originX)===resolveOrigin(p)||resolveOrigin(e.originX)===resolveOrigin(v)&&n.x<0||resolveOrigin(e.originX)===resolveOrigin(m)&&n.x>0){const{target:t}=e,i=t.strokeWidth/(t.strokeUniform?t.scaleX:1),s=isTransformCentered(e)?2:1,r=t.width,o=Math.abs(n.x*s/t.scaleX)-i;return t.set("width",Math.max(o,1)),r!==t.width}return!1},Ft=wrapWithFireEvent(M,wrapWithFixedAnchor(changeObjectWidth)),Lt=6,jt=20,It=3;function renderCircleControl(t,e,i,s,n){s=s||{};const r=this.sizeX||s.cornerSize||n.cornerSize,o=this.sizeY||s.cornerSize||n.cornerSize,a=void 0!==s.transparentCorners?s.transparentCorners:n.transparentCorners,h=a?B:I,c=!a&&(s.cornerStrokeColor||n.cornerStrokeColor);let d=e,u=i,g;t.save(),t.fillStyle=s.cornerColor||n.cornerColor||"",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"",r>o?(g=r,t.scale(1,o/r),u=i*r/o):o>r?(g=o,t.scale(r/o,1),d=e*o/r):g=r,t.beginPath(),t.arc(d,u,g/2,0,l,!1),t[h](),c&&t.stroke(),t.restore()}function renderSquareControl(t,e,i,s,n){s=s||{};const r=this.sizeX||s.cornerSize||n.cornerSize,o=this.sizeY||s.cornerSize||n.cornerSize,a=void 0!==s.transparentCorners?s.transparentCorners:n.transparentCorners,h=a?B:I,l=!a&&(s.cornerStrokeColor||n.cornerStrokeColor),c=r/2,d=o/2;t.save(),t.fillStyle=s.cornerColor||n.cornerColor||"",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"",t.translate(e,i);const u=n.getTotalAngle();t.rotate(degreesToRadians(u)),t[`${h}Rect`](-c,-d,r,o),l&&t.strokeRect(-c,-d,r,o),t.restore()}function renderHorizontalPillControl(t,e,i,s,n){s=s||{};const r=6,o=jt,a=3;t.save(),t.translate(e,i);const h=n.getTotalAngle();t.rotate(degreesToRadians(h)),t.fillStyle=s.cornerColor||n.cornerColor||"#ffffff",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"#0d99ff",t.lineWidth=1.5,t.beginPath(),t.roundRect(-3,-10,6,o,3),t.fill(),t.stroke(),t.restore()}function renderVerticalPillControl(t,e,i,s,n){s=s||{};const r=jt,o=6,a=3;t.save(),t.translate(e,i);const h=n.getTotalAngle();t.rotate(degreesToRadians(h)),t.fillStyle=s.cornerColor||n.cornerColor||"#ffffff",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"#0d99ff",t.lineWidth=1.5,t.beginPath(),t.roundRect(-10,-3,r,6,3),t.fill(),t.stroke(),t.restore()}class Control{constructor(t){_defineProperty(this,"visible",!0),_defineProperty(this,"actionName",E),_defineProperty(this,"angle",0),_defineProperty(this,"x",0),_defineProperty(this,"y",0),_defineProperty(this,"offsetX",0),_defineProperty(this,"offsetY",0),_defineProperty(this,"sizeX",0),_defineProperty(this,"sizeY",0),_defineProperty(this,"touchSizeX",0),_defineProperty(this,"touchSizeY",0),_defineProperty(this,"cursorStyle","crosshair"),_defineProperty(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,i,s){var n;let{tl:r,tr:o,br:a,bl:h}=s;return(null===(n=e.canvas)||void 0===n?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&Intersection.isPointInPolygon(i,[r,o,a,h])}getActionHandler(t,e,i){return this.actionHandler}getMouseDownHandler(t,e,i){return this.mouseDownHandler}getMouseUpHandler(t,e,i){return this.mouseUpHandler}cursorStyleHandler(t,e,i,s){return e.cursorStyle}getActionName(t,e,i){return e.actionName}getVisibility(t,e){var i,s;return null!==(i=null===(s=t._controlsVisibility)||void 0===s?void 0:s[e])&&void 0!==i?i:this.visible}setVisibility(t,e,i){this.visible=t}positionHandler(t,e,i,s){return new Point(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,i,s,n,r){const o=multiplyTransformMatrixArray([createTranslateMatrix(i,s),createRotateMatrix({angle:t}),createScaleMatrix((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new Point(-.5,-.5).transform(o),tr:new Point(.5,-.5).transform(o),br:new Point(.5,.5).transform(o),bl:new Point(-.5,.5).transform(o)}}render(t,e,i,s,n){s=s||{};const r=undefined;if(!(0!==this.x&&0!==this.y||0===this.x&&0===this.y)&&!s.cornerStyle){if(0===this.y&&0!==this.x)return void renderHorizontalPillControl.call(this,t,e,i,s,n);if(0===this.x&&0!==this.y)return void renderVerticalPillControl.call(this,t,e,i,s,n)}switch(s.cornerStyle||n.cornerStyle){case"circle":renderCircleControl.call(this,t,e,i,s,n);break;default:renderSquareControl.call(this,t,e,i,s,n)}}}const rotationStyleHandler=(t,e,i)=>i.lockRotation?K:e.cursorStyle,Bt=undefined,Rt=wrapWithFireEvent(w,wrapWithFixedAnchor((t,e,i,s)=>{let{target:n,ex:r,ey:o,theta:a,originX:h,originY:l}=e;const c=n.translateToOriginPoint(n.getRelativeCenterPoint(),h,l);if(isLocked(n,"lockRotation"))return!1;const d=Math.atan2(o-c.y,r-c.x),u=Math.atan2(s-c.y,i-c.x);let g=radiansToDegrees(u-d+a);if(n.snapAngle&&n.snapAngle>0){const t=n.snapAngle,e=n.snapThreshold||t,i=Math.ceil(g/t)*t,s=Math.floor(g/t)*t;Math.abs(g-s)<e?g=s:Math.abs(g-i)<e&&(g=i)}g<0&&(g=360+g),g%=360;const f=n.angle!==g;return n.angle=g,f}));function scaleIsProportional(t,e){const i=e.canvas,s=t[i.uniScaleKey];return i.uniformScaling&&!s||!i.uniformScaling&&s}function scalingIsForbidden(t,e,i){const s=isLocked(t,"lockScalingX"),n=isLocked(t,"lockScalingY");if(s&&n)return!0;if(!e&&(s||n)&&i)return!0;if(s&&"x"===e)return!0;if(n&&"y"===e)return!0;const{width:r,height:o,strokeWidth:a}=t;return 0===r&&0===a&&"y"!==e||0===o&&0===a&&"x"!==e}const Wt=["e","se","s","sw","w","nw","n","ne","e"],scaleCursorStyleHandler=(t,e,i,s)=>{const n=scaleIsProportional(t,i),r=undefined;if(scalingIsForbidden(i,0!==e.x&&0===e.y?"x":0===e.x&&0!==e.y?"y":"",n))return K;const o=findCornerQuadrant(i,e,s);return`${Wt[o]}-resize`};function scaleObject(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const r=e.target,o=n.by,a=scaleIsProportional(t,r),h=undefined;let l,c,d,u,g,f;if(scalingIsForbidden(r,o,a))return!1;if(e.gestureScale)c=e.scaleX*e.gestureScale,d=e.scaleY*e.gestureScale;else{if(l=getLocalPoint(e,e.originX,e.originY,i,s),g="y"!==o?Math.sign(l.x||e.signX||1):1,f="x"!==o?Math.sign(l.y||e.signY||1):1,e.signX||(e.signX=g),e.signY||(e.signY=f),isLocked(r,"lockScalingFlip")&&(e.signX!==g||e.signY!==f))return!1;if(u=r._getTransformedDimensions(),a&&!o){const t=Math.abs(l.x)+Math.abs(l.y),{original:i}=e,s=undefined,n=t/(Math.abs(u.x*i.scaleX/r.scaleX)+Math.abs(u.y*i.scaleY/r.scaleY));c=i.scaleX*n,d=i.scaleY*n}else c=Math.abs(l.x*r.scaleX/u.x),d=Math.abs(l.y*r.scaleY/u.y);isTransformCentered(e)&&(c*=2,d*=2),e.signX!==g&&"y"!==o&&(e.originX=invertOrigin(e.originX),c*=-1,e.signX=g),e.signY!==f&&"x"!==o&&(e.originY=invertOrigin(e.originY),d*=-1,e.signY=f)}const p=r.scaleX,m=r.scaleY;return o?("x"===o&&r.set(A,c),"y"===o&&r.set(F,d)):(!isLocked(r,"lockScalingX")&&r.set(A,c),!isLocked(r,"lockScalingY")&&r.set(F,d)),p!==r.scaleX||m!==r.scaleY}const scaleObjectFromCorner=(t,e,i,s)=>scaleObject(t,e,i,s),scaleObjectX=(t,e,i,s)=>scaleObject(t,e,i,s,{by:"x"}),scaleObjectY=(t,e,i,s)=>scaleObject(t,e,i,s,{by:"y"}),Ht=wrapWithFireEvent(S,wrapWithFixedAnchor(scaleObjectFromCorner)),Xt=wrapWithFireEvent(S,wrapWithFixedAnchor(scaleObjectX)),$t=wrapWithFireEvent(S,wrapWithFixedAnchor(scaleObjectY)),zt={x:{counterAxis:"y",scale:A,skew:L,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:F,skew:j,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Yt=["ns","nesw","ew","nwse"],skewCursorStyleHandler=(t,e,i,s)=>{if(0!==e.x&&isLocked(i,"lockSkewingY"))return K;if(0!==e.y&&isLocked(i,"lockSkewingX"))return K;const n=findCornerQuadrant(i,e,s)%4;return`${Yt[n]}-resize`};function skewObject(t,e,i){let{target:s,ex:n,ey:r,skewingSide:o,...a}=e;const{skew:h}=zt[t],l=i.subtract(new Point(n,r)).divide(new Point(s.scaleX,s.scaleY))[t],c=s[h],d=a[h],u=Math.tan(degreesToRadians(d)),g="y"===t?s._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:s._getTransformedDimensions({scaleX:1,scaleY:1}).y,f=2*l*o/Math.max(g,1)+u,p=radiansToDegrees(Math.atan(f));s.set(h,p);const m=c!==s[h];if(m&&"y"===t){const{skewX:t,scaleX:e}=s,i=s._getTransformedDimensions({skewY:c}),n=s._getTransformedDimensions(),r=0!==t?i.x/n.x:1;1!==r&&s.set(A,r*e)}return m}function skewHandler(t,e,i,s,n){const{target:r}=i,{counterAxis:o,origin:a,lockSkewing:h,skew:l,flip:c}=zt[t];if(isLocked(r,h))return!1;const{origin:d,flip:u}=zt[o],g=resolveOrigin(i[d])*(r[u]?-1:1),f=-Math.sign(g)*(r[c]?-1:1),m=undefined,y=.5*-((0===r[l]&&getLocalPoint(i,p,p,s,n)[t]>0||r[l]>0?1:-1)*f)+.5,x=wrapWithFireEvent(P,wrapWithFixedAnchor((e,i,s,n)=>skewObject(t,i,new Point(s,n))));return x(e,{...i,[a]:y,skewingSide:f},s,n)}const skewHandlerX=(t,e,i,s)=>skewHandler("x",t,e,i,s),skewHandlerY=(t,e,i,s)=>skewHandler("y",t,e,i,s);function isAltAction(t,e){return t[e.canvas.altActionKey]}const scaleOrSkewActionName=(t,e,i)=>{const s=isAltAction(t,i);return 0===e.x?s?L:F:0===e.y?s?j:A:""},scaleSkewCursorStyleHandler=(t,e,i,s)=>isAltAction(t,i)?skewCursorStyleHandler(t,e,i,s):scaleCursorStyleHandler(t,e,i,s),scalingXOrSkewingY=(t,e,i,s)=>isAltAction(t,e.target)?skewHandlerY(t,e,i,s):Xt(t,e,i,s),scalingYOrSkewingX=(t,e,i,s)=>isAltAction(t,e.target)?skewHandlerX(t,e,i,s):$t(t,e,i,s),createObjectDefaultControls=()=>({ml:new Control({x:-.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingXOrSkewingY,getActionName:scaleOrSkewActionName,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mr:new Control({x:.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingXOrSkewingY,getActionName:scaleOrSkewActionName,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mb:new Control({x:0,y:.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingYOrSkewingX,getActionName:scaleOrSkewActionName,render:renderVerticalPillControl,sizeX:20,sizeY:6}),mt:new Control({x:0,y:-.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingYOrSkewingX,getActionName:scaleOrSkewActionName,render:renderVerticalPillControl,sizeX:20,sizeY:6}),tl:new Control({x:-.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),tr:new Control({x:.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),bl:new Control({x:-.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),br:new Control({x:.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),mtr:new Control({x:0,y:-.5,actionHandler:Rt,cursorStyleHandler:rotationStyleHandler,offsetY:-40,withConnection:!0,actionName:T})}),createResizeControls=()=>({mr:new Control({x:.5,y:0,actionHandler:Ft,cursorStyleHandler:scaleSkewCursorStyleHandler,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),ml:new Control({x:-.5,y:0,actionHandler:Ft,cursorStyleHandler:scaleSkewCursorStyleHandler,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20})}),createTextboxDefaultControls=()=>{const{mt:t,mb:e,...i}={...createObjectDefaultControls(),...createResizeControls()};return i},Vt="#ffffff",Gt="#8b5cf6",Nt="rgba(139, 92, 246, 0.1)",Ut="#8b5cf6",qt=[6,4],Kt=6,Jt=20,Zt=10,Qt=2,createDefaultExpansion=()=>({expandLeft:0,expandRight:0,expandTop:0,expandBottom:0});function getExpansion(t){return t.expansion||(t.expansion={expandLeft:0,expandRight:0,expandTop:0,expandBottom:0}),t.expansion}function setExpansion(t,e){const i=getExpansion(t);Object.assign(i,e)}class ExpandControl extends Control{constructor(t){super(t),this.expandDirections=t.expandDirections,this.actionName="expand"}positionHandler(t,e,i,s){const n=getExpansion(i),{expandLeft:r,expandRight:o,expandTop:a,expandBottom:h}=n,l=i.width||1,c=i.height||1,d=r/l,u=o/l,g=a/c,f=h/c;let p=this.x,m=this.y;return this.x<0?p=this.x-d:this.x>0&&(p=this.x+u),this.y<0?m=this.y-g:this.y>0&&(m=this.y+f),new Point(p*t.x+this.offsetX,m*t.y+this.offsetY).transform(e)}render(t,e,i,s,n){t.save(),t.translate(e,i);const r=n.getTotalAngle();t.rotate(degreesToRadians(r)),t.shadowColor="rgba(0, 0, 0, 0.2)",t.shadowBlur=3,t.shadowOffsetX=0,t.shadowOffsetY=1,t.fillStyle=Vt,t.strokeStyle=Gt,t.lineWidth=2;const o=undefined;0!==this.x&&0!==this.y?(t.beginPath(),t.arc(0,0,5,0,2*Math.PI),t.fill(),t.stroke()):0===this.y?(t.beginPath(),t.roundRect(-3,-10,6,Jt,2),t.fill(),t.stroke()):(t.beginPath(),t.roundRect(-10,-3,Jt,6,2),t.fill(),t.stroke()),t.restore()}}const expandLeftHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleX||1,h=undefined,l=n._getTransformedDimensions().x/2,c=undefined,d=Math.max(0,-l-o.x)/a;var u;return Math.abs(d-r.expandLeft)>.5&&(r.expandLeft=d,n.setCoords(),null===(u=n.canvas)||void 0===u||u.requestRenderAll(),!0)},expandRightHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleX||1,h=n.width*a/2,l=undefined,c=Math.max(0,o.x-h)/a;var d;return Math.abs(c-r.expandRight)>.5&&(r.expandRight=c,n.setCoords(),null===(d=n.canvas)||void 0===d||d.requestRenderAll(),!0)},expandTopHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleY||1,h=n.height*a/2,l=undefined,c=Math.max(0,-h-o.y)/a;var d;return Math.abs(c-r.expandTop)>.5&&(r.expandTop=c,n.setCoords(),null===(d=n.canvas)||void 0===d||d.requestRenderAll(),!0)},expandBottomHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleY||1,h=n.height*a/2,l=undefined,c=Math.max(0,o.y-h)/a;var d;return Math.abs(c-r.expandBottom)>.5&&(r.expandBottom=c,n.setCoords(),null===(d=n.canvas)||void 0===d||d.requestRenderAll(),!0)};function createCornerExpandHandler(t,e){return(i,s,n,r)=>{const o=t(i,s,n,r),a=e(i,s,n,r);return o||a}}function expandCursorStyleHandler(t,e,i){const s=undefined,n=e.expandDirections;return n.includes("left")&&n.includes("right")?"ew-resize":n.includes("top")&&n.includes("bottom")?"ns-resize":n.includes("left")||n.includes("right")?"ew-resize":n.includes("top")||n.includes("bottom")?"ns-resize":2===n.length?n.includes("left")&&n.includes("top")||n.includes("right")&&n.includes("bottom")?"nwse-resize":"nesw-resize":"move"}function createExpandControls(){return{ml:new ExpandControl({x:-.5,y:0,expandDirections:["left"],actionHandler:expandLeftHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:6,sizeY:Jt}),mr:new ExpandControl({x:.5,y:0,expandDirections:["right"],actionHandler:expandRightHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:6,sizeY:Jt}),mt:new ExpandControl({x:0,y:-.5,expandDirections:["top"],actionHandler:expandTopHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:Jt,sizeY:6}),mb:new ExpandControl({x:0,y:.5,expandDirections:["bottom"],actionHandler:expandBottomHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:Jt,sizeY:6}),tl:new ExpandControl({x:-.5,y:-.5,expandDirections:["left","top"],actionHandler:createCornerExpandHandler(expandLeftHandler,expandTopHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt}),tr:new ExpandControl({x:.5,y:-.5,expandDirections:["right","top"],actionHandler:createCornerExpandHandler(expandRightHandler,expandTopHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt}),bl:new ExpandControl({x:-.5,y:.5,expandDirections:["left","bottom"],actionHandler:createCornerExpandHandler(expandLeftHandler,expandBottomHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt}),br:new ExpandControl({x:.5,y:.5,expandDirections:["right","bottom"],actionHandler:createCornerExpandHandler(expandRightHandler,expandBottomHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt})}}class InteractiveFabricObject extends At{static getDefaults(){return{...super.getDefaults(),...InteractiveFabricObject.ownDefaults}}constructor(t){super(),Object.assign(this,this.constructor.createControls(),InteractiveFabricObject.ownDefaults),this.setOptions(t),this.expandMode=!1,this.expansion={expandLeft:0,expandRight:0,expandTop:0,expandBottom:0}}static createControls(){return{controls:createObjectDefaultControls()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,i=e.target,s=e.action;if(this===i&&s&&s.startsWith(E))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&&void 0!==arguments[1]&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const i=Object.entries(this.oCoords);for(let s=i.length-1;s>=0;s--){const[n,r]=i[s],o=this.controls[n];if(o.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:o,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),i=createTranslateMatrix(e.x,e.y),s=createRotateMatrix({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=multiplyTransformMatrices(i,s),r=multiplyTransformMatrices(t,n),o=multiplyTransformMatrices(r,[1/t[0],0,0,1/t[3],0,0]),a=this.group?qrDecompose(this.calcTransformMatrix()):void 0;a&&(a.scaleX=Math.abs(a.scaleX),a.scaleY=Math.abs(a.scaleY));const h=this._calculateCurrentDimensions(a),l={};return this.forEachControl((t,e)=>{const i=t.positionHandler(h,o,this,t);l[e]=Object.assign(i,this._calcCornerCoords(t,i))}),l}_calcCornerCoords(t,e){const i=this.getTotalAngle(),s=undefined,n=undefined;return{corner:t.calcCornerCoords(i,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(i,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(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(),i=this._calculateCurrentDimensions(),s=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/s[0],1/s[3]),t.rotate(degreesToRadians(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-i.x/2,-i.y/2,i.x,i.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const s={hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray,...i};t.save(),t.strokeStyle=s.borderColor,this._setLineDash(t,s.borderDashArray),this.strokeBorders(t,e),s.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{hasBorders:i,hasControls:s}=this,n={hasBorders:i,hasControls:s,...e},r=this.getViewportTransform(),o=n.hasBorders,a=n.hasControls,h=multiplyTransformMatrices(r,this.calcTransformMatrix()),l=qrDecompose(h);t.save(),t.translate(l.translateX,l.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(l.angle-=180),t.rotate(degreesToRadians(this.group?l.angle:this.angle)),o&&this.drawBorders(t,l,e),a&&this.drawControls(t,e),t.restore()}drawBorders(t,e,i){let s;if(i&&i.forActiveSelection||this.group){const t=sizeAfterTransform(this.width,this.height,calcDimensionsMatrix(e)),i=this.isStrokeAccountedForInDimensions()?z:(this.strokeUniform?(new Point).scalarAdd(this.canvas?this.canvas.getZoom():1):new Point(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);s=t.add(i).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else s=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this.expandMode&&this.drawExpandPreview(t,s,e),this._drawBorders(t,s,i)}drawControlsConnectingLines(t,e){let i=!1;t.beginPath(),this.forEachControl((s,n)=>{s.withConnection&&s.getVisibility(this,n)&&(i=!0,t.moveTo(s.x*e.x,s.y*e.y),t.lineTo(s.x*e.x+s.offsetX,s.y*e.y+s.offsetY))}),i&&t.stroke()}drawControls(t){var e;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=null===(e=this.canvas)||void 0===e?void 0:e._currentTransform,n=undefined;if(s&&s.target===this&&this.isMoving){const e=s.corner;if(!e)return;const n=this.controls[e];if(n&&n.getVisibility(this,e)){t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:o,cornerColor:a}=this,h={cornerStrokeColor:r,cornerDashArray:o,cornerColor:a,...i};t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=h.cornerColor,this.transparentCorners||(t.strokeStyle=h.cornerStrokeColor),this._setLineDash(t,h.cornerDashArray);const l=this.oCoords[e];n.render(t,l.x,l.y,h,this),t.restore()}return}t.save();const r=this.getCanvasRetinaScaling(),{cornerStrokeColor:o,cornerDashArray:a,cornerColor:h}=this,l={cornerStrokeColor:o,cornerDashArray:a,cornerColor:h,...i};t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=l.cornerColor,this.transparentCorners||(t.strokeStyle=l.cornerStrokeColor),this._setLineDash(t,l.cornerDashArray),this.forEachControl((e,i)=>{if(e.getVisibility(this,i)){const s=this.oCoords[i];e.render(t,s.x,s.y,l,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&&void 0!==arguments[0]?arguments[0]:{};Object.entries(t).forEach(t=>{let[e,i]=t;return this.setControlVisible(e,i)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e);const s=this.width+4,n=this.height+4;return e.clearRect(-s/2,-n/2,s,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}enterExpandMode(){var t;this.expandMode||(this._savedControls=this.controls,this._savedLockMovementX=this.lockMovementX,this._savedLockMovementY=this.lockMovementY,this._savedLockScalingX=this.lockScalingX,this._savedLockScalingY=this.lockScalingY,this.lockMovementX=!0,this.lockMovementY=!0,this.lockScalingX=!0,this.lockScalingY=!0,this.controls=createExpandControls(),this.expandMode=!0,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}exitExpandMode(){var t;this.expandMode&&(this._savedControls?(this.controls=this._savedControls,this._savedControls=void 0):this.controls=createObjectDefaultControls(),void 0!==this._savedLockMovementX&&(this.lockMovementX=this._savedLockMovementX,this._savedLockMovementX=void 0),void 0!==this._savedLockMovementY&&(this.lockMovementY=this._savedLockMovementY,this._savedLockMovementY=void 0),void 0!==this._savedLockScalingX&&(this.lockScalingX=this._savedLockScalingX,this._savedLockScalingX=void 0),void 0!==this._savedLockScalingY&&(this.lockScalingY=this._savedLockScalingY,this._savedLockScalingY=void 0),this.expandMode=!1,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}toggleExpandMode(){this.expandMode?this.exitExpandMode():this.enterExpandMode()}getExpansion(){return{...this.expansion}}setExpansion(t){var e;Object.assign(this.expansion,t),this.setCoords(),null===(e=this.canvas)||void 0===e||e.requestRenderAll()}resetExpansion(){var t;this.expansion={expandLeft:0,expandRight:0,expandTop:0,expandBottom:0},this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()}hasExpansion(){const{expandLeft:t,expandRight:e,expandTop:i,expandBottom:s}=this.expansion;return t>0||e>0||i>0||s>0}getExpandedDimensions(){const{expandLeft:t,expandRight:e,expandTop:i,expandBottom:s}=this.expansion;return{expandedWidth:this.width+t+e,expandedHeight:this.height+i+s}}drawExpandPreview(t,e,i){if(!this.expandMode)return;const s=this.borderScaleFactor||1,n=2*(this.padding||0),r=e.x-s-n,o=e.y-s-n,a=r/(this.width||1),h=o/(this.height||1),{expandLeft:l,expandRight:c,expandTop:d,expandBottom:u}=this.expansion,g=l*a,f=c*a,p=d*h,m=u*h,y=r+g+f,x=o+p+m,v=(f-g)/2,_=(m-p)/2;t.save(),t.fillStyle=Nt,t.fillRect(-y/2+v,-x/2+_,y,x),t.strokeStyle=Ut,t.lineWidth=1,t.setLineDash(qt),t.strokeRect(-y/2+v,-x/2+_,y,x),t.restore()}}function applyMixins(t,e){return e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i)||Object.create(null))})}),t}_defineProperty(InteractiveFabricObject,"ownDefaults",Dt);class FabricObject extends InteractiveFabricObject{}applyMixins(FabricObject,[FabricObjectSVGExportMixin]),X.setClass(FabricObject),X.setClass(FabricObject,"object");const isTransparent=(t,e,i,s)=>{const n=2*(s=Math.round(s))+1,{data:r}=t.getImageData(e-s,i-s,n,n);for(let t=3;t<r.length;t+=4){const e=undefined;if(r[t]>0)return!1}return!0},findIndexRight=(t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i],i,t))return i;return-1};class StrokeProjectionsBase{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new Point(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new Point(1/this.options.scaleX,1/this.options.scaleY):new Point(1,1)}createSideVector(t,e){const i=createVector(t,e);return this.options.strokeUniform?i.multiply(this.scale):i}projectOrthogonally(t,e,i){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,i)))}isSkewed(){return 0!==this.options.skewX||0!==this.options.skewY}applySkew(t){const e=new Point(t);return e.y+=e.x*Math.tan(degreesToRadians(this.options.skewY)),e.x+=e.y*Math.tan(degreesToRadians(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const te=new Point;class StrokeLineJoinProjections extends StrokeProjectionsBase{static getOrthogonalRotationFactor(t,e){const i=e?calcAngleBetweenVectors(t,e):calcVectorRotation(t);return Math.abs(i)<a?-1:1}constructor(t,e,i,s){super(s),_defineProperty(this,"AB",void 0),_defineProperty(this,"AC",void 0),_defineProperty(this,"alpha",void 0),_defineProperty(this,"bisector",void 0),this.A=new Point(t),this.B=new Point(e),this.C=new Point(i),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=calcAngleBetweenVectors(this.AB,this.AC),this.bisector=getUnitVector(rotateVector(this.AB.eq(te)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.strokeProjectionMagnitude;const s=this.createSideVector(t,e),n=getOrthonormalVector(s),r=StrokeLineJoinProjections.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,i*r)}projectBevel(){const t=[];return(this.alpha%l===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),i=1/Math.sin(e/2),s=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*i),n=this.options.strokeUniform?magnitude(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return magnitude(s)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(s))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const i=[],s=new Point(StrokeLineJoinProjections.getOrthogonalRotationFactor(this.bisector),StrokeLineJoinProjections.getOrthogonalRotationFactor(new Point(this.bisector.y,this.bisector.x))),n=undefined,r=undefined;return[new Point(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(s),new Point(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(s)].forEach(s=>{isBetweenVectors(s,t,e)&&i.push(this.A.add(s))}),i}projectRoundWithSkew(t,e){const i=[],{skewX:s,skewY:n,scaleX:r,scaleY:o,strokeUniform:a}=this.options,h=new Point(Math.tan(degreesToRadians(s)),Math.tan(degreesToRadians(n))),l=this.strokeProjectionMagnitude,c=a?l/o/Math.sqrt(1/o**2+1/r**2*h.y**2):l/Math.sqrt(1+h.y**2),d=new Point(Math.sqrt(Math.max(l**2-c**2,0)),c),u=a?l/Math.sqrt(1+h.x**2*(1/o)**2/(1/r+1/r*h.x*h.y)**2):l/Math.sqrt(1+h.x**2/(1+h.x*h.y)**2),g=new Point(u,Math.sqrt(Math.max(l**2-u**2,0)));return[g,g.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(t=>this.applySkew(a?t.multiply(this.strokeUniformScalar):t)).forEach(s=>{isBetweenVectors(s,t,e)&&i.push(this.applySkew(this.A).add(s))}),i}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%l===0,i=this.applySkew(this.A),s=t[e?0:2].subtract(i),n=t[e?1:0].subtract(i),r=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),o=crossProduct(s,r)>0,a=o?s:n,h=o?n:s;return this.isSkewed()?t.push(...this.projectRoundWithSkew(a,h)):t.push(...this.projectRoundNoSkew(a,h)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class StrokeLineCapProjections extends StrokeProjectionsBase{constructor(t,e,i){super(i),this.A=new Point(t),this.T=new Point(e)}calcOrthogonalProjection(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.strokeProjectionMagnitude;const s=this.createSideVector(t,e);return this.scaleUnitVector(getOrthonormalVector(s),i)}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 Point(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 StrokeLineJoinProjections(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new Point(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),i=this.scaleUnitVector(getUnitVector(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),s=this.A.add(i);t.push(s.add(e),s.subtract(e))}return t.map(t=>this.applySkew(t))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}const projectStrokeOnPoints=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const s=[];if(0===t.length)return s;const n=t.reduce((t,e)=>(t[t.length-1].eq(e)||t.push(new Point(e)),t),[new Point(t[0])]);if(1===n.length)i=!0;else if(!i){const t=n[0],e=findIndexRight(n,e=>!e.eq(t));n.splice(e+1)}return n.forEach((t,n,r)=>{let o,a;0===n?(a=r[1],o=i?t:r[r.length-1]):n===r.length-1?(o=r[n-1],a=i?t:r[0]):(o=r[n-1],a=r[n+1]),i&&1===r.length?s.push(...new StrokeLineCapProjections(t,t,e).project()):!i||0!==n&&n!==r.length-1?s.push(...new StrokeLineJoinProjections(t,o,a,e).project()):s.push(...new StrokeLineCapProjections(t,0===n?a:o,e).project())}),s},cloneStyles=t=>{const e={};return Object.keys(t).forEach(i=>{e[i]={},Object.keys(t[i]).forEach(s=>{e[i][s]={...t[i][s]}})}),e},capitalize=function(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return`${t.charAt(0).toUpperCase()}${e?t.slice(1):t.slice(1).toLowerCase()}`},escapeXml=t=>t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let ee;const getSegmenter=()=>(ee||(ee="Intl"in getFabricWindow()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),ee),graphemeSplit=t=>{if(ee||getSegmenter(),ee){const e=ee.segment(t);return Array.from(e).map(t=>{let{segment:e}=t;return e})}return graphemeSplitImpl(t)},graphemeSplitImpl=t=>{const e=[];for(let i=0,s;i<t.length;i++)!1!==(s=getWholeChar(t,i))&&e.push(s);return e},getWholeChar=(t,e)=>{const i=t.charCodeAt(e);if(isNaN(i))return"";if(i<55296||i>57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";const i=t.charCodeAt(e+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";const s=t.charCodeAt(e-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var ie=Object.freeze({__proto__:null,capitalize:capitalize,escapeXml:escapeXml,graphemeSplit:graphemeSplit});const hasStyleChanged=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle||t.textDecorationThickness!==e.textDecorationThickness||t.textBackgroundColor!==e.textBackgroundColor||t.deltaY!==e.deltaY||i&&(t.overline!==e.overline||t.underline!==e.underline||t.linethrough!==e.linethrough)},stylesToArray=(t,e)=>{const i=e.split("\n"),s=[];let n=-1,r={};t=cloneStyles(t);for(let e=0;e<i.length;e++){const o=graphemeSplit(i[e]);if(t[e])for(let i=0;i<o.length;i++){n++;const o=t[e][i];o&&Object.keys(o).length>0&&(hasStyleChanged(r,o,!0)?s.push({start:n,end:n+1,style:o}):s[s.length-1].end++),r=o||{}}else n+=o.length,r={}}return s},stylesFromArray=(t,e)=>{if(!Array.isArray(t))return cloneStyles(t);const i=e.split(C),s={};let n=-1,r=0;for(let e=0;e<i.length;e++){const o=graphemeSplit(i[e]);for(let i=0;i<o.length;i++)n++,t[r]&&t[r].start<=n&&n<t[r].end&&(s[e]=s[e]||{},s[e][i]={...t[r].style},n===t[r].end-1&&r++)}return s},se=["display","transform",I,"fill-opacity","fill-rule","opacity",B,"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 selectorMatches(t,e){const i=t.nodeName,s=t.getAttribute("class"),n=t.getAttribute("id"),r="(?![a-zA-Z\\-]+)";let o;if(o=new RegExp("^"+i,"i"),e=e.replace(o,""),n&&e.length&&(o=new RegExp("#"+n+r,"i"),e=e.replace(o,"")),s&&e.length){const t=s.split(" ");for(let i=t.length;i--;)o=new RegExp("\\."+t[i]+r,"i"),e=e.replace(o,"")}return 0===e.length}function doesSomeParentMatch(t,e){let i,s=!0;for(;t.parentElement&&1===t.parentElement.nodeType&&e.length;)s&&(i=e.pop()),s=selectorMatches(t=t.parentElement,i);return 0===e.length}function elementMatchesRule(t,e){let i=!0;const s=selectorMatches(t,e.pop());return s&&e.length&&(i=doesSomeParentMatch(t,e)),s&&i&&0===e.length}function getGlobalStylesForElement(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};for(const s in e)elementMatchesRule(t,s.split(" "))&&(i={...i,...e[s]});return i}const normalizeAttr=t=>{var e;return null!==(e=yt[t])&&void 0!==e?e:t},ne=new RegExp(`(${lt})`,"gi"),cleanupSvgAttribute=t=>t.replace(ne," $1 ").replace(/,/gi," ").replace(/\s+/gi," "),re=`(${lt})`,oe=String.raw`(skewX)\(${re}\)`,ae=String.raw`(skewY)\(${re}\)`,he=String.raw`(rotate)\(${re}(?: ${re} ${re})?\)`,le=String.raw`(scale)\(${re}(?: ${re})?\)`,ce=String.raw`(translate)\(${re}(?: ${re})?\)`,de=undefined,ue=`(?:${String.raw`(matrix)\(${re} ${re} ${re} ${re} ${re} ${re}\)`}|${ce}|${he}|${le}|${oe}|${ae})`,ge=`(?:${ue}*)`,fe=String.raw`^\s*(?:${ge}?)\s*$`,pe=new RegExp(fe),me=new RegExp(ue),ye=new RegExp(ue,"g");function parseTransformAttribute(t){const e=[];if(!(t=cleanupSvgAttribute(t).replace(/\s*([()])\s*/gi,"$1"))||t&&!pe.test(t))return[...d];for(const i of t.matchAll(ye)){const t=me.exec(i[0]);if(!t)continue;let s=d;const n=t.filter(t=>!!t),[,r,...o]=n,[a,h,l,c,u,g]=o.map(t=>parseFloat(t));switch(r){case"translate":s=createTranslateMatrix(a,h);break;case T:s=createRotateMatrix({angle:a},{x:h,y:l});break;case E:s=createScaleMatrix(a,h);break;case L:s=createSkewXMatrix(a);break;case j:s=createSkewYMatrix(a);break;case"matrix":s=[a,h,l,c,u,g];break}e.push(s)}return multiplyTransformMatrixArray(e)}function normalizeValue(t,e,i,s){const n=Array.isArray(e);let r,o=e;if(t!==I&&t!==B||e!==_){if("strokeUniform"===t)return"non-scaling-stroke"===e;if("strokeDashArray"===t)o=e===_?null:e.replace(/,/g," ").split(/\s+/).map(parseFloat);else if("transformMatrix"===t)o=i&&i.transformMatrix?multiplyTransformMatrices(i.transformMatrix,parseTransformAttribute(e)):parseTransformAttribute(e);else if("visible"===t)o=e!==_&&"hidden"!==e,i&&!1===i.visible&&(o=!1);else if("opacity"===t)o=parseFloat(e),i&&void 0!==i.opacity&&(o*=i.opacity);else if("textAnchor"===t)o="start"===e?m:"end"===e?v:p;else if("charSpacing"===t||t===Z)r=parseUnit(e,s)/s*1e3;else if("paintFirst"===t){const t=e.indexOf(I),i=e.indexOf(B);o=I,(t>-1&&i>-1&&i<t||-1===t&&i>-1)&&(o=B)}else{if("href"===t||"xlink:href"===t||"font"===t||"id"===t)return e;if("imageSmoothing"===t)return"optimizeQuality"===e;r=n?e.map(parseUnit):parseUnit(e,s)}}else o="";return!n&&isNaN(r)?o:r}function parseFontDeclaration(t,e){const i=t.match(ut);if(!i)return;const s=i[1],n=i[3],r=i[4],o=i[5],a=i[6];s&&(e.fontStyle=s),n&&(e.fontWeight=isNaN(parseFloat(n))?n:parseFloat(n)),r&&(e.fontSize=parseUnit(r)),a&&(e.fontFamily=a),o&&(e.lineHeight="normal"===o?1:o)}function parseStyleObject(t,e){Object.entries(t).forEach(t=>{let[i,s]=t;void 0!==s&&(e[i.toLowerCase()]=s)})}function parseStyleString(t,e){t.replace(/;\s*$/,"").split(";").forEach(t=>{if(!t)return;const[i,s]=t.split(":");e[i.trim().toLowerCase()]=s.trim()})}function parseStyleAttribute(t){const e={},i=t.getAttribute("style");return i?("string"==typeof i?parseStyleString(i,e):parseStyleObject(i,e),e):e}const xe={stroke:"strokeOpacity",fill:"fillOpacity"};function setStrokeFillOpacity(t){const e=FabricObject.getDefaults();return Object.entries(xe).forEach(i=>{let[s,n]=i;if(void 0===t[n]||""===t[s])return;if(void 0===t[s]){if(!e[s])return;t[s]=e[s]}if(0===t[s].indexOf("url("))return;const r=new Color(t[s]);t[s]=r.setAlpha(toFixed(r.getAlpha()*t[n],2)).toRgba()}),t}function parseAttributes(t,e,i){if(!t)return{};let s={},n,r=u;t.parentNode&&bt.test(t.parentNode.nodeName)&&(s=parseAttributes(t.parentElement,e,i),s.fontSize&&(n=r=parseUnit(s.fontSize)));const o={...e.reduce((e,i)=>{const s=t.getAttribute(i);return s&&(e[i]=s),e},{}),...getGlobalStylesForElement(t,i),...parseStyleAttribute(t)};o[vt]&&t.setAttribute(vt,o[vt]),o[xt]&&(n=parseUnit(o[xt],r),o[xt]=`${n}`);const a={};for(const t in o){const e=normalizeAttr(t),i=normalizeValue(e,o[t],s,n);a[e]=i}a&&a.font&&parseFontDeclaration(a.font,a);const h={...s,...a};return bt.test(t.nodeName)?h:setStrokeFillOpacity(h)}const ve={rx:0,ry:0},_e=["rx","ry"];class Rect extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Rect.ownDefaults}}constructor(t){super(),Object.assign(this,Rect.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:i}=this,s=-e/2,n=-i/2,r=this.rx?Math.min(this.rx,e/2):0,o=this.ry?Math.min(this.ry,i/2):0,a=0!==r||0!==o;t.beginPath(),t.moveTo(s+r,n),t.lineTo(s+e-r,n),a&&t.bezierCurveTo(s+e-f*r,n,s+e,n+f*o,s+e,n+o),t.lineTo(s+e,n+i-o),a&&t.bezierCurveTo(s+e,n+i-f*o,s+e-f*r,n+i,s+e-r,n+i),t.lineTo(s+r,n+i),a&&t.bezierCurveTo(s+f*r,n+i,s,n+i-f*o,s,n+i-o),t.lineTo(s,n+o),a&&t.bezierCurveTo(s,n+f*o,s+f*r,n,s+r,n),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([..._e,...t])}_toSVG(){const{width:t,height:e,rx:i,ry:s}=this;return["<rect ","COMMON_PARTS",`x="${-t/2}" y="${-e/2}" rx="${i}" ry="${s}" width="${t}" height="${e}" />\n`]}static async fromElement(t,e,i){const{left:s=0,top:n=0,width:r=0,height:o=0,visible:a=!0,...h}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this({...e,...h,left:s,top:n,width:r,height:o,visible:Boolean(a&&r&&o)})}}_defineProperty(Rect,"type","Rect"),_defineProperty(Rect,"cacheProperties",[...Ot,..._e]),_defineProperty(Rect,"ownDefaults",ve),_defineProperty(Rect,"ATTRIBUTE_NAMES",[...se,"x","y","rx","ry","width","height"]),X.setClass(Rect),X.setSVGClass(Rect);const Ce="initialization",be="added",Se="removed",we="imperative",Te="object_modified",Pe="object_modifying",getObjectBounds=(t,e)=>{const{strokeUniform:i,strokeWidth:s,width:n,height:r,group:o}=e,a=o&&o!==t?calcPlaneChangeMatrix(o.calcTransformMatrix(),t.calcTransformMatrix()):null,h=a?e.getRelativeCenterPoint().transform(a):e.getRelativeCenterPoint(),l=!e.isStrokeAccountedForInDimensions(),c=i&&l?sendVectorToPlane(new Point(s,s),void 0,t.calcTransformMatrix()):z,d=!i&&l?s:0,u=sizeAfterTransform(n+d,r+d,multiplyTransformMatrixArray([a,e.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[h.subtract(u),h.add(u)]};class LayoutStrategy{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:i,strategy:s}=t;return e===Ce||e===we||!!i&&s!==i}shouldLayoutClipPath(t){let{type:e,target:{clipPath:i}}=t;return e!==Ce&&i&&!i.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:i,target:s}=e;if(i===we&&e.overrides)return e.overrides;if(0===t.length)return;const{left:n,top:r,width:o,height:a}=makeBoundingBoxFromPoints(t.map(t=>getObjectBounds(s,t)).reduce((t,e)=>t.concat(e),[])),h=new Point(o,a),l=undefined,c=new Point(n,r).add(h.scalarDivide(2));if(i===Ce){const t=this.getInitialSize(e,{size:h,center:c});return{center:c,relativeCorrection:new Point(0,0),size:t}}{const t=undefined;return{center:c.transform(s.calcOwnMatrix()),size:h}}}}_defineProperty(LayoutStrategy,"type","strategy");class FitContentLayout extends LayoutStrategy{shouldPerformLayout(t){return!0}}_defineProperty(FitContentLayout,"type","fit-content"),X.setClass(FitContentLayout);const Me="layoutManager";class LayoutManager{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new FitContentLayout;_defineProperty(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 i=this.getLayoutResult(e);i&&this.commitLayout(e,i),this.onAfterLayout(e,i),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:i}=e;return[R,b,M,w,S,P,D,O,k].map(e=>t.on(e,t=>this.performLayout(e===R?{type:Te,trigger:e,e:t,target:i}:{type:Pe,trigger:e,e:t,target:i})))}subscribe(t,e){this.unsubscribe(t,e);const i=this.attachHandlers(t,e);this._subscriptions.set(t,i)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(t=>t()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){const{target:e,type:i}=t,{canvas:s}=e;if(i===Ce||i===be?this.subscribeTargets(t):i===Se&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),s&&s.fire("object:layout:before",{target:e,context:t}),i===we&&t.deep){const{strategy:i,...s}=t;e.forEachObject(t=>t.layoutManager&&t.layoutManager.performLayout({...s,bubbles:!1,target:t}))}}getLayoutResult(t){const{target:e,strategy:i,type:s}=t,n=i.calcLayoutResult(t,e.getObjects());if(!n)return;const r=s===Ce?new Point:e.getRelativeCenterPoint(),{center:o,correction:a=new Point,relativeCorrection:h=new Point}=n,l=r.subtract(o).add(a).transform(s===Ce?d:invertTransform(e.calcOwnMatrix()),!0).add(h);return{result:n,prevCenter:r,nextCenter:o,offset:l}}commitLayout(t,e){const{target:i}=t,{result:{size:s},nextCenter:n}=e;var r,o;(i.set({width:s.x,height:s.y}),this.layoutObjects(t,e),t.type===Ce)?i.set({left:null!==(r=t.x)&&void 0!==r?r:n.x+s.x*resolveOrigin(i.originX),top:null!==(o=t.y)&&void 0!==o?o:n.y+s.y*resolveOrigin(i.originY)}):(i.setPositionByOrigin(n,p,p),i.setCoords(),i.set("dirty",!0))}layoutObjects(t,e){const{target:i}=t;i.forEachObject(s=>{s.group===i&&this.layoutObject(t,e,s)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,i.clipPath)}layoutObject(t,e,i){let{offset:s}=e;i.set({left:i.left+s.x,top:i.top+s.y})}onAfterLayout(t,e){const{target:i,strategy:s,bubbles:n,prevStrategy:r,...o}=t,{canvas:a}=i;i.fire("layout:after",{context:t,result:e}),a&&a.fire("object:layout:after",{context:t,result:e,target:i});const h=i.parent;n&&null!=h&&h.layoutManager&&((o.path||(o.path=[])).push(i),h.layoutManager.performLayout({...o,target:h})),i.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(t=>t.forEach(t=>t())),t.clear()}toObject(){return{type:Me,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}X.setClass(LayoutManager,Me);class NoopLayoutManager extends LayoutManager{performLayout(){}}const Oe={strokeWidth:0,subTargetCheck:!1,interactive:!1};class Group extends(createCollectionMixin(FabricObject)){static getDefaults(){return{...super.getDefaults(),...Group.ownDefaults}}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_defineProperty(this,"_activeObjects",[]),_defineProperty(this,"__objectSelectionTracker",void 0),_defineProperty(this,"__objectSelectionDisposer",void 0),Object.assign(this,Group.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var i;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(t=>{this.enterGroup(t,!1)}),this.layoutManager=null!==(i=e.layoutManager)&&void 0!==i?i:new LayoutManager,this.layoutManager.performLayout({type:Ce,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(log("error","Group: circular object trees are not supported, this call has no effect"),!1):-1===this._objects.indexOf(t)||(log("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((t,e,i)=>this.canEnterGroup(t)&&i.indexOf(t)===e)}add(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const s=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...s);return this._onAfterObjectsChange(be,s),n}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];const n=this._filterObjectsBeforeEnteringGroup(i),r=super.insertAt(t,...n);return this._onAfterObjectsChange(be,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Se,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 i=this[t];return super._set(t,e),"canvas"===t&&i!==e&&(this._objects||[]).forEach(i=>{i._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:i}=e;const s=this._activeObjects;if(t)s.push(i),this._set("dirty",!0);else if(s.length>0){const t=s.indexOf(i);t>-1&&(s.splice(t,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&applyTransformToObject(t,multiplyTransformMatrices(invertTransform(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const i=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();i&&(i===t||t.isDescendantOf(i))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(applyTransformToObject(t,multiplyTransformMatrices(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const i=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;i>-1&&this._activeObjects.splice(i,1)}shouldCache(){const t=FabricObject.prototype.shouldCache.call(this);if(t)for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return this.ownCaching=!1,!1;return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,i){this._renderBackground(t);for(let e=0;e<this._objects.length;e++){var s;const i=this._objects[e];null!==(s=this.canvas)&&void 0!==s&&s.preserveObjectStacking&&i.group!==this?(t.save(),t.transform(...invertTransform(this.calcTransformMatrix())),i.render(t),t.restore()):i.group===this&&i.render(t)}this._drawClipPath(t,this.clipPath,i)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.layoutManager.performLayout({target:this,type:we,...t})}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const i=this.includeDefaultValues;return this._objects.filter(function(t){return!t.excludeFromExport}).map(function(s){const n=s.includeDefaultValues;s.includeDefaultValues=i;const r=s[t||"toObject"](e);return s.includeDefaultValues=n,r})}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=this.layoutManager.toObject();return{...super.toObject(["subTargetCheck","interactive",...t]),..."fit-content"!==e.strategy||this.includeDefaultValues?{layoutManager:e}:{},objects:this.__serializeObjects("toObject",t)}}toString(){return`#<Group: (${this.complexity()})>`}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Rect.prototype._toSVG.call(this),i=e.indexOf("COMMON_PARTS");e[i]='for="group" ';const s=e.join("");return t?t(s):s}_toSVG(t){const e=["<g ","COMMON_PARTS"," >\n"],i=this._createSVGBgRect(t);i&&e.push("\t\t",i);for(let i=0;i<this._objects.length;i++)e.push("\t\t",this._objects[i].toSVG(t));return e.push("</g>\n"),e}getSvgStyles(){const t=void 0!==this.opacity&&1!==this.opacity?`opacity: ${this.opacity};`:"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],i=this._createSVGBgRect(t);i&&e.push("\t",i);for(let i=0;i<this._objects.length;i++)e.push("\t",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:i,objects:s=[],layoutManager:n,...r}=t;return Promise.all([enlivenObjects(s,e),enlivenObjectEnlivables(r,e)]).then(t=>{let[e,i]=t;const s=new this(e,{...r,...i,layoutManager:new NoopLayoutManager});if(n){const t=X.getClass(n.type),e=X.getClass(n.strategy);s.layoutManager=new t(new e)}else s.layoutManager=new LayoutManager;return s.layoutManager.subscribeTargets({type:Ce,target:s,targets:s.getObjects()}),s.setCoords(),s})}}_defineProperty(Group,"type","Group"),_defineProperty(Group,"ownDefaults",Oe),X.setClass(Group);const groupSVGElements=(t,e)=>t&&1===t.length?t[0]:new Group(t,e),findScaleToFit=(t,e)=>Math.min(e.width/t.width,e.height/t.height),findScaleToCover=(t,e)=>Math.max(e.width/t.width,e.height/t.height),ke="\\s*,?\\s*",De=`${ke}(${lt})`,Ee=`${De}${De}${De}${ke}([01])${ke}([01])${De}${De}`,Ae=undefined,Fe={m:"l",M:"L"},segmentToBezier=(t,e,i,s,n,r,o,a,h,l,c)=>{const d=cos(t),u=sin(t),g=cos(e),f=sin(e),p=i*n*g-s*r*f+o,m=s*n*g+i*r*f+a,y=undefined,x=undefined,v=undefined,_=undefined;return["C",l+h*(-i*n*u-s*r*d),c+h*(-s*n*u+i*r*d),p+h*(i*n*f+s*r*g),m+h*(s*n*f-i*r*g),p,m]},arcToSegments=(t,e,i,s,n,r,o)=>{if(0===i||0===s)return[];let a=0,h=0,l=0;const d=Math.PI,u=o*c,g=sin(u),f=cos(u),p=.5*(-f*t-g*e),m=.5*(-f*e+g*t),y=i**2,x=s**2,v=m**2,_=p**2,C=y*x-y*v-x*_;let b=Math.abs(i),S=Math.abs(s);if(C<0){const t=Math.sqrt(1-C/(y*x));b*=t,S*=t}else l=(n===r?-1:1)*Math.sqrt(C/(y*v+x*_));const w=l*b*m/S,T=-l*S*p/b,P=f*w-g*T+.5*t,M=g*w+f*T+.5*e;let O=calcVectorAngle(1,0,(p-w)/b,(m-T)/S),k=calcVectorAngle((p-w)/b,(m-T)/S,(-p-w)/b,(-m-T)/S);0===r&&k>0?k-=2*d:1===r&&k<0&&(k+=2*d);const D=Math.ceil(Math.abs(k/d*2)),E=[],A=k/D,F=8/3*Math.sin(A/4)*Math.sin(A/4)/Math.sin(A/2);let L=O+A;for(let t=0;t<D;t++)E[t]=segmentToBezier(O,L,f,g,b,S,P,M,F,a,h),a=E[t][5],h=E[t][6],O=L,L+=A;return E},calcVectorAngle=(t,e,i,s)=>{const n=Math.atan2(e,t),r=Math.atan2(s,i);return r>=n?r-n:2*Math.PI-(n-r)},CB1=t=>t**3,CB2=t=>3*t**2*(1-t),CB3=t=>3*t*(1-t)**2,CB4=t=>(1-t)**3;function getBoundsOfCurve(t,i,s,r,o,a,h,l){let c;if(e.cachesBoundsOfCurve&&(c=[...arguments].join(),n.boundsOfCurveCache[c]))return n.boundsOfCurveCache[c];const d=Math.sqrt,u=Math.abs,g=[],f=[[0,0],[0,0]];let p=6*t-12*s+6*o,m=-3*t+9*s-9*o+3*h,y=3*s-3*t;for(let t=0;t<2;++t){if(t>0&&(p=6*i-12*r+6*a,m=-3*i+9*r-9*a+3*l,y=3*r-3*i),u(m)<1e-12){if(u(p)<1e-12)continue;const t=-y/p;0<t&&t<1&&g.push(t);continue}const e=p*p-4*y*m;if(e<0)continue;const s=d(e),n=(-p+s)/(2*m);0<n&&n<1&&g.push(n);const o=(-p-s)/(2*m);0<o&&o<1&&g.push(o)}let x=g.length;const v=x,_=getPointOnCubicBezierIterator(t,i,s,r,o,a,h,l);for(;x--;){const{x:t,y:e}=_(g[x]);f[0][x]=t,f[1][x]=e}f[0][v]=t,f[1][v]=i,f[0][v+1]=h,f[1][v+1]=l;const C=[new Point(Math.min(...f[0]),Math.min(...f[1])),new Point(Math.max(...f[0]),Math.max(...f[1]))];return e.cachesBoundsOfCurve&&(n.boundsOfCurveCache[c]=C),C}const fromArcToBeziers=(t,e,i)=>{let[s,n,r,o,a,h,l,c]=i;const d=arcToSegments(l-t,c-e,n,r,a,h,o);for(let i=0,s=d.length;i<s;i++)d[i][1]+=t,d[i][2]+=e,d[i][3]+=t,d[i][4]+=e,d[i][5]+=t,d[i][6]+=e;return d},makePathSimpler=t=>{let e=0,i=0,s=0,n=0;const r=[];let o,a=0,h=0;for(const l of t){const t=[...l];let c;switch(t[0]){case"l":t[1]+=e,t[2]+=i;case"L":e=t[1],i=t[2],c=["L",e,i];break;case"h":t[1]+=e;case"H":e=t[1],c=["L",e,i];break;case"v":t[1]+=i;case"V":i=t[1],c=["L",e,i];break;case"m":t[1]+=e,t[2]+=i;case"M":e=t[1],i=t[2],s=t[1],n=t[2],c=["M",e,i];break;case"c":t[1]+=e,t[2]+=i,t[3]+=e,t[4]+=i,t[5]+=e,t[6]+=i;case"C":a=t[3],h=t[4],e=t[5],i=t[6],c=["C",t[1],t[2],a,h,e,i];break;case"s":t[1]+=e,t[2]+=i,t[3]+=e,t[4]+=i;case"S":"C"===o?(a=2*e-a,h=2*i-h):(a=e,h=i),e=t[3],i=t[4],c=["C",a,h,t[1],t[2],e,i],a=c[3],h=c[4];break;case"q":t[1]+=e,t[2]+=i,t[3]+=e,t[4]+=i;case"Q":a=t[1],h=t[2],e=t[3],i=t[4],c=["Q",a,h,e,i];break;case"t":t[1]+=e,t[2]+=i;case"T":"Q"===o?(a=2*e-a,h=2*i-h):(a=e,h=i),e=t[1],i=t[2],c=["Q",a,h,e,i];break;case"a":t[6]+=e,t[7]+=i;case"A":fromArcToBeziers(e,i,t).forEach(t=>r.push(t)),e=t[6],i=t[7];break;case"z":case"Z":e=s,i=n,c=["Z"];break}c?(r.push(c),o=c[0]):o=""}return r},calcLineLength=(t,e,i,s)=>Math.sqrt((i-t)**2+(s-e)**2),getPointOnCubicBezierIterator=(t,e,i,s,n,r,o,a)=>h=>{const l=CB1(h),c=CB2(h),d=CB3(h),u=CB4(h);return new Point(o*l+n*c+i*d+t*u,a*l+r*c+s*d+e*u)},QB1=t=>t**2,QB2=t=>2*t*(1-t),QB3=t=>(1-t)**2,getTangentCubicIterator=(t,e,i,s,n,r,o,a)=>h=>{const l=QB1(h),c=QB2(h),d=QB3(h),u=3*(d*(i-t)+c*(n-i)+l*(o-n)),g=3*(d*(s-e)+c*(r-s)+l*(a-r));return Math.atan2(g,u)},getPointOnQuadraticBezierIterator=(t,e,i,s,n,r)=>o=>{const a=QB1(o),h=QB2(o),l=QB3(o);return new Point(n*a+i*h+t*l,r*a+s*h+e*l)},getTangentQuadraticIterator=(t,e,i,s,n,r)=>o=>{const a=1-o,h=2*(a*(i-t)+o*(n-i)),l=2*(a*(s-e)+o*(r-s));return Math.atan2(l,h)},pathIterator=(t,e,i)=>{let s=new Point(e,i),n=0;for(let e=1;e<=100;e+=1){const i=t(e/100);n+=calcLineLength(s.x,s.y,i.x,i.y),s=i}return n},findPercentageForDistance=(t,e)=>{let i=0,s=0,n={x:t.x,y:t.y},r={...n},o,a=.01,h=0;const l=t.iterator,c=t.angleFinder;for(;s<e&&a>1e-4;)r=l(i),h=i,o=calcLineLength(n.x,n.y,r.x,r.y),o+s>e?(i-=a,a/=2):(n=r,i+=a,s+=o);return{...r,angle:c(h)}},getPathSegmentsInfo=t=>{let e=0,i=0,s=0,n=0,r=0,o,a;const h=[];for(const l of t){const t={x:i,y:s,command:l[0],length:0};switch(l[0]){case"M":a=t,a.x=n=i=l[1],a.y=r=s=l[2];break;case"L":a=t,a.length=calcLineLength(i,s,l[1],l[2]),i=l[1],s=l[2];break;case"C":o=getPointOnCubicBezierIterator(i,s,l[1],l[2],l[3],l[4],l[5],l[6]),a=t,a.iterator=o,a.angleFinder=getTangentCubicIterator(i,s,l[1],l[2],l[3],l[4],l[5],l[6]),a.length=pathIterator(o,i,s),i=l[5],s=l[6];break;case"Q":o=getPointOnQuadraticBezierIterator(i,s,l[1],l[2],l[3],l[4]),a=t,a.iterator=o,a.angleFinder=getTangentQuadraticIterator(i,s,l[1],l[2],l[3],l[4]),a.length=pathIterator(o,i,s),i=l[3],s=l[4];break;case"Z":a=t,a.destX=n,a.destY=r,a.length=calcLineLength(i,s,n,r),i=n,s=r;break}e+=a.length,h.push(a)}return h.push({length:e,x:i,y:s}),h},getPointOnPath=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:getPathSegmentsInfo(t),s=0;for(;e-i[s].length>0&&s<i.length-2;)e-=i[s].length,s++;const n=i[s],r=e/n.length,o=t[s];switch(n.command){case"M":return{x:n.x,y:n.y,angle:0};case"Z":return{...new Point(n.x,n.y).lerp(new Point(n.destX,n.destY),r),angle:Math.atan2(n.destY-n.y,n.destX-n.x)};case"L":return{...new Point(n.x,n.y).lerp(new Point(o[1],o[2]),r),angle:Math.atan2(o[2]-n.y,o[1]-n.x)};case"C":return findPercentageForDistance(n,e);case"Q":return findPercentageForDistance(n,e)}},Le=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),je=new RegExp(Ee,"g"),Ie=new RegExp(lt,"gi"),Be={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},parsePath=t=>{var e;const i=[],s=null!==(e=t.match(Le))&&void 0!==e?e:[];for(const t of s){const e=t[0];if("z"===e||"Z"===e){i.push([e]);continue}const s=Be[e.toLowerCase()];let n=[];if("a"===e||"A"===e){je.lastIndex=0;for(let e=null;e=je.exec(t);)n.push(...e.slice(1))}else n=t.match(Ie)||[];for(let t=0;t<n.length;t+=s){const r=new Array(s),o=Fe[e];r[0]=t>0&&o?o:e;for(let e=0;e<s;e++)r[e+1]=parseFloat(n[t+e]);i.push(r)}}return i},getSmoothPathFromPoints=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new Point(t[0]),s=new Point(t[1]),n=1,r=0;const o=[],a=t.length,h=a>2;let l;for(h&&(n=t[2].x<s.x?-1:t[2].x===s.x?0:1,r=t[2].y<s.y?-1:t[2].y===s.y?0:1),o.push(["M",i.x-n*e,i.y-r*e]),l=1;l<a;l++){if(!i.eq(s)){const t=i.midPointFrom(s);o.push(["Q",i.x,i.y,t.x,t.y])}i=t[l],l+1<t.length&&(s=t[l+1])}return h&&(n=i.x>t[l-2].x?1:i.x===t[l-2].x?0:-1,r=i.y>t[l-2].y?1:i.y===t[l-2].y?0:-1),o.push(["L",i.x+n*e,i.y+r*e]),o},transformPath=(t,e,i)=>(i&&(e=multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(t=>{const i=[...t];for(let s=1;s<t.length-1;s+=2){const{x:n,y:r}=transformPoint({x:t[s],y:t[s+1]},e);i[s]=n,i[s+1]=r}return i})),getRegularPolygonPath=(t,e)=>{const i=2*Math.PI/t;let s=-a;t%2==0&&(s+=i/2);const n=new Array(t+1);for(let r=0;r<t;r++){const t=r*i+s,{x:o,y:a}=new Point(cos(t),sin(t)).scalarMultiply(e);n[r]=[0===r?"M":"L",o,a]}return n[t]=["Z"],n},joinPath=(t,e)=>t.map(t=>t.map((t,i)=>0===i||void 0===e?t:toFixed(t,e)).join(" ")).join(" "),mergeClipPaths=(t,e)=>{var i;let s=t,n=e;s.inverted&&!n.inverted&&(s=e,n=t),sendObjectToPlane(n,null===(i=n.group)||void 0===i?void 0:i.calcTransformMatrix(),s.calcTransformMatrix());const r=s.inverted&&n.inverted;return r&&(s.inverted=n.inverted=!1),new Group([s],{clipPath:n,inverted:r})},getRandomInt=(t,e)=>Math.floor(Math.random()*(e-t+1))+t,_assignTransformMatrixProps=t=>{if(t.transformMatrix){const{scaleX:e,scaleY:i,angle:s,skewX:n}=qrDecompose(t.transformMatrix);t.flipX=!1,t.flipY=!1,t.set(A,e),t.set(F,i),t.angle=s,t.skewX=n,t.skewY=0}},removeTransformMatrixForSvgParsing=(t,e)=>{let i=t._findCenterFromElement();t.transformMatrix&&(_assignTransformMatrixProps(t),i=i.transform(t.transformMatrix)),delete t.transformMatrix,e&&(t.scaleX*=e.scaleX,t.scaleY*=e.scaleY,t.cropX=e.cropX,t.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,t.width=e.width,t.height=e.height),t.setPositionByOrigin(i,p,p)};var Re=Object.freeze({__proto__:null,addTransformToObject:addTransformToObject,animate:animate,animateColor:animateColor,applyTransformToObject:applyTransformToObject,calcAngleBetweenVectors:calcAngleBetweenVectors,calcDimensionsMatrix:calcDimensionsMatrix,calcPlaneChangeMatrix:calcPlaneChangeMatrix,calcVectorRotation:calcVectorRotation,cancelAnimFrame:cancelAnimFrame,capValue:capValue,composeMatrix:composeMatrix,copyCanvasElement:copyCanvasElement,cos:cos,createCanvasElement:createCanvasElement,createImage:createImage,createRotateMatrix:createRotateMatrix,createScaleMatrix:createScaleMatrix,createSkewXMatrix:createSkewXMatrix,createSkewYMatrix:createSkewYMatrix,createTranslateMatrix:createTranslateMatrix,createVector:createVector,crossProduct:crossProduct,degreesToRadians:degreesToRadians,dotProduct:dotProduct,ease:Et,enlivenObjectEnlivables:enlivenObjectEnlivables,enlivenObjects:enlivenObjects,findScaleToCover:findScaleToCover,findScaleToFit:findScaleToFit,getBoundsOfCurve:getBoundsOfCurve,getOrthonormalVector:getOrthonormalVector,getPathSegmentsInfo:getPathSegmentsInfo,getPointOnPath:getPointOnPath,getPointer:getPointer,getRandomInt:getRandomInt,getRegularPolygonPath:getRegularPolygonPath,getSmoothPathFromPoints:getSmoothPathFromPoints,getSvgAttributes:getSvgAttributes,getUnitVector:getUnitVector,groupSVGElements:groupSVGElements,hasStyleChanged:hasStyleChanged,invertTransform:invertTransform,isBetweenVectors:isBetweenVectors,isIdentityMatrix:isIdentityMatrix,isTouchEvent:isTouchEvent,isTransparent:isTransparent,joinPath:joinPath,loadImage:loadImage,magnitude:magnitude,makeBoundingBoxFromPoints:makeBoundingBoxFromPoints,makePathSimpler:makePathSimpler,matrixToSVG:matrixToSVG,mergeClipPaths:mergeClipPaths,multiplyTransformMatrices:multiplyTransformMatrices,multiplyTransformMatrixArray:multiplyTransformMatrixArray,parsePath:parsePath,parsePreserveAspectRatioAttribute:parsePreserveAspectRatioAttribute,parseUnit:parseUnit,pick:pick,projectStrokeOnPoints:projectStrokeOnPoints,qrDecompose:qrDecompose,radiansToDegrees:radiansToDegrees,removeFromArray:removeFromArray,removeTransformFromObject:removeTransformFromObject,removeTransformMatrixForSvgParsing:removeTransformMatrixForSvgParsing,requestAnimFrame:requestAnimFrame,resetObjectTransform:resetObjectTransform,rotateVector:rotateVector,saveObjectTransform:saveObjectTransform,sendObjectToPlane:sendObjectToPlane,sendPointToPlane:sendPointToPlane,sendVectorToPlane:sendVectorToPlane,sin:sin,sizeAfterTransform:sizeAfterTransform,string:ie,stylesFromArray:stylesFromArray,stylesToArray:stylesToArray,toBlob:toBlob,toDataURL:toDataURL,toFixed:toFixed,transformPath:transformPath,transformPoint:transformPoint});function setStyle(t,e){const i=t.style;i&&Object.entries(e).forEach(t=>{let[e,s]=t;return i.setProperty(e,s)})}class CanvasDOMManager extends StaticCanvasDOMManager{constructor(t){let{allowTouchScrolling:e=!1,containerClass:i=""}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(t),_defineProperty(this,"upper",void 0),_defineProperty(this,"container",void 0);const{el:s}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(s,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(i),s.parentNode&&s.parentNode.replaceChild(r,s),r.append(s,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=createCanvasElement();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=getFabricDocument().createElement("div");return t.setAttribute("data-fabric","wrapper"),setStyle(t,{position:"relative"}),makeElementUnselectable(t),t}applyCanvasStyle(t,e){const{styles:i,allowTouchScrolling:s}=e;setStyle(t,{...i,"touch-action":s?"manipulation":_}),makeElementUnselectable(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:i,ctx:s}=this.upper;setCanvasDimensions(i,s,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),setCSSDimensions(this.upper.el,t),setCSSDimensions(this.container,t)}cleanupDOM(t){const e=this.container,{el:i}=this.lower,{el:s}=this.upper;super.cleanupDOM(t),e.removeChild(s),e.removeChild(i),e.parentNode&&e.parentNode.replaceChild(i,e)}dispose(){super.dispose(),getEnv().dispose(this.upper.el),delete this.upper,delete this.container}}const We={uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!0};class SelectableCanvas extends StaticCanvas{constructor(){super(...arguments),_defineProperty(this,"_hoveredTargets",[]),_defineProperty(this,"_objectsToRender",void 0),_defineProperty(this,"_currentTransform",null),_defineProperty(this,"_groupSelector",null),_defineProperty(this,"contextTopDirty",!1)}static getDefaults(){return{...super.getDefaults(),...SelectableCanvas.ownDefaults}}get upperCanvasEl(){var t;return null===(t=this.elements.upper)||void 0===t?void 0:t.el}get contextTop(){var t;return null===(t=this.elements.upper)||void 0===t?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new CanvasDOMManager(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(),i=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=i,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,i){const s=this.targetFindTolerance,n=this.pixelFindContext;this.clearContext(n),n.save(),n.translate(-e+s,-i+s),n.transform(...this.viewportTransform);const r=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(n),t.selectionBackgroundColor=r,n.restore();const o=Math.round(s*this.getRetinaScaling());return isTransparent(n,o,o,o)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(e=>!!e&&!0===t[e]):t[e])}_shouldClearSelection(t,e){const i=this.getActiveObjects(),s=this._activeObject;return!!(!e||e&&s&&i.length>1&&-1===i.indexOf(e)&&s!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&s&&s!==e)}_shouldCenterTransform(t,e,i){if(!t)return;let s;return e===E||e===A||e===F||e===M?s=this.centeredScaling||t.centeredScaling:e===T&&(s=this.centeredRotation||t.centeredRotation),s?!i:i}_getOriginFromCorner(t,e){const i={x:t.originX,y:t.originY};return e?(["ml","tl","bl"].includes(e)?i.x=v:["mr","tr","br"].includes(e)&&(i.x=m),["tl","mt","tr"].includes(e)?i.y=x:["bl","mb","br"].includes(e)&&(i.y=y),i):i}_setupCurrentTransform(t,e,i){var s;const n=e.group?sendPointToPlane(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},a=i&&o?null===(s=o.getActionHandler(t,e,o))||void 0===s?void 0:s.bind(o):dragHandler,h=getActionFromCorner(i,r,t,e),l=t[this.centeredKey],c=this._shouldCenterTransform(e,h,l)?{x:p,y:p}:this._getOriginFromCorner(e,r),d={target:e,action:h,actionHandler:a,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:c.x,originY:c.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:degreesToRadians(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:l,original:{...saveObjectTransform(e),originX:c.x,originY:c.y}};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:i,deltaX:s,deltaY:n}=this._groupSelector,r=new Point(e,i).transform(this.viewportTransform),o=new Point(e+s,i+n).transform(this.viewportTransform),a=this.selectionLineWidth/2;let h=Math.min(r.x,o.x),l=Math.min(r.y,o.y),c=Math.max(r.x,o.x),d=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(h,l,c-h,d-l)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,h+=a,l+=a,c-=a,d-=a,FabricObject.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(h,l,c-h,d-l))}findTarget(t){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};const e=this.getScenePoint(t),i=this._activeObject,s=this.getActiveObjects(),n=this.searchPossibleTargets(this._objects,e),{subTargets:r,container:o,target:a}=n,h={...n,currentSubTargets:r,currentContainer:o,currentTarget:a};if(!i)return h;const l={...this.searchPossibleTargets([i],e),currentSubTargets:r,currentContainer:o,currentTarget:a},c=undefined;if(i.findControl(this.getViewportPoint(t),isTouchEvent(t)))return{...l,target:i};if(l.target){if(s.length>1)return l;if(!this.preserveObjectStacking)return l;if(this.preserveObjectStacking&&t[this.altSelectionKey])return l}return h}_pointIsInObjectSelectionArea(t,e){let i=t.getCoords();const s=this.getZoom(),n=t.padding/s;if(n){const[t,e,s,r]=i,o=Math.atan2(e.y-t.y,e.x-t.x),a=cos(o)*n,h=sin(o)*n,l=a+h,c=a-h;i=[new Point(t.x-c,t.y-l),new Point(e.x+l,e.y-c),new Point(s.x+c,s.y+l),new Point(r.x-l,r.y+c)]}return Intersection.isPointInPolygon(e,i)}_checkTarget(t,e){if(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;{const i=e.transform(this.viewportTransform);if(!this.isTargetTransparent(t,i.x,i.y))return!0}}return!1}_searchPossibleTargets(t,e,i){let s=t.length;for(;s--;){const n=t[s];if(this._checkTarget(n,e)){if(isCollection(n)&&n.subTargetCheck){const{target:t}=this._searchPossibleTargets(n._objects,e,i);t&&i.push(t)}return{target:n,subTargets:i}}}return{subTargets:[]}}searchPossibleTargets(t,e){const i=this._searchPossibleTargets(t,e,[]);i.container=i.target;const{container:s,subTargets:n}=i;if(s&&isCollection(s)&&s.interactive&&n[0]){for(let t=n.length-1;t>0;t--){const e=n[t];if(!isCollection(e)||!e.interactive)return i.target=e,i}return i.target=n[0],i}return i}getViewportPoint(t){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(t,!0)}getScenePoint(t){return this._scenePoint?this._scenePoint:this._getPointerImpl(t)}_getPointerImpl(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=this.upperCanvasEl,s=i.getBoundingClientRect();let n=getPointer(t),r=s.width||0,o=s.height||0;r&&o||(y in s&&x in s&&(o=Math.abs(s.top-s.bottom)),v in s&&m in s&&(r=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=sendPointToPlane(n,void 0,this.viewportTransform));const a=this.getRetinaScaling();1!==a&&(n.x/=a,n.y/=a);const h=0===r||0===o?new Point(1,1):new Point(i.width/r,i.height/o);return n.multiply(h)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=createCanvasElement(),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 isActiveSelection(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let i=!1,s=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach(t=>{n.includes(t)||(i=!0,t.fire("deselected",{e:e,target:t}),o.push(t))}),n.forEach(s=>{t.includes(s)||(i=!0,s.fire("selected",{e:e,target:s}),r.push(s))}),t.length>0&&n.length>0?(s=!0,i&&this.fire("selection:updated",{e:e,selected:r,deselected:o})):n.length>0?(s=!0,this.fire("selection:created",{e:e,selected:r})):t.length>0&&(s=!0,this.fire("selection:cleared",{e:e,deselected:o})),s&&(this._objectsToRender=void 0)}setActiveObject(t,e){const i=this.getActiveObjects(),s=this._setActiveObject(t,e);return this._fireSelectionEvents(i,e),s}_setActiveObject(t,e){const i=this._activeObject;return i!==t&&(!(!this._discardActiveObject(e,t)&&this._activeObject)&&(!t.onSelect({e:e})&&(this._activeObject=t,isActiveSelection(t)&&i!==t&&t.set("canvas",this),t.setCoords(),!0)))}_discardActiveObject(t,e){const i=this._activeObject;return!!i&&(!i.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===i&&this.endCurrentTransform(t),isActiveSelection(i)&&i===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0))}discardActiveObject(t){const e=this.getActiveObjects(),i=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[i]});const s=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),s}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,i=e.target,s={e:t,target:i,transform:e,action:e.action};i._scaling&&(i._scaling=!1),i.setCoords(),e.actionPerformed&&(this.fire("object:modified",s),i.fire(R,s))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;isActiveSelection(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,i){const s=this._realizeGroupTransformOnObject(t),n=super._toObject(t,e,i);return t.set(s),n}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&isActiveSelection(e)&&this._activeObject===e){const i=undefined,s=pick(t,["angle","flipX","flipY",m,A,F,L,j,y]);return addTransformToObject(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,i){const s=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,i),e.set(s)}}_defineProperty(SelectableCanvas,"ownDefaults",We);class TextEditingManager{constructor(t){_defineProperty(this,"targets",[]),_defineProperty(this,"__disposer",void 0);const cb=()=>{const{hiddenTextarea:e}=t.getActiveObject()||{};e&&e.focus()},e=t.upperCanvasEl;e.addEventListener("click",cb),this.__disposer=()=>e.removeEventListener("click",cb)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),removeFromArray(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;(null===(e=this.target)||void 0===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 He={passive:!1},getEventPoints=(t,e)=>{const i=undefined,s=undefined;return{viewportPoint:t.getViewportPoint(e),scenePoint:t.getScenePoint(e)}},addListener=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return t.addEventListener(...i)},removeListener=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return t.removeEventListener(...i)},Xe={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 Canvas extends SelectableCanvas{constructor(t){let e;super(t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),_defineProperty(this,"_isClick",void 0),_defineProperty(this,"textEditingManager",new TextEditingManager(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(t=>{this[t]=this[t].bind(this)}),this.addOrRemove(addListener,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const i=this.upperCanvasEl,s=this._getEventPrefix();t(getWindowFromElement(i),"resize",this._onResize),t(i,s+"down",this._onMouseDown),t(i,`${s}move`,this._onMouseMove,He),t(i,`${s}out`,this._onMouseOut),t(i,`${s}enter`,this._onMouseEnter),t(i,"wheel",this._onMouseWheel,{passive:!1}),t(i,"contextmenu",this._onContextMenu),t(i,"click",this._onClick),t(i,"dblclick",this._onClick),t(i,"dragstart",this._onDragStart),t(i,"dragend",this._onDragEnd),t(i,"dragover",this._onDragOver),t(i,"dragenter",this._onDragEnter),t(i,"dragleave",this._onDragLeave),t(i,"drop",this._onDrop),this.enablePointerEvents||t(i,"touchstart",this._onTouchStart,He)}removeListeners(){this.addOrRemove(removeListener,"remove");const t=this._getEventPrefix(),e=getDocumentFromElement(this.upperCanvasEl);removeListener(e,`${t}up`,this._onMouseUp),removeListener(e,"touchend",this._onTouchEnd,He),removeListener(e,`${t}move`,this._onMouseMove,He),removeListener(e,"touchmove",this._onMouseMove,He),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_onMouseOut(t){const e=this._hoveredTarget,i={e:t,...getEventPoints(this,t)};this.fire("mouse:out",{...i,target:e}),this._hoveredTarget=void 0,e&&e.fire("mouseout",{...i}),this._hoveredTargets.forEach(t=>{this.fire("mouse:out",{...i,target:t}),t&&t.fire("mouseout",{...i})}),this._hoveredTargets=[]}_onMouseEnter(t){const{target:e}=this.findTarget(t);this._currentTransform||e||(this.fire("mouse:over",{e:t,...getEventPoints(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 i={e:t,target:e};return this.fire("dragstart",i),e.fire("dragstart",i),void addListener(this.upperCanvasEl,"drag",this._onDragProgress)}stopEvent(t)}_renderDragEffects(t,e,i){let s=!1;const n=this._dropTarget;n&&n!==e&&n!==i&&(n.clearContextTop(),s=!0),null==e||e.clearContextTop(),i!==e&&(null==i||i.clearContextTop());const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),s=!0),i&&(r.save(),i.transform(r),i.renderDropTargetEffect(t),r.restore(),s=!0),r.restore(),s&&(this.contextTopDirty=!0)}_onDragEnd(t){const{currentSubTargets:e}=this.findTarget(t),i=!!t.dataTransfer&&t.dataTransfer.dropEffect!==_,s=i?this._activeObject:void 0,n={e:t,target:this._dragSource,subTargets:e,dragSource:this._dragSource,didDrop:i,dropTarget:s};removeListener(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",n),this._dragSource&&this._dragSource.fire("dragend",n),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:i,currentSubTargets:s}=this.findTarget(t),n=this._dragSource,r={e:t,target:i,subTargets:s,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(t,i,r),i&&(i.canDrop(t)&&(o=i),i.fire(e,r));for(let i=0;i<s.length;i++){const n=s[i];n.canDrop(t)&&(o=n),n.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{currentContainer:e,currentSubTargets:i}=this.findTarget(t),s={e:t,target:e,subTargets:i,dragSource:this._dragSource};this.fire("dragenter",s),this._fireEnterLeaveEvents(t,e,s)}_onDragLeave(t){const{currentSubTargets:e}=this.findTarget(t),i={e:t,target:this._draggedoverTarget,subTargets:e,dragSource:this._dragSource};this.fire("dragleave",i),this._fireEnterLeaveEvents(t,void 0,i),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(t){const{currentContainer:e,currentSubTargets:i}=this.findTarget(t),s=this._basicEventHandler("drop:before",{e:t,target:e,subTargets:i,dragSource:this._dragSource,...getEventPoints(this,t)});s.didDrop=!1,s.dropTarget=void 0,this._basicEventHandler("drop",s),this.fire("drop:after",s)}_onContextMenu(t){const{target:e,subTargets:i}=this.findTarget(t),s=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:i});return this.stopContextMenu&&stopEvent(t),this._basicEventHandler("contextmenu",s),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),2==e&&"dblclick"===t.type&&this._handleEvent(t,"dblclick"),3==e&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||(!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId))}_onTouchStart(t){this._cacheTransformEventData(t);let e=!this.allowTouchScrolling;const i=this._activeObject;void 0===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t);const{target:s}=this.findTarget(t);(this.isDrawingMode||i&&s===i)&&(e=!0),e&&t.preventDefault();const n=this.upperCanvasEl,r=this._getEventPrefix(),o=getDocumentFromElement(n);addListener(o,"touchend",this._onTouchEnd,He),e&&addListener(o,"touchmove",this._onMouseMove,He),removeListener(n,`${r}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(t){this._cacheTransformEventData(t),this.__onMouseDown(t);const e=this.upperCanvasEl,i=this._getEventPrefix();removeListener(e,`${i}move`,this._onMouseMove,He);const s=getDocumentFromElement(e);addListener(s,`${i}up`,this._onMouseUp),addListener(s,`${i}move`,this._onMouseMove,He),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(),i=getDocumentFromElement(this.upperCanvasEl);removeListener(i,"touchend",this._onTouchEnd,He),removeListener(i,"touchmove",this._onMouseMove,He),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{addListener(this.upperCanvasEl,`${e}down`,this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this._cacheTransformEventData(t),this.__onMouseUp(t);const e=this.upperCanvasEl,i=this._getEventPrefix();if(this._isMainEvent(t)){const t=getDocumentFromElement(this.upperCanvasEl);removeListener(t,`${i}up`,this._onMouseUp),removeListener(t,`${i}move`,this._onMouseMove,He),addListener(e,`${i}move`,this._onMouseMove,He)}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 i=this._currentTransform,s=this._isClick,{target:n}=this.findTarget(t),{button:r}=t;if(r)return void((this.fireMiddleClick&&1===r||this.fireRightClick&&2===r)&&this._handleEvent(t,"up"));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o=!1,a,h;if(i&&(this._finalizeCurrentTransform(t),o=i.actionPerformed),!s){const e=n===this._activeObject;this.handleSelection(t),o||(o=this._shouldRender(n)||!e&&n===this._activeObject)}if(n){const e=n.findControl(this.getViewportPoint(t),isTouchEvent(t)),{key:s,control:r}=e||{};if(h=s,n.selectable&&n!==this._activeObject&&"up"===n.activeOn)this.setActiveObject(n,t),o=!0;else if(r){const e=r.getMouseUpHandler(t,n,r);e&&(a=this.getScenePoint(t),e.call(r,t,i,a.x,a.y))}n.isMoving=!1}if(i&&(i.target!==n||i.corner!==h)){const e=i.target&&i.target.controls[i.corner],s=e&&e.getMouseUpHandler(t,i.target,e);a=a||this.getScenePoint(t),s&&s.call(e,t,i,a.x,a.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),o?this.requestRenderAll():s||null!==(e=this._activeObject)&&void 0!==e&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:i,subTargets:s=[]}=e;this.fire(t,e),i&&i.fire(t,e);for(let n=0;n<s.length;n++)s[n]!==i&&s[n].fire(t,e);return e}_handleEvent(t,e,i){const{target:s,subTargets:n}=this.findTarget(t),r={e:t,target:s,subTargets:n,...getEventPoints(this,t),transform:this._currentTransform,..."down:before"===e||"down"===e?i:{}};"up:before"!==e&&"up"!==e||(r.isClick=this._isClick),this.fire(`mouse:${e}`,r),s&&s.fire(`mouse${e}`,r);for(let t=0;t<n.length;t++)n[t]!==s&&n[t].fire(`mouse${e}`,r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._handleEvent(t,"down:before");let{target:e}=this.findTarget(t),i=!!e&&e===this._activeObject;const{button:s}=t;if(s)return void((this.fireMiddleClick&&1===s||this.fireRightClick&&2===s)&&this._handleEvent(t,"down",{alreadySelected:i}));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t))return;if(this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const e=this.getScenePoint(t);this._groupSelector={x:e.x,y:e.y,deltaY:0,deltaX:0}}if(i=!!e&&e===this._activeObject,e){e.selectable&&"down"===e.activeOn&&this.setActiveObject(e,t);const s=e.findControl(this.getViewportPoint(t),isTouchEvent(t));if(e===this._activeObject&&(s||!r)){this._setupCurrentTransform(t,e,i);const n=s?s.control:void 0,r=this.getScenePoint(t),o=n&&n.getMouseDownHandler(t,e,n);o&&o.call(n,t,this._currentTransform,r.x,r.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:i}),n&&this.requestRenderAll()}_resetTransformEventData(){this._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(t),this._scenePoint=sendPointToPlane(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 i=this.getScenePoint(t);e.deltaX=i.x-e.x,e.deltaY=i.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const{target:e}=this.findTarget(t);this._setCursorFromEvent(t,e),this._fireOverOutEvents(t,e)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move")}_fireOverOutEvents(t,e){const i=this._hoveredTarget,s=this._hoveredTargets,{subTargets:n}=this.findTarget(t),r=Math.max(s.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:i,fireCanvas:!0});for(let e=0;e<r;e++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[e],oldTarget:s[e]});this._hoveredTarget=e,this._hoveredTargets=n}_fireEnterLeaveEvents(t,e,i){const s=this._draggedoverTarget,n=this._hoveredTargets,{subTargets:r}=this.findTarget(t),o=Math.max(n.length,r.length);this.fireSyntheticInOutEvents("drag",{...i,target:e,oldTarget:s,fireCanvas:!0});for(let t=0;t<o;t++)this.fireSyntheticInOutEvents("drag",{...i,target:r[t],oldTarget:n[t]});this._draggedoverTarget=e}fireSyntheticInOutEvents(t,e){let{target:i,oldTarget:s,fireCanvas:n,e:r,...o}=e;const{targetIn:a,targetOut:h,canvasIn:l,canvasOut:c}=Xe[t],d=s!==i;if(s&&d){const t={...o,e:r,target:s,nextTarget:i,...getEventPoints(this,r)};n&&this.fire(c,t),s.fire(h,t)}if(i&&d){const t={...o,e:r,target:i,previousTarget:s,...getEventPoints(this,r)};n&&this.fire(l,t),i.fire(a,t)}}_transformObject(t){const e=this.getScenePoint(t),i=this._currentTransform,s=i.target,n=s.group?sendPointToPlane(e,void 0,s.group.calcTransformMatrix()):e;i.shiftKey=t.shiftKey,i.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,i,n),i.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,i){const{action:s,actionHandler:n,target:r}=e,o=!!n&&n(t,e,i.x,i.y);o&&r.setCoords(),"drag"===s&&o&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||o}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let i=e.hoverCursor||this.hoverCursor;const s=isActiveSelection(this._activeObject)?this._activeObject:null,n=(!s||e.group!==s)&&e.findControl(this.getViewportPoint(t));if(n){const{control:i,coord:s}=n;this.setCursor(i.cursorStyleHandler(t,i,e,s))}else{if(e.subTargetCheck){const{subTargets:e}=this.findTarget(t);e.concat().reverse().forEach(t=>{i=t.hoverCursor||i})}this.setCursor(i)}}handleMultiSelection(t,e){const i=this._activeObject,s=isActiveSelection(i);if(i&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(i!==e||s)&&(s||!e.isDescendantOf(i)&&!i.isDescendantOf(e))&&!e.onSelect({e:t})&&!i.getActiveControl()){if(s){const s=i.getObjects();let n=[];if(e===i){const i=this.getScenePoint(t);let r=this.searchPossibleTargets(s,i);if(r.target?(e=r.target,n=r.subTargets):(r=this.searchPossibleTargets(this._objects,i),e=r.target,n=r.subTargets),!e||!e.selectable)return!1}e.group===i?(i.remove(e),this._hoveredTarget=e,this._hoveredTargets=n,1===i.size()&&this._setActiveObject(i.item(0),t)):(i.multiSelectAdd(e),this._hoveredTarget=i,this._hoveredTargets=n),this._fireSelectionEvents(s,t)}else{i.isEditing&&i.exitEditing();const s=undefined,n=new(X.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(i,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([i],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:i,deltaX:s,deltaY:n}=this._groupSelector,r=new Point(e,i),o=r.add(new Point(s,n)),a=r.min(o),h=undefined,l=r.max(o).subtract(a),c=this.collectObjects({left:a.x,top:a.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),d=r.eq(o)?c[0]?[c[0]]:[]:c.length>1?c.filter(e=>!e.onSelect({e:t})).reverse():c;if(1===d.length)this.setActiveObject(d[0],t);else if(d.length>1){const e=X.getClass("ActiveSelection");this.setActiveObject(new e(d,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const $e={x1:0,y1:0,x2:0,y2:0},ze={...$e,r1:0,r2:0},ifNaN=(t,e)=>isNaN(t)&&"number"==typeof e?e:t,Ye=/^(\d+\.\d+)%|(\d+)%$/;function isPercent(t){return t&&Ye.test(t)}function parsePercent(t,e){const i="number"==typeof t?t:"string"==typeof t?parseFloat(t)/(isPercent(t)?100:1):NaN;return capValue(0,ifNaN(i,e),1)}const Ve=/\s*;\s*/,Ge=/\s*:\s*/;function parseColorStop(t,e){let i,s;const n=t.getAttribute("style");if(n){const t=n.split(Ve);""===t[t.length-1]&&t.pop();for(let e=t.length;e--;){const[n,r]=t[e].split(Ge).map(t=>t.trim());"stop-color"===n?i=r:"stop-opacity"===n&&(s=r)}}i=i||t.getAttribute("stop-color")||"rgb(0,0,0)",s=ifNaN(parseFloat(s||t.getAttribute("stop-opacity")||""),1);const r=new Color(i);return r.setAlpha(r.getAlpha()*s*e),{offset:parsePercent(t.getAttribute("offset"),0),color:r.toRgba()}}function parseColorStops(t,e){const i=[],s=t.getElementsByTagName("stop"),n=parsePercent(e,1);for(let t=s.length;t--;)i.push(parseColorStop(s[t],n));return i}function parseType(t){return"linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?"linear":"radial"}function parseGradientUnits(t){return"userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage"}function convertPercentUnitsToValues(t,e){let{width:i,height:s,gradientUnits:n}=e,r;return Object.keys(t).reduce((e,o)=>{const a=t[o];return"Infinity"===a?r=1:"-Infinity"===a?r=0:(r="string"==typeof a?parseFloat(a):a,"string"==typeof a&&isPercent(a)&&(r*=.01,"pixels"===n&&("x1"!==o&&"x2"!==o&&"r2"!==o||(r*=i),"y1"!==o&&"y2"!==o||(r*=s)))),e[o]=r,e},{})}function getValue(t,e){return t.getAttribute(e)}function parseLinearCoords(t){return{x1:getValue(t,"x1")||0,y1:getValue(t,"y1")||0,x2:getValue(t,"x2")||"100%",y2:getValue(t,"y2")||0}}function parseRadialCoords(t){return{x1:getValue(t,"fx")||getValue(t,"cx")||"50%",y1:getValue(t,"fy")||getValue(t,"cy")||"50%",r1:0,x2:getValue(t,"cx")||"50%",y2:getValue(t,"cy")||"50%",r2:getValue(t,"r")||"50%"}}function parseCoords(t,e){return convertPercentUnitsToValues("linear"===parseType(t)?parseLinearCoords(t):parseRadialCoords(t),{...e,gradientUnits:parseGradientUnits(t)})}class Gradient{constructor(t){const{type:e="linear",gradientUnits:i="pixels",coords:s={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:a,id:h}=t||{};Object.assign(this,{type:e,gradientUnits:i,coords:{..."radial"===e?ze:$e,...s},colorStops:n,offsetX:r,offsetY:o,gradientTransform:a,id:h?`${h}_${uid()}`:uid()})}addColorStop(t){for(const e in t)this.colorStops.push({offset:parseFloat(e),color:t[e]});return this}toObject(t){return{...pick(this,t),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map(t=>({...t})),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0}}toSVG(t){let{additionalTransform:e}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=[],s=this.gradientTransform?this.gradientTransform.concat():d.concat(),n="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(t=>({...t})).sort((t,e)=>t.offset-e.offset);let o=-this.offsetX,a=-this.offsetY;"objectBoundingBox"===n?(o/=t.width,a/=t.height):(o+=t.width/2,a+=t.height/2),isPath(t)&&"percentage"!==this.gradientUnits&&(o-=t.pathOffset.x,a-=t.pathOffset.y),s[4]-=o,s[5]-=a;const h=[`id="SVGID_${this.id}"`,`gradientUnits="${n}"`,`gradientTransform="${e?e+" ":""}${matrixToSVG(s)}"`,""].join(" ");if("linear"===this.type){const{x1:t,y1:e,x2:s,y2:n}=this.coords;i.push("<linearGradient ",h,' x1="',t,'" y1="',e,'" x2="',s,'" y2="',n,'">\n')}else if("radial"===this.type){const{x1:t,y1:e,x2:s,y2:n,r1:o,r2:a}=this.coords,l=o>a;i.push("<radialGradient ",h,' cx="',l?t:s,'" cy="',l?e:n,'" r="',l?o:a,'" fx="',l?s:t,'" fy="',l?n:e,'">\n'),l&&(r.reverse(),r.forEach(t=>{t.offset=1-t.offset}));const c=Math.min(o,a);if(c>0){const t=undefined,e=c/Math.max(o,a);r.forEach(t=>{t.offset+=e*(1-t.offset)})}}return r.forEach(t=>{let{color:e,offset:s}=t;i.push(`<stop offset="${100*s}%" style="stop-color:${e};"/>\n`)}),i.push("linear"===this.type?"</linearGradient>":"</radialGradient>","\n"),i.join("")}toLive(t){const{x1:e,y1:i,x2:s,y2:n,r1:r,r2:o}=this.coords,a="linear"===this.type?t.createLinearGradient(e,i,s,n):t.createRadialGradient(e,i,r,s,n,o);return this.colorStops.forEach(t=>{let{color:e,offset:i}=t;a.addColorStop(i,e)}),a}static async fromObject(t){const{colorStops:e,gradientTransform:i}=t;return new this({...t,colorStops:e?e.map(t=>({...t})):void 0,gradientTransform:i?[...i]:void 0})}static fromElement(t,e,i){const s=parseGradientUnits(t),n=e._findCenterFromElement();return new this({id:t.getAttribute("id")||void 0,type:parseType(t),coords:parseCoords(t,{width:i.viewBoxWidth||i.width,height:i.viewBoxHeight||i.height}),colorStops:parseColorStops(t,i.opacity),gradientUnits:s,gradientTransform:parseTransformAttribute(t.getAttribute("gradientTransform")||""),..."pixels"===s?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}})}}_defineProperty(Gradient,"type","Gradient"),X.setClass(Gradient,"gradient"),X.setClass(Gradient,"linear"),X.setClass(Gradient,"radial");class Pattern{get type(){return"pattern"}set type(t){log("warn","Setting type has no effect",t)}constructor(t){_defineProperty(this,"repeat","repeat"),_defineProperty(this,"offsetX",0),_defineProperty(this,"offsetY",0),_defineProperty(this,"crossOrigin",""),this.id=uid(),Object.assign(this,t)}isImageSource(){return!!this.source&&"string"==typeof this.source.src}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&0!==this.source.naturalWidth&&0!==this.source.naturalHeight)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const{repeat:i,crossOrigin:s}=this;return{...pick(this,t),type:"pattern",source:this.sourceToString(),repeat:i,crossOrigin:s,offsetX:toFixed(this.offsetX,e.NUM_FRACTION_DIGITS),offsetY:toFixed(this.offsetY,e.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null}}toSVG(t){let{width:e,height:i}=t;const{source:s,repeat:n,id:r}=this,o=ifNaN(this.offsetX/e,0),a=ifNaN(this.offsetY/i,0),h=undefined,l=undefined;return[`<pattern id="SVGID_${r}" x="${o}" y="${a}" width="${"repeat-y"===n||"no-repeat"===n?1+Math.abs(o||0):ifNaN(s.width/e,0)}" height="${"repeat-x"===n||"no-repeat"===n?1+Math.abs(a||0):ifNaN(s.height/i,0)}">`,`<image x="0" y="0" width="${s.width}" height="${s.height}" xlink:href="${this.sourceToString()}"></image>`,"</pattern>",""].join("\n")}static async fromObject(t,e){let{type:i,source:s,patternTransform:n,...r}=t;const o=await loadImage(s,{...e,crossOrigin:r.crossOrigin});return new this({...r,patternTransform:n&&n.slice(0),source:o})}}_defineProperty(Pattern,"type","Pattern"),X.setClass(Pattern),X.setClass(Pattern,"pattern");class BaseBrush{constructor(t){_defineProperty(this,"color","rgb(0, 0, 0)"),_defineProperty(this,"width",1),_defineProperty(this,"shadow",null),_defineProperty(this,"strokeLineCap","round"),_defineProperty(this,"strokeLineJoin","round"),_defineProperty(this,"strokeMiterLimit",10),_defineProperty(this,"strokeDashArray",null),_defineProperty(this,"limitedToCanvasSize",!1),this.canvas=t}_setBrushStyles(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])}_saveAndTransform(t){const e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])}needsFullRender(){const t=undefined;return new Color(this.color).getAlpha()<1||!!this.shadow}_setShadow(){if(!this.shadow||!this.canvas)return;const t=this.canvas,e=this.shadow,i=t.contextTop,s=t.getZoom()*t.getRetinaScaling();i.shadowColor=e.color,i.shadowBlur=e.blur*s,i.shadowOffsetX=e.offsetX*s,i.shadowOffsetY=e.offsetY*s}_resetShadow(){const t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}_isOutSideCanvas(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}class Path extends FabricObject{constructor(t){let{path:e,left:i,top:s,...n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,Path.ownDefaults),this.setOptions(n),this._setPath(t||[],!0),"number"==typeof i&&this.set(m,i),"number"==typeof s&&this.set(y,s)}_setPath(t,e){this.path=makePathSimpler(Array.isArray(t)?t:parsePath(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new Point(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,i=-this.pathOffset.y;t.beginPath();for(const s of this.path)switch(s[0]){case"L":t.lineTo(s[1]+e,s[2]+i);break;case"M":t.moveTo(s[1]+e,s[2]+i);break;case"C":t.bezierCurveTo(s[1]+e,s[2]+i,s[3]+e,s[4]+i,s[5]+e,s[6]+i);break;case"Q":t.quadraticCurveTo(s[1]+e,s[2]+i,s[3]+e,s[4]+i);break;case"Z":t.closePath();break}}_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&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject(t),path:this.path.map(t=>t.slice())}}toDatalessObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=undefined;return["<path ","COMMON_PARTS",`d="${joinPath(this.path,e.NUM_FRACTION_DIGITS)}" stroke-linecap="round" />\n`]}_getOffsetTransform(){const t=e.NUM_FRACTION_DIGITS;return` translate(${toFixed(-this.pathOffset.x,t)}, ${toFixed(-this.pathOffset.y,t)})`}toClipPathSVG(t){const e=this._getOffsetTransform();return"\t"+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:i,pathOffset:s}=this._calcDimensions();this.set({width:e,height:i,pathOffset:s}),t&&this.setPositionByOrigin(s,p,p)}_calcBoundsFromPath(){const t=[];let e=0,i=0,s=0,n=0;for(const r of this.path)switch(r[0]){case"L":s=r[1],n=r[2],t.push({x:e,y:i},{x:s,y:n});break;case"M":s=r[1],n=r[2],e=s,i=n;break;case"C":t.push(...getBoundsOfCurve(s,n,r[1],r[2],r[3],r[4],r[5],r[6])),s=r[5],n=r[6];break;case"Q":t.push(...getBoundsOfCurve(s,n,r[1],r[2],r[1],r[2],r[3],r[4])),s=r[3],n=r[4];break;case"Z":s=e,n=i;break}return makeBoundingBoxFromPoints(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return{...t,pathOffset:new Point(t.left+t.width/2,t.top+t.height/2)}}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,i){const{d:s,...n}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this(s,{...n,...e,left:void 0,top:void 0})}}function isEmptySVGPath(t){return"M 0 0 Q 0 0 0 0 L 0 0"===joinPath(t)}_defineProperty(Path,"type","Path"),_defineProperty(Path,"cacheProperties",[...Ot,"path","fillRule"]),_defineProperty(Path,"ATTRIBUTE_NAMES",[...se,"d"]),X.setClass(Path),X.setSVGClass(Path);class PencilBrush extends BaseBrush{constructor(t){super(t),_defineProperty(this,"decimate",.4),_defineProperty(this,"drawStraightLine",!1),_defineProperty(this,"straightLineKey","shiftKey"),this._points=[],this._hasStraightLine=!1}needsFullRender(){return super.needsFullRender()||this._hasStraightLine}static drawSegment(t,e,i){const s=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,s.x,s.y),s}onMouseDown(t,e){let{e:i}=e;this.canvas._isMainEvent(i)&&(this.drawStraightLine=!!this.straightLineKey&&i[this.straightLineKey],this._prepareForDrawing(t),this._addPoint(t),this._render())}onMouseMove(t,e){let{e:i}=e;if(this.canvas._isMainEvent(i)&&(this.drawStraightLine=!!this.straightLineKey&&i[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._addPoint(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{const t=this._points,e=t.length,i=this.canvas.contextTop;this._saveAndTransform(i),this.oldEnd&&(i.beginPath(),i.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=PencilBrush.drawSegment(i,t[e-2],t[e-1]),i.stroke(),i.restore()}}onMouseUp(t){let{e:e}=t;return!this.canvas._isMainEvent(e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)}_prepareForDrawing(t){this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)}_addPoint(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1]))&&(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),!0)}_reset(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1}_render(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.canvas.contextTop,e=this._points[0],i=this._points[1];if(this._saveAndTransform(t),t.beginPath(),2===this._points.length&&e.x===i.x&&e.y===i.y){const t=this.width/1e3;e.x-=t,i.x+=t}t.moveTo(e.x,e.y);for(let s=1;s<this._points.length;s++)PencilBrush.drawSegment(t,e,i),e=this._points[s],i=this._points[s+1];t.lineTo(e.x,e.y),t.stroke(),t.restore()}convertPointsToSVGPath(t){const e=this.width/1e3;return getSmoothPathFromPoints(t,e)}createPath(t){const e=new Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new Shadow(this.shadow)),e}decimatePoints(t,e){if(t.length<=2)return t;let i=t[0],s;const n=this.canvas.getZoom(),r=Math.pow(e/n,2),o=t.length-1,a=[i];for(let e=1;e<o-1;e++)s=Math.pow(i.x-t[e].x,2)+Math.pow(i.y-t[e].y,2),s>=r&&(i=t[e],a.push(i));return a.push(t[o]),a}_finalizeAndAddPath(){const t=undefined;this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));const e=this.convertPointsToSVGPath(this._points);if(isEmptySVGPath(e))return void this.canvas.requestRenderAll();const i=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:i}),this.canvas.add(i),this.canvas.requestRenderAll(),i.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:i})}}const Ne=["radius","startAngle","endAngle","counterClockwise"],Ue={radius:0,startAngle:0,endAngle:360,counterClockwise:!1};class Circle extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Circle.ownDefaults}}constructor(t){super(),Object.assign(this,Circle.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),"radius"===t&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,degreesToRadians(this.startAngle),degreesToRadians(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(A)}getRadiusY(){return this.get("radius")*this.get(F)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...Ne,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(0===t)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',`${this.radius}`,'" />\n'];{const{radius:e}=this,i=degreesToRadians(this.startAngle),s=degreesToRadians(this.endAngle),n=cos(i)*e,r=sin(i)*e,o=cos(s)*e,a=sin(s)*e,h=undefined,l=undefined;return[`<path d="M ${n} ${r} A ${e} ${e} 0 ${t>180?1:0} ${this.counterClockwise?0:1} ${o} ${a}" `,"COMMON_PARTS"," />\n"]}}static async fromElement(t,e,i){const{left:s=0,top:n=0,radius:r=0,...o}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this({...o,radius:r,left:s-r,top:n-r})}static fromObject(t){return super._fromObject(t)}}_defineProperty(Circle,"type","Circle"),_defineProperty(Circle,"cacheProperties",[...Ot,...Ne]),_defineProperty(Circle,"ownDefaults",Ue),_defineProperty(Circle,"ATTRIBUTE_NAMES",["cx","cy","r",...se]),X.setClass(Circle),X.setSVGClass(Circle);class CircleBrush extends BaseBrush{constructor(t){super(t),_defineProperty(this,"width",10),this.points=[]}drawDot(t){const e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()}dot(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()}onMouseDown(t){this.points=[],this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)}_render(){const t=this.canvas.contextTop,e=this.points;this._saveAndTransform(t);for(let i=0;i<e.length;i++)this.dot(t,e[i]);t.restore()}onMouseMove(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.needsFullRender()?(this.canvas.clearContext(this.canvas.contextTop),this.addPoint(t),this._render()):this.drawDot(t))}onMouseUp(){const t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;const e=[];for(let t=0;t<this.points.length;t++){const i=this.points[t],s=new Circle({radius:i.radius,left:i.x,top:i.y,originX:p,originY:p,fill:i.fill});this.shadow&&(s.shadow=new Shadow(this.shadow)),e.push(s)}const i=new Group(e,{canvas:this.canvas});this.canvas.fire("before:path:created",{path:i}),this.canvas.add(i),this.canvas.fire("path:created",{path:i}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()}addPoint(t){let{x:e,y:i}=t;const s={x:e,y:i,radius:getRandomInt(Math.max(0,this.width-20),this.width+20)/2,fill:new Color(this.color).setAlpha(getRandomInt(0,100)/100).toRgba()};return this.points.push(s),s}}function getUniqueRects(t){const e={},i=[];for(let s=0,n;s<t.length;s++)n=`${t[s].left}${t[s].top}`,e[n]||(e[n]=!0,i.push(t[s]));return i}class SprayBrush extends BaseBrush{constructor(t){super(t),_defineProperty(this,"width",10),_defineProperty(this,"density",20),_defineProperty(this,"dotWidth",1),_defineProperty(this,"dotWidthVariance",1),_defineProperty(this,"randomOpacity",!1),_defineProperty(this,"optimizeOverlapping",!0),this.sprayChunks=[],this.sprayChunk=[]}onMouseDown(t){this.sprayChunks=[],this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.addSprayChunk(t),this.renderChunck(this.sprayChunk)}onMouseMove(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.addSprayChunk(t),this.renderChunck(this.sprayChunk))}onMouseUp(){const t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;const e=[];for(let t=0;t<this.sprayChunks.length;t++){const i=this.sprayChunks[t];for(let t=0;t<i.length;t++){const s=i[t],n=new Rect({width:s.width,height:s.width,left:s.x+1,top:s.y+1,originX:p,originY:p,fill:this.color});e.push(n)}}const i=new Group(this.optimizeOverlapping?getUniqueRects(e):e,{objectCaching:!0,subTargetCheck:!1,interactive:!1});this.shadow&&i.set("shadow",new Shadow(this.shadow)),this.canvas.fire("before:path:created",{path:i}),this.canvas.add(i),this.canvas.fire("path:created",{path:i}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()}renderChunck(t){const e=this.canvas.contextTop;e.fillStyle=this.color,this._saveAndTransform(e);for(let i=0;i<t.length;i++){const s=t[i];e.globalAlpha=s.opacity,e.fillRect(s.x,s.y,s.width,s.width)}e.restore()}_render(){const t=this.canvas.contextTop;t.fillStyle=this.color,this._saveAndTransform(t);for(let t=0;t<this.sprayChunks.length;t++)this.renderChunck(this.sprayChunks[t]);t.restore()}addSprayChunk(t){this.sprayChunk=[];const e=this.width/2;for(let i=0;i<this.density;i++)this.sprayChunk.push({x:getRandomInt(t.x-e,t.x+e),y:getRandomInt(t.y-e,t.y+e),width:this.dotWidthVariance?getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance):this.dotWidth,opacity:this.randomOpacity?getRandomInt(0,100)/100:1});this.sprayChunks.push(this.sprayChunk)}}class PatternBrush extends PencilBrush{constructor(t){super(t)}getPatternSrc(){const t=20,e=5,i=createCanvasElement(),s=i.getContext("2d");return i.width=i.height=25,s&&(s.fillStyle=this.color,s.beginPath(),s.arc(10,10,10,0,2*Math.PI,!1),s.closePath(),s.fill()),i}getPattern(t){return t.createPattern(this.source||this.getPatternSrc(),"repeat")}_setBrushStyles(t){super._setBrushStyles(t);const e=this.getPattern(t);e&&(t.strokeStyle=e)}createPath(t){const e=super.createPath(t),i=e._getLeftTopCoords().scalarAdd(e.strokeWidth/2);return e.stroke=new Pattern({source:this.source||this.getPatternSrc(),offsetX:-i.x,offsetY:-i.y}),e}}const qe=["x1","x2","y1","y2"];class Line extends FabricObject{constructor(){let[t,e,i,s]=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,100,0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_defineProperty(this,"hitStrokeWidth","auto"),_defineProperty(this,"_updatingEndpoints",!1),_defineProperty(this,"_useEndpointCoords",!0),_defineProperty(this,"_exportingSVG",!1),this.setOptions(n),this.x1=t,this.x2=i,this.y1=e,this.y2=s,void 0!==n.hitStrokeWidth&&(this.hitStrokeWidth=n.hitStrokeWidth),this.hasBorders=!1,this.hasControls=!0,this.selectable=!0,this.hoverCursor="move",this.perPixelTargetFind=!1,this.strokeLineCap="butt",this._setWidthHeight();const{left:r,top:o}=n;"number"==typeof r&&this.set(m,r),"number"==typeof o&&this.set(y,o),this._setupLineControls()}_setupLineControls(){this.controls={p1:new Control({x:0,y:0,cursorStyle:"move",actionHandler:this._endpointActionHandler.bind(this),positionHandler:this._p1PositionHandler.bind(this),render:this._renderEndpointControl.bind(this),sizeX:12,sizeY:12}),p2:new Control({x:0,y:0,cursorStyle:"move",actionHandler:this._endpointActionHandler.bind(this),positionHandler:this._p2PositionHandler.bind(this),render:this._renderEndpointControl.bind(this),sizeX:12,sizeY:12})}}_p1PositionHandler(){return new Point(this.x1,this.y1).transform(this.getViewportTransform())}_p2PositionHandler(){return new Point(this.x2,this.y2).transform(this.getViewportTransform())}_renderEndpointControl(t,e,i){const s=12;t.save(),t.fillStyle="#007bff",t.strokeStyle="#ffffff",t.lineWidth=2,t.beginPath(),t.arc(e,i,6,0,2*Math.PI),t.fill(),t.stroke(),t.restore()}drawBorders(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this._useEndpointCoords?(this._drawLineBorders(t,e),this):super.drawBorders(t,e,{})}_drawLineBorders(t){var e;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=(null===(e=this.canvas)||void 0===e?void 0:e.viewportTransform)||[1,0,0,1,0,0];t.save(),t.setTransform(s[0],s[1],s[2],s[3],s[4],s[5]),t.strokeStyle=i.borderColor||this.borderColor||"rgba(100, 200, 200, 0.5)",t.lineWidth=(this.strokeWidth||1)+5,t.lineCap=this.strokeLineCap||"butt",t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,t.beginPath(),t.moveTo(this.x1,this.y1),t.lineTo(this.x2,this.y2),t.stroke(),t.restore()}_renderControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.drawControls(t,e),t.restore()}getBoundingRect(){if(this._useEndpointCoords){const{x1:t,y1:e,x2:i,y2:s}=this,n="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth,r=Math.max(n/2+5,10);return{left:Math.min(t,i)-r,top:Math.min(e,s)-r,width:Math.abs(i-t)+2*r||2*r,height:Math.abs(s-e)+2*r||2*r}}return super.getBoundingRect()}setCoords(){if(this._useEndpointCoords){const t="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth,e=Math.max(t/2+5,10);if(this.width=Math.abs(this.x2-this.x1)+2*e,this.height=Math.abs(this.y2-this.y1)+2*e,0===this.left&&0===this.top){const t=this._findCenterFromElement();this.left=t.x,this.top=t.y}}super.setCoords()}getCoords(){if(this._useEndpointCoords){const t=this.x2-this.x1,e=this.y2-this.y1,i=Math.sqrt(t*t+e*e);if(0===i)return super.getCoords();const s="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth,n=Math.max(s/2+2,5),r=-e/i,o=t/i;return[new Point(this.x1+r*n,this.y1+o*n),new Point(this.x2+r*n,this.y2+o*n),new Point(this.x2-r*n,this.y2-o*n),new Point(this.x1-r*n,this.y1-o*n)]}return super.getCoords()}containsPoint(t){if(this._useEndpointCoords){var e;if((null===(e=this.canvas)||void 0===e?void 0:e.getActiveObject())===this)return super.containsPoint(t);const i=this._distanceToLineSegment(t.x,t.y),s="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth||1,n=undefined;return i<=Math.max(s/2+2,5)}return super.containsPoint(t)}_distanceToLineSegment(t,e){const i=this.x1,s=this.y1,n=this.x2,r=this.y2,o=(i-n)*(i-n)+(s-r)*(s-r);if(0===o)return Math.sqrt((t-i)*(t-i)+(e-s)*(e-s));const a=((t-i)*(n-i)+(e-s)*(r-s))/o;let h,l;return a<0?(h=i,l=s):a>1?(h=n,l=r):(h=i+a*(n-i),l=s+a*(r-s)),Math.sqrt((t-h)*(t-h)+(e-l)*(e-l))}_endpointActionHandler(t,e,i,s){var n;const r=e.corner,o=new Point(i,s);let a=o.x,h=o.y;if(t.shiftKey){const t="p1"===r?"p2":"p1",e=this["p1"===t?"x1":"x2"],i=this["p1"===t?"y1":"y2"],s=this._snapToAngle(e,i,a,h);a=s.x,h=s.y}var l;return this._useEndpointCoords?("p1"===r?(this.x1=a,this.y1=h):"p2"===r&&(this.x2=a,this.y2=h),this.stroke instanceof Gradient&&!this._exportingSVG&&(this.stroke.coords.x1=this.x1,this.stroke.coords.y1=this.y1,this.stroke.coords.x2=this.x2,this.stroke.coords.y2=this.y2),this.dirty=!0,this.setCoords(),null===(l=this.canvas)||void 0===l||l.requestRenderAll(),!0):(this._updatingEndpoints=!0,"p1"===r?(this.x1=a,this.y1=h):"p2"===r&&(this.x2=a,this.y2=h),this._setWidthHeight(),this.dirty=!0,this._updatingEndpoints=!1,null===(n=this.canvas)||void 0===n||n.requestRenderAll(),this.fire("modified",{transform:e,target:this,e:t}),!0)}_snapToAngle(t,e,i,s){const n=i-t,r=s-e,o=Math.sqrt(n*n+r*r);if(0===o)return{x:i,y:s};let a=Math.atan2(r,n)*(180/Math.PI);const h=15,l=undefined,c=Math.round(a/h)*h*(Math.PI/180);return{x:t+Math.cos(c)*o,y:e+Math.sin(c)*o}}_setWidthHeight(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.width=Math.abs(this.x2-this.x1)||1,this.height=Math.abs(this.y2-this.y1)||1,!t&&!this._updatingEndpoints){const{left:t,top:e,width:i,height:s}=makeBoundingBoxFromPoints([{x:this.x1,y:this.y1},{x:this.x2,y:this.y2}]);this.setPositionByOrigin(new Point(t+i/2,e+s/2),p,p)}}_set(t,e){const i=this.left,s=this.top;if(super._set(t,e),qe.includes(t)&&(this._setWidthHeight(),this.dirty=!0,this.stroke instanceof Gradient&&!this._exportingSVG&&(this.stroke.coords.x1=this.x1,this.stroke.coords.y1=this.y1,this.stroke.coords.x2=this.x2,this.stroke.coords.y2=this.y2)),("left"===t||"top"===t)&&this.canvas&&!this._updatingEndpoints){const t=this.left-i,e=this.top-s;0===t&&0===e||(this._updatingEndpoints=!0,this.x1+=t,this.y1+=e,this.x2+=t,this.y2+=e,this.stroke instanceof Gradient&&(this.stroke.coords.x1=this.x1,this.stroke.coords.y1=this.y1,this.stroke.coords.x2=this.x2,this.stroke.coords.y2=this.y2),this._updatingEndpoints=!1)}return this}render(t){this._useEndpointCoords?this._renderDirectly(t):super.render(t)}_renderDirectly(t){if(!this.visible)return;t.save(),t.globalAlpha=this.opacity,t.lineWidth=this.strokeWidth,t.lineCap=this.strokeLineCap||"butt",t.beginPath(),t.moveTo(this.x1,this.y1),t.lineTo(this.x2,this.y2);const e=t.strokeStyle;var i;isFiller(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(null===(i=this.stroke)||void 0===i?void 0:i.toString())||"#000";t.stroke(),t.strokeStyle=e,t.restore()}_render(t){if(this._useEndpointCoords)return;t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const i=t.strokeStyle;isFiller(this.stroke)&&(t.strokeStyle=this.stroke.toLive(t)),this.stroke&&this._renderStroke(t),t.strokeStyle=i}_findCenterFromElement(){return new Point((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return this._useEndpointCoords?{...super.toObject(t),x1:this.x1,y1:this.y1,x2:this.x2,y2:this.y2}:{...super.toObject(t),...this.calcLinePoints()}}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return"round"===this.strokeLineCap&&(t.x+=this.strokeWidth,t.y+=this.strokeWidth),t}calcLinePoints(){if(this._updatingEndpoints){const t=(this.x1+this.x2)/2,e=(this.y1+this.y2)/2;return{x1:this.x1-t,y1:this.y1-e,x2:this.x2-t,y2:this.y2-e}}const{x1:t,x2:e,y1:i,y2:s,width:n,height:r}=this,o=t<=e?-1:1,a=i<=s?-1:1;return{x1:o*n/2,y1:a*r/2,x2:o*-n/2,y2:a*-r/2}}_toSVG(){if(this._useEndpointCoords){let t="";return t=this.stroke instanceof Gradient?`stroke="url(#${this.stroke.id})"`:`stroke="${this.stroke||"none"}"`,[`<line ${t} stroke-width="${this.strokeWidth}" stroke-linecap="${this.strokeLineCap}" `,`stroke-dasharray="${this.strokeDashArray?this.strokeDashArray.join(" "):"none"}" `,`stroke-dashoffset="${this.strokeDashOffset}" stroke-linejoin="${this.strokeLineJoin}" `,`stroke-miterlimit="${this.strokeMiterLimit}" fill="${this.fill||"none"}" `,`fill-rule="${this.fillRule}" opacity="${this.opacity}" `,`x1="${this.x1}" y1="${this.y1}" x2="${this.x2}" y2="${this.y2}" />\n`]}{const{x1:t,x2:e,y1:i,y2:s}=this.calcLinePoints();return["<line ","COMMON_PARTS",`x1="${t}" y1="${i}" x2="${e}" y2="${s}" />\n`]}}toSVG(t){if(this._useEndpointCoords){const e=this.left,i=this.top;this.left=(this.x1+this.x2)/2,this.top=(this.y1+this.y2)/2;const s=super.toSVG(t);this.left=e,this.top=i;const n=undefined;return s.replace(/<g transform="[^"]*"[^>]*>/g,"").replace(/<\/g>/g,"").replace(/x1="[^"]*"/g,`x1="${this.x1}"`).replace(/y1="[^"]*"/g,`y1="${this.y1}"`).replace(/x2="[^"]*"/g,`x2="${this.x2}"`).replace(/y2="[^"]*"/g,`y2="${this.y2}"`)}return super.toSVG(t)}static async fromElement(t,e,i){const{x1:s=0,y1:n=0,x2:r=0,y2:o=0,...a}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this([s,n,r,o],a)}static fromObject(t){let{x1:e,y1:i,x2:s,y2:n,...r}=t;return this._fromObject({...r,points:[e,i,s,n]},{extraParam:"points"})}}function pointDistance(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function normalizeVector(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return 0===e?{x:0,y:0}:{x:t.x/e,y:t.y/e}}function getMaxRadius(t,e,i){const s=pointDistance(t,e),n=pointDistance(e,i);return Math.min(s,n)/2}function calculateRoundedCorner(t,e,i,s){const n={x:e.x-t.x,y:e.y-t.y},r={x:i.x-e.x,y:i.y-e.y},o=normalizeVector(n),a=normalizeVector(r),h=getMaxRadius(t,e,i),l=Math.min(s,h),c={x:e.x-o.x*l,y:e.y-o.y*l},d={x:e.x+a.x*l,y:e.y+a.y*l},u=l*f,g=undefined,p=undefined;return{corner:e,start:c,end:d,cp1:{x:c.x+o.x*u,y:c.y+o.y*u},cp2:{x:d.x-a.x*u,y:d.y-a.y*u},actualRadius:l}}function applyCornerRadiusToPolygon(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(t.length<3)throw new Error("Polygon must have at least 3 points");let s=e;if(i){const i=Math.min(...t.map(t=>t.x)),n=Math.max(...t.map(t=>t.x)),r=Math.min(...t.map(t=>t.y)),o=Math.max(...t.map(t=>t.y)),a=n-i,h=o-r,l=undefined;s=e/100*Math.min(a,h)}const n=[];for(let e=0;e<t.length;e++){const i=(e-1+t.length)%t.length,r=(e+1)%t.length,o=undefined,a=undefined,h=undefined,l=calculateRoundedCorner(t[i],t[e],t[r],s);n.push(l)}return n}function renderRoundedPolygon(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(0===e.length)return;t.beginPath();const s=e[0];t.moveTo(s.start.x,s.start.y);for(let s=0;s<e.length;s++){const n=e[s],r=undefined,o=e[(s+1)%e.length];t.bezierCurveTo(n.cp1.x,n.cp1.y,n.cp2.x,n.cp2.y,n.end.x,n.end.y),(s<e.length-1||i)&&t.lineTo(o.start.x,o.start.y)}i&&t.closePath()}function generateRoundedPolygonPath(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(0===t.length)return"";const i=[],s=t[0];i.push(`M ${s.start.x} ${s.start.y}`);for(let s=0;s<t.length;s++){const n=t[s],r=undefined,o=t[(s+1)%t.length];i.push(`C ${n.cp1.x} ${n.cp1.y} ${n.cp2.x} ${n.cp2.y} ${n.end.x} ${n.end.y}`),(s<t.length-1||e)&&i.push(`L ${o.start.x} ${o.start.y}`)}return e&&i.push("Z"),i.join(" ")}_defineProperty(Line,"type","Line"),_defineProperty(Line,"cacheProperties",[...Ot,...qe]),_defineProperty(Line,"ATTRIBUTE_NAMES",se.concat(qe)),X.setClass(Line),X.setSVGClass(Line);const Ke={width:100,height:100,cornerRadius:0},Je=["cornerRadius"];class Triangle extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Triangle.ownDefaults}}constructor(t){super(),Object.assign(this,Triangle.ownDefaults),this.setOptions(t)}_getTrianglePoints(){const t=this.width/2,e=this.height/2;return[{x:-t,y:e},{x:0,y:-e},{x:t,y:e}]}_render(t){if(this.cornerRadius>0){const e=undefined,i=undefined;renderRoundedPolygon(t,applyCornerRadiusToPolygon(this._getTrianglePoints(),this.cornerRadius),!0)}else{const e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath()}this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...Je,...t])}_toSVG(){if(this.cornerRadius>0){const t=undefined,e=undefined,i=undefined;return["<path ","COMMON_PARTS",`d="${generateRoundedPolygonPath(applyCornerRadiusToPolygon(this._getTrianglePoints(),this.cornerRadius),!0)}" />`]}{const t=this.width/2,e=this.height/2,i=undefined;return["<polygon ","COMMON_PARTS",'points="',`${-t} ${e},0 ${-e},${t} ${e}`,'" />']}}}_defineProperty(Triangle,"type","Triangle"),_defineProperty(Triangle,"cacheProperties",[...Ot,...Je]),_defineProperty(Triangle,"ownDefaults",Ke),X.setClass(Triangle),X.setSVGClass(Triangle);const Ze={rx:0,ry:0},Qe=["rx","ry"];class Ellipse extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Ellipse.ownDefaults}}constructor(t){super(),Object.assign(this,Ellipse.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);break}return this}getRx(){return this.get("rx")*this.get(A)}getRy(){return this.get("ry")*this.get(F)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...Qe,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",`cx="0" cy="0" rx="${this.rx}" ry="${this.ry}" />\n`]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,l,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,i){const s=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return s.left=(s.left||0)-s.rx,s.top=(s.top||0)-s.ry,new this(s)}}function parsePointsAttribute(t){if(!t)return[];const e=t.replace(/,/g," ").trim().split(/\s+/),i=[];for(let t=0;t<e.length;t+=2)i.push({x:parseFloat(e[t]),y:parseFloat(e[t+1])});return i}_defineProperty(Ellipse,"type","Ellipse"),_defineProperty(Ellipse,"cacheProperties",[...Ot,...Qe]),_defineProperty(Ellipse,"ownDefaults",Ze),_defineProperty(Ellipse,"ATTRIBUTE_NAMES",[...se,"cx","cy","rx","ry"]),X.setClass(Ellipse),X.setSVGClass(Ellipse);const ti={exactBoundingBox:!1,cornerRadius:0};class Polyline extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Polyline.ownDefaults}}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_defineProperty(this,"strokeDiff",void 0),Object.assign(this,Polyline.ownDefaults),this.setOptions(e),this.points=t;const{left:i,top:s}=e;this.initialized=!0,this.setBoundingBox(!0),"number"==typeof i&&this.set(m,i),"number"==typeof s&&this.set(y,s)}isOpen(){return!0}_projectStrokeOnPoints(t){return projectStrokeOnPoints(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(t=>t.projectedPoint):this.points;if(0===e.length)return{left:0,top:0,width:0,height:0,pathOffset:new Point,strokeOffset:new Point,strokeDiff:new Point};const i=makeBoundingBoxFromPoints(e),s=calcDimensionsMatrix({...t,scaleX:1,scaleY:1}),n=makeBoundingBoxFromPoints(this.points.map(t=>transformPoint(t,s,!0))),r=new Point(this.scaleX,this.scaleY);let o=i.left+i.width/2,a=i.top+i.height/2;return this.exactBoundingBox&&(o-=a*Math.tan(degreesToRadians(this.skewX)),a-=o*Math.tan(degreesToRadians(this.skewY))),{...i,pathOffset:new Point(o,a),strokeOffset:new Point(n.left,n.top).subtract(new Point(i.left,i.top)).multiply(r),strokeDiff:new Point(i.width,i.height).subtract(new Point(n.width,n.height)).multiply(r)}}_findCenterFromElement(){const t=makeBoundingBoxFromPoints(this.points);return new Point(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:i,width:s,height:n,pathOffset:r,strokeOffset:o,strokeDiff:a}=this._calcDimensions();this.set({width:s,height:n,pathOffset:r,strokeOffset:o,strokeDiff:a}),t&&this.setPositionByOrigin(new Point(e+s/2,i+n/2),p,p)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new Point(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.exactBoundingBox){let r;if(Object.keys(t).some(t=>this.strokeUniform||this.constructor.layoutProperties.includes(t))){var e,i;const{width:s,height:n}=this._calcDimensions(t);r=new Point(null!==(e=t.width)&&void 0!==e?e:s,null!==(i=t.height)&&void 0!==i?i:n)}else{var s,n;r=new Point(null!==(s=t.width)&&void 0!==s?s:this.width,null!==(n=t.height)&&void 0!==n?n:this.height)}return r.multiply(new Point(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const i=this.initialized&&this[t]!==e,s=super._set(t,e);return this.exactBoundingBox&&i&&((t===A||t===F)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),s}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject(["cornerRadius",...t]),points:this.points.map(t=>{let{x:e,y:i}=t;return{x:e,y:i}})}}_toSVG(){if(this.cornerRadius>0&&this.points.length>=3){const t=this.pathOffset.x,e=this.pathOffset.y,i=undefined,s=undefined,n=undefined;return["<path ","COMMON_PARTS",`d="${generateRoundedPolygonPath(applyCornerRadiusToPolygon(this.points.map(i=>({x:i.x-t,y:i.y-e})),this.cornerRadius),!this.isOpen())}" />\n`]}{const t=[],i=this.pathOffset.x,s=this.pathOffset.y,n=e.NUM_FRACTION_DIGITS;for(let e=0,r=this.points.length;e<r;e++)t.push(toFixed(this.points[e].x-i,n),",",toFixed(this.points[e].y-s,n)," ");return[`<${this.constructor.type.toLowerCase()} `,"COMMON_PARTS",`points="${t.join("")}" />\n`]}}_render(t){const e=this.points.length,i=this.pathOffset.x,s=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){if(this.cornerRadius>0&&e>=3){const e=undefined,n=undefined;renderRoundedPolygon(t,applyCornerRadiusToPolygon(this.points.map(t=>({x:t.x-i,y:t.y-s})),this.cornerRadius),!this.isOpen())}else{t.beginPath(),t.moveTo(this.points[0].x-i,this.points[0].y-s);for(let n=0;n<e;n++){const e=this.points[n];t.lineTo(e.x-i,e.y-s)}!this.isOpen()&&t.closePath()}this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,i){const s=parsePointsAttribute(t.getAttribute("points")),{left:n,top:r,...o}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this(s,{...o,...e})}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}_defineProperty(Polyline,"ownDefaults",ti),_defineProperty(Polyline,"type","Polyline"),_defineProperty(Polyline,"layoutProperties",[L,j,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),_defineProperty(Polyline,"cacheProperties",[...Ot,"points","cornerRadius"]),_defineProperty(Polyline,"ATTRIBUTE_NAMES",[...se]),X.setClass(Polyline),X.setSVGClass(Polyline);class Polygon extends Polyline{isOpen(){return!1}}_defineProperty(Polygon,"ownDefaults",ti),_defineProperty(Polygon,"type","Polygon"),X.setClass(Polygon),X.setSVGClass(Polygon);class StyledText extends FabricObject{isEmptyStyles(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;const e=void 0===t?this.styles:{line:this.styles[t]};for(const t in e)for(const i in e[t])for(const s in e[t][i])return!1;return!0}styleHas(t,e){if(!this.styles)return!1;if(void 0!==e&&!this.styles[e])return!1;const i=void 0===e?this.styles:{0:this.styles[e]};for(const e in i)for(const s in i[e])if(void 0!==i[e][s][t])return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let i=0,s,n,r=!0,o=0;for(const o in e){s=0;for(const a in e[o]){const h=e[o][a]||{},l=undefined;i++,void 0!==h[t]?(n?h[t]!==n&&(r=!1):n=h[t],h[t]===this[t]&&delete h[t]):r=!1,0!==Object.keys(h).length?s++:delete e[o][a]}0===s&&delete e[o]}for(let t=0;t<this._textLines.length;t++)o+=this._textLines[t].length;r&&i===o&&(this[t]=n,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let i,s,n;for(s in e){for(n in i=e[s],i)delete i[n][t],0===Object.keys(i[n]).length&&delete i[n];0===Object.keys(i).length&&delete e[s]}}_extendStyles(t,e){const{lineIndex:i,charIndex:s}=this.get2DCursorLocation(t);this._getLineStyle(i)||this._setLineStyle(i);const n=pickBy({...this._getStyleDeclaration(i,s),...e},t=>void 0!==t);this._setStyleDeclaration(i,s,n)}getSelectionStyles(t,e,i){const s=[];for(let n=t;n<(e||t);n++)s.push(this.getStyleAtPosition(n,i));return s}getStyleAtPosition(t,e){const{lineIndex:i,charIndex:s}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(i,s):this._getStyleDeclaration(i,s)}setSelectionStyles(t,e,i){for(let s=e;s<(i||e);s++)this._extendStyles(s,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var i;const s=this.styles&&this.styles[t];return s&&null!==(i=s[e])&&void 0!==i?i:{}}getCompleteStyleDeclaration(t,e){return{...pick(this,this.constructor._styleProperties),...this._getStyleDeclaration(t,e)}}_setStyleDeclaration(t,e,i){this.styles[t][e]=i}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}_defineProperty(StyledText,"_styleProperties",st);let ei=null;function getMeasurementContext(){if(!ei){const t=createCanvasElementFor({width:0,height:0});ei=t.getContext("2d")}return ei}function measureGrapheme(t,e,i){const s=ii.get(t,e);if(s)return s;const n=i||getMeasurementContext();applyFontStyle(n,e);const r=n.measureText(t),o=getFontMetrics(e),a={width:r.width,height:o.lineHeight,ascent:o.ascent,descent:o.descent,baseline:o.ascent};return ii.set(t,e,a),a}function measureGraphemeWithKerning(t,e,i,s){const n=measureGrapheme(t,i,s);if(!e)return{...n,kernedWidth:n.width};const r=`${e}${t}`,o=si.get(r,i);if(o)return{...n,kernedWidth:o};const a=getMeasurementContext();applyFontStyle(a,i);const h=undefined,l=undefined,c=a.measureText(e+t).width-measureGrapheme(e,i,a).width;return si.set(r,i,c),{...n,kernedWidth:c}}function getRepresentativeCharacter(t){const e=getMeasurementContext();if("undefined"!=typeof document&&"fonts"in document)try{if(!document.fonts.check(`16px ${t}`))return"M"}catch(t){return"M"}const i=[{char:"م",script:"Arabic"},{char:"א",script:"Hebrew"},{char:"अ",script:"Devanagari"},{char:"ا",script:"Urdu"},{char:"ک",script:"Persian"},{char:"த",script:"Tamil"},{char:"ก",script:"Thai"},{char:"М",script:"Cyrillic"},{char:"Ω",script:"Greek"},{char:"M",script:"Latin"}];e.font=`16px ${t}`;const s=e.measureText("M").width;for(const t of i){const i=e.measureText(t.char);if(i.width>0&&Math.abs(i.width-s)>.1)return t.char}return"M"}function getFontMetrics(t){var e,i,s,n;const r=getFontDeclaration(t),o=ni.get(r);if(o)return o;const a=getMeasurementContext();applyFontStyle(a,t);const h=getRepresentativeCharacter(t.fontFamily),l=a.measureText(h),c=t.fontSize,d=null!==(e=l.fontBoundingBoxAscent)&&void 0!==e?e:.91*c,u=null!==(i=l.fontBoundingBoxDescent)&&void 0!==i?i:.21*c,g=undefined,f=undefined,p={ascent:d,descent:u,lineHeight:c,baseline:"alphabetic",fontBoundingBoxAscent:d,fontBoundingBoxDescent:u,actualBoundingBoxAscent:null!==(s=l.actualBoundingBoxAscent)&&void 0!==s?s:.716*c,actualBoundingBoxDescent:null!==(n=l.actualBoundingBoxDescent)&&void 0!==n?n:0};return ni.set(r,p),p}function applyFontStyle(t,e){const i=getFontDeclaration(e);t.font=i,e.letterSpacing&&"letterSpacing"in t&&(t.letterSpacing=`${e.letterSpacing}px`),e.direction&&(t.direction=e.direction),t.textBaseline="alphabetic"}function getFontDeclaration(t){const{fontStyle:e,fontWeight:i,fontSize:s,fontFamily:n}=t;let r;return`${e} ${i} ${s}px ${!n.includes(" ")||n.includes('"')||n.includes("'")?n:`"${n}"`}`}class LRUCache{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;_defineProperty(this,"cache",new Map),_defineProperty(this,"maxSize",void 0),_defineProperty(this,"hits",0),_defineProperty(this,"misses",0),this.maxSize=t}get(t){const e=this.cache.get(t);if(e)return e.timestamp=Date.now(),this.hits++,e.value;this.misses++}set(t,e){if(this.cache.size>=this.maxSize){const t=this.findOldestKey();t&&this.cache.delete(t)}this.cache.set(t,{value:e,timestamp:Date.now()})}findOldestKey(){let t,e=1/0;for(const[i,s]of this.cache.entries())s.timestamp<e&&(e=s.timestamp,t=i);return t}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){const t=this.hits+this.misses;return{size:this.cache.size,hitRate:t>0?this.hits/t:0,hits:this.hits,misses:this.misses}}}class MeasurementCache{constructor(){_defineProperty(this,"cache",new LRUCache(1e3))}getCacheKey(t,e){const i=undefined,s=undefined;return`${getFontDeclaration(e)}|${t}|${e.letterSpacing||0}`}get(t,e){const i=this.getCacheKey(t,e);return this.cache.get(i)}set(t,e,i){const s=this.getCacheKey(t,e);this.cache.set(s,i)}clear(){this.cache.clear()}getStats(){return this.cache.getStats()}}class KerningCache{constructor(){_defineProperty(this,"cache",new LRUCache(5e3))}getCacheKey(t,e){const i=undefined;return`${getFontDeclaration(e)}|${t}`}get(t,e){const i=this.getCacheKey(t,e);return this.cache.get(i)}set(t,e,i){const s=this.getCacheKey(t,e);this.cache.set(s,i)}clear(){this.cache.clear()}getStats(){return this.cache.getStats()}}class FontMetricsCache{constructor(){_defineProperty(this,"cache",new Map)}get(t){return this.cache.get(t)}set(t,e){this.cache.set(t,e)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size}}}const ii=new MeasurementCache,si=new KerningCache,ni=new FontMetricsCache;function clearAllCaches(){ii.clear(),si.clear(),ni.clear()}function fontLacksEnglishGlyphs(t){if("undefined"==typeof document)return!1;const e=["stv","arabic","naskh","thuluth","kufi","diwani","nastaliq","kufic","hijazi","madinah","makkah"],i=t.toLowerCase();if(e.some(t=>i.includes(t)))return!0;const s=getMeasurementContext();s.font=`16px ${t}`;const n=["A","B","C","a","b","c","M","W"],r="Arial, sans-serif",o=n.map(t=>s.measureText(t).width);s.font=`16px ${r}`;const a=n.map(t=>s.measureText(t).width);let h=0;for(let t=0;t<n.length;t++)Math.abs(o[t]-a[t])<.5&&h++;const l=undefined,c=undefined;return h>=.7*n.length}"undefined"!=typeof document&&"fonts"in document&&document.fonts.addEventListener("loadingdone",()=>{clearAllCaches()});const ri=new Map;function fontLacksEnglishGlyphsCached(t){if(ri.has(t))return ri.get(t);const e=fontLacksEnglishGlyphs(t);return ri.set(t,e),e}const oi={L:/[\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]/,R:/[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0608\u060B\u060D]/,AL:/[\u0627\u0629-\u063A\u0641-\u064A\u066D-\u066F\u0671-\u06D3\u06D5]/,EN:/[\u0030-\u0039\u00B2\u00B3\u00B9\u06F0-\u06F9]/,AN:/[\u0660-\u0669\u066B\u066C]/};function segmentGraphemes(t){if("undefined"!=typeof Intl&&"Segmenter"in Intl)try{const e=undefined,i=new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(t);return Array.from(i,t=>t.segment)}catch(t){}return graphemeSplit(t)}function analyzeBiDi(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"ltr";if(!t)return[];const i=[],s=Array.from(t);let n=null;for(let t=0;t<s.length;t++){const r=s[t],o=getBidiDirection(r,e);n&&n.direction===o?(n.text+=r,n.end=t+1):(n&&i.push(n),n={text:r,direction:o,level:"rtl"===o?1:0,start:t,end:t+1})}return n&&i.push(n),i.length>0?i:[{text:t,direction:e,level:"rtl"===e?1:0,start:0,end:t.length}]}function isWhitespace(t){return/\s/.test(t)}function getBidiDirection(t,e){return oi.R.test(t)||oi.AL.test(t)?"rtl":oi.L.test(t)?"ltr":(oi.EN.test(t)||oi.AN.test(t),e)}const ai="ـ",hi=new Set(["ا","د","ذ","ر","ز","و","ة","ء","آ","أ","إ","ٲ","ٳ","ٵ","ڈ","ډ","ڊ","ڋ","ڌ","ڍ","ڎ","ڏ","ڐ","ڑ","ڒ","ړ","ڔ","ڕ","ږ","ڗ","ژ","ڙ","ۄ","ۅ","ۆ","ۇ","ۈ","ۉ","ۊ","ۋ","ۍ","ۏ"]);function isArabicLetter(t){if(!t)return!1;const e=t.charCodeAt(0);return e>=1568&&e<=1610||e>=1646&&e<=1747||e>=1872&&e<=1919||e>=2208&&e<=2303}const li=new Set(["ا","أ","إ","آ","ٱ"]),ci="ل";function canInsertKashida(t,e){return!(!t||!e)&&(!/\s/.test(t)&&!/\s/.test(e)&&(!(!isArabicLetter(t)||!isArabicLetter(e))&&(!hi.has(t)&&(t!==ci||!li.has(e)))))}function findKashidaPoints(t){const e=[];for(let i=0;i<t.length-1;i++){const s=undefined,n=undefined;if(canInsertKashida(t[i],t[i+1])){let s=1,n=i,r=i+1;for(;n>0&&!isWhitespace(t[n-1]);)n--;for(;r<t.length&&!isWhitespace(t[r]);)r++;const o=r-n,a=i-n,h=undefined;s=Math.min(a,o-1-a)+1,o>4&&(s+=1),o>6&&(s+=1),e.push({charIndex:i,priority:s})}}return e.sort((t,e)=>e.priority-t.priority),e}function applyEllipsis(t,e){const{maxWidth:i,maxHeight:s,ellipsisChar:n,measureFn:r}=e;if(!t)return{truncatedText:"",isTruncated:!1,truncationIndex:0,ellipsisWidth:0,originalLength:0};const o="number"==typeof r(n)?r(n):r(n).width,a=r(t),h="number"==typeof a?a:a.width,l="number"==typeof a?0:a.height;let c=!1;if(i&&h>i&&(c=!0),s&&l>s&&(c=!0),!c)return{truncatedText:t,isTruncated:!1,truncationIndex:segmentGraphemes(t).length,ellipsisWidth:o,originalLength:segmentGraphemes(t).length};if(i){const e=undefined;return{...truncateByWidth(t,i,n,o,r),ellipsisWidth:o,originalLength:segmentGraphemes(t).length}}if(s){const e=undefined;return{...truncateByHeight(t,s,n,r),ellipsisWidth:o,originalLength:segmentGraphemes(t).length}}return{truncatedText:t,isTruncated:!1,truncationIndex:segmentGraphemes(t).length,ellipsisWidth:o,originalLength:segmentGraphemes(t).length}}function truncateByWidth(t,e,i,s,n){const r=segmentGraphemes(t),o=e-s;let a=0,h=r.length,l=0;for(;a<=h;){const t=Math.floor((a+h)/2),e=undefined,i=n(r.slice(0,t).join("")),s=undefined;("number"==typeof i?i:i.width)<=o?(l=t,a=t+1):h=t-1}if(0===l)return{truncatedText:i,isTruncated:!0,truncationIndex:0};if(l===r.length)return{truncatedText:t,isTruncated:!1,truncationIndex:r.length};const c=undefined;return{truncatedText:r.slice(0,l).join("")+i,isTruncated:!0,truncationIndex:l}}function truncateByHeight(t,e,i,s){var n;const r=t.split("\n");let o="",a=0;for(a=0;a<r.length;a++){const i=0===a?r[a]:o+"\n"+r[a],n=s(i),h=undefined;if(("number"==typeof n?0:n.height)>e&&o)break;if(o=i,a===r.length-1)return{truncatedText:t,isTruncated:!1,truncationIndex:segmentGraphemes(t).length}}if(a>0){const t=r[a-1],e=t+i,s=segmentGraphemes(o);return{truncatedText:o.replace(/[^\n]*$/,e),isTruncated:!0,truncationIndex:s.length-segmentGraphemes(t).length+segmentGraphemes(e).length-1}}const h="function"==typeof s&&(null===(n=s(r[0]))||void 0===n?void 0:n.width)||1e3;return truncateByWidth(r[0],h,i,0,s)}function layoutText(t){var e;const{text:i,width:s,height:n,wrap:r,align:o,ellipsis:a,direction:h,padding:l=0,verticalAlign:c="top"}=t;if(!i)return{lines:[],totalWidth:0,totalHeight:0,isTruncated:!1,graphemeCount:0};const d=s?s-2*l:1/0,u=n?n-2*l:1/0,g=i.split("\n"),f=[];let p=0,m=0,y=0,x;for(let e=0;e<g.length;e++){const i=g[e],s=e===g.length-1,r=layoutParagraph(i,{...t,width:d,isLastParagraph:s});for(const e of r){if(n&&p+e.height>u){const i=handleHeightOverflow(f,e,u-p,t);return{lines:i.lines,totalWidth:Math.max(m,...i.lines.map(t=>t.width)),totalHeight:u,isTruncated:!0,graphemeCount:y+i.addedGraphemes,ellipsisApplied:i.ellipsisResult}}e===r[r.length-1]&&(e.isLastInParagraph=!0),f.push(e),p+=e.height,m=Math.max(m,e.width),y+=e.graphemes.length}}if(a&&s)for(const e of f)if(e.width>d&&(x=applyEllipsis(e.text,{maxWidth:d,maxHeight:1/0,ellipsisChar:"string"==typeof a?a:"…",measureFn:e=>measureLineWidth(e,t)}),x.isTruncated)){const i=layoutSingleLine(x.truncatedText,t);Object.assign(e,i);break}const v=applyAlignment(f,o,m,t),_=calculateVerticalOffset(p,n||p,c);return v.forEach(t=>{t.bounds.forEach(t=>{t.y+=_})}),{lines:v,totalWidth:m,totalHeight:p,isTruncated:!(null===(e=x)||void 0===e||!e.isTruncated),graphemeCount:y,ellipsisApplied:x}}function layoutParagraph(t,e){const{wrap:i,width:s}=e;if(!t)return[createEmptyLine(e)];if("none"===i||s===1/0)return[layoutSingleLine(t,e,0)];const n=[];"word"===i?n.push(...wrapByWords(t,s,e)):"char"===i&&n.push(...wrapByCharacters(t,s,e));let r=0;const o=undefined;return n.map(t=>{const i=layoutSingleLine(t,e,r);return r+=t.length+1,i})}function layoutSingleLine(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const s=segmentGraphemes(t),n=[],r=createMeasurementOptions(e);let o=0,a=0,h=0,l=i;for(let t=0;t<s.length;t++){const c=s[t],d=undefined,u=measureGraphemeWithKerning(c,t>0?s[t-1]:void 0,r),g=undefined,f=undefined,p=(e.letterSpacing||0)+(e.charSpacing?e.fontSize*e.charSpacing/1e3:0),m=u.kernedWidth+p;n.push({grapheme:c,x:o,y:0,width:u.width,height:u.height,kernedWidth:u.kernedWidth,left:o,baseline:u.baseline,charIndex:l,graphemeIndex:i+t}),l+=c.length,o+=m,a+=m,h=Math.max(h,u.height)}n.length>0&&(e.letterSpacing,e.charSpacing&&(e.fontSize,e.charSpacing));const c=1.13,d=h*e.lineHeight*c;return{text:t,graphemes:s,width:a,height:d,bounds:n,isWrapped:!1,isLastInParagraph:!1,baseline:.8*d}}function wrapByWords(t,e,i){const s=[],n=t.split(/(\s+)/);let r="";for(let t=0;t<n.length;t++){const o=n[t],a=measureLineWidth(o,i),h=r?r+o:o,l=undefined;if(measureLineWidth(h,i)>e&&r)s.push(r.trim()),r=o;else if(a>e&&!r){const t=wrapByCharacters(o,e,i);s.push(...t.slice(0,-1)),r=t[t.length-1],measureLineWidth(r,i)}else r=h}return r&&s.push(r.trim()),s.length>0?s:[""]}function wrapByCharacters(t,e,i){const s=[],n=segmentGraphemes(t);let r="";for(const t of n){const n=r+t,o=undefined;measureLineWidth(n,i)>e&&r?(s.push(r),r=t):r=n}return r&&s.push(r),s.length>0?s:[""]}function applyBiDiVisualReordering(t,e){const i="inherit"===e.direction?"ltr":e.direction,s=analyzeBiDi(t.text,i),n=undefined;if(!(s.length>1||1===s.length&&s[0].direction!==i))return"rtl"===i&&t.bounds.forEach(e=>{e.x=t.width-e.left-e.kernedWidth}),t;const r=[];let o=0;for(let t=0;t<s.length;t++){const e=undefined,i=segmentGraphemes(s[t].text);for(let e=0;e<i.length;e++)r.push(t);o+=i.length}const a=[],h=[];let l=0;for(const i of s){h.push(l);const s=segmentGraphemes(i.text);let n=0;for(let i=0;i<s.length;i++)if(l+i<t.bounds.length){const s=e.letterSpacing||0,r=e.charSpacing?e.fontSize*e.charSpacing/1e3:0;n+=t.bounds[l+i].kernedWidth+s+r}a.push(n),l+=s.length}const c=s.map((t,e)=>e);"rtl"===i&&c.reverse();const d=new Array(s.length);let u=0;for(const t of c)d[t]=u,u+=a[t];for(let i=0;i<t.bounds.length;i++){const n=r[i];if(void 0===n)continue;const o=s[n],l=h[n],c=undefined,u=undefined,g=(e.letterSpacing||0)+(e.charSpacing?e.fontSize*e.charSpacing/1e3:0);let f=0;for(let e=l;e<i;e++)f+=t.bounds[e].kernedWidth+g;const p=t.bounds[i].kernedWidth+g;"rtl"===o.direction?t.bounds[i].x=d[n]+a[n]-f-p:t.bounds[i].x=d[n]+f}return t}function applyAlignment(t,e,i,s){return t.map(t=>{applyBiDiVisualReordering(t,s);let n=0;switch(e){case"center":n=(i-t.width)/2;break;case"right":n=i-t.width;break;case"justify":if(!t.isLastInParagraph&&t.graphemes.length>1)return applyJustification(t,i,s);break;case"left":default:n=0;break}return 0!==n&&t.bounds.forEach(t=>{t.x+=n,t.left+=n}),t})}function applyJustification(t,e,i){const s=t.graphemes.filter(t=>/\s/.test(t)).length;if(0===s)return t;const n=undefined,r=(e-t.width)/s;let o=0;return t.bounds.forEach(t=>{t.x+=o,t.left+=o,/\s/.test(t.grapheme)&&(t.kernedWidth+=r,t.width+=r,o+=r)}),t.width=e,t.justifyRatio=1+r/(.25*i.fontSize),t}function calculateVerticalOffset(t,e,i){switch(i){case"middle":return(e-t)/2;case"bottom":return e-t;case"top":default:return 0}}function handleHeightOverflow(t,e,i,s){if(s.ellipsis&&i>0){const n="string"==typeof s.ellipsis?s.ellipsis:"…",r=s.width||1/0,o=applyEllipsis(e.text,{maxWidth:r,maxHeight:i,ellipsisChar:n,measureFn:t=>measureLineWidth(t,s)});if(o.isTruncated){const e=layoutSingleLine(o.truncatedText,s);return e.isLastInParagraph=!0,{lines:[...t,e],addedGraphemes:e.graphemes.length,ellipsisResult:o}}}return{lines:t,addedGraphemes:0}}function createEmptyLine(t){const e=1.13,i=t.fontSize*t.lineHeight*e;return{text:"",graphemes:[],width:0,height:i,bounds:[],isWrapped:!1,isLastInParagraph:!0,baseline:.8*i}}function measureLineWidth(t,e){const i=segmentGraphemes(t),s=createMeasurementOptions(e);let n=0;for(let t=0;t<i.length;t++){const r=undefined,o=undefined,a=measureGraphemeWithKerning(i[t],t>0?i[t-1]:void 0,s),h=e.letterSpacing||0,l=e.charSpacing?e.fontSize*e.charSpacing/1e3:0;n+=a.kernedWidth+h+l}return n}function createMeasurementOptions(t){return{fontFamily:t.fontFamily,fontSize:t.fontSize,fontStyle:t.fontStyle,fontWeight:t.fontWeight,letterSpacing:t.letterSpacing,direction:"inherit"===t.direction?"ltr":t.direction}}const di=/ +/g,ui=/"/g;function createSVGInlineRect(t,e,i,s,n){return`\t\t${createSVGRect(t,{left:e,top:i,width:s,height:n})}\n`}class TextSVGExportMixin extends FabricObjectSVGExportMixin{_toSVG(){const t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)}toSVG(t){const e=this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0}),i=this.path;return i?e+i._createBaseSVGMarkup(i._toSVG(),{reviver:t,withShadow:!0,additionalTransform:matrixToSVG(this.calcOwnMatrix())}):e}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(t){let{textBgRects:e,textSpans:i}=t;const s=!0,n=this.getSvgTextDecoration(this);return[e.join(""),'\t\t<text xml:space="preserve" ',`font-family="${this.fontFamily.replace(ui,"'")}" `,`font-size="${this.fontSize}" `,this.fontStyle?`font-style="${this.fontStyle}" `:"",this.fontWeight?`font-weight="${this.fontWeight}" `:"",n?`text-decoration="${n}" `:"","rtl"===this.direction?`direction="${this.direction}" `:"",'style="',this.getSvgStyles(s),'"',this.addPaintOrder()," >",i.join(""),"</text>\n"]}_getSVGTextAndBg(t,e){const i=[],s=[];let n=t,r;this.backgroundColor&&s.push(...createSVGInlineRect(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let t=0,o=this._textLines.length;t<o;t++)r=this._getLineLeftOffset(t),"rtl"===this.direction&&(r+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",t))&&this._setSVGTextLineBg(s,t,e+r,n),this._setSVGTextLineText(i,t,e+r,n),n+=this.getHeightOfLine(t);return{textSpans:i,textBgRects:s}}_createTextCharSpan(t,i,s,n,r){const o=e.NUM_FRACTION_DIGITS,a=this.getSvgSpanStyles(i,t!==t.trim()||!!t.match(di)),h=a?`style="${a}"`:"",l=i.deltaY,c=l?` dy="${toFixed(l,o)}" `:"",{angle:d,renderLeft:u,renderTop:g,width:f}=r;let p="";if(void 0!==u){const t=f/2;d&&(p=` rotate="${toFixed(radiansToDegrees(d),o)}"`);const e=createRotateMatrix({angle:radiansToDegrees(d)});e[4]=u,e[5]=g;const i=new Point(-t,0).transform(e);s=i.x,n=i.y}return`<tspan x="${toFixed(s,o)}" y="${toFixed(n,o)}" ${c}${p}${h}>${escapeXml(t)}</tspan>`}_setSVGTextLineText(t,e,i,s){const n=this.getHeightOfLine(e),r=this.textAlign.includes(rt),o=this._textLines[e];let a,h,l="",c,d,u=0,g;s+=n*(1-this._fontSizeFraction)/this.lineHeight;for(let n=0,f=o.length-1;n<=f;n++)g=n===f||this.charSpacing||this.path,l+=o[n],c=this.__charBounds[e][n],0===u?(i+=c.kernedWidth-c.width,u+=c.width):u+=c.kernedWidth,r&&!g&&this._reSpaceAndTab.test(o[n])&&(g=!0),g||(a=a||this.getCompleteStyleDeclaration(e,n),h=this.getCompleteStyleDeclaration(e,n+1),g=hasStyleChanged(a,h,!0)),g&&(d=this._getStyleDeclaration(e,n),t.push(this._createTextCharSpan(l,d,i,s,c)),l="",a=h,"rtl"===this.direction?i-=u:i+=u,u=0)}_setSVGTextLineBg(t,e,i,s){const n=this._textLines[e],r=this.getHeightOfLine(e)/this.lineHeight;let o=0,a=0,h,l=this.getValueOfPropertyAt(e,0,"textBackgroundColor");for(let c=0;c<n.length;c++){const{left:n,width:d,kernedWidth:u}=this.__charBounds[e][c];h=this.getValueOfPropertyAt(e,c,"textBackgroundColor"),h!==l?(l&&t.push(...createSVGInlineRect(l,i+a,s,o,r)),a=n,o=d,l=h):o+=u}h&&t.push(...createSVGInlineRect(l,i+a,s,o,r))}getSvgStyles(t){return`${super.getSvgStyles(t)} text-decoration-thickness: ${toFixed(this.textDecorationThickness*this.getObjectScaling().y/10,e.NUM_FRACTION_DIGITS)}%; white-space: pre;`}getSvgSpanStyles(t,i){const{fontFamily:s,strokeWidth:n,stroke:r,fill:o,fontSize:a,fontStyle:h,fontWeight:l,deltaY:c,textDecorationThickness:d,linethrough:u,overline:g,underline:f}=t,p=this.getSvgTextDecoration({underline:null!=f?f:this.underline,overline:null!=g?g:this.overline,linethrough:null!=u?u:this.linethrough}),m=d||this.textDecorationThickness;return[r?colorPropToSVG(B,r):"",n?`stroke-width: ${n}; `:"",s?`font-family: ${s.includes("'")||s.includes('"')?s:`'${s}'`}; `:"",a?`font-size: ${a}px; `:"",h?`font-style: ${h}; `:"",l?`font-weight: ${l}; `:"",p?`text-decoration: ${p}; text-decoration-thickness: ${toFixed(m*this.getObjectScaling().y/10,e.NUM_FRACTION_DIGITS)}%; `:"",o?colorPropToSVG(I,o):"",c?`baseline-shift: ${-c}; `:"",i?"white-space: pre; ":""].join("")}getSvgTextDecoration(t){return["overline","underline","line-through"].filter(e=>t[e.replace("-","")]).join(" ")}}function segmentIntoGraphemes(t){if("undefined"!=typeof Intl&&Intl.Segmenter){const e=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(e.segment(t),t=>t.segment)}return Array.from(t)}function extractLinesFromDOM(t){const e=t.value;if(!e)return{lines:[],totalWidth:0,totalHeight:0};const i=getComputedStyle(t),s=t.parentElement;if(!s)throw new Error("Textarea must be in DOM to extract lines");const n=document.createElement("div");n.style.position="absolute",n.style.left="-9999px",n.style.top="-9999px",n.style.visibility="hidden",n.style.pointerEvents="none";const r=undefined;["fontSize","fontFamily","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textAlign","textTransform","whiteSpace","overflowWrap","wordBreak","direction","unicodeBidi","width","height","maxWidth","maxHeight","minWidth","minHeight","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","border","borderTop","borderRight","borderBottom","borderLeft","boxSizing"].forEach(t=>{n.style[t]=i[t]}),n.style.overflow="hidden",n.style.resize="none",s.appendChild(n);try{const t=segmentIntoGraphemes(e),i=[];t.forEach((t,e)=>{const s=document.createElement("span");s.textContent=t,s.setAttribute("data-index",e.toString()),n.appendChild(s),i.push(s)});const s=new Map;i.forEach((t,e)=>{const i=t.offsetTop;s.has(i)||s.set(i,{spans:[],indices:[]}),s.get(i).spans.push(t),s.get(i).indices.push(e)});const r=[],o=undefined;Array.from(s.keys()).sort((t,e)=>t-e).forEach(e=>{const i=undefined,n=s.get(e).indices.sort((t,e)=>t-e),o=n[0],a=n[n.length-1]+1,h=t.slice(o,a).join("");r.push({text:h,start:o,end:a})});const a=Math.max(...i.map(t=>t.offsetLeft+t.offsetWidth)),h=i.length>0?Math.max(...i.map(t=>t.offsetTop+t.offsetHeight)):0;return{lines:r,totalWidth:a,totalHeight:h}}finally{s.removeChild(n)}}function createLayoutHash(t){const e=undefined;return[t.text,t.width,t.height,t.fontFamily,t.fontSize,t.fontWeight,t.fontStyle,t.lineHeight,t.charSpacing,t.textAlign,t.direction].map(t=>String(t)).join("|")}function areBrowserLinesValid(t,e){if(!e||!t.__lastBrowserLines)return!1;const i=undefined;return createLayoutHash(t)===e}function storeBrowserLines(t,e,i){t.__lastBrowserLines=e,t.__lastBrowserLinesHash=createLayoutHash(t)}function clearBrowserLines(t){delete t.__lastBrowserLines,delete t.__lastBrowserLinesHash}function getBrowserLines(t){const e=t.__lastBrowserLines,i=t.__lastBrowserLinesHash;return e&&areBrowserLinesValid(t,i)?e:null}let gi;function getMeasuringContext(){if(!gi){const t=createCanvasElementFor({width:0,height:0});gi=t.getContext("2d")}return gi}class FabricText extends StyledText{static getDefaults(){return{...super.getDefaults(),...FabricText.ownDefaults}}constructor(t,e){super(),_defineProperty(this,"__charBounds",[]),_defineProperty(this,"__kashidaInfo",[]),Object.assign(this,FabricText.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=getPathSegmentsInfo(t.path))}_splitText(){const t=getBrowserLines(this);if(t&&this.useOverlayEditing)return this._splitTextFromBrowserLines(t);const e=this._splitTextIntoLines(this.text);return this.textLines=e.lines,this._textLines=e.graphemeLines,this._unwrappedTextLines=e._unwrappedLines,this._text=e.graphemeText,e}_splitTextFromBrowserLines(t){const e=[],i=[],s=[];let n=[];for(const r of t){e.push(r.text);const o=this.graphemeSplit(r.text);i.push(o),s.push(o),n=n.concat(o),r!==t[t.length-1]&&n.push("\n")}const r={lines:e,graphemeLines:i,graphemeText:n,_unwrappedLines:s};return this.textLines=r.lines,this._textLines=r.graphemeLines,this._unwrappedTextLines=r._unwrappedLines,this._text=r.graphemeText,r}initDimensions(){const t=undefined;if(this._isFontReady()||this.initialized||this._scheduleInitAfterFontLoad(),this.enableAdvancedLayout&&!this.path)return this.initDimensionsAdvanced();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(rt)&&this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces()}enlargeSpaces(){const t=undefined,e={none:0,short:.25,medium:.5,long:.75,stylistic:1}[this.kashida]||0;this.__kashidaInfo=[];for(let t=0,i=this._textLines.length;t<i;t++){this.__kashidaInfo[t]=[];const s=this._textLines.slice(t+1).some(t=>{const e=Array.isArray(t)?t.join(""):t;return/\S/.test(e)}),n=!s,r=t===i-1||this.isEndOfWrapping(t)||n,o=undefined;if(!(this.textAlign.includes("justify")&&!r))continue;const a=this._textLines[t],h=this.getLineWidth(t),l=this.width-h;if(l<=0)continue;const c=this.textLines[t].match(this._reSpacesAndTabs),d=c?c.length:0,u=e>0?findKashidaPoints(a):[],g=u.length>0;let f=0;g&&e>0&&(f=l*e);const p=g?f/u.length:0;if(g&&p>0){const e=[...u].sort((t,e)=>e.charIndex-t.charIndex),i=getMeasuringContext();if(i){i.font=this._getFontDeclaration();const s=i.measureText(ai).width;if(s>0){const i=[...a];for(const n of e){const e=Math.max(1,Math.round(p/s));for(let t=0;t<e;t++)i.splice(n.charIndex+1,0,ai);this.__kashidaInfo[t].push({charIndex:n.charIndex,width:p,tatweelCount:e})}this._textLines[t]=i,this.textLines&&void 0!==this.textLines[t]&&(this.textLines[t]=i.join("")),this.__charBounds[t]=[],this.__lineWidths[t]=void 0,this._measureLine(t)}}}const m=this.getLineWidth(t),y=this.width-m;if(y>0&&d>0){const e=y/d;let i=0;for(let s=0;s<this._textLines[t].length;s++){const n=this.__charBounds[t][s];n&&(n.left+=i,this._reSpaceAndTab.test(this._textLines[t][s])&&(n.width+=e,n.kernedWidth+=e,i+=e))}}}}_layoutTextAdvanced(){const t=undefined;return layoutText(this._getAdvancedLayoutOptions())}_getAdvancedLayoutOptions(){return{text:this.text,width:this.width,height:this.ellipsis?this.height:void 0,wrap:this.wrap||"word",align:this._mapTextAlignToAlign(this.textAlign),ellipsis:this.ellipsis||!1,fontSize:this.fontSize,lineHeight:this.lineHeight,letterSpacing:this.letterSpacing||0,charSpacing:this.charSpacing,direction:"inherit"===this.direction?"ltr":this.direction,fontFamily:this.fontFamily,fontStyle:this.fontStyle,fontWeight:this.fontWeight,verticalAlign:this.verticalAlign||"top"}}_mapTextAlignToAlign(t){switch(t){case"center":case p:return"center";case"right":case v:return"right";case"justify":case rt:case ot:case at:case ht:return"justify";default:return"left"}}initDimensionsAdvanced(){if(!this.enableAdvancedLayout)return this.initDimensions();const t=this._layoutTextAdvanced();this.width=t.totalWidth||this.MIN_TEXT_WIDTH,this.height=t.totalHeight,this._convertLayoutToLegacyFormat(t),this.textAlign.includes(rt)&&this.kashida&&"none"!==this.kashida&&this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces(),this.dirty=!0}_convertLayoutToLegacyFormat(t){this._textLines=t.lines.map(t=>t.graphemes),this.textLines=t.lines.map(t=>t.text),this._text=t.lines.flatMap(t=>t.graphemes),this.__charBounds=t.lines.map(t=>t.bounds.map(t=>({left:t.left,top:t.y,width:t.width,height:t.height,kernedWidth:t.kernedWidth,deltaY:t.deltaY||0,renderLeft:t.x}))),this.__lineWidths=t.lines.map(t=>t.width),t.lines.length>0&&(this._unwrappedTextLines=t.lines.map(t=>t.graphemes))}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const i=e?this._unwrappedTextLines:this._textLines;let s;for(s=0;s<i.length;s++){if(t<=i[s].length)return{lineIndex:s,charIndex:t};t-=i[s].length+this.missingNewlineOffset(s,e)}return{lineIndex:s-1,charIndex:i[s-1].length<t?i[s-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.__overlayEditor||(this.paintFirst===B?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t)))}_setTextStyles(t,e,i){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case p:t.textBaseline="middle";break;case"ascender":t.textBaseline=y;break;case"descender":t.textBaseline=x;break}t.font=this._getFontDeclaration(e,i)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,i=this._textLines.length;e<i;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,i,s,n,r){this._renderChars(t,e,i,s,n,r)}_buildKashidaDisplayLines(){if("none"===this.kashida||!this.__kashidaInfo)return this._textLines;const t=[];for(let e=0;e<this._textLines.length;e++){const i=this._textLines[e],s=this.__kashidaInfo[e];if(!s||0===s.length){t.push([...i]);continue}const n=[...s].sort((t,e)=>e.charIndex-t.charIndex),r=[...i];for(const{charIndex:t,width:e}of n){if(e<=0||t>=r.length)continue;const i=Math.max(1,Math.round(e/3)),s=ai.repeat(i);r.splice(t+1,0,s)}t.push(r)}return t}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,i=this._getLeftOffset();let s=this._getTopOffset();for(let e=0,n=this._textLines.length;e<n;e++){const n=this.getHeightOfLine(e);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",e)){s+=n;continue}const r=this._textLines[e].length,o=this._getLineLeftOffset(e);let a=0,h=0,l,c,d=this.getValueOfPropertyAt(e,0,"textBackgroundColor");for(let u=0;u<r;u++){const r=this.__charBounds[e][u];c=this.getValueOfPropertyAt(e,u,"textBackgroundColor"),this.path?(t.save(),t.translate(r.renderLeft,r.renderTop),t.rotate(r.angle),t.fillStyle=c,c&&t.fillRect(-r.width/2,-n/this.lineHeight*(1-this._fontSizeFraction),r.width,n/this.lineHeight),t.restore()):c!==d?(l=i+o+h,"rtl"===this.direction&&(l=this.width-l-a),t.fillStyle=d,d&&t.fillRect(l,s,a,n/this.lineHeight),h=r.left,a=r.width,d=c):a+=r.kernedWidth}c&&!this.path&&(l=i+o+h,"rtl"===this.direction&&(l=this.width-l-a),t.fillStyle=c,t.fillRect(l,s,a,n/this.lineHeight)),s+=n}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,i,s){const r=n.getFontCache(e),o=this._getFontDeclaration(e),a=i+t,h="ـ"===i,l=i&&!h&&o===this._getFontDeclaration(s),c=e.fontSize/this.CACHE_FONT_SIZE;let d,u,g,f;if(i&&!h&&void 0!==r[i]&&(g=r[i]),void 0!==r[t]&&(f=d=r[t]),l&&void 0!==r[a]&&(u=r[a],f=u-g),void 0===d||void 0===g||void 0===u){const s=getMeasuringContext();this._setTextStyles(s,e,!0),void 0===d&&(f=d=s.measureText(t).width,r[t]=d),void 0===g&&l&&i&&!h&&(g=s.measureText(i).width,r[i]=g),l&&void 0===u&&!h&&(u=s.measureText(a).width,r[a]=u,f=u-g)}return{width:d*c,kernedWidth:f*c}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){this._justifyApplied;let e=0,i,s;const n=this.pathSide===v,r=this.path,o=this._textLines[t],a=o.length,h=new Array(a);this.__charBounds[t]=h;for(let n=0;n<a;n++){const r=o[n];s=this._getGraphemeBox(r,t,n,i),h[n]=s,e+=s.kernedWidth,i=r}if(h[a]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let t=0;const i=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case m:t=n?i-e:0;break;case p:t=(i-e)/2;break;case v:t=n?0:i-e;break}t+=this.pathStartOffset*(n?-1:1);for(let e=n?a-1:0;n?e>=0:e<a;n?e--:e++)s=h[e],t>i?t%=i:t<0&&(t+=i),this._setGraphemeOnPath(t,s),t+=s.kernedWidth}return{width:e,numOfSpaces:0}}_setGraphemeOnPath(t,e){const i=t+e.kernedWidth/2,s=this.path,n=getPointOnPath(s.path,i,s.segmentsInfo);e.renderLeft=n.x-s.pathOffset.x,e.renderTop=n.y-s.pathOffset.y,e.angle=n.angle+(this.pathSide===v?Math.PI:0)}_getGraphemeBox(t,e,i,s,n){const r=this.getCompleteStyleDeclaration(e,i),o=s?this.getCompleteStyleDeclaration(e,i-1):{},a=this._measureChar(t,r,s,o);let h=a.kernedWidth,l=a.width,c;0!==this.charSpacing&&(c=this._getWidthOfCharSpacing(),l+=c,h+=c);const d={width:l,left:0,height:r.fontSize,kernedWidth:h,deltaY:r.deltaY};if(i>0&&!n){const t=this.__charBounds[e][i-1];d.left=t.left+t.width+a.kernedWidth-a.width}return d}getHeightOfLine(t){if(this.__lineHeights[t])return this.__lineHeights[t];let e=this.getHeightOfChar(t,0);for(let i=1,s=this._textLines[t].length;i<s;i++)e=Math.max(this.getHeightOfChar(t,i),e);return this.__lineHeights[t]=e*this.lineHeight*this._fontSizeMult}calcTextHeight(){let t,e=0;for(let i=0,s=this._textLines.length;i<s;i++)t=this.getHeightOfLine(i),e+=i===s-1?t/this.lineHeight:t;return e}_getLeftOffset(){return"ltr"===this.direction?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){var i;t.save();let s=0;const n=this._getLeftOffset(),r=this._getTopOffset();"fillText"===e&&null!==(i=this.textAlign)&&void 0!==i&&i.includes("justify");for(let i=0,a=this._textLines.length;i<a;i++){var o;const a=this.getHeightOfLine(i),h=a/this.lineHeight,l=this._getLineLeftOffset(i);"fillText"===e&&null!==(o=this.textAlign)&&void 0!==o&&o.includes("justify")&&this.getLineWidth(i),this._renderTextLine(e,t,this._textLines[i],n+l,r+s+h,i),s+=a}t.restore()}_renderTextFill(t){(this.fill||this.styleHas(I))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&0!==this.strokeWidth||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,i,s,n,r){const o=this.getHeightOfLine(r),a=this.textAlign.includes(rt),h=this.path,l="ltr"===this.direction,c="ltr"===this.direction?1:-1,d=e.direction,u=this.__charBounds[r];this.enableAdvancedLayout&&(null==u?void 0:u.length)>0&&u[0].renderLeft;const g=!a&&0===this.charSpacing&&this.isEmptyStyles(r)&&!h;let f,p,y="",x,_=0,C,b;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",l?"ltr":"rtl"),e.direction=l?"ltr":"rtl",e.textAlign=l?m:v),n-=o*this._fontSizeFraction/this.lineHeight,g)return this._renderChar(t,e,r,0,i.join(""),s,n),void e.restore();if(a&&0===r&&"fillText"===t){const t=this.__charBounds[r];null==t||t.reduce((t,e)=>t+((null==e?void 0:e.kernedWidth)||0),0);const e=undefined;[3,9,15,23,31].forEach(e=>{var i;const s=null==t?void 0:t[e];s&&console.log(` Space at idx ${e}: kernedWidth=${null===(i=s.kernedWidth)||void 0===i?void 0:i.toFixed(2)}`)})}for(let o=0,d=i.length-1;o<=d;o++)C=o===d||this.charSpacing||h,y+=i[o],x=this.__charBounds[r][o],0===_&&l?(s+=c*(x.kernedWidth-x.width),_+=x.width):_+=x.kernedWidth,a&&!C&&this._reSpaceAndTab.test(i[o])&&(C=!0),C||(f=f||this.getCompleteStyleDeclaration(r,o),p=this.getCompleteStyleDeclaration(r,o+1),C=hasStyleChanged(f,p,!1)),C&&(h?(e.save(),e.translate(x.renderLeft,x.renderTop),e.rotate(x.angle),this._renderChar(t,e,r,o,y,-_/2,0),e.restore()):(b=s,this._renderChar(t,e,r,o,y,b,n)),y="",f=p,s+=c*_,_=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,i=this.height+this.strokeWidth,s=createCanvasElementFor({width:e,height:i}),n=s.getContext("2d");return s.width=e,s.height=i,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,i),n.lineTo(0,i),n.closePath(),n.translate(e/2,i/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(s,"no-repeat")}handleFiller(t,e,i){let s,n;return isFiller(i)?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?(s=-this.width/2,n=-this.height/2,t.translate(s,n),t[e]=this._applyPatternGradientTransformText(i),{offsetX:s,offsetY:n}):(t[e]=i.toLive(t),this._applyPatternGradientTransform(t,i)):(t[e]=i,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:i,strokeWidth:s}=e;return t.lineWidth=s,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",i)}_setFillStyles(t,e){let{fill:i}=e;return this.handleFiller(t,"fillStyle",i)}_renderChar(t,e,i,s,n,r,o){const a=this._getStyleDeclaration(i,s),h=this.getCompleteStyleDeclaration(i,s),l="fillText"===t&&h.fill,c="strokeText"===t&&h.stroke&&h.strokeWidth;if(c||l){if(e.save(),e.font=this._getFontDeclaration(h),a.textBackgroundColor&&this._removeShadow(e),a.deltaY&&(o+=a.deltaY),l){const t=this._setFillStyles(e,h);e.fillText(n,r-t.offsetX,o-t.offsetY)}if(c){const t=this._setStrokeStyles(e,h);e.strokeText(n,r-t.offsetX,o-t.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,i){const s=this.get2DCursorLocation(t,!0),n=this.getValueOfPropertyAt(s.lineIndex,s.charIndex,"fontSize"),r=this.getValueOfPropertyAt(s.lineIndex,s.charIndex,"deltaY"),o={fontSize:n*i.size,deltaY:r+n*i.baseline};this.setSelectionStyles(o,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),i=this.width-e,s=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t),o=undefined,a=!this._textLines.slice(t+1).some(t=>{const e=Array.isArray(t)?t.join(""):t;return/\S/.test(e)});let h=0;const l=undefined;return s===rt||s===ht&&!r&&!a||s===at&&!r&&!a||s===ot&&!r&&!a?0:(s===p||s===ht?h=i/2:s!==v&&s!==at||(h=i),"rtl"===n&&(s===v||s===rt||s===at?h=0:s===m||s===ot?h=-i:s!==p&&s!==ht||(h=-i/2),i<=0&&(h=0)),h)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[],this.__kashidaInfo=[],this._justifyApplied=!1,this._lastDimensionState=null}_displayToOriginalIndex(t,e){var i;const s=null===(i=this.__kashidaInfo)||void 0===i?void 0:i[t];if(!s||0===s.length)return e;const n=[...s].sort((t,e)=>t.charIndex-e.charIndex);let r=0;for(const t of n){const i=t.tatweelCount||0,s=t.charIndex+1+r,n=s+i;if(e<s)break;if(e<n)return t.charIndex+1;r+=i}const o=undefined;return e-r}_originalToDisplayIndex(t,e){var i;const s=null===(i=this.__kashidaInfo)||void 0===i?void 0:i[t];if(!s||0===s.length)return e;const n=[...s].sort((t,e)=>t.charIndex-e.charIndex);let r=0;for(const t of n){const i=t.tatweelCount||0;if(!(e>t.charIndex))break;r+=i}return e+r}_isTatweelAtDisplayIndex(t,e){var i;const s=null===(i=this.__kashidaInfo)||void 0===i?void 0:i[t];if(!s||0===s.length)return!1;const n=[...s].sort((t,e)=>t.charIndex-e.charIndex);let r=0;for(const t of n){const i=t.tatweelCount||0,s=t.charIndex+1+r,n=undefined;if(e>=s&&e<s+i)return!0;r+=i}return!1}_getTatweelCountForLine(t){var e;const i=null===(e=this.__kashidaInfo)||void 0===e?void 0:e[t];return i&&0!==i.length?i.reduce((t,e)=>t+(e.tatweelCount||0),0):0}_getOriginalLineLength(t){var e;const i=undefined;return((null===(e=this._textLines[t])||void 0===e?void 0:e.length)||0)-this._getTatweelCountForLine(t)}getLineWidth(t){if(void 0!==this.__lineWidths[t])return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return 0!==this.charSpacing?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,i){var s;const n=undefined;return null!==(s=this._getStyleDeclaration(t,e)[i])&&void 0!==s?s:this[i]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let i=this._getTopOffset();const s=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),o="linethrough"===e?.5:"overline"===e?1:0,a=this.offsets[e];for(let h=0,l=this._textLines.length;h<l;h++){const l=this.getHeightOfLine(h);if(!this[e]&&!this.styleHas(e,h)){i+=l;continue}const c=this._textLines[h],d=l/this.lineHeight,u=this._getLineLeftOffset(h);let g=0,f=0,p=this.getValueOfPropertyAt(h,0,e),m=this.getValueOfPropertyAt(h,0,I),y=this.getValueOfPropertyAt(h,0,Z),x=p,v=m,_=y;const C=i+d*(1-this._fontSizeFraction);let b=this.getHeightOfChar(h,0),S=this.getValueOfPropertyAt(h,0,"deltaY");for(let i=0,r=c.length;i<r;i++){const r=this.__charBounds[h][i];x=this.getValueOfPropertyAt(h,i,e),v=this.getValueOfPropertyAt(h,i,I),_=this.getValueOfPropertyAt(h,i,Z);const l=this.getHeightOfChar(h,i),c=this.getValueOfPropertyAt(h,i,"deltaY");if(n&&x&&v){const e=this.fontSize*_/1e3;t.save(),t.fillStyle=m,t.translate(r.renderLeft,r.renderTop),t.rotate(r.angle),t.fillRect(-r.kernedWidth/2,a*l+c-o*e,r.kernedWidth,e),t.restore()}else if((x!==p||v!==m||l!==b||_!==y||c!==S)&&f>0){const e=this.fontSize*y/1e3;let i=s+u+g;"rtl"===this.direction&&(i=this.width-i-f),p&&m&&y&&(t.fillStyle=m,t.fillRect(i,C+a*b+S-o*e,f,e)),g=r.left,f=r.width,p=x,y=_,m=v,b=l,S=c}else f+=r.kernedWidth}let w=s+u+g;"rtl"===this.direction&&(w=this.width-w-f),t.fillStyle=v;const T=this.fontSize*_/1e3;x&&v&&_&&t.fillRect(w,C+a*b+S-o*T,f-r,T),i+=l}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:i=this.fontWeight,fontSize:s=this.fontSize}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0,r=t.includes("'")||t.includes('"')||t.includes(",")||FabricText.genericFonts.includes(t.toLowerCase())?t:`"${t}"`;return n||t.includes(",")||!(t.toLowerCase().includes("stv")||t.toLowerCase().includes("arabic")||t.toLowerCase().includes("naskh")||t.toLowerCase().includes("kufi"))||(r=`${r}, "Arial Unicode MS", Arial, sans-serif`),[e,i,`${n?this.CACHE_FONT_SIZE:s}px`,r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return graphemeSplit(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),i=new Array(e.length),s=["\n"];let n=[];for(let t=0;t<e.length;t++)"rtl"===this.direction||this._containsArabicText(e[t])?i[t]=segmentGraphemes(e[t]):i[t]=this.graphemeSplit(e[t]),n=n.concat(i[t],s);return n.pop(),{_unwrappedLines:i,lines:e,graphemeText:n,graphemeLines:i}}_containsArabicText(t){return/[\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(t)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject([...it,...t]),styles:stylesToArray(this.styles,this.text),...this.path?{path:this.path.toObject()}:{}}}set(t,e){const{textLayoutProperties:i}=this.constructor;super.set(t,e);let s=!1,n=!1;if("object"==typeof t)for(const e in t)"path"===e&&this.setPathInfo(),s=s||i.includes(e),n=n||"path"===e;else s=i.includes(t),n="path"===t;return n&&this.setPathInfo(),s&&this.initialized&&(clearBrowserLines(this),this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,i){const s=parseAttributes(t,FabricText.ATTRIBUTE_NAMES,i),{textAnchor:n=m,textDecoration:r="",dx:o=0,dy:a=0,top:h=0,left:l=0,fontSize:c=u,strokeWidth:d=1,...g}={...e,...s},f=undefined,y=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),{left:l+o,top:h+a,underline:r.includes("underline"),overline:r.includes("overline"),linethrough:r.includes("line-through"),strokeWidth:0,fontSize:c,...g}),x=y.getScaledHeight()/y.height,_=undefined,C=((y.height+y.strokeWidth)*y.lineHeight-y.height)*x,b=y.getScaledHeight()+C;let S=0;return n===p&&(S=y.getScaledWidth()/2),n===v&&(S=y.getScaledWidth()),y.set({left:y.left-S,top:y.top-(b-y.fontSize*(.07+y._fontSizeFraction))/y.lineHeight,strokeWidth:d}),y}_isFontReady(){if("undefined"==typeof document||!("fonts"in document))return!0;try{return document.fonts.check(`${this.fontSize}px ${this.fontFamily}`)}catch(t){return!0}}_scheduleInitAfterFontLoad(){if("undefined"==typeof document||!("fonts"in document))return;if(this._fontLoadScheduled)return;this._fontLoadScheduled=!0;const t=`${this.fontSize}px ${this.fontFamily}`;document.fonts.load(t).then(()=>{var t;(this._fontLoadScheduled=!1,this.initDimensions(),this.textAlign&&this.textAlign.includes(rt))?setTimeout(()=>{var t;this.enlargeSpaces&&this.enlargeSpaces(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()},10):null===(t=this.canvas)||void 0===t||t.requestRenderAll()}).catch(()=>{this._fontLoadScheduled=!1})}forceTextReinitialization(){this._clearCache(),this.dirty=!0,this._splitText(),this.initDimensions(),this.textAlign&&this.textAlign.includes(rt)&&setTimeout(()=>{var t;this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces&&(this.enlargeSpaces(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())},10)}static fromObject(t){return this._fromObject({...t,styles:stylesFromArray(t.styles||{},t.text)},{extraParam:"text"}).then(t=>{t.initialized=!0,t._clearCache&&t._clearCache(),t.dirty=!0;const e=`${t.fontSize}px ${t.fontFamily}`;return"undefined"!=typeof document&&"fonts"in document&&"Arial"!==t.fontFamily&&"Times New Roman"!==t.fontFamily?document.fonts.load(e).then(()=>{var e;t.initialized=!0;const i=undefined;if(null===(e=t.fontFamily)||void 0===e?void 0:e.toLowerCase().includes("stv")){t._browserWrapCache=null,t._lastDimensionState=null,t._browserWrapInitialized=!1,t._usingBrowserWrapping=!0,t.useOverlayEditing=!0;const reinitWithDelay=e=>{t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions(),t.width<50&&e<3&&setTimeout(()=>reinitWithDelay(e+1),100*e)};reinitWithDelay(0)}else t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions();return t}).catch(()=>(t.initialized=!0,t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions(),t)):(t.initialized=!0,t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions(),t)})}}_defineProperty(FabricText,"textLayoutProperties",et),_defineProperty(FabricText,"cacheProperties",[...Ot,...it]),_defineProperty(FabricText,"ownDefaults",nt),_defineProperty(FabricText,"type","Text"),_defineProperty(FabricText,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),_defineProperty(FabricText,"ATTRIBUTE_NAMES",se.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),applyMixins(FabricText,[TextSVGExportMixin]),X.setClass(FabricText),X.setSVGClass(FabricText);class DraggableTextDelegate{constructor(t){_defineProperty(this,"target",void 0),_defineProperty(this,"__mouseDownInPlace",!1),_defineProperty(this,"__dragStartFired",!1),_defineProperty(this,"__isDraggingOver",!1),_defineProperty(this,"__dragStartSelection",void 0),_defineProperty(this,"__dragImageDisposer",void 0),_defineProperty(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(t=>t()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,i=e.getSelectionStartFromPointer(t);return e.isEditing&&i>=e.selectionStart&&i<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){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 i;let{selectionStart:s,selectionEnd:n}=e;const r=this.target,o=r.canvas,a=new Point(r.flipX?-1:1,r.flipY?-1:1),h=r._getCursorBoundaries(s),l=undefined,c=new Point(h.left+h.leftOffset,h.top+h.topOffset).multiply(a).transform(r.calcTransformMatrix()),d=undefined,u=o.getScenePoint(t).subtract(c),g=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),p=c.subtract(new Point(f.left,f.top)),m=o.viewportTransform,y=p.add(u).transform(m,!0),x=r.backgroundColor,v=cloneStyles(r.styles);r.backgroundColor="";const C={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(C,0,s),r.setSelectionStyles(C,n,r.text.length),r.dirty=!0;const b=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=x,r.styles=v,r.dirty=!0,setStyle(b,{position:"fixed",left:-b.width+"px",border:_,width:b.width/g+"px",height:b.height/g+"px"}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{b.remove()},getDocumentFromElement(t.target||this.target.hiddenTextarea).body.appendChild(b),null===(i=t.dataTransfer)||void 0===i||i.setDragImage(b,y.x,y.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,i=this.isActive();if(i&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},s=e._text.slice(i.selectionStart,i.selectionEnd).join(""),n={text:e.text,value:s,...i};t.dataTransfer.setData("text/plain",s),t.dataTransfer.setData("application/fabric",JSON.stringify({value:s,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,n)}return e.abortCursorAnimation(),i}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),i=this.__dragStartSelection;return e<i.selectionStart||e>i.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e:e}=t;const i=this.targetCanDrop(e);!this.__isDraggingOver&&i&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e:e}=t,i=this.targetCanDrop(e);!this.__isDraggingOver&&i?this.__isDraggingOver=!0:this.__isDraggingOver&&!i&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:i}=t,s=i.defaultPrevented;this.__isDraggingOver=!1,i.preventDefault();let n=null===(e=i.dataTransfer)||void 0===e?void 0:e.getData("text/plain");if(n&&!s){const e=this.target,s=e.canvas;let r=e.getSelectionStartFromPointer(i);const{styles:o}=i.dataTransfer.types.includes("application/fabric")?JSON.parse(i.dataTransfer.getData("application/fabric")):{},a=n[Math.max(0,n.length-1)],h=0;if(this.__dragStartSelection){const t=this.__dragStartSelection.selectionStart,i=this.__dragStartSelection.selectionEnd;r>t&&r<=i?r=t:r>i&&(r-=i-t),e.removeChars(t,i),delete this.__dragStartSelection}e._reNewline.test(a)&&(e._reNewline.test(e._text[r])||r===e._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=e,e.insertChars(n,o,r),s.setActiveObject(e),e.enterEditing(i),e.selectionStart=Math.min(r+h,e._text.length),e.selectionEnd=Math.min(e.selectionStart+n.length,e._text.length),e.hiddenTextarea.value=e.text,e._updateTextarea(),e.hiddenTextarea.focus(),e.fire(D,{index:r+h,action:"drop"}),s.fire("text:changed",{target:e}),s.contextTopDirty=!0,s.requestRenderAll()}}dragEndHandler(t){let{e:e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var i;const t=this.target,s=this.target.canvas,{selectionStart:n,selectionEnd:r}=this.__dragStartSelection,o=(null===(i=e.dataTransfer)||void 0===i?void 0:i.dropEffect)||_;o===_?(t.selectionStart=n,t.selectionEnd=r,t._updateTextarea(),t.hiddenTextarea.focus()):(t.clearContextTop(),"move"===o&&(t.removeChars(n,r),t.selectionStart=t.selectionEnd=n,t.hiddenTextarea&&(t.hiddenTextarea.value=t.text),t._updateTextarea(),t.fire(D,{index:n,action:"dragend"}),s.fire("text:changed",{target:t}),s.requestRenderAll()),t.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}class OverlayEditor{constructor(t){_defineProperty(this,"canvas",void 0),_defineProperty(this,"target",void 0),_defineProperty(this,"container",void 0),_defineProperty(this,"textarea",void 0),_defineProperty(this,"hostDiv",void 0),_defineProperty(this,"isDestroyed",!1),_defineProperty(this,"isComposing",!1),_defineProperty(this,"lastText",void 0),_defineProperty(this,"onCommit",void 0),_defineProperty(this,"onCancel",void 0),_defineProperty(this,"boundHandlers",{onInput:this.handleInput.bind(this),onKeyDown:this.handleKeyDown.bind(this),onBlur:this.handleBlur.bind(this),onCompositionStart:this.handleCompositionStart.bind(this),onCompositionEnd:this.handleCompositionEnd.bind(this),onAfterRender:this.handleAfterRender.bind(this),onMouseWheel:this.handleMouseWheel.bind(this),onFocus:this.handleFocus.bind(this),onMouseDown:this.handleMouseDown.bind(this)}),this.canvas=t.canvas,this.target=t.target,this.onCommit=t.onCommit,this.onCancel=t.onCancel,this.lastText=this.target.text||"",this.container=this.getCanvasContainer(),this.createOverlayDOM(),this.attachEventListeners(),this.refresh(),this.focusTextarea()}getCanvasContainer(){const t=undefined,e=this.canvas.upperCanvasEl.parentElement;if(!e)throw new Error("Canvas must be mounted in DOM to use overlay editing");return e.style.position="relative",e}createOverlayDOM(){this.hostDiv=document.createElement("div"),this.hostDiv.style.position="absolute",this.hostDiv.style.pointerEvents="none",this.hostDiv.style.zIndex="1000",this.hostDiv.style.transformOrigin="left top",this.textarea=document.createElement("textarea"),this.textarea.style.position="absolute",this.textarea.style.left="0",this.textarea.style.top="0",this.textarea.style.margin="0",this.textarea.style.resize="none",this.textarea.style.pointerEvents="auto";const t=/[\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(this.target.text||""),e=/[a-zA-Z]/.test(this.target.text||""),i="ltr"===this.target.direction;this.textarea.style.unicodeBidi=t&&e&&i||t&&i?"embed":"plaintext",this.textarea.style.caretColor="auto",this.textarea.style.border="none",this.textarea.style.padding="0",this.textarea.style.background="transparent",this.textarea.style.outline="none",this.textarea.style.overflow="hidden",this.textarea.style.whiteSpace="pre-wrap",this.textarea.style.wordBreak="normal",this.textarea.style.overflowWrap="break-word",this.textarea.style.userSelect="text",this.textarea.style.textTransform="none",this.textarea.style.opacity="1",this.textarea.value=this.target.text||"",this.hostDiv.appendChild(this.textarea),document.body.appendChild(this.hostDiv)}attachEventListeners(){this.textarea.addEventListener("input",this.boundHandlers.onInput),this.textarea.addEventListener("keydown",this.boundHandlers.onKeyDown),this.textarea.addEventListener("blur",this.boundHandlers.onBlur),this.textarea.addEventListener("compositionstart",this.boundHandlers.onCompositionStart),this.textarea.addEventListener("compositionend",this.boundHandlers.onCompositionEnd),this.textarea.addEventListener("focus",this.boundHandlers.onFocus),this.canvas.on("after:render",this.boundHandlers.onAfterRender),this.canvas.on("mouse:wheel",this.boundHandlers.onMouseWheel),this.canvas.on("mouse:down",this.boundHandlers.onMouseDown),this.setupViewportChangeDetection()}removeEventListeners(){this.textarea.removeEventListener("input",this.boundHandlers.onInput),this.textarea.removeEventListener("keydown",this.boundHandlers.onKeyDown),this.textarea.removeEventListener("blur",this.boundHandlers.onBlur),this.textarea.removeEventListener("compositionstart",this.boundHandlers.onCompositionStart),this.textarea.removeEventListener("compositionend",this.boundHandlers.onCompositionEnd),this.textarea.removeEventListener("focus",this.boundHandlers.onFocus),this.canvas.off("after:render",this.boundHandlers.onAfterRender),this.canvas.off("mouse:wheel",this.boundHandlers.onMouseWheel),this.canvas.off("mouse:down",this.boundHandlers.onMouseDown),this.restoreViewportChangeDetection()}updatePosition(){this.applyOverlayStyle()}updateObjectBounds(){if(this.isDestroyed)return;const t=this.target,e=this.canvas.getZoom();parseFloat(this.hostDiv.style.width);const i=parseFloat(this.hostDiv.style.height)/e,s=undefined,n=undefined;Math.abs(i-t.height)>.5&&(t.height,t.height=i,t.setCoords(),t.dirty=!0,this.canvas.requestRenderAll(),requestAnimationFrame(()=>{this.isDestroyed||this.applyOverlayStyle()}))}letterSpacingPx(t,e){return t/1e3*e}firstStrongDir(t){const e=undefined;return/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(t)?"rtl":"ltr"}applyOverlayStyle(){var t,e;const i=this.target,s=this.canvas;i.setCoords();const n=i.aCoords,r=undefined,o=s.upperCanvasEl.getBoundingClientRect(),a=window.scrollX||window.pageXOffset,h=window.scrollY||window.pageYOffset,l=s.getZoom(),c=s.viewportTransform,d=i.padding||0,u=d*(i.scaleX||1)*l,g=d*(i.scaleY||1)*l,f=transformPoint({x:n.tl.x,y:n.tl.y},c),p=o.left+a+f.x,m=o.top+h+f.y,y=i.getBoundingRect(),x=Math.round(y.width*l),v=Math.round(y.height*l);this.hostDiv.style.position="absolute",this.hostDiv.style.left=`${p}px`,this.hostDiv.style.top=`${m}px`,this.hostDiv.style.width=`${x}px`,this.hostDiv.style.height=`${v}px`,this.hostDiv.style.overflow="hidden",i.angle?(this.hostDiv.style.transform=`rotate(${i.angle}deg)`,this.hostDiv.style.transformOrigin="top left"):(this.hostDiv.style.transform="",this.hostDiv.style.transformOrigin="");const _=undefined,C=undefined,b=(null!==(t=i.fontSize)&&void 0!==t?t:16)*(i.scaleX||1)*l,S=i.lineHeight||1.16;this.textarea.style.boxSizing="border-box",this.textarea.style.width=`${x}px`,this.textarea.style.height="100%",this.textarea.style.padding=`${g}px ${u}px`;const w=(i.charSpacing||0)/1e3*b;!1!==i.dirty&&i.initDimensions&&i.initDimensions(),this.textarea.style.fontSize=`${b}px`,this.textarea.style.lineHeight=String(S),this.textarea.style.fontFamily=i.fontFamily||"Arial",this.textarea.style.fontWeight=String(i.fontWeight||"normal"),this.textarea.style.fontStyle=i.fontStyle||"normal";const T=i.textAlign||"left";let P=T;const M=this.firstStrongDir(this.textarea.value||"");if(T.includes("justify"))try{P="justify","justify"===T||"justify-left"===T?this.textarea.style.textAlignLast="rtl"===M?"right":"left":"justify-right"===T?this.textarea.style.textAlignLast="ltr"===M?"left":"right":"justify-center"===T&&(this.textarea.style.textAlignLast="center"),this.textarea.style.textJustify="inter-word",this.textarea.style.wordSpacing="normal",this.textarea.style.textAlign="justify",this.textarea.style.textAlignLast=this.textarea.style.textAlignLast,this.textarea.style.textJustifyTrim="none",this.textarea.style.textAutospace="none"}catch(t){P=T.replace("justify-","").replace("justify","left")}else this.textarea.style.textAlignLast="auto",this.textarea.style.textJustify="auto",this.textarea.style.wordSpacing="normal";this.textarea.style.textAlign=P,this.textarea.style.color=(null===(e=i.fill)||void 0===e?void 0:e.toString())||"#000",this.textarea.style.letterSpacing=`${w}px`;const O=i.direction;this.textarea.style.direction=M||O||"ltr",this.textarea.style.fontVariant="normal",this.textarea.style.fontStretch="normal",this.textarea.style.textRendering="auto",this.textarea.style.fontKerning="normal",this.textarea.style.fontFeatureSettings="normal",this.textarea.style.fontVariationSettings="normal",this.textarea.style.margin="0",this.textarea.style.border="none",this.textarea.style.outline="none",this.textarea.style.background="transparent",this.textarea.style.overflowWrap="break-word",this.textarea.style.whiteSpace="pre-wrap",this.textarea.style.hyphens="none",T.includes("justify"),this.textarea.style.webkitFontSmoothing="auto",this.textarea.style.mozOsxFontSmoothing="auto",this.textarea.style.fontSmooth="auto",this.textarea.style.textSizeAdjust="none";const k=String(i.fontWeight||"normal"),D=undefined;("bold"===k||"700"===k||parseInt(k)>=600)&&(this.textarea.style.webkitFontSmoothing="subpixel-antialiased",this.textarea.style.mozOsxFontSmoothing="unset")}debugBoundingBoxComparison(){const t=this.target,e=this.canvas,i=e.getZoom(),s=this.textarea.getBoundingClientRect(),n=this.hostDiv.getBoundingClientRect(),r=t.getBoundingRect(),o=e.upperCanvasEl.getBoundingClientRect(),a=e.viewportTransform,h=o.left+r.left*i+a[4],l=o.top+r.top*i+a[5],c=r.width*i,d=r.height*i;Math.round(100*(n.left-h)),Math.round(100*(n.top-l)),Math.round(100*(n.width-c)),Math.round(100*(n.height-d)),Math.round(100*(s.left-h)),Math.round(100*(s.top-l)),Math.round(100*(s.width-c)),Math.round(100*(s.height-d))}debugTextWrapping(){this.target;const t=undefined,e=this.textarea.value.split("\n");e.forEach((t,e)=>{});const i=window.getComputedStyle(this.textarea);this.target.getBoundingRect().width;const s=parseFloat(window.getComputedStyle(this.textarea).width);this.canvas.getZoom();const n=this.textarea.scrollHeight,r=parseFloat(i.lineHeight)||1.2*parseFloat(i.fontSize),o=Math.round(n/r);e.length}focusTextarea(){this.target.opacity=.01,this.target.selected=!0,this.target.isEditing=!1,this.target.set({hasControls:!0,hasBorders:!0,selectable:!0,lockMovementX:!1,lockMovementY:!1}),this.canvas.setActiveObject(this.target),this.canvas.requestRenderAll(),this.target.setCoords(),this.applyOverlayStyle(),this.target._fixCharacterMappingAfterJsonLoad&&this.target._fixCharacterMappingAfterJsonLoad(),this.textarea.focus(),this.textarea.setSelectionRange(this.textarea.value.length,this.textarea.value.length),this.canvas.setActiveObject(this.target),this.canvas.requestRenderAll()}refresh(){this.isDestroyed||this.updatePosition()}destroy(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(!this.isDestroyed){if(this.isDestroyed=!0,this.removeEventListeners(),this.target.__overlayEditor===this&&(this.target.__overlayEditor=void 0,void 0!==this.target.__overlayOriginalOpacity&&(this.target.opacity=this.target.__overlayOriginalOpacity,delete this.target.__overlayOriginalOpacity)),this.hostDiv.parentNode&&this.hostDiv.parentNode.removeChild(this.hostDiv),t&&!this.isComposing){const t=this.textarea.value,e=this.firstStrongDir(t),i=this.target.direction||"ltr",s=undefined;!("inherit"!==i)&&e&&e!==i&&(this.target.set("direction",e),this.canvas.requestRenderAll()),this.onCommit&&this.onCommit(t)}else!t&&this.onCancel&&this.onCancel();setTimeout(()=>{this.canvas.upperCanvasEl.style.cursor="",this.canvas.setCursor(this.canvas.defaultCursor)},0),this.canvas.requestRenderAll()}}handleInput(){this.isComposing||this.target.text===this.textarea.value||(this.target.text=this.textarea.value,this.autoResizeTextarea(),this.target.selected=!0,this.target.isEditing=!1,this.canvas.setActiveObject(this.target),this.canvas.requestRenderAll())}autoResizeTextarea(){const t=this.textarea.scrollTop,e=parseFloat(this.hostDiv.style.height||"0");this.textarea.style.height="1px";const i=undefined,s=2,n=this.textarea.scrollHeight+2,r=undefined;Math.abs(n-e)>1?(this.textarea.style.height=`${n}px`,this.hostDiv.style.height=`${n}px`,this.updateObjectBounds()):this.textarea.style.height=this.hostDiv.style.height,this.textarea.scrollTop=t}handleKeyDown(t){"Escape"===t.key?(t.preventDefault(),this.destroy(!1)):(t.ctrlKey||t.metaKey)&&"Enter"===t.key?(t.preventDefault(),this.destroy(!0)):"Enter"!==t.key&&"Backspace"!==t.key&&"Delete"!==t.key||(requestAnimationFrame(()=>{this.isDestroyed||this.autoResizeTextarea()}),setTimeout(()=>{this.isDestroyed||this.autoResizeTextarea()},10))}handleFocus(){}handleBlur(){this.isComposing||this.destroy(!0)}handleCompositionStart(){this.isComposing=!0}handleCompositionEnd(){this.isComposing=!1,this.handleInput()}handleAfterRender(){this.refresh()}handleMouseWheel(){this.refresh()}handleMouseDown(t){t.target!==this.target&&this.destroy(!0)}setupViewportChangeDetection(){this.canvas.__originalSetZoom=this.canvas.setZoom,this.canvas.__originalSetViewportTransform=this.canvas.setViewportTransform,this.canvas.__overlayEditor=this;const t=this.canvas.setZoom.bind(this.canvas);this.canvas.setZoom=e=>{const i=t(e);return this.canvas.__overlayEditor&&!this.isDestroyed&&this.refresh(),i};const e=this.canvas.setViewportTransform.bind(this.canvas);this.canvas.setViewportTransform=t=>{const i=e(t);return this.canvas.__overlayEditor&&!this.isDestroyed&&this.refresh(),i}}restoreViewportChangeDetection(){this.canvas.__originalSetZoom&&(this.canvas.setZoom=this.canvas.__originalSetZoom,delete this.canvas.__originalSetZoom),this.canvas.__originalSetViewportTransform&&(this.canvas.setViewportTransform=this.canvas.__originalSetViewportTransform,delete this.canvas.__originalSetViewportTransform),delete this.canvas.__overlayEditor}}function enterTextOverlayEdit(t,e,i){e.__overlayEditor&&e.__overlayEditor.destroy(!1),e.__overlayOriginalOpacity=e.opacity;const s=new OverlayEditor({canvas:t,target:e,onCommit:null==i?void 0:i.onCommit,onCancel:null==i?void 0:i.onCancel});return e.__overlayEditor=s,s}const fi=/[ \n\.,;!\?\-\u060C\u061B\u061F\u06D4\u0640\u05C3\u05F4\u2000-\u206F]/;class ITextBehavior extends FabricText{constructor(){super(...arguments),_defineProperty(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:i,delay:s,onComplete:n}=t;return animate({startValue:this._currentCursorOpacity,endValue:e,duration:i,delay:s,onComplete:n,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:t=>{this._currentCursorOpacity=t,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;null===(t=this._currentTickCompleteState)||void 0===t||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/S/.test(this._text[i])&&i>-1;)e++,i--;return t-e}findWordBoundaryRight(t){let e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/S/.test(this._text[i])&&i<this._text.length;)e++,i++;return t+e}findLineBoundaryLeft(t){let e=0,i=t-1;for(;!/\n/.test(this._text[i])&&i>-1;)e++,i--;return t-e}findLineBoundaryRight(t){let e=0,i=t;for(;!/\n/.test(this._text[i])&&i<this._text.length;)e++,i++;return t+e}searchWordBoundary(t,e){return"undefined"!=typeof Intl&&Intl.Segmenter?this._searchWordBoundaryWithSegmenter(t,e):this._searchWordBoundaryWithRegex(t,e)}_searchWordBoundaryWithSegmenter(t,e){const i=this.text,s=undefined,n=new(0,Intl.Segmenter)(void 0,{granularity:"word"}),r=Array.from(n.segment(i));if(0===r.length)return-1===e?0:i.length;let o=0;for(let e=0;e<r.length;e++){const i=r[e];if(t>=i.index&&t<i.index+i.segment.length){o=e;break}t>=i.index+i.segment.length&&(o=e)}if(-1===e){let e=o;for(t===r[e].index&&e>0&&e--;e>0&&!r[e].isWordLike;)e--;return r[e].isWordLike?r[e].index:0}{let t=o;if(r[t].isWordLike)return r[t].index+r[t].segment.length;for(;t<r.length&&!r[t].isWordLike;)t++;return t<r.length&&r[t].isWordLike?r[t].index+r[t].segment.length:i.length}}_searchWordBoundaryWithRegex(t,e){const i=Array.from(this.text);let s=t>0&&this._reSpace.test(i[t])&&(-1===e||!C.test(i[t-1]))?t-1:t,n=i[s];for(;s>0&&s<i.length&&!fi.test(n);)s+=e,n=i[s];return-1===e&&fi.test(n)&&s++,s}selectWord(t){t=null!=t?t:this.selectionStart;const e=this.searchWordBoundary(t,-1),i=Math.max(e,this.searchWordBoundary(t,1));this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){t=null!=t?t:this.selectionStart;const e=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.useOverlayEditing?this.enterOverlayEditing():(this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick())}enterOverlayEditing(){this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this.canvas&&enterTextOverlayEdit(this.canvas,this,{onCommit:t=>{this.commitOverlayEdit(t)},onCancel:()=>{this.cancelOverlayEdit()}})}commitOverlayEdit(t){const e=this.left,i=this.top,s=this.get("width"),n=this.dynamicMinWidth,r=this._usingBrowserWrapping,o=this.lockDynamicMinWidth;this.lockDynamicMinWidth=!0;const a=this.__overlayEditor;if(a)try{const t=undefined;storeBrowserLines(this,extractLinesFromDOM(a.textareaElement).lines)}catch(t){}this.text=t,void 0!==n&&(this.dynamicMinWidth=Math.max(n||0,s||0)),void 0!==r&&(this._usingBrowserWrapping=r),this.dirty=!0,this.initDimensions(),this.set({left:e,top:i,width:s}),this.setCoords(),this.exitEditing(),this.lockDynamicMinWidth=o,this.fire("changed"),this.canvas&&this.canvas.requestRenderAll()}cancelOverlayEdit(){this.text=this._textBeforeEdit||this.text,this.exitEditing()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;getDocumentFromElement(e).activeElement!==e&&e.focus();const i=this.getSelectionStartFromPointer(t),s=this.selectionStart,n=this.selectionEnd;if(!(i===this.__selectionStartOnMouseDown&&s!==n||s!==i&&n!==i))return;const r=Math.min(i,this.__selectionStartOnMouseDown),o=Math.max(i,this.__selectionStartOnMouseDown);this.selectionStart=r,this.selectionEnd=o,this.selectionStart===s&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection())}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,i){const s=i.slice(0,t),n=this.graphemeSplit(s).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=i.slice(t,e),o=undefined;return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,i){const s=undefined,n=i.slice(0,t).join("").length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=undefined,o=undefined;return{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},!this.hiddenTextarea)return;const t=this.text;if(this.hiddenTextarea.value!==t&&(this.hiddenTextarea.value=t),!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),s=i.lineIndex,n=i.charIndex,r=this.getValueOfPropertyAt(s,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.getCanvasRetinaScaling(),h=this.canvas.upperCanvasEl,l=h.width/a,c=h.height/a,d=l-r,u=c-r,g=new Point(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new Point(h.clientWidth/l,h.clientHeight/c));return g.x<0&&(g.x=0),g.x>d&&(g.x=d),g.y<0&&(g.y=0),g.y>u&&(g.y=u),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:`${g.x}px`,top:`${g.y}px`,fontSize:`${r}px`,charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:null,selectable:this.selectable,defaultCursor:"default",moveCursor:"move"}}_restoreEditingProps(){if(this._savedProps){var t,e;if(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=null!==(t=this._savedProps.defaultCursor)&&void 0!==t?t:"default",this.canvas.moveCursor=null!==(e=this._savedProps.moveCursor)&&void 0!==e?e:"move";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(R),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:i,charIndex:s}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(i!==n){if(this.styles[i])for(let t=s;t<this._unwrappedTextLines[i].length;t++)delete this.styles[i][t];if(this.styles[n])for(let t=r;t<this._unwrappedTextLines[n].length;t++){const e=this.styles[n][t];e&&(this.styles[i]||(this.styles[i]={}),this.styles[i][s+t-r]=e)}for(let t=i+1;t<=n;t++)delete this.styles[t];this.shiftLineStyles(n,i-n)}else if(this.styles[i]){const t=this.styles[i],e=r-s;for(let e=s;e<r;e++)delete t[e];for(const s in this.styles[i]){const i=parseInt(s,10);i>=r&&(t[i-e]=t[s],delete t[s])}}}shiftLineStyles(t,e){const i=Object.assign({},this.styles);for(const s in this.styles){const n=parseInt(s,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,i,s){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let a=!1;i||(i=1),this.shiftLineStyles(t,i);const h=this.styles[t]?this.styles[t][0===e?e:e-1]:void 0;for(const i in this.styles[t]){const s=parseInt(i,10);s>=e&&(a=!0,n[s-e]=this.styles[t][i],o&&0===e||delete this.styles[t][i])}let l=!1;for(a&&!o&&(this.styles[t+i]=n,l=!0),(l||r>e)&&i--;i>0;)s&&s[i-1]?this.styles[t+i]={0:{...s[i-1]}}:h?this.styles[t+i]={0:{...h}}:delete this.styles[t+i],i--;this._forceClearCache=!0}insertCharStyleObject(t,e,i,s){this.styles||(this.styles={});const n=this.styles[t],r=n?{...n}:{};i||(i=1);for(const t in r){const s=parseInt(t,10);s>=e&&(n[s+i]=r[s],r[s-i]||delete n[s])}if(this._forceClearCache=!0,s){for(;i--;)Object.keys(s[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]={...s[i]});return}if(!n)return;const o=n[e?e-1:1];for(;o&&i--;)this.styles[t][e+i]={...o}}insertNewStyleBlock(t,e,i){const s=this.get2DCursorLocation(e,!0),n=[0];let r=0,o;for(let e=0;e<t.length;e++)"\n"===t[e]?(r++,n[r]=0):n[r]++;for(n[0]>0&&(this.insertCharStyleObject(s.lineIndex,s.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),r&&this.insertNewlineStyleObject(s.lineIndex,s.charIndex+n[0],r),o=1;o<r;o++)n[o]>0?this.insertCharStyleObject(s.lineIndex+o,0,n[o],i):i&&this.styles[s.lineIndex+o]&&i[0]&&(this.styles[s.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(s.lineIndex+o,0,n[o],i)}removeChars(t){let e=arguments.length>1&&void 0!==arguments[1]?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,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:i;s>i&&this.removeStyleFromTo(i,s);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[...this._text.slice(0,i),...n,...this._text.slice(s)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,i){i<=t?(e===t?this._selectionDirection=m:this._selectionDirection===v&&(this._selectionDirection=m,this.selectionEnd=t),this.selectionStart=i):i>t&&i<e?this._selectionDirection===v?this.selectionEnd=i:this.selectionStart=i:(e===t?this._selectionDirection=v:this._selectionDirection===m&&(this._selectionDirection=v,this.selectionStart=e),this.selectionEnd=i)}}class ITextKeyBehavior extends ITextBehavior{initHiddenTextarea(){const t=this.canvas&&getDocumentFromElement(this.canvas.getElement())||getFabricDocument(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off"}).map(t=>{let[i,s]=t;return e.setAttribute(i,s)});const{top:i,left:s,fontSize:n}=this._calcTextareaPosition();e.style.cssText=`position: absolute; top: ${i}; left: ${s}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${n};`,(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map(t=>{let[i,s]=t;return e.addEventListener(i,this[s].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const i=this.fromPaste,{value:s,selectionStart:n,selectionEnd:r}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;if(this.text!==s&&!this.inCompositionMode)return this.cursorOffsetCache={},this._browserWrapCache=null,this._lastDimensionState=null,this._forceClearCache=!0,this.updateFromTextArea(),this.fire(D),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.renderAll()));const updateAndFire=()=>{this.updateFromTextArea(),this.fire(D),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(""===this.hiddenTextarea.value)return this.styles={},void updateAndFire();const o=this._splitTextIntoLines(s).graphemeText,a=this._text.length,h=o.length,l=this.selectionStart,c=this.selectionEnd,d=l!==c;let u,g,f=h-a,p,m;const y=this.fromStringToGraphemeSelection(n,r,s),x=l>y.selectionStart;d?(g=this._text.slice(l,c),f+=c-l):h<a&&(g=x?this._text.slice(c+f,c):this._text.slice(l,l-f));const v=o.slice(y.selectionEnd-f,y.selectionEnd);if(g&&g.length&&(v.length&&(u=this.getSelectionStyles(l,l+1,!1),u=v.map(()=>u[0])),d?(p=l,m=c):x?(p=c-g.length,m=c):(p=c,m=c+g.length),this.removeStyleFromTo(p,m)),v.length){const{copyPasteData:t}=getEnv();i&&v.join("")===t.copiedText&&!e.disableStyleCopyPaste&&(u=t.copiedTextStyle),this.insertNewStyleBlock(v,l,u)}updateAndFire()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:i,selectionEnd:s}=e;this.compositionStart=i,this.compositionEnd=s,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=getEnv();t.copiedText=this.getSelectedText(),e.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 i=this._getLineLeftOffset(t),s;return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const i=this._getSelectionForOffset(t,e),s=this.get2DCursorLocation(i),n=s.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;const r=s.charIndex,o=this._getWidthBeforeCursor(n,r),a=this._getIndexOnLine(n+1,o),h=undefined;return this._textLines[n].slice(r).length+a+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const i=this._getSelectionForOffset(t,e),s=this.get2DCursorLocation(i),n=s.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;const r=s.charIndex,o=this._getWidthBeforeCursor(n,r),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,r),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)}_getIndexOnLine(t,e){const i=this._textLines[t],s=undefined;let n=this._getLineLeftOffset(t),r=0,o,a;for(let s=0,h=i.length;s<h;s++)if(o=this.__charBounds[t][s].width,n+=o,n>e){a=!0;const t=n-o,i=n,h=Math.abs(t-e),l=undefined;r=Math.abs(i-e)<h?s:s-1;break}return a||(r=i.length-1),r}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const i=this[`get${t}CursorOffset`](e,this._selectionDirection===v);if(e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i){const t=this.text.length;this.selectionStart=capValue(0,this.selectionStart,t),this.selectionEnd=capValue(0,this.selectionEnd,t),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===m?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t}moveCursorLeft(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)}_move(t,e,i){let s;if(t.altKey)s=this[`findWordBoundary${i}`](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;s=this[`findLineBoundary${i}`](this[e])}return void 0!==s&&this[e]!==s&&(this[e]=s,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=m,this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===v&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection=m,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 i=`moveCursor${t}${e.shiftKey?"WithShift":"WithoutShift"}`;this._currentCursorOpacity=1,this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===m&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=v,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=v,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const notALeftClick=t=>!!t.button;class ITextClickBehavior extends ITextKeyBehavior{constructor(){super(...arguments),_defineProperty(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 DraggableTextDelegate(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.useOverlayEditing&&this.editable?this.enterEditing(t.e):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:e,alreadySelected:i}=t;this.canvas&&this.editable&&!notALeftClick(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),i&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=i||this.isEditing)))}mouseUpHandler(t){let{e:e,transform:i}=t;const s=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const t=this.canvas._activeObject;if(t&&t!==this)return}!this.editable||this.group&&!this.group.interactive||i&&i.actionPerformed||notALeftClick(e)||s||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),i=this.selectionStart,s=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,s,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(invertTransform(this.calcTransformMatrix())).add(new Point(-this._getLeftOffset(),-this._getTopOffset()));"rtl"===this.direction&&(e.x*=-1);let i=0,s=0,n=0;for(let t=0;t<this._textLines.length&&i<=e.y;t++)i+=this.getHeightOfLine(t),n=t,t>0&&(s+=this._textLines[t-1].length+this.missingNewlineOffset(t-1));const r=this._getLineLeftOffset(n),o=this._textLines[n].length,a=this.__charBounds[n],h=s;for(let t=0;t<o;t++){var l,c;const i=r+a[t].left,n=r+(null!==(l=null===(c=a[t+1])||void 0===c?void 0:c.left)&&void 0!==l?l:a[t].left+a[t].kernedWidth),d=(i+n)/2;if(e.x<=d){s=h+t;break}if(e.x<=n){s=h+t+1;break}s=h+o}let d=s-h;this.flipX&&(d=o-d);const u=this._displayToOriginalIndex(n,d);let g=0;for(let t=0;t<n;t++){const e=undefined;g+=this._getOriginalLineLength(t)+this.missingNewlineOffset(t)}const f=g+u;return Math.min(f,this.text.length)}}function getCursorRect(t,e,i){if(0===e.lines.length)return{x:0,y:0,width:2,height:i.fontSize,baseline:.8*i.fontSize};const s=findPositionFromIndex(t,e),n=e.lines[s.lineIndex];if(!n){const t=undefined;return{x:e.lines[e.lines.length-1].width,y:(e.lines.length-1)*(i.fontSize*i.lineHeight),width:2,height:i.fontSize*i.lineHeight,baseline:.8*i.fontSize}}let r=0;if(s.graphemeIndex>0&&n.bounds.length>0){const t=Math.min(s.graphemeIndex-1,n.bounds.length-1),e=n.bounds[t];r=e.x+e.kernedWidth}const o=calculateLineY(s.lineIndex,e);return{x:r,y:o,width:2,height:n.height,baseline:o+n.baseline}}function findPositionFromIndex(t,e){let i=0;for(let s=0;s<e.lines.length;s++){const n=undefined,r=e.lines[s].graphemes.length;if(t>=i&&t<=i+r)return{lineIndex:s,graphemeIndex:t-i};if(i+=r,s<e.lines.length-1&&(i+=1,t===i-1))return{lineIndex:s,graphemeIndex:r}}const s=e.lines.length-1,n=e.lines[s];return{lineIndex:s,graphemeIndex:n?n.graphemes.length:0}}function calculateLineY(t,e,i){let s=0;for(let i=0;i<t&&i<e.lines.length;i++)s+=e.lines[i].height;return s}const pi="moveCursorUp",mi="moveCursorDown",yi="moveCursorLeft",xi="moveCursorRight",vi="exitEditing",_i=undefined,Ci=undefined,bi=undefined,Si=undefined,applyCanvasTransform=(t,e)=>{const i=e.getRetinaScaling();t.setTransform(i,0,0,i,0,0);const s=e.viewportTransform;t.transform(s[0],s[1],s[2],s[3],s[4],s[5])},wi=undefined,Ti={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:vi,27:vi,33:pi,34:mi,35:xi,36:yi,37:yi,38:pi,39:xi,40:mi},keysMapRtl:{9:vi,27:vi,33:pi,34:mi,35:yi,36:xi,37:xi,38:pi,39:yi,40:mi},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"},...{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1}};class IText extends ITextClickBehavior{static getDefaults(){return{...super.getDefaults(),...IText.ownDefaults}}get type(){const t=super.type;return"itext"===t?"i-text":t}constructor(t,e){super(t,{...IText.ownDefaults,...e}),_defineProperty(this,"_visualPositionsCache",new Map),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):("canvas"===t&&(this.canvas instanceof Canvas&&this.canvas.textEditingManager.remove(this),e instanceof Canvas&&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&&void 0!==arguments[0]?arguments[0]:this.selectionStart||0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.selectionEnd,i=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,i)}setSelectionStyles(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.selectionStart||0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,i)}get2DCursorLocation(){let t=arguments.length>0&&void 0!==arguments[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._clearVisualPositionsCache(),this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const i=super.toCanvasElement(t);return this.isEditing=e,i}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;this.cursorOffsetCache={};const e=this._getCursorBoundaries(),i=this.findAncestorsWithClipPath(),s=i.length>0;let n=t,r;if(s){r=createCanvasElementFor(t.canvas),n=r.getContext("2d"),applyCanvasTransform(n,this.canvas);const e=this.calcTransformMatrix();n.transform(e[0],e[1],e[2],e[3],e[4],e[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(n,e):this.renderCursor(n,e),s)for(const e of i){const i=e.clipPath,s=createCanvasElementFor(t.canvas),r=s.getContext("2d");if(applyCanvasTransform(r,this.canvas),!i.absolutePositioned){const t=e.calcTransformMatrix();r.transform(t[0],t[1],t[2],t[3],t[4],t[5])}i.transform(r),i.drawObject(r,!0,{}),this.drawClipPathOnCache(n,i,s)}s&&(t.setTransform(1,0,0,1,0,0),t.drawImage(r,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&&void 0!==arguments[0]?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return this._getCursorBoundariesOriginal(t,e)}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}_getCursorBoundariesAdvanced(t){if(!this.enableAdvancedLayout||!this._layoutTextAdvanced)return this._getCursorBoundariesOriginal(t);const e=undefined,i=getCursorRect(t,this._layoutTextAdvanced(),this._getAdvancedLayoutOptions());return{left:this._getLeftOffset(),top:this._getTopOffset(),leftOffset:i.x,topOffset:i.y}}getSelectionStartFromPointer(t){const e=undefined,i=this.canvas.getScenePoint(t).transform(invertTransform(this.calcTransformMatrix())),s=i.x+this.width/2,n=i.y+this.height/2;let r=0,o=0;for(let t=0;t<this._textLines.length;t++){const e=this.getHeightOfLine(t);if(n>=r&&n<r+e){o=t;break}r+=e,t===this._textLines.length-1&&(o=t)}let a=0;for(let t=0;t<o;t++){const e=this._getOriginalLineLength(t),i=this.missingNewlineOffset(t);console.log(`📍 Line ${t}: origLen=${e}, displayLen=${this._textLines[t].length}, tatweels=${this._getTatweelCountForLine(t)}, newlineOffset=${i}`),a+=e+i}console.log(`📍 Click on line ${o}, lineStartIndex=${a}`);const h=this._textLines[o],l=h.join(""),c=h.length,d=this._getOriginalLineLength(o);if(0===c)return a;const u=this._measureVisualPositions(o,l),g=this.getLineWidth(o);let f=0;"center"===this.textAlign||"justify-center"===this.textAlign?f=(this.width-g)/2:"right"===this.textAlign||"justify-right"===this.textAlign?f=this.width-g:"rtl"!==this.direction||"justify"!==this.textAlign&&"left"!==this.textAlign||(f=this.width-g);const p=s-f,m=[...u].sort((t,e)=>t.visualX-e.visualX);if(m.length>0&&p<m[0].visualX)return"rtl"===this.direction?a+d:a;if(m.length>0){const t=m[m.length-1];if(p>t.visualX+t.width)return"rtl"===this.direction?a:a+d}for(let t=0;t<m.length;t++){const e=m[t],i=e.visualX+e.width;if(p>=e.visualX&&p<=i){const t=this._displayToOriginalIndex(o,e.logicalIndex),i=this._isTatweelAtDisplayIndex(o,e.logicalIndex);console.log(`📍 Hit char: displayIdx=${e.logicalIndex}, origIdx=${t}, isTatweel=${i}, char="${this._textLines[o][e.logicalIndex]}"`);const s=undefined,n=p<=e.visualX+e.width/2;if(i){const e=a+t;return console.log(`📍 Tatweel click result: ${e}`),e}if(e.isRtl){const e=a+(n?t+1:t);return console.log(`📍 RTL char result: ${e} (clickedLeftHalf=${n})`),e}{const e=a+(n?t:t+1);return console.log(`📍 LTR char result: ${e} (clickedLeftHalf=${n})`),e}}}return a+d}_clearVisualPositionsCache(){this._visualPositionsCache.clear()}_measureVisualPositions(t,e){if(this._visualPositionsCache.has(t))return this._visualPositionsCache.get(t);const i=this._textLines[t],s=[],n=this.__charBounds[t];if(!n||0===n.length)return this._visualPositionsCache.set(t,s),s;if("rtl"!==this.direction){for(let t=0;t<i.length;t++){var r,o;s.push({logicalIndex:t,visualX:(null===(r=n[t])||void 0===r?void 0:r.left)||0,width:(null===(o=n[t])||void 0===o?void 0:o.kernedWidth)||0,isRtl:!1})}return this._visualPositionsCache.set(t,s),s}const a=analyzeBiDi(e,"rtl"),h=[];let l=0;for(let t=0;t<i.length;t++){const e=i[t];for(let i=0;i<e.length;i++)h[l+i]=t;l+=e.length}const c=[];for(const t of a){const e=[];let i=0;const s=new Set;for(let r=t.start;r<t.end;r++){const t=h[r];var d;if(void 0!==t&&!s.has(t))s.add(t),e.push(t),i+=(null===(d=n[t])||void 0===d?void 0:d.kernedWidth)||0}c.push({run:t,width:i,charIndices:e})}const u=undefined;let g=this.getLineWidth(t);for(const t of c){g-=t.width;const e=undefined;if("rtl"===t.run.direction){let e=g+t.width;for(const i of t.charIndices){var f;const t=(null===(f=n[i])||void 0===f?void 0:f.kernedWidth)||0;e-=t,s.push({logicalIndex:i,visualX:e,width:t,isRtl:!0})}}else{let e=g;for(const i of t.charIndices){var p;const t=(null===(p=n[i])||void 0===p?void 0:p.kernedWidth)||0;s.push({logicalIndex:i,visualX:e,width:t,isRtl:!1}),e+=t}}}return this._visualPositionsCache.set(t,s),s}_getCursorBoundariesOriginal(t,e){const i=this._getLeftOffset(),s=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:i,top:s,leftOffset:n.left,topOffset:n.top}}__getCursorBoundariesOffsets(t){let e=0,i=0,s=t;for(let t=0;t<this._textLines.length;t++){const e=this._getOriginalLineLength(t);if(s<=e){i=t;break}s-=e+this.missingNewlineOffset(t),i=t+1}i>=this._textLines.length&&(i=this._textLines.length-1,s=this._getOriginalLineLength(i));for(let t=0;t<i;t++)e+=this.getHeightOfLine(t);const n=this._originalToDisplayIndex(i,s),r=this._textLines[i].join(""),o=this._measureVisualPositions(i,r),a=this.getLineWidth(i);this._textLines[i].length;const h=this._getOriginalLineLength(i);let l=0;if(0===o.length)return{top:e,left:0};if(0===s)l="rtl"===this.direction?a:0;else if(s>=h)l="rtl"===this.direction?0:a;else{const t=o.find(t=>t.logicalIndex===n);if(t)l=t.isRtl?t.visualX+t.width:t.visualX;else{const t=n>0?n-1:0,e=o.find(e=>e.logicalIndex===t);if(e)l=e.isRtl?e.visualX:e.visualX+e.width;else{const t=this.__charBounds[i][n];l=(null==t?void 0:t.left)||0}}}let c=0,d;return"center"===this.textAlign||"justify-center"===this.textAlign?c=(this.width-a)/2:"right"===this.textAlign||"justify-right"===this.textAlign?c=this.width-a:"rtl"!==this.direction||"justify"!==this.textAlign&&"left"!==this.textAlign||(c=this.width-a),d="rtl"===this.direction?-this.width+c+l:c+l,{top:e,left:d}}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&&void 0!==arguments[0]?arguments[0]:this.selectionStart,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._getCursorBoundaries(t);const i=this.get2DCursorLocation(t),s=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,r=this.getValueOfPropertyAt(s,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),a=this.cursorWidth/o,h=this.getValueOfPropertyAt(s,n,"deltaY"),l=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(s)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(s,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-a/2,top:l+e.top+h,width:a,height:r}}_renderCursor(t,e,i){const{color:s,opacity:n,left:r,top:o,width:a,height:h}=this.getCursorRenderingData(i,e);t.fillStyle=s,t.globalAlpha=n,t.fillRect(r,o,a,h)}renderSelection(t,e){const i={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,i,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,i){const s=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(rt);let o=0,a=0,h=s,l=n,c=0;for(let t=0;t<this._textLines.length;t++){const e=this._getOriginalLineLength(t);if(c+e>=s){o=t,h=s-c;break}c+=e+this.missingNewlineOffset(t)}c=0;for(let t=0;t<this._textLines.length;t++){const e=this._getOriginalLineLength(t);if(c+e>=n){a=t,l=n-c;break}c+=e+this.missingNewlineOffset(t),t===this._textLines.length-1&&(a=t,l=e)}for(let e=o;e<=a;e++){let s=this.getHeightOfLine(e),n=0;const c=this._textLines[e].join(""),d=this._measureVisualPositions(e,c);this._textLines[e].length;const u=undefined;let g=0,f=this._getOriginalLineLength(e);e===o&&(g=h),e===a&&(f=l);const p=this._originalToDisplayIndex(e,g),m=this._originalToDisplayIndex(e,f);let y=1/0,x=-1/0;for(const t of d)t.logicalIndex>=p&&t.logicalIndex<m&&(y=Math.min(y,t.visualX),x=Math.max(x,t.visualX+t.width));if(y===1/0||x===-1/0){if(!(e>=o&&e<a))continue;y=0,x=r&&!this.isEndOfWrapping(e)?this.width:this.getLineWidth(e)||5}n=s,(this.lineHeight<1||e===a&&this.lineHeight>1)&&(s/=this.lineHeight);const v=this.getLineWidth(e);let _=0;"center"===this.textAlign||"justify-center"===this.textAlign?_=(this.width-v)/2:"right"===this.textAlign||"justify-right"===this.textAlign?_=this.width-v:"rtl"!==this.direction||"justify"!==this.textAlign&&"left"!==this.textAlign||(_=this.width-v);const C=-this.width/2+_+y,b=x-y;let S=s,w=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,w=s):t.fillStyle=this.selectionColor,t.fillRect(C,i.top+i.topOffset+w,b,S),i.topOffset+=n}}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,I)}_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()}}_defineProperty(IText,"ownDefaults",Ti),_defineProperty(IText,"type","IText"),X.setClass(IText),X.setClass(IText,"i-text");const Pi={minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1};class Textbox extends IText{static getDefaults(){return{...super.getDefaults(),...Textbox.ownDefaults}}constructor(t,e){super(t,{...Textbox.ownDefaults,...e}),this.initializeEventListeners()}static createControls(){return{controls:createTextboxDefaultControls()}}initDimensions(){this.initialized||(this.initialized=!0);const t=`${this.text}|${this.width}|${this.fontSize}|${this.fontFamily}|${this.textAlign}|${this.kashida}`;if(this._lastDimensionState===t&&this._textLines&&this._textLines.length>0)return;if(this._lastDimensionState=t,this.enableAdvancedLayout)return this.initDimensionsAdvanced();this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0;const e=this._splitText();if(this._styleMap=this._generateStyleMap(e),this._usingBrowserWrapping&&e&&e.lines){this._textLines=e.lines.map(t=>t.split(""));const t=e.justifySpaceMeasurements;t&&(this._styleMap.justifySpaceMeasurements=t);const i=e.actualBrowserHeight;i&&(this._actualBrowserHeight=i)}if(!this._usingBrowserWrapping&&this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this._usingBrowserWrapping&&this.width<50&&(this.width=300),this.height=this.calcTextHeight(),this.textAlign.includes(rt)){for(let t=0;t<this._textLines.length;t++)this.getLineWidth(t);this._usingBrowserWrapping?this._applyBrowserJustifySpaces():this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces()}}_scheduleJustifyAfterFontLoad(){if("undefined"==typeof document||!("fonts"in document))return;if(this._fontJustifyScheduled)return;this._fontJustifyScheduled=!0;const t=`${this.fontSize}px ${this.fontFamily}`;document.fonts.load(t).then(()=>{var t;this._fontJustifyScheduled=!1,this.initDimensions(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()}).catch(()=>{this._fontJustifyScheduled=!1})}initDimensionsAdvanced(){if(!this.initialized)return;this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.lockDynamicMinWidth||(this.dynamicMinWidth=0);const t=undefined,e="none"!==this.kashida&&this.textAlign.includes(rt)?"rtl"===this.direction?"right":"left":this._mapTextAlignToAlign(this.textAlign),i=layoutText({text:this.text,width:this.width,height:this.ellipsis?this.height:void 0,wrap:this.wrap||"word",align:e,ellipsis:this.ellipsis||!1,fontSize:this.fontSize,lineHeight:this.lineHeight,letterSpacing:this.letterSpacing||0,charSpacing:this.charSpacing,direction:"inherit"===this.direction?"ltr":this.direction,fontFamily:this.fontFamily,fontStyle:this.fontStyle,fontWeight:this.fontWeight,verticalAlign:this.verticalAlign||"top"});if(this.lockDynamicMinWidth)this.height=i.totalHeight,this._convertLayoutToLegacyFormat(i);else{if(i.lines.length>0){const t=Math.max(...i.lines.map(t=>t.width));this.dynamicMinWidth=Math.max(this.minWidth,t)}if(this.dynamicMinWidth>this.width){this._set("width",this.dynamicMinWidth);const t=layoutText({...this._getAdvancedLayoutOptions(),width:this.width});this.height=t.totalHeight,this._convertLayoutToLegacyFormat(t)}else this.height=i.totalHeight,this._convertLayoutToLegacyFormat(i)}this._styleMap=this._generateStyleMapFromLayout(i),this.textAlign.includes(rt)&&"none"!==this.kashida&&this._applyKashidaToLayout(),this.dirty=!0}_applyKashidaToLayout(){if(!this._textLines||!this.__charBounds)return;this._visualPositionsCache&&this._clearVisualPositionsCache();const t=undefined,e={none:0,short:.25,medium:.5,long:.75,stylistic:1}[this.kashida]||0;if(0===e)return;const i=undefined,s=document.createElement("canvas").getContext("2d");if(!s)return;s.font=this._getFontDeclaration();const n=s.measureText(ai).width;if(n<=0)return;this.__kashidaInfo=[];const r=this._textLines.length;for(let t=0;t<r;t++){this.__kashidaInfo[t]=[];const i=this._textLines[t];if(!this.__charBounds||!this.__charBounds[t])continue;const s=undefined;if(t===r-1)continue;const a=this.__charBounds[t],h=a[a.length-1],l=h?h.left+h.kernedWidth:0,c=this.width-l;if(c<=2)continue;const d=findKashidaPoints(i);if(0===d.length)continue;const u=c*e,g=Math.floor(u/n);if(0===g)continue;const f=Math.min(d.length,g),p=d.slice(0,f),m=Math.floor(g/f),y=g%f,x=[...p].sort((t,e)=>e.charIndex-t.charIndex),v=[...i];for(let e=0;e<x.length;e++){const i=x[e],s=undefined,r=m+(p.indexOf(i)<y?1:0);if(r>0){const e=Array(r).fill(ai);v.splice(i.charIndex+1,0,...e),this.__kashidaInfo[t].push({charIndex:i.charIndex,width:r*n,tatweelCount:r})}}this._textLines[t]=v,this.textLines&&(this.textLines[t]=v.join("")),this.__charBounds[t]=[],this.__lineWidths[t]=void 0,this._measureLine(t);let _=this.__charBounds[t];if(_&&_.length>0){let e=_[_.length-1],i=e?e.left+e.kernedWidth:0,s=this.width-i;if(s>.5){let t=0;for(let e=0;e<v.length;e++)/\s/.test(v[e])&&t++;if(t>0){const n=s/t;let r=0;for(let t=0;t<_.length;t++){const e=_[t];e&&(e.left+=r,/\s/.test(v[t])&&(e.width+=n,e.kernedWidth+=n,r+=n))}_[v.length]&&(_[v.length].left+=r),e=_[_.length-1],i=e?e.left+e.kernedWidth:0,s=this.width-i}}if(s>.5&&this.__kashidaInfo[t].length>0){const e=undefined,i=s/this.__kashidaInfo[t].length;let n=0,r=0;for(let e=0;e<_.length;e++){const s=_[e];if(s&&(s.left+=r,v[e]===ai)){var o;const a=i/((null===(o=this.__kashidaInfo[t][n])||void 0===o?void 0:o.tatweelCount)||1);s.width+=a,s.kernedWidth+=a,r+=a;const h=undefined;this.__kashidaInfo[t][n]&&e>0&&(e+1>=v.length||v[e+1]!==ai)&&n++}}_[v.length]&&(_[v.length].left+=r)}}this.__lineWidths[t]=this.width}for(let t=0;t<this._textLines.length;t++)if(void 0===this.__lineWidths[t]&&this.__charBounds[t]){const e=this.__charBounds[t],i=e[e.length-1];i&&(this.__lineWidths[t]=i.left+i.kernedWidth)}this._text=this._textLines.flat(),this._justifyApplied=!0}_generateStyleMapFromLayout(t){const e={};let i=0,s=0;return t.lines.forEach((n,r)=>{n.text.includes("\n")&&r>0&&i++,e[r]={line:i,offset:0},s+=n.graphemes.length,r<t.lines.length-1&&(s+=1)}),e}_generateStyleMap(t){let e=0,i=0,s=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)"\n"===t.graphemeText[s]&&r>0?(i=0,s++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[s])&&r>0&&(i++,s++),n[r]={line:e,offset:i},s+=t.graphemeLines[r].length,i+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const t=this._styleMap[e];t&&(e=t.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e=0,i=t+1,s,n=!1;const r=this._styleMap[t],o=this._styleMap[t+1];r&&(t=r.line,e=r.offset),o&&(i=o.line,n=i===t,s=o.offset);const a=void 0===t?this.styles:{line:this.styles[t]};for(const t in a)for(const i in a[t]){const r=parseInt(i,10);if(r>=e&&(!n||r<s))for(const e in a[t][i])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const i=this._styleMap[t];if(!i)return{};t=i.line,e=i.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,i){const s=this._styleMap[t];super._setStyleDeclaration(s.line,s.offset+e,i)}_deleteStyleDeclaration(t,e){const i=this._styleMap[t];super._deleteStyleDeclaration(i.line,i.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 i=this.getGraphemeDataForRender(t),s=[];for(let t=0;t<i.wordsData.length;t++)s.push(...this._wrapLine(t,e,i));return this.isWrapping=!1,s}getGraphemeDataForRender(t){const e=this.splitByGrapheme,i=e?"":" ";let s=0;const n=undefined;return{wordsData:t.map((t,n)=>{let r=0;const o=e?this.graphemeSplit(t):this.wordSplit(t);return 0===o.length?[{word:[],width:0}]:o.map(t=>{const o=e?[t]:this.graphemeSplit(t),a=this._measureWord(o,n,r);return s=Math.max(a,s),r+=o.length+i.length,{word:o,width:a}})}),largestWordWidth:s}}_measureWord(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=0,n;const r=!0;for(let o=0,a=t.length;o<a;o++){const a=undefined;s+=this._getGraphemeBox(t[o],e,o+i,n,r).kernedWidth,n=t[o]}return s}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,i){let{largestWordWidth:s,wordsData:n}=i,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;const o=this._getWidthOfCharSpacing(),a=this.splitByGrapheme,h=[],l=a?"":" ";let c=0,d=[],u=0,g=0,f=!0;e-=r;const p=Math.max(e,s,this.dynamicMinWidth),m=n[t];let y;for(u=0,y=0;y<m.length;y++){const{word:e,width:i}=m[y];u+=e.length;const s=c+g+i-o;s>p&&!f?(h.push(d),d=[],c=i,f=!0):c=s+o,f||a||d.push(l),d=d.concat(e),g=a?0:this._measureWord([l],t,u),u++,f=!1}return y&&h.push(d),!this._usingBrowserWrapping&&s+r>this.dynamicMinWidth&&(this.dynamicMinWidth=s-o+r),h}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=undefined;if(this.fontFamily&&fontLacksEnglishGlyphsCached(this.fontFamily)){const e=undefined,i=`${t.length+t.slice(0,50)}|${this.width}|${this.fontSize}|${this.fontFamily}|${this.textAlign}`;if(this._browserWrapCache&&this._browserWrapCache.key===i){const t=this._browserWrapCache.result;if(!this.textAlign.includes("justify")||t.justifySpaceMeasurements)return t}const s=this._splitTextIntoLinesWithBrowser(t);return this._browserWrapCache={key:i,result:s},this._usingBrowserWrapping=!0,s}this._usingBrowserWrapping=!1;const i=super._splitTextIntoLines(t),s=this._wrapText(i.lines,this.width),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=s[t].join("");return i.lines=n,i.graphemeLines=s,i}_splitTextIntoLinesWithBrowser(t){if("undefined"==typeof document)return this._splitTextIntoLinesDefault(t);const e=document.createElement("div");e.style.position="absolute",e.style.left="-9999px",e.style.visibility="hidden",e.style.fontSize=`${this.fontSize}px`,e.style.fontFamily=`"${this.fontFamily}"`,e.style.fontWeight=String(this.fontWeight||"normal"),e.style.fontStyle=String(this.fontStyle||"normal"),e.style.lineHeight=String(this.lineHeight||1.16),e.style.width=`${this.width}px`,e.style.direction=this.direction||"ltr",e.style.whiteSpace="pre-wrap",e.style.wordBreak="normal",e.style.overflowWrap="break-word",this.textAlign.includes("justify")?(e.style.textAlign="justify",e.style.textAlignLast="auto"):e.style.textAlign=this.textAlign,e.textContent=t,document.body.appendChild(e);const i=document.createRange(),s=[],n=[];try{const r=e.firstChild;if(r&&r.nodeType===Node.TEXT_NODE){let e=0;const o=t.length;let a=0;for(let h=0;h<=o;h++){i.setStart(r,e),i.setEnd(r,h);const l=i.getBoundingClientRect();if(h>e&&(l.bottom>a+5||h===o)){const i=h===o?h:h-1,r=t.substring(e,i).trim();if(r){s.push(r);const t=r.split("");n.push(t)}e=i,a=l.bottom}}}}catch(i){return document.body.removeChild(e),this._splitTextIntoLinesDefault(t)}const r=e.scrollHeight,o=e.getBoundingClientRect();let a=null;this.textAlign.includes("justify")&&(a=this._extractJustifySpaceMeasurements(e,s)),document.body.removeChild(e);let h=Math.max(r,o.height);const l=undefined;if(fontLacksEnglishGlyphsCached(this.fontFamily)){const t=undefined;h+=.25*this.fontSize}return{_unwrappedLines:[t.split("")],lines:s,graphemeText:t.split(""),graphemeLines:n,justifySpaceMeasurements:a,actualBrowserHeight:h}}_extractJustifySpaceMeasurements(t,e){const i=this._browserMeasureCtx||(this._browserMeasureCtx=document.createElement("canvas").getContext("2d"));if(!i)return[];i.font=`${this.fontStyle||"normal"} ${this.fontWeight||"normal"} ${this.fontSize}px "${this.fontFamily}"`;const s=i.measureText(" ").width||6,n=[];return e.forEach((t,r)=>{const o=[],a=(t.match(/\s/g)||[]).length,h=r===e.length-1;if(a>0&&!h){const e=i.measureText(t).width,n=this.width-e,r=undefined,h=s+(n>0?n/a:0),l=Math.max(s,h);for(let t=0;t<a;t++)o.push(l)}else if(a>0)for(let t=0;t<a;t++)o.push(s);n.push(o)}),n}_applyBrowserJustifySpaces(){if(!this._textLines||!this.__charBounds)return;const t=undefined,e={none:0,short:.25,medium:.5,long:.75,stylistic:1}[this.kashida]||0;this.__kashidaInfo=[];const i=this._textLines.length;this._textLines.forEach((t,s)=>{if(this.__kashidaInfo[s]=[],!this.__charBounds||!this.__charBounds[s])return;const n=undefined;if(s===i-1)return;const r=undefined,o=this.__charBounds[s].reduce((t,e)=>t+((null==e?void 0:e.kernedWidth)||0),0),a=this.width-o;if(a<=0)return;const h=[];for(let e=0;e<t.length;e++)/\s/.test(t[e])&&h.push(e);const l=h.length,c=e>0?findKashidaPoints(t):[],d=c.length>0;let u=0;d&&e>0&&(u=a*e);const g=d?u/c.length:0;if(d&&g>0){const e=[...c].sort((t,e)=>e.charIndex-t.charIndex),i=undefined,n=document.createElement("canvas").getContext("2d");if(n){n.font=this._getFontDeclaration();const i=n.measureText(ai).width;if(i>0){const n=[...t];for(const t of e){const e=Math.max(1,Math.round(g/i));for(let i=0;i<e;i++)n.splice(t.charIndex+1,0,ai);this.__kashidaInfo[s].push({charIndex:t.charIndex,width:g,tatweelCount:e})}this._textLines[s]=n,this.textLines&&void 0!==this.textLines[s]&&(this.textLines[s]=n.join("")),this.__charBounds[s]=[],this.__lineWidths[s]=void 0,this._measureLine(s)}}}else for(const t of c)this.__kashidaInfo[s].push({charIndex:t.charIndex,width:g,tatweelCount:0});const f=this.__charBounds[s],p=f.reduce((t,e)=>t+((null==e?void 0:e.kernedWidth)||0),0),m=this.width-p;if(m>0&&l>0){const t=m/l;let e=0;for(let i=0;i<this._textLines[s].length;i++){const n=f[i];n&&(n.left+=e,/\s/.test(this._textLines[s][i])&&(n.width+=t,n.kernedWidth+=t,e+=t))}}const y=undefined,x=this.__charBounds[s].reduce((t,e)=>Math.max(t,((null==e?void 0:e.left)||0)+((null==e?void 0:e.width)||0)),0);this.__lineWidths[s]=x}),this.dirty=!0,this._justifyApplied=!0}_splitTextIntoLinesDefault(t){const e=super._splitTextIntoLines(t),i=this._wrapText(e.lines,this.width),s=new Array(i.length);for(let t=0;t<i.length;t++)s[t]=i[t].join("");return e.lines=s,e.graphemeLines=i,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const i=parseInt(e,10);if(this._textLines[i]){const i=this._styleMap[e].line;t.set(`${i}`,!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}initializeEventListeners(){var t;let e=null;this.on("resizing",t=>{if(t.transform){const{originX:i}=t.transform;e="right"===i?"left":"left"===i?"right":null}else if(t.originX){const{originX:i}=t;e="right"===i?"left":"left"===i?"right":null}}),this.on("modified",()=>{const t=e;setTimeout(()=>this.safetySnapWidth(t),10),e=null}),null===(t=this.canvas)||void 0===t||t.on("object:modified",t=>{if(t.target===this){const t=e;setTimeout(()=>this.safetySnapWidth(t),10),e=null}})}safetySnapWidth(t){if(!this._textLines||"textbox"!==this.type.toLowerCase()||0===this._textLines.length)return;if(null==t)return;const e=this._textLines.length;if(0===e)return;let i=0;for(let t=0;t<e;t++){const e=this._textLines[t].join(""),s=this.getLineWidth(t),n=undefined;if(/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(e)){const t=.15*(this.fontSize||16);i=Math.max(i,s+t)}else i=Math.max(i,s)}const s=2;if(i>this.width-2){var n;const t=i+1,e=this.left,s=this.top,r=t-this.width,o=this.lockDynamicMinWidth;this.lockDynamicMinWidth=!0,this.set("width",t),this.initDimensions(),this.lockDynamicMinWidth=o,this.set({left:e-r,top:s}),this.setCoords(),this.__overlayEditor&&setTimeout(()=>{this.__overlayEditor.refresh()},0),null===(n=this.canvas)||void 0===n||n.requestRenderAll()}}_fixCharacterMappingAfterJsonLoad(){this._usingBrowserWrapping&&(this._browserWrapCache=null,this._lastDimensionState=null,this.initDimensions(),this._forceClearCache=!0,this.setCoords(),this.canvas&&this.canvas.requestRenderAll())}forceTextReinitialization(){this.initialized=!0,this._clearCache(),this.dirty=!0,this.dynamicMinWidth=0,this.isEditing=!1,this.initDimensions(),this.textAlign.includes("justify")&&this.__charBounds&&setTimeout(()=>{var t;let e=!1;this.__charBounds.forEach((t,i)=>{if(t&&this._textLines&&this._textLines[i]){const s=t.filter((t,e)=>/\s/.test(this._textLines[i][e]));if(s.length>1){const t=s[0].width;e=s.some(e=>Math.abs(e.width-t)>.1)}}}),!e&&this.__charBounds.length>0&&this.enlargeSpaces&&this.enlargeSpaces(),this._usingBrowserWrapping&&this._actualBrowserHeight?this.height=this._actualBrowserHeight:this.height=this.calcTextHeight(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()},10)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}_defineProperty(Textbox,"type","Textbox"),_defineProperty(Textbox,"textLayoutProperties",[...IText.textLayoutProperties,"width"]),_defineProperty(Textbox,"ownDefaults",Pi),X.setClass(Textbox);const Mi=20;function getOriginalDimensions(t){const e=t.getElement();return e?{width:e.naturalWidth||e.width||t.width||100,height:e.naturalHeight||e.height||t.height||100}:{width:t.width||100,height:t.height||100}}const resizeFromRightHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleX||1,a=n.cropX||0,h=getLocalPoint(e,e.originX,e.originY,i,s),l=Math.max(Mi,Math.abs(h.x)),c=undefined;if(l<=(r.width-a)*o)n.width=l/o;else{n.width=r.width-a;const t=l/n.width;n.scaleX=t,n.scaleY=t;const e=(n.height||r.height)*o;n.height=e/t}return n.setCoords(),!0},resizeFromLeftHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleX||1,a=n.cropX||0,h=n.width||r.width,l=getLocalPoint(e,e.originX,e.originY,i,s),c=Math.max(Mi,Math.abs(l.x)),d=a+h,u=undefined;if(c<=d*o){const t=c/o,e=d-t;e>=0?(n.cropX=e,n.width=t):(n.cropX=0,n.width=d)}else{n.cropX=0,n.width=d;const t=c/n.width;n.scaleX=t,n.scaleY=t;const e=(n.height||r.height)*o;n.height=e/t}return n.setCoords(),!0},cropFromRightHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"left","center",i,s),o=getOriginalDimensions(n),a=n.cropX||0,h=n.scaleX||1,l=(o.width-a)*h,c=Math.max(Mi,r.x);if(c<=l)n.width=c/h;else{n.width=o.width-a;const t=c/n.width;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},resizeFromBottomHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleY||1,a=n.cropY||0,h=getLocalPoint(e,e.originX,e.originY,i,s),l=Math.max(Mi,Math.abs(h.y)),c=undefined;if(l<=(r.height-a)*o)n.height=l/o;else{n.height=r.height-a;const t=l/n.height;n.scaleX=t,n.scaleY=t;const e=(n.width||r.width)*o;n.width=e/t}return n.setCoords(),!0},resizeFromTopHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleY||1,a=n.cropY||0,h=n.height||r.height,l=getLocalPoint(e,e.originX,e.originY,i,s),c=Math.max(Mi,Math.abs(l.y)),d=a+h,u=undefined;if(c<=d*o){const t=c/o,e=d-t;e>=0?(n.cropY=e,n.height=t):(n.cropY=0,n.height=d)}else{n.cropY=0,n.height=d;const t=c/n.height;n.scaleX=t,n.scaleY=t;const e=(n.width||r.width)*o;n.width=e/t}return n.setCoords(),!0},Oi=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromRightHandler)),ki=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromLeftHandler)),Di=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromBottomHandler)),Ei=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromTopHandler)),cropFromLeftHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"right","center",i,s);getOriginalDimensions(n);const o=n.cropX||0,a=n.width||100,h=n.scaleX||1,l=Math.max(Mi,Math.abs(r.x)),c=o+a,d=undefined;if(l<=c*h){const t=l/h,e=c-t;e>=0?(n.cropX=e,n.width=t):(n.cropX=0,n.width=c)}else{n.cropX=0,n.width=c;const t=l/n.width;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},cropFromBottomHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"center","top",i,s),o=getOriginalDimensions(n),a=n.cropY||0,h=n.scaleY||1,l=(o.height-a)*h,c=Math.max(Mi,r.y);if(c<=l)n.height=c/h;else{n.height=o.height-a;const t=c/n.height;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},cropFromTopHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"center","bottom",i,s);getOriginalDimensions(n);const o=n.cropY||0,a=n.height||100,h=n.scaleY||1,l=Math.max(Mi,Math.abs(r.y)),c=o+a,d=undefined;if(l<=c*h){const t=l/h,e=c-t;e>=0?(n.cropY=e,n.height=t):(n.cropY=0,n.height=c)}else{n.cropY=0,n.height=c;const t=l/n.height;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},createCornerCropHandler=(t,e)=>{const i="left"===t?cropFromLeftHandler:cropFromRightHandler,s="top"===e?cropFromTopHandler:cropFromBottomHandler;return(t,e,n,r)=>{const o=i(t,e,n,r),a=s(t,e,n,r);return o||a}},Ai=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromRightHandler)),Fi=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromLeftHandler)),Li=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromBottomHandler)),ji=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromTopHandler)),Ii=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("left","top"))),Bi=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("right","top"))),Ri=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("left","bottom"))),Wi=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("right","bottom"))),createImageCropControls=()=>({ml:new Control({x:-.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:ki,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mr:new Control({x:.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Oi,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mb:new Control({x:0,y:.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Di,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6}),mt:new Control({x:0,y:-.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Ei,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6}),tl:new Control({x:-.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),tr:new Control({x:.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),bl:new Control({x:-.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),br:new Control({x:.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),mtr:new Control({x:0,y:-.5,actionHandler:Rt,cursorStyleHandler:rotationStyleHandler,offsetY:-40,withConnection:!0,actionName:T})}),createImageCropModeControls=()=>({ml:new Control({x:-.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Fi,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mr:new Control({x:.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Ai,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mb:new Control({x:0,y:.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Li,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6}),mt:new Control({x:0,y:-.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:ji,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6})});class Canvas2dFilterBackend{constructor(){_defineProperty(this,"resources",{})}applyFilters(t,e,i,s,n){const r=n.getContext("2d",{willReadFrequently:!0,desynchronized:!0});if(!r)return;r.drawImage(e,0,0,i,s);const o=undefined,a=undefined,h={sourceWidth:i,sourceHeight:s,imageData:r.getImageData(0,0,i,s),originalEl:e,originalImageData:r.getImageData(0,0,i,s),canvasEl:n,ctx:r,filterBackend:this};t.forEach(t=>{t.applyTo(h)});const{imageData:l}=h;return l.width===i&&l.height===s||(n.width=l.width,n.height=l.height),r.putImageData(l,0,0),h}}class WebGLFilterBackend{constructor(){let{tileSize:t=e.textureSize}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_defineProperty(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),_defineProperty(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const i=createCanvasElementFor({width:t,height:e}),s={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",s);n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)}applyFilters(t,e,i,s,n,r){const o=this.gl,a=n.getContext("2d");if(!o||!a)return;let h;r&&(h=this.getCachedTexture(r,e));const l={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:i,sourceHeight:s,destinationWidth:i,destinationHeight:s,context:o,sourceTexture:this.createTexture(o,i,s,h?void 0:e),targetTexture:this.createTexture(o,i,s),originalTexture:h||this.createTexture(o,i,s,h?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},c=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,c),t.forEach(t=>{t&&t.applyTo(l)}),resizeCanvasIfNeeded(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(c),a.setTransform(1,0,0,1,0,0),l}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,i,s,n){const{NEAREST:r,TEXTURE_2D:o,RGBA:a,UNSIGNED_BYTE:h,CLAMP_TO_EDGE:l,TEXTURE_MAG_FILTER:c,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:u,TEXTURE_WRAP_T:g}=t,f=t.createTexture();return t.bindTexture(o,f),t.texParameteri(o,c,n||r),t.texParameteri(o,d,n||r),t.texParameteri(o,u,l),t.texParameteri(o,g,l),s?t.texImage2D(o,0,a,a,h,s):t.texImage2D(o,0,a,e,i,0,a,h,null),f}getCachedTexture(t,e,i){const{textureCache:s}=this;if(s[t])return s[t];{const n=this.createTexture(this.gl,e.width,e.height,e,i);return n&&(s[t]=n),n}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const i=t.canvas,s=e.targetCanvas,n=s.getContext("2d");if(!n)return;n.translate(0,s.height),n.scale(1,-1);const r=i.height-s.height;n.drawImage(i,0,r,s.width,s.height,0,0,s.width,s.height)}copyGLTo2DPutImageData(t,e){const i=undefined,s=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,o=n*r*4;if(!s)return;const a=new Uint8Array(this.imageBuffer,0,o),h=new Uint8ClampedArray(this.imageBuffer,0,o);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,a);const l=new ImageData(h,n,r);s.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const s=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);s&&(e.renderer=s.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}function resizeCanvasIfNeeded(t){const e=t.targetCanvas,i=e.width,s=e.height,n=t.destinationWidth,r=t.destinationHeight;i===n&&s===r||(e.width=n,e.height=r)}let Hi;function initFilterBackend(){const{WebGLProbe:t}=getEnv();return t.queryWebGL(createCanvasElement()),e.enableGLFiltering&&t.isSupported(e.textureSize)?new WebGLFilterBackend({tileSize:e.textureSize}):new Canvas2dFilterBackend}function getFilterBackend(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return!Hi&&t&&(Hi=initFilterBackend()),Hi}function setFilterBackend(t){Hi=t}const Xi={strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0,cropMode:!1},$i=["cropX","cropY"];class FabricImage extends FabricObject{static getDefaults(){return{...super.getDefaults(),...FabricImage.ownDefaults}}static createControls(){return{controls:createImageCropControls()}}enterCropMode(){var t;this.cropMode||(this.cropMode=!0,this._normalControls={...this.controls},this.controls=createImageCropModeControls(),this.dirty=!0,this._cropModeDragActive=!1,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}exitCropMode(){var t;this.cropMode&&(this.cropMode=!1,this._normalControls?(this.controls=this._normalControls,this._normalControls=void 0):this.controls=createImageCropControls(),this.dirty=!0,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}toggleCropMode(){this.cropMode?this.exitCropMode():this.enterCropMode()}set(t,e){if(this.cropMode&&this.isMoving&&"string"==typeof t){if("left"===t&&"number"==typeof e)return this._setCropModePosition("left",e);if("top"===t&&"number"==typeof e)return this._setCropModePosition("top",e)}return super.set(t,e)}_setCropModePosition(t,e){const i=this._element;if(!i)return super.set(t,e);this._cropModeDragActive||(this._cropModeDragActive=!0,this._cropModeOriginalLeft=this.left,this._cropModeOriginalTop=this.top,this._cropModeOriginalCropX=this.cropX,this._cropModeOriginalCropY=this.cropY);const s="left"===t?this.scaleX||1:this.scaleY||1,n="left"===t?this._cropModeOriginalLeft:this._cropModeOriginalTop,r="left"===t?this._cropModeOriginalCropX:this._cropModeOriginalCropY,o="left"===t?"cropX":"cropY",a="left"===t?"width":"height",h="left"===t?i.naturalWidth||i.width:i.naturalHeight||i.height;if(void 0===n||void 0===r)return super.set(t,e);const l=undefined,c=-(e-n)/Math.abs(s),d=this[a]||h;let u=r+c;const g=Math.max(0,h-d);return u=Math.max(0,Math.min(g,u)),super.set(o,u),super.set(t,n),this.dirty=!0,this}_onMouseUp(){this.cropMode&&(this._cropModeDragActive=!1)}constructor(t,e){super(),_defineProperty(this,"_lastScaleX",1),_defineProperty(this,"_lastScaleY",1),_defineProperty(this,"_filterScalingX",1),_defineProperty(this,"_filterScalingY",1),_defineProperty(this,"_normalControls",void 0),_defineProperty(this,"_cropModeOriginalLeft",void 0),_defineProperty(this,"_cropModeOriginalTop",void 0),_defineProperty(this,"_cropModeOriginalCropX",void 0),_defineProperty(this,"_cropModeOriginalCropY",void 0),_defineProperty(this,"_cropModeDragActive",void 0),this.filters=[],Object.assign(this,FabricImage.ownDefaults),this.setOptions(e),this.cacheKey=`texture${uid()}`,this.setElement("string"==typeof t?(this.canvas&&getDocumentFromElement(this.canvas.getElement())||getFabricDocument()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._element=t,this._originalElement=t,this._setWidthHeight(e),0!==this.filters.length&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=getFilterBackend(!1);e instanceof WebGLFilterBackend&&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&&getEnv().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||0===this.strokeWidth)return;const e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,-i),t.lineTo(e,-i),t.lineTo(e,i),t.lineTo(-e,i),t.lineTo(-e,-i),t.closePath()}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=[];return this.filters.forEach(t=>{t&&e.push(t.toObject())}),{...super.toObject([...$i,...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,i=-this.width/2,s=-this.height/2;let n=[],r=[],o="",a="";if(!e)return[];if(this.hasCrop()){const t=uid();n.push('<clipPath id="imageCrop_'+t+'">\n','\t<rect x="'+i+'" y="'+s+'" width="'+this.width+'" height="'+this.height+'" />\n',"</clipPath>\n"),o=' clip-path="url(#imageCrop_'+t+')" '}if(this.imageSmoothing||(a=' image-rendering="optimizeSpeed"'),t.push("\t<image ","COMMON_PARTS",`xlink:href="${this.getSvgSrc(!0)}" x="${i-this.cropX}" y="${s-this.cropY}" width="${e.width||e.naturalWidth}" height="${e.height||e.naturalHeight}"${a}${o}></image>\n`),this.stroke||this.strokeDashArray){const t=this.fill;this.fill=null,r=[`\t<rect x="${i}" y="${s}" width="${this.width}" height="${this.height}" style="${this.getSvgStyles()}" />\n`],this.fill=t}return n=this.paintFirst!==I?n.concat(r,t):n.concat(t,r),n}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:i}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return loadImage(t,{crossOrigin:e,signal:i}).then(t=>{void 0!==e&&this.set({crossOrigin:e}),this.setElement(t)})}toString(){return`#<Image: { src: "${this.getSrc()}" }>`}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),s=i.x,n=i.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||s>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=s,void(this._lastScaleY=n);const o=createCanvasElementFor(r),{width:a,height:h}=r;this._element=o,this._lastScaleX=t.scaleX=s,this._lastScaleY=t.scaleY=n,getFilterBackend().applyFilters([t],r,a,h,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.filters||[];if(t=t.filter(t=>t&&!t.isNeutralState()),this.set("dirty",!0),this.removeTexture(`${this.cacheKey}_filtered`),0===t.length)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,i=e.naturalWidth||e.width,s=e.naturalHeight||e.height;if(this._element===this._originalElement){const t=createCanvasElementFor({width:i,height:s});this._element=t,this._filteredEl=t}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,s),this._lastScaleX=1,this._lastScaleY=1);getFilterBackend().applyFilters(t,this._originalElement,i,s,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return!this.cropMode&&this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const i=this._filterScalingX,s=this._filterScalingY,n=this.width,r=this.height,o=Math.max(this.cropX,0),a=Math.max(this.cropY,0),h=e.naturalWidth||e.width,l=e.naturalHeight||e.height,c=o*i,d=a*s,u=Math.min(n*i,h-c),g=Math.min(r*s,l-d),f=-n/2,p=-r/2,m=Math.min(n,h/i-o),y=Math.min(r,l/s-a);this.cropMode?this._renderCropMode(t,e,h,l,i,s):e&&t.drawImage(e,c,d,u,g,f,p,m,y)}_renderCropMode(t,e,i,s,n,r){const o=this.width,a=this.height,h=Math.max(this.cropX,0),l=Math.max(this.cropY,0),c=i/n,d=s/r,u=-o/2-h,g=-a/2-l;t.save(),t.globalAlpha=.3,t.drawImage(e,0,0,i,s,u,g,c,d),t.restore(),t.save(),t.fillStyle="rgba(0, 0, 0, 0.5)",h>0&&t.fillRect(u,g,h,d);const f=-o/2+o,p=c-h-o;p>0&&t.fillRect(f,g,p,d),l>0&&t.fillRect(-o/2,g,o,l);const m=-a/2+a,y=d-l-a;y>0&&t.fillRect(-o/2,m,o,y),t.restore();const x=h*n,v=l*r,_=Math.min(o*n,i-x),C=Math.min(a*r,s-v),b=-o/2,S=-a/2,w=Math.min(o,i/n-h),T=Math.min(a,s/r-l);t.drawImage(e,x,v,_,C,b,S,w,T),t.save(),t.strokeStyle="#fff",t.lineWidth=2,t.strokeRect(-o/2,-a/2,o,a),t.restore()}_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&&void 0!==arguments[0]?arguments[0]:{};const i=this.getOriginalSize();this.width=t||i.width,this.height=e||i.height}parsePreserveAspectRatioAttribute(){const t=parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),e=this.width,i=this.height,s={width:e,height:i};let n=this._element.width,r=this._element.height,o=1,a=1,h=0,l=0,c=0,d=0,u;return!t||t.alignX===_&&t.alignY===_?(o=e/n,a=i/r):("meet"===t.meetOrSlice&&(o=a=findScaleToFit(this._element,s),u=(e-n*o)/2,"Min"===t.alignX&&(h=-u),"Max"===t.alignX&&(h=u),u=(i-r*a)/2,"Min"===t.alignY&&(l=-u),"Max"===t.alignY&&(l=u)),"slice"===t.meetOrSlice&&(o=a=findScaleToCover(this._element,s),u=n-e/o,"Mid"===t.alignX&&(c=u/2),"Max"===t.alignX&&(c=u),u=r-i/a,"Mid"===t.alignY&&(d=u/2),"Max"===t.alignY&&(d=u),n=e/o,r=i/a)),{width:n,height:r,scaleX:o,scaleY:a,offsetLeft:h,offsetTop:l,cropX:c,cropY:d}}static fromObject(t,e){let{filters:i,resizeFilter:s,src:n,crossOrigin:r,type:o,...a}=t;return Promise.all([loadImage(n,{...e,crossOrigin:r}),i&&enlivenObjects(i,e),s?enlivenObjects([s],e):[],enlivenObjectEnlivables(a,e)]).then(t=>{let[e,i=[],[s],r={}]=t;return new this(e,{...a,src:n,filters:i,resizeFilter:s,...r})})}static fromURL(t){let{crossOrigin:e=null,signal:i}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;return loadImage(t,{crossOrigin:e,signal:i}).then(t=>new this(t,s))}static async fromElement(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const s=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return this.fromURL(s["xlink:href"]||s.href,e,s).catch(t=>(log("log","Unable to parse Image",t),null))}}_defineProperty(FabricImage,"type","Image"),_defineProperty(FabricImage,"cacheProperties",[...Ot,...$i]),_defineProperty(FabricImage,"ownDefaults",Xi),_defineProperty(FabricImage,"ATTRIBUTE_NAMES",[...se,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),X.setClass(FabricImage),X.setSVGClass(FabricImage);class FrameLayout extends LayoutStrategy{shouldPerformLayout(t){let{type:e}=t;return e===Ce}calcBoundingBox(t,e){var i,s,n,r;const{type:o,target:a}=e,h=null!==(i=null!==(s=a.frameWidth)&&void 0!==s?s:a.width)&&void 0!==i?i:200,l=null!==(n=null!==(r=a.frameHeight)&&void 0!==r?r:a.height)&&void 0!==n?n:200,c=new Point(h,l);if(o===Ce){const t=undefined;return{center:new Point(0,0),size:c,relativeCorrection:new Point(0,0)}}const d=undefined;return{center:a.getRelativeCenterPoint(),size:c}}getInitialSize(t,e){var i,s,n,r;const{target:o}=t,a=null!==(i=null!==(s=o.frameWidth)&&void 0!==s?s:o.width)&&void 0!==i?i:200,h=null!==(n=null!==(r=o.frameHeight)&&void 0!==r?r:o.height)&&void 0!==n?n:200;return new Point(a,h)}}_defineProperty(FrameLayout,"type","frame-layout"),X.setClass(FrameLayout);const zi={frameWidth:200,frameHeight:200,frameShape:"rect",frameBorderRadius:0,isEditMode:!1,placeholderText:"Drop image here",placeholderColor:"#d0d0d0",frameMeta:{contentScale:1,contentOffsetX:0,contentOffsetY:0}};class Frame extends Group{static getDefaults(){return{...super.getDefaults(),...Frame.ownDefaults}}constructor(){var t,e,i;let s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=new LayoutManager(new FrameLayout);super(s,{...n,layoutManager:r}),_defineProperty(this,"_contentImage",null),_defineProperty(this,"_placeholder",null),_defineProperty(this,"_editModeObjectCaching",void 0),_defineProperty(this,"_editModeOriginalControls",void 0),_defineProperty(this,"_boundConstrainMove",void 0),_defineProperty(this,"_boundConstrainScale",void 0),_defineProperty(this,"_editModeClipPath",void 0),_defineProperty(this,"_contentExpandMode",!1),Object.assign(this,Frame.ownDefaults),this.setOptions(n);const o=zi.frameMeta||{};this.frameMeta={contentScale:null!==(t=o.contentScale)&&void 0!==t?t:1,contentOffsetX:null!==(e=o.contentOffsetX)&&void 0!==e?e:0,contentOffsetY:null!==(i=o.contentOffsetY)&&void 0!==i?i:0,...n.frameMeta},this.set({width:this.frameWidth,height:this.frameHeight}),this._updateClipPath(),0===s.length&&this._createPlaceholder(),this._setupResizeControls()}_setupResizeControls(){const changeFrameWidth=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,e.originX,e.originY,i,s),o=n.frameWidth,a=Math.max(20,Math.abs(r.x));return!(Math.abs(o-a)<1)&&(n.frameWidth=a,n.width=a,n._updateClipPath(),n._adjustContentAfterResize(),!0)},changeFrameHeight=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,e.originX,e.originY,i,s),o=n.frameHeight,a=Math.max(20,Math.abs(r.y));return!(Math.abs(o-a)<1)&&(n.frameHeight=a,n.height=a,n._updateClipPath(),n._adjustContentAfterResize(),!0)},changeFrameSize=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,e.originX,e.originY,i,s),o=n.frameWidth,a=n.frameHeight,h=Math.max(20,Math.abs(r.x)),l=Math.max(20,Math.abs(r.y));return!(Math.abs(o-h)<1&&Math.abs(a-l)<1)&&(n.frameWidth=h,n.frameHeight=l,n.width=h,n.height=l,n._updateClipPath(),n._adjustContentAfterResize(),!0)},t=wrapWithFireEvent(M,wrapWithFixedAnchor(changeFrameSize)),e=wrapWithFireEvent(M,wrapWithFixedAnchor(changeFrameWidth)),i=wrapWithFireEvent(M,wrapWithFixedAnchor(changeFrameHeight));if(!this.controls)return void console.warn("Frame: controls not initialized yet");const s=undefined;["tl","tr","bl","br"].forEach(e=>{const i=this.controls[e];i&&(this.controls[e]=new Control({x:i.x,y:i.y,cursorStyleHandler:i.cursorStyleHandler,actionHandler:t,actionName:"resizing"}))});const n=undefined;["ml","mr"].forEach(t=>{const i=this.controls[t];i&&(this.controls[t]=new Control({x:i.x,y:i.y,cursorStyleHandler:i.cursorStyleHandler,actionHandler:e,actionName:"resizing",render:i.render,sizeX:i.sizeX,sizeY:i.sizeY}))});const r=undefined;["mt","mb"].forEach(t=>{const e=this.controls[t];e&&(this.controls[t]=new Control({x:e.x,y:e.y,cursorStyleHandler:e.cursorStyleHandler,actionHandler:i,actionName:"resizing",render:e.render,sizeX:e.sizeX,sizeY:e.sizeY}))})}_adjustContentAfterResize(){if(this._placeholder&&this._placeholder.set({width:this.frameWidth,height:this.frameHeight}),this._contentImage){var t,e,i,s,n,r,o;const a=this._contentImage,h=null!==(t=null!==(e=this.frameMeta.originalWidth)&&void 0!==e?e:a.width)&&void 0!==t?t:100,l=null!==(i=null!==(s=this.frameMeta.originalHeight)&&void 0!==s?s:a.height)&&void 0!==i?i:100;let c=null!==(n=a.scaleX)&&void 0!==n?n:1,d=null!==(r=a.left)&&void 0!==r?r:0,u=null!==(o=a.top)&&void 0!==o?o:0;const g=this._calculateCoverScale(h,l);if(c<g){const t=g/c;d*=t,u*=t,c=g,a.set({scaleX:c,scaleY:c}),this.frameMeta={...this.frameMeta,contentScale:c}}const f=h*c/2,p=l*c/2,m=this.frameWidth/2,y=this.frameHeight/2,x=Math.max(0,f-m),v=Math.max(0,p-y),_=Math.abs(d)>x,C=Math.abs(u)>v;_&&(d=Math.max(-x,Math.min(x,d))),C&&(u=Math.max(-v,Math.min(v,u))),(_||C)&&(a.set({left:d,top:u}),this.frameMeta={...this.frameMeta,contentOffsetX:d,contentOffsetY:u}),a.setCoords()}this.setCoords()}_updateClipPath(){let t;switch(this.frameShape){case"circle":{const e=Math.min(this.frameWidth,this.frameHeight)/2;t=new Circle({radius:e,originX:"center",originY:"center",left:0,top:0});break}case"rounded-rect":t=new Rect({width:this.frameWidth,height:this.frameHeight,rx:this.frameBorderRadius,ry:this.frameBorderRadius,originX:"center",originY:"center",left:0,top:0});break;case"custom":if(this.frameCustomPath){t=new Path(this.frameCustomPath,{originX:"center",originY:"center",left:0,top:0});const e=t.getBoundingRect(),i=this.frameWidth/e.width,s=this.frameHeight/e.height;t.set({scaleX:i,scaleY:s})}else t=new Rect({width:this.frameWidth,height:this.frameHeight,originX:"center",originY:"center",left:0,top:0});break;case"rect":default:t=new Rect({width:this.frameWidth,height:this.frameHeight,originX:"center",originY:"center",left:0,top:0});break}this.clipPath=t,this.set("dirty",!0)}_createPlaceholder(){this._placeholder&&(super.remove(this._placeholder),this._placeholder=null);const t=new Rect({width:this.frameWidth,height:this.frameHeight,fill:this.placeholderColor,originX:"center",originY:"center",left:0,top:0,selectable:!1,evented:!1});this._placeholder=t,super.add(t),this._restoreFixedDimensions()}_removePlaceholder(){this._placeholder&&(super.remove(this._placeholder),this._placeholder=null)}_restoreFixedDimensions(){this.set({width:this.frameWidth,height:this.frameHeight})}async setImage(t){var e,i;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{crossOrigin:n="anonymous",signal:r}=s,o=await FabricImage.fromURL(t,{crossOrigin:n,signal:r}),a=null!==(e=o.width)&&void 0!==e?e:100,h=null!==(i=o.height)&&void 0!==i?i:100,l=this._calculateCoverScale(a,h);o.set({scaleX:l,scaleY:l,originX:"center",originY:"center",left:0,top:0,selectable:!1,evented:!1}),this._clearContent(),this._contentImage=o,super.add(o),this._contentImage.set({left:0,top:0}),this.frameMeta={...this.frameMeta,contentScale:l,contentOffsetX:0,contentOffsetY:0,imageSrc:t,originalWidth:a,originalHeight:h},this._restoreFixedDimensions(),this.setCoords(),this._contentImage.setCoords(),this.set("dirty",!0)}setImageObject(t){var e,i;const s=null!==(e=t.width)&&void 0!==e?e:100,n=null!==(i=t.height)&&void 0!==i?i:100,r=this._calculateCoverScale(s,n);t.set({scaleX:r,scaleY:r,originX:"center",originY:"center",left:0,top:0,selectable:!1,evented:!1}),this._clearContent(),this._contentImage=t,super.add(t),this.frameMeta={...this.frameMeta,contentScale:r,contentOffsetX:0,contentOffsetY:0,imageSrc:t.getSrc(),originalWidth:s,originalHeight:n},this._restoreFixedDimensions(),this.set("dirty",!0)}_calculateCoverScale(t,e){const i=this.frameWidth/t,s=this.frameHeight/e;return Math.max(i,s)}_clearContent(){this._removePlaceholder(),this._contentImage&&(super.remove(this._contentImage),this._contentImage=null);const t=undefined;this.getObjects().forEach(t=>super.remove(t))}clearContent(){this._clearContent(),this._createPlaceholder(),this.frameMeta={contentScale:1,contentOffsetX:0,contentOffsetY:0},this.set("dirty",!0)}hasContent(){return null!==this._contentImage}getContentImage(){return this._contentImage}enterEditMode(){var t,e,i,s;if(!this._contentImage||this.isEditMode)return;this.isEditMode=!0,this._editModeObjectCaching=this.objectCaching,this.objectCaching=!1,this.dirty=!0,this._cacheCanvas&&(this._cacheCanvas=null,this._cacheContext=null),this.subTargetCheck=!0,this.interactive=!0;const n=null!==(t=null!==(e=this.frameMeta.originalWidth)&&void 0!==e?e:this._contentImage.width)&&void 0!==t?t:100,r=null!==(i=null!==(s=this.frameMeta.originalHeight)&&void 0!==s?s:this._contentImage.height)&&void 0!==i?i:100,o=this._calculateCoverScale(n,r);this._contentImage.set({selectable:!0,evented:!0,hasControls:!0,hasBorders:!0,minScaleLimit:o,lockScalingFlip:!0,lockUniScaling:!1,objectCaching:!1}),this._contentImage.dirty=!0,this._editModeOriginalControls=this._contentImage.controls,this._contentImage.controls={tl:this._contentImage.controls.tl,tr:this._contentImage.controls.tr,bl:this._contentImage.controls.bl,br:this._contentImage.controls.br},this.clipPath&&(this._editModeClipPath=this.clipPath,this.clipPath=void 0),this._setupEditModeConstraints(),this.set("dirty",!0),this.canvas&&requestAnimationFrame(()=>{this._contentImage&&this.canvas&&(this.canvas.setActiveObject(this._contentImage),this.canvas.requestRenderAll())}),this.fire("frame:editmode:enter",{target:this})}_setupEditModeConstraints(){if(!this._contentImage||!this.canvas)return;const t=this,e=this._contentImage;this._boundConstrainMove=i=>{var s,n,r,o,a,h,l,c;if(i.target!==e||!t.isEditMode)return;const d=null!==(s=null!==(n=t.frameMeta.originalWidth)&&void 0!==n?n:e.width)&&void 0!==s?s:100,u=null!==(r=null!==(o=t.frameMeta.originalHeight)&&void 0!==o?o:e.height)&&void 0!==r?r:100,g=undefined,f=undefined,p=d*(null!==(a=e.scaleX)&&void 0!==a?a:1)/2,m=u*(null!==(h=e.scaleY)&&void 0!==h?h:1)/2,y=t.frameWidth/2,x=t.frameHeight/2,v=Math.max(0,p-y),_=Math.max(0,m-x);let C=null!==(l=e.left)&&void 0!==l?l:0,b=null!==(c=e.top)&&void 0!==c?c:0;C=Math.max(-v,Math.min(v,C)),b=Math.max(-_,Math.min(_,b)),e.set({left:C,top:b})},this._boundConstrainScale=i=>{var s,n,r,o,a,h,l;if(i.target!==e||!t.isEditMode)return;const c=null!==(s=null!==(n=t.frameMeta.originalWidth)&&void 0!==n?n:e.width)&&void 0!==s?s:100,d=null!==(r=null!==(o=t.frameMeta.originalHeight)&&void 0!==o?o:e.height)&&void 0!==r?r:100,u=t.frameWidth/c,g=t.frameHeight/d;let f=null!==(a=e.scaleX)&&void 0!==a?a:1,p=null!==(h=e.scaleY)&&void 0!==h?h:1;f=Math.max(u,f),p=Math.max(g,p),e.set({scaleX:f,scaleY:p}),null===(l=t._boundConstrainMove)||void 0===l||l.call(t,i)},this.canvas.on("object:moving",this._boundConstrainMove),this.canvas.on("object:scaling",this._boundConstrainScale)}_removeEditModeConstraints(){this.canvas&&(this._boundConstrainMove&&(this.canvas.off("object:moving",this._boundConstrainMove),this._boundConstrainMove=void 0),this._boundConstrainScale&&(this.canvas.off("object:scaling",this._boundConstrainScale),this._boundConstrainScale=void 0))}shouldCache(){return this.isEditMode?(this.ownCaching=!1,!1):super.shouldCache()}drawObject(t,e,i){this._renderBackground(t);for(let e=0;e<this._objects.length;e++){const i=this._objects[e];i.group===this&&i.render(t)}this.isEditMode||this._drawClipPath(t,this.clipPath,i)}render(t){super.render(t),this.isEditMode&&this._editModeClipPath&&this._renderEditModeOverlay(t,!1)}_renderEditModeOverlay(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t.save();const i=this.calcTransformMatrix();if(t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),!e){t.beginPath();const e=2e3;if(t.rect(-e,-e,2*e,2*e),"circle"===this.frameShape){const e=Math.min(this.frameWidth,this.frameHeight)/2;t.moveTo(e,0),t.arc(0,0,e,0,2*Math.PI,!0)}else if("rounded-rect"===this.frameShape){const e=this.frameWidth/2,i=this.frameHeight/2,s=Math.min(this.frameBorderRadius,e,i);t.moveTo(e,i-s),t.arcTo(e,-i,e-s,-i,s),t.arcTo(-e,-i,-e,-i+s,s),t.arcTo(-e,i,-e+s,i,s),t.arcTo(e,i,e,i-s,s),t.closePath()}else{const e=this.frameWidth/2,i=this.frameHeight/2;t.moveTo(e,-i),t.lineTo(-e,-i),t.lineTo(-e,i),t.lineTo(e,i),t.closePath()}t.fillStyle="rgba(0, 0, 0, 0.5)",t.fill("evenodd")}if(t.beginPath(),"circle"===this.frameShape){const e=Math.min(this.frameWidth,this.frameHeight)/2;t.arc(0,0,e,0,2*Math.PI)}else if("rounded-rect"===this.frameShape){const e=this.frameWidth/2,i=this.frameHeight/2,s=Math.min(this.frameBorderRadius,e,i);t.moveTo(e-s,-i),t.arcTo(e,-i,e,-i+s,s),t.arcTo(e,i,e-s,i,s),t.arcTo(-e,i,-e,i-s,s),t.arcTo(-e,-i,-e+s,-i,s),t.closePath()}else{const e=this.frameWidth/2,i=this.frameHeight/2;t.rect(-e,-i,this.frameWidth,this.frameHeight)}t.strokeStyle="rgba(255, 255, 255, 0.8)",t.lineWidth=2,t.stroke(),t.setLineDash([5,5]),t.strokeStyle="rgba(0, 150, 255, 0.8)",t.lineWidth=1,t.stroke(),t.restore()}exitEditMode(){var t,e,i,s,n,r,o,a;if(!this._contentImage||!this.isEditMode)return;this._contentExpandMode&&this.exitContentExpandMode(),this.isEditMode=!1,this._removeEditModeConstraints(),this.subTargetCheck=!1,this.interactive=!1;const h=null!==(t=this._contentImage.left)&&void 0!==t?t:0,l=null!==(e=this._contentImage.top)&&void 0!==e?e:0,c=null!==(i=this._contentImage.scaleX)&&void 0!==i?i:1,d=null!==(s=this._contentImage.scaleY)&&void 0!==s?s:1,u=undefined,g=undefined,f=(null!==(n=null!==(r=this.frameMeta.originalWidth)&&void 0!==r?r:this._contentImage.width)&&void 0!==n?n:100)*c/2,p=(null!==(o=null!==(a=this.frameMeta.originalHeight)&&void 0!==a?a:this._contentImage.height)&&void 0!==o?o:100)*d/2,m=this.frameWidth/2,y=this.frameHeight/2,x=Math.max(0,f-m),v=Math.max(0,p-y),_=Math.max(-x,Math.min(x,h)),C=Math.max(-v,Math.min(v,l));this._contentImage.set({left:_,top:C}),this.frameMeta={...this.frameMeta,contentOffsetX:_,contentOffsetY:C,contentScaleX:c,contentScaleY:d},this._editModeOriginalControls&&(this._contentImage.controls=this._editModeOriginalControls,this._editModeOriginalControls=void 0),this._contentImage.set({selectable:!1,evented:!1,hasControls:!1,hasBorders:!1,lockUniScaling:!1,centeredScaling:!1,objectCaching:!0}),this._editModeClipPath&&(this.clipPath=this._editModeClipPath,this._editModeClipPath=void 0),void 0!==this._editModeObjectCaching&&(this.objectCaching=this._editModeObjectCaching,this._editModeObjectCaching=void 0),this.set("dirty",!0),this.canvas&&(this.canvas.setActiveObject(this),this.canvas.renderAll()),this.fire("frame:editmode:exit",{target:this})}toggleEditMode(){this.isEditMode?this.exitEditMode():this.enterEditMode()}enterContentExpandMode(){this._contentImage&&this.isEditMode?this._contentExpandMode||(this._contentExpandMode=!0,this._removeEditModeConstraints(),this._contentImage.enterExpandMode(),this.canvas&&this.canvas.requestRenderAll()):console.warn("Frame: Must be in edit mode with content to enter expand mode")}exitContentExpandMode(){this._contentImage&&this._contentExpandMode&&(this._contentExpandMode=!1,this._contentImage.exitExpandMode(),this.isEditMode&&this._setupEditModeConstraints(),this.canvas&&this.canvas.requestRenderAll())}toggleContentExpandMode(){this._contentExpandMode?this.exitContentExpandMode():this.enterContentExpandMode()}isContentExpandMode(){return this._contentExpandMode}getContentExpansion(){return this._contentImage?this._contentImage.getExpansion():null}setContentExpansion(t){this._contentImage&&this._contentImage.setExpansion(t)}resetContentExpansion(){this._contentImage&&this._contentImage.resetExpansion()}hasContentExpansion(){return!!this._contentImage&&this._contentImage.hasExpansion()}resizeFrame(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{maintainAspect:s=!1}=i;if(s){const i=this.frameWidth/this.frameHeight,s=undefined;t/e>i?e=t/i:t=e*i}this.frameWidth=t,this.frameHeight=e,super.set({width:this.frameWidth,height:this.frameHeight}),this._updateClipPath(),this._adjustContentAfterResize(),this.set("dirty",!0),this.setCoords()}setFrameShape(t,e){this.frameShape=t,e&&(this.frameCustomPath=e),this._updateClipPath(),this.set("dirty",!0)}setBorderRadius(t){this.frameBorderRadius=t,"rounded-rect"===this.frameShape&&(this._updateClipPath(),this.set("dirty",!0))}add(){const t=super.add(...arguments);return this._restoreFixedDimensions(),t}remove(){const t=super.remove(...arguments);return this._restoreFixedDimensions(),t}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];const n=super.insertAt(t,...i);return this._restoreFixedDimensions(),n}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject(t),frameWidth:this.frameWidth,frameHeight:this.frameHeight,frameShape:this.frameShape,frameBorderRadius:this.frameBorderRadius,frameCustomPath:this.frameCustomPath,frameMeta:{...this.frameMeta},isEditMode:!1,placeholderText:this.placeholderText,placeholderColor:this.placeholderColor}}static fromObject(t,e){const{objects:i=[],layoutManager:s,frameWidth:n,frameHeight:r,frameShape:o,frameBorderRadius:a,frameCustomPath:h,frameMeta:l,placeholderText:c,placeholderColor:d,...u}=t;return Promise.all([enlivenObjects(i,e),enlivenObjectEnlivables(u,e)]).then(t=>{var e,i,s;let[g,f]=t;const p=new Frame([],{...u,...f,frameWidth:n,frameHeight:r,frameShape:o,frameBorderRadius:a,frameCustomPath:h,frameMeta:l?{contentScale:null!==(e=l.contentScale)&&void 0!==e?e:1,contentOffsetX:null!==(i=l.contentOffsetX)&&void 0!==i?i:0,contentOffsetY:null!==(s=l.contentOffsetY)&&void 0!==s?s:0,...l}:void 0,placeholderText:c,placeholderColor:d});return null!=l&&l.imageSrc&&p.setImage(l.imageSrc).then(()=>{var t,e,i,s;p._contentImage&&p._contentImage.set({left:null!==(t=l.contentOffsetX)&&void 0!==t?t:0,top:null!==(e=l.contentOffsetY)&&void 0!==e?e:0,scaleX:null!==(i=l.contentScale)&&void 0!==i?i:1,scaleY:null!==(s=l.contentScale)&&void 0!==s?s:1});p.set("dirty",!0)}).catch(t=>{console.warn("Failed to restore frame image:",t)}),p})}static createWithAspect(t){var e,i,s;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o,a;switch(t){case"16:9":o=n,a=n*(9/16);break;case"9:16":o=n*(9/16),a=n;break;case"4:5":o=.8*n,a=n;break;case"4:3":o=n,a=n*(3/4);break;case"3:4":o=n*(3/4),a=n;break;case"1:1":default:o=n,a=n;break}const h=zi.frameMeta||{};return new Frame([],{...r,frameWidth:o,frameHeight:a,frameMeta:{contentScale:null!==(e=h.contentScale)&&void 0!==e?e:1,contentOffsetX:null!==(i=h.contentOffsetX)&&void 0!==i?i:0,contentOffsetY:null!==(s=h.contentOffsetY)&&void 0!==s?s:0,aspect:t,...r.frameMeta}})}}_defineProperty(Frame,"type","Frame"),_defineProperty(Frame,"ownDefaults",zi),X.setClass(Frame),X.setClass(Frame,"frame");class ClipPathLayout extends LayoutStrategy{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:i}=t,{clipPath:s,group:n}=i;if(!s||!this.shouldPerformLayout(t))return;const{width:r,height:o}=makeBoundingBoxFromPoints(getObjectBounds(i,s)),a=new Point(r,o);if(s.absolutePositioned){const t=undefined;return{center:sendPointToPlane(s.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:a}}{const n=s.getRelativeCenterPoint().transform(i.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:i=new Point,correction:s=new Point}=this.calcBoundingBox(e,t)||{};return{center:i.add(n),correction:s.subtract(n),size:a}}return{center:i.getRelativeCenterPoint().add(n),size:a}}}}_defineProperty(ClipPathLayout,"type","clip-path"),X.setClass(ClipPathLayout);class FixedLayout extends LayoutStrategy{getInitialSize(t,e){let{target:i}=t,{size:s}=e;return new Point(i.width||s.x,i.height||s.y)}}_defineProperty(FixedLayout,"type","fixed"),X.setClass(FixedLayout);class ActiveSelectionLayoutManager extends LayoutManager{subscribeTargets(t){const e=t.target,i=undefined;t.targets.reduce((t,e)=>(e.parent&&t.add(e.parent),t),new Set).forEach(t=>{t.layoutManager.subscribeTargets({target:t,targets:[e]})})}unsubscribeTargets(t){const e=t.target,i=e.getObjects(),s=undefined;t.targets.reduce((t,e)=>(e.parent&&t.add(e.parent),t),new Set).forEach(t=>{!i.some(e=>e.parent===t)&&t.layoutManager.unsubscribeTargets({target:t,targets:[e]})})}}const Yi={multiSelectionStacking:"canvas-stacking"};class ActiveSelection extends Group{static getDefaults(){return{...super.getDefaults(),...ActiveSelection.ownDefaults}}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,ActiveSelection.ownDefaults),this.setOptions(e);const{left:i,top:s,layoutManager:n}=e;this.groupInit(t,{left:i,top:s,layoutManager:null!=n?n:new ActiveSelectionLayoutManager})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];"selection-order"===this.multiSelectionStacking?this.add(...e):e.forEach(t=>{const e=this._objects.findIndex(e=>e.isInFrontOf(t)),i=-1===e?this.size():e;this.insertAt(i,t)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(log("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 i=new Set;e.forEach(t=>{const{parent:e}=t;e&&i.add(e)}),t===Se?i.forEach(t=>{t._onAfterObjectsChange(be,e)}):i.forEach(t=>{t._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return`#<ActiveSelection: (${this.complexity()})>`}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const s={hasControls:!1,...i,forActiveSelection:!0};for(let e=0;e<this._objects.length;e++)this._objects[e]._renderControls(t,s);super._renderControls(t,e),t.restore()}}function applyViewboxTransform(t){if(!Ct.test(t.nodeName))return{};const e=t.getAttribute("viewBox");let i=1,s=1,n=0,r=0,o,a;const h=t.getAttribute("width"),l=t.getAttribute("height"),c=t.getAttribute("x")||0,d=t.getAttribute("y")||0,u=undefined,g=!(e&&St.test(e)),f=!h||!l||"100%"===h||"100%"===l;let p="",m=0,y=0;if(g&&(c||d)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(p=" translate("+parseUnit(c||"0")+" "+parseUnit(d||"0")+") ",o=(t.getAttribute("transform")||"")+p,t.setAttribute("transform",o),t.removeAttribute("x"),t.removeAttribute("y")),g&&f)return{width:0,height:0};const x={width:0,height:0};if(g)return x.width=parseUnit(h),x.height=parseUnit(l),x;const v=e.match(St);n=-parseFloat(v[1]),r=-parseFloat(v[2]);const C=parseFloat(v[3]),b=parseFloat(v[4]);x.minX=n,x.minY=r,x.viewBoxWidth=C,x.viewBoxHeight=b,f?(x.width=C,x.height=b):(x.width=parseUnit(h),x.height=parseUnit(l),i=x.width/C,s=x.height/b);const S=parsePreserveAspectRatioAttribute(t.getAttribute("preserveAspectRatio")||"");if(S.alignX!==_&&("meet"===S.meetOrSlice&&(s=i=i>s?s:i),"slice"===S.meetOrSlice&&(s=i=i>s?i:s),m=x.width-C*i,y=x.height-b*i,"Mid"===S.alignX&&(m/=2),"Mid"===S.alignY&&(y/=2),"Min"===S.alignX&&(m=0),"Min"===S.alignY&&(y=0)),1===i&&1===s&&0===n&&0===r&&0===c&&0===d)return x;if((c||d)&&"#document"!==t.parentNode.nodeName&&(p=" translate("+parseUnit(c||"0")+" "+parseUnit(d||"0")+") "),o=p+" matrix("+i+" 0 0 "+s+" "+(n*i+m)+" "+(r*s+y)+") ","svg"===t.nodeName){for(a=t.ownerDocument.createElementNS(dt,"g");t.firstChild;)a.appendChild(t.firstChild);t.appendChild(a)}else a=t,a.removeAttribute("x"),a.removeAttribute("y"),o=a.getAttribute("transform")+o;return a.setAttribute("transform",o),x}_defineProperty(ActiveSelection,"type","ActiveSelection"),_defineProperty(ActiveSelection,"ownDefaults",Yi),X.setClass(ActiveSelection),X.setClass(ActiveSelection,"activeSelection");const getTagName=t=>t.tagName.replace("svg:",""),Vi=getSvgRegex(pt);function hasInvalidAncestor(t){let e=t;for(;e&&(e=e.parentElement);)if(e&&e.nodeName&&Vi.test(getTagName(e))&&!e.getAttribute("instantiated_by_use"))return!0;return!1}function getMultipleNodes(t,e){let i,s=[],n,r,o;for(r=0,o=e.length;r<o;r++)i=e[r],n=t.getElementsByTagNameNS("http://www.w3.org/2000/svg",i),s=s.concat(Array.from(n));return s}function parseUseDirectives(t){const e=getMultipleNodes(t,["use","svg:use"]),i=["x","y","xlink:href","href","transform"];for(const s of e){const e=s.attributes,n={};for(const t of e)t.value&&(n[t.name]=t.value);const r=(n["xlink:href"]||n.href||"").slice(1);if(""===r)return;const o=t.getElementById(r);if(null===o)return;let a=o.cloneNode(!0);const h=a.attributes,l={};for(const t of h)t.value&&(l[t.name]=t.value);const{x:c=0,y:d=0,transform:u=""}=n,g=`${u} ${l.transform||""} translate(${c}, ${d})`;if(applyViewboxTransform(a),/^svg$/i.test(a.nodeName)){const t=a.ownerDocument.createElementNS(dt,"g");Object.entries(l).forEach(e=>{let[i,s]=e;return t.setAttributeNS(dt,i,s)}),t.append(...a.childNodes),a=t}for(const t of e){if(!t)continue;const{name:e,value:s}=t;if(!i.includes(e))if("style"===e){const t={};parseStyleString(s,t),Object.entries(l).forEach(e=>{let[i,s]=e;t[i]=s}),parseStyleString(l.style||"",t);const i=Object.entries(t).map(t=>t.join(":")).join(";");a.setAttribute(e,i)}else!l[e]&&a.setAttribute(e,s)}a.setAttribute("transform",g),a.setAttribute("instantiated_by_use","1"),a.removeAttribute("id"),s.parentNode.replaceChild(a,s)}}const Gi=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Ni="xlink:href";function recursivelyParseGradientsXlink(t,e){var i;const s=(null===(i=e.getAttribute(Ni))||void 0===i?void 0:i.slice(1))||"",n=t.getElementById(s);if(n&&n.getAttribute(Ni)&&recursivelyParseGradientsXlink(t,n),n&&(Gi.forEach(t=>{const i=n.getAttribute(t);!e.hasAttribute(t)&&i&&e.setAttribute(t,i)}),!e.children.length)){const t=n.cloneNode(!0);for(;t.firstChild;)e.appendChild(t.firstChild)}e.removeAttribute(Ni)}const Ui=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function getGradientDefs(t){const e=getMultipleNodes(t,Ui),i={};let s=e.length;for(;s--;){const n=e[s];n.getAttribute("xlink:href")&&recursivelyParseGradientsXlink(t,n);const r=n.getAttribute("id");r&&(i[r]=n)}return i}function getCSSRules(t){const e=t.getElementsByTagName("style"),i={};for(let t=0;t<e.length;t++){const s=(e[t].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");""!==s.trim()&&s.split("}").filter((t,e,i)=>i.length>1&&t.trim()).forEach(t=>{if((t.match(/{/g)||[]).length>1&&t.trim().startsWith("@"))return;const e=t.split("{"),s={},n=undefined,r=e[1].trim().split(";").filter(function(t){return t.trim()});for(let t=0;t<r.length;t++){const e=r[t].split(":"),i=e[0].trim(),n=e[1].trim();s[i]=n}(t=e[0].trim()).split(",").forEach(t=>{""!==(t=t.replace(/^svg/i,"").trim())&&(i[t]={...i[t]||{},...s})})})}return i}const findTag=t=>X.getSVGClass(getTagName(t).toLowerCase());class ElementsParser{constructor(t,e,i,s,n){this.elements=t,this.options=e,this.reviver=i,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=s,this.clipPaths=n,this.gradientDefs=getGradientDefs(s),this.cssRules=getCSSRules(s)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=findTag(t);if(e){const i=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(i,t,I),this.resolveGradient(i,t,B),i instanceof FabricImage&&i._originalElement?removeTransformMatrixForSvgParsing(i,i.parsePreserveAspectRatioAttribute()):removeTransformMatrixForSvgParsing(i),await this.resolveClipPath(i,t),this.reviver&&this.reviver(t,i),i}return null}extractPropertyDefinition(t,e,i){const s=t[e],n=this.regexUrl;if(!n.test(s))return;n.lastIndex=0;const r=n.exec(s)[1];return n.lastIndex=0,i[r]}resolveGradient(t,e,i){const s=this.extractPropertyDefinition(t,i,this.gradientDefs);if(s){const n=e.getAttribute(i+"-opacity"),r=Gradient.fromElement(s,t,{...this.options,opacity:n});t.set(i,r)}}async resolveClipPath(t,e,i){const s=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(s){const n=invertTransform(t.calcTransformMatrix()),r=s[0].parentElement;let o=e;for(;!i&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const a=parseTransformAttribute(`${o.getAttribute("transform")||""} ${r.getAttribute("originalTransform")||""}`);r.setAttribute("transform",`matrix(${a.join(",")})`);const h=await Promise.all(s.map(t=>findTag(t).fromElement(t,this.options,this.cssRules).then(t=>(removeTransformMatrixForSvgParsing(t),t.fillRule=t.clipRule,delete t.clipRule,t)))),l=1===h.length?h[0]:new Group(h),c=multiplyTransformMatrices(n,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:d,scaleY:u,angle:g,skewX:f,translateX:m,translateY:y}=qrDecompose(c);l.set({flipX:!1,flipY:!1}),l.set({scaleX:d,scaleY:u,angle:g,skewX:f,skewY:0}),l.setPositionByOrigin(new Point(m,y),p,p),t.clipPath=l}else delete t.clipPath}}const isValidSvgTag=t=>_t.test(getTagName(t)),createEmptyResponse=()=>({objects:[],elements:[],options:{},allElements:[]});async function parseSVGDocument(t,e){let{crossOrigin:i,signal:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(s&&s.aborted)return log("log",new SignalAbortedError("parseSVGDocument")),{objects:[],elements:[],options:{},allElements:[]};const n=t.documentElement;parseUseDirectives(t);const r=Array.from(n.getElementsByTagName("*")),o={...applyViewboxTransform(n),crossOrigin:i,signal:s},a=r.filter(t=>(applyViewboxTransform(t),isValidSvgTag(t)&&!hasInvalidAncestor(t)));if(!a||a&&!a.length)return{objects:[],elements:[],options:{},allElements:[],options:o,allElements:r};const h={};r.filter(t=>"clipPath"===getTagName(t)).forEach(t=>{t.setAttribute("originalTransform",t.getAttribute("transform")||"");const e=t.getAttribute("id");h[e]=Array.from(t.getElementsByTagName("*")).filter(t=>isValidSvgTag(t))});const l=new ElementsParser(a,o,e,t,h),c=undefined;return{objects:await l.parse(),elements:a,options:o,allElements:r}}function loadSVGFromString(t,e,i){const s=undefined,n=undefined;return parseSVGDocument((new(getFabricWindow().DOMParser)).parseFromString(t.trim(),"text/xml"),e,i)}function loadSVGFromURL(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return fetch(t.replace(/^\n\s*/,"").trim(),{signal:i.signal}).then(t=>{if(!t.ok)throw new FabricError(`HTTP error! status: ${t.status}`);return t.text()}).then(t=>loadSVGFromString(t,e,i)).catch(()=>({objects:[],elements:[],options:{},allElements:[]}))}const qi=O,createPolyPositionHandler=t=>function(e,i,s){const{points:n,pathOffset:r}=s;return new Point(n[t]).subtract(r).transform(multiplyTransformMatrices(s.getViewportTransform(),s.calcTransformMatrix()))},polyActionHandler=(t,e,i,s)=>{const{target:n,pointIndex:r}=e,o=n,a=sendPointToPlane(new Point(i,s),void 0,o.calcOwnMatrix());return o.points[r]=a.add(o.pathOffset),o.setDimensions(),o.set("dirty",!0),!0},factoryPolyActionHandler=(t,e)=>function(i,s,n,r){const o=s.target,a=new Point(o.points[(t>0?t:o.points.length)-1]),h=a.subtract(o.pathOffset).transform(o.calcOwnMatrix()),l=e(i,{...s,pointIndex:t},n,r),c=undefined,d=a.subtract(o.pathOffset).transform(o.calcOwnMatrix()).subtract(h);return o.left-=d.x,o.top-=d.y,l},createPolyActionHandler=t=>wrapWithFireEvent(qi,factoryPolyActionHandler(t,polyActionHandler));function createPolyControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i={};for(let s=0;s<("number"==typeof t?t:t.points.length);s++)i[`p${s}`]=new Control({actionName:qi,positionHandler:createPolyPositionHandler(s),actionHandler:createPolyActionHandler(s),...e});return i}const Ki="modifyPath",calcPathPointPosition=(t,e,i)=>{const{path:s,pathOffset:n}=t,r=s[e];return new Point(r[i]-n.x,r[i+1]-n.y).transform(multiplyTransformMatrices(t.getViewportTransform(),t.calcTransformMatrix()))},movePathPoint=(t,e,i,s,n)=>{const{path:r,pathOffset:o}=t,a=r[(s>0?s:r.length)-1],h=new Point(a[n],a[n+1]),l=h.subtract(o).transform(t.calcOwnMatrix()),c=sendPointToPlane(new Point(e,i),void 0,t.calcOwnMatrix());r[s][n]=c.x+o.x,r[s][n+1]=c.y+o.y,t.setDimensions();const d=undefined,u=h.subtract(t.pathOffset).transform(t.calcOwnMatrix()).subtract(l);return t.left-=u.x,t.top-=u.y,t.set("dirty",!0),!0};function pathPositionHandler(t,e,i){const{commandIndex:s,pointIndex:n}=this;return calcPathPointPosition(i,s,n)}function pathActionHandler(t,e,i,s){const{target:n}=e,{commandIndex:r,pointIndex:o}=this,a=movePathPoint(n,i,s,r,o);return fireEvent(this.actionName,{...commonEventInfo(t,e,i,s),commandIndex:r,pointIndex:o}),a}const indexFromPrevCommand=t=>"C"===t?5:"Q"===t?3:1;class PathPointControl extends Control{constructor(t){super(t)}render(t,e,i,s,n){const r={...s,cornerColor:this.controlFill,cornerStrokeColor:this.controlStroke,transparentCorners:!this.controlFill};super.render(t,e,i,r,n)}}class PathControlPointControl extends PathPointControl{constructor(t){super(t)}render(t,e,i,s,n){const{path:r}=n,{commandIndex:o,pointIndex:a,connectToCommandIndex:h,connectToPointIndex:l}=this;t.save(),t.strokeStyle=this.controlStroke,this.connectionDashArray&&t.setLineDash(this.connectionDashArray);const[c]=r[o],d=calcPathPointPosition(n,h,l);if("Q"===c){const s=calcPathPointPosition(n,o,a+2);t.moveTo(s.x,s.y),t.lineTo(e,i)}else t.moveTo(e,i);t.lineTo(d.x,d.y),t.stroke(),t.restore(),super.render(t,e,i,s,n)}}const createControl=(t,e,i,s,n,r)=>new(i?PathControlPointControl:PathPointControl)({commandIndex:t,pointIndex:e,actionName:Ki,positionHandler:pathPositionHandler,actionHandler:pathActionHandler,connectToCommandIndex:n,connectToPointIndex:r,...s,...i?s.controlPointStyle:s.pointStyle});function createPathControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i={};let s="M";return t.path.forEach((t,n)=>{const r=t[0];switch("Z"!==r&&(i[`c_${n}_${r}`]=createControl(n,t.length-2,!1,e)),r){case"C":i[`c_${n}_C_CP_1`]=createControl(n,1,!0,e,n-1,indexFromPrevCommand(s)),i[`c_${n}_C_CP_2`]=createControl(n,3,!0,e,n,5);break;case"Q":i[`c_${n}_Q_CP_1`]=createControl(n,1,!0,e,n,3);break}s=r}),i}var Ji=Object.freeze({__proto__:null,EXPAND_HANDLE_FILL:Vt,EXPAND_HANDLE_STROKE:Gt,EXPAND_PREVIEW_DASH:qt,EXPAND_PREVIEW_FILL:Nt,EXPAND_PREVIEW_STROKE:Ut,ExpandControl:ExpandControl,changeWidth:Ft,createDefaultExpansion:createDefaultExpansion,createExpandControls:createExpandControls,createImageCropControls:createImageCropControls,createImageCropModeControls:createImageCropModeControls,createObjectDefaultControls:createObjectDefaultControls,createPathControls:createPathControls,createPolyActionHandler:createPolyActionHandler,createPolyControls:createPolyControls,createPolyPositionHandler:createPolyPositionHandler,createResizeControls:createResizeControls,createTextboxDefaultControls:createTextboxDefaultControls,cropFromBottom:Li,cropFromBottomLeft:Ri,cropFromBottomRight:Wi,cropFromLeft:Fi,cropFromRight:Ai,cropFromTop:ji,cropFromTopLeft:Ii,cropFromTopRight:Bi,dragHandler:dragHandler,expandBottomHandler:expandBottomHandler,expandLeftHandler:expandLeftHandler,expandRightHandler:expandRightHandler,expandTopHandler:expandTopHandler,factoryPolyActionHandler:factoryPolyActionHandler,getExpansion:getExpansion,getLocalPoint:getLocalPoint,polyActionHandler:polyActionHandler,renderCircleControl:renderCircleControl,renderSquareControl:renderSquareControl,rotationStyleHandler:rotationStyleHandler,rotationWithSnapping:Rt,scaleCursorStyleHandler:scaleCursorStyleHandler,scaleOrSkewActionName:scaleOrSkewActionName,scaleSkewCursorStyleHandler:scaleSkewCursorStyleHandler,scalingEqually:Ht,scalingX:Xt,scalingXOrSkewingY:scalingXOrSkewingY,scalingY:$t,scalingYOrSkewingX:scalingYOrSkewingX,setExpansion:setExpansion,skewCursorStyleHandler:skewCursorStyleHandler,skewHandlerX:skewHandlerX,skewHandlerY:skewHandlerY,wrapWithFireEvent:wrapWithFireEvent,wrapWithFixedAnchor:wrapWithFixedAnchor});const isWebGLPipelineState=t=>void 0!==t.webgl,isPutImageFaster=(t,e)=>{const i=createCanvasElementFor({width:t,height:e}),s=undefined,n=createCanvasElement().getContext("webgl"),r=undefined,o={imageBuffer:new ArrayBuffer(t*e*4)},a={destinationWidth:t,destinationHeight:e,targetCanvas:i};let h;h=getFabricWindow().performance.now(),WebGLFilterBackend.prototype.copyGLTo2D.call(o,n,a);const l=getFabricWindow().performance.now()-h;h=getFabricWindow().performance.now(),WebGLFilterBackend.prototype.copyGLTo2DPutImageData.call(o,n,a);const c=undefined;return l>getFabricWindow().performance.now()-h},Zi="precision highp float",Qi=`\n ${Zi};\n varying vec2 vTexCoord;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n }`,ts="\n attribute vec2 aPosition;\n varying vec2 vTexCoord;\n void main() {\n vTexCoord = aPosition;\n gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n }",es=new RegExp(Zi,"g");class BaseFilter{get type(){return this.constructor.type}constructor(){let{type:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,this.constructor.defaults,e)}getFragmentSource(){return Qi}getVertexSource(){return ts}createProgram(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.getFragmentSource(),i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:s="highp"}}=getEnv();"highp"!==s&&(e=e.replace(es,Zi.replace("highp",s)));const n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER),o=t.createProgram();if(!n||!r||!o)throw new FabricError("Vertex, fragment shader or program creation error");if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new FabricError(`Vertex shader compile error for ${this.type}: ${t.getShaderInfoLog(n)}`);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new FabricError(`Fragment shader compile error for ${this.type}: ${t.getShaderInfoLog(r)}`);if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new FabricError(`Shader link error for "${this.type}" ${t.getProgramInfoLog(o)}`);const a=this.getUniformLocations(t,o)||{};return a.uStepW=t.getUniformLocation(o,"uStepW"),a.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:a}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const i=this.constructor.uniformLocations,s={};for(let n=0;n<i.length;n++)s[i[n]]=t.getUniformLocation(e,i[n]);return s}sendAttributeData(t,e,i){const s=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(s),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const i=t.destinationWidth,s=t.destinationHeight;t.sourceWidth===i&&t.sourceHeight===s||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,i,s)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){isWebGLPipelineState(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,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const{sourceWidth:e,sourceHeight:i}=t,s=createCanvasElementFor({width:e,height:i});t.helpLayer=s}}toObject(){const t=Object.keys(this.constructor.defaults||{});return{type:this.type,...t.reduce((t,e)=>(t[e]=this[e],t),{})}}toJSON(){return this.toObject()}static async fromObject(t,e){let{type:i,...s}=t;return new this(s)}}_defineProperty(BaseFilter,"type","BaseFilter"),_defineProperty(BaseFilter,"uniformLocations",[]);const is={multiply:"gl_FragColor.rgb *= uColor.rgb;\n",screen:"gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",add:"gl_FragColor.rgb += uColor.rgb;\n",difference:"gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",subtract:"gl_FragColor.rgb -= uColor.rgb;\n",lighten:"gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",darken:"gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",exclusion:"gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",overlay:"\n if (uColor.r < 0.5) {\n gl_FragColor.r *= 2.0 * uColor.r;\n } else {\n gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n }\n if (uColor.g < 0.5) {\n gl_FragColor.g *= 2.0 * uColor.g;\n } else {\n gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n }\n if (uColor.b < 0.5) {\n gl_FragColor.b *= 2.0 * uColor.b;\n } else {\n gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n }\n ",tint:"\n gl_FragColor.rgb *= (1.0 - uColor.a);\n gl_FragColor.rgb += uColor.rgb;\n "},ss={color:"#F95C63",mode:"multiply",alpha:1};class BlendColor extends BaseFilter{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n gl_FragColor = color;\n if (color.a > 0.0) {\n ${is[this.mode]}\n }\n }\n `}applyTo2d(t){let{imageData:{data:e}}=t;const i=new Color(this.color).getSource(),s=this.alpha,n=i[0]*s,r=i[1]*s,o=i[2]*s,a=1-s;for(let t=0;t<e.length;t+=4){const i=e[t],s=e[t+1],h=e[t+2];let l,c,d;switch(this.mode){case"multiply":l=i*n/255,c=s*r/255,d=h*o/255;break;case"screen":l=255-(255-i)*(255-n)/255,c=255-(255-s)*(255-r)/255,d=255-(255-h)*(255-o)/255;break;case"add":l=i+n,c=s+r,d=h+o;break;case"difference":l=Math.abs(i-n),c=Math.abs(s-r),d=Math.abs(h-o);break;case"subtract":l=i-n,c=s-r,d=h-o;break;case"darken":l=Math.min(i,n),c=Math.min(s,r),d=Math.min(h,o);break;case"lighten":l=Math.max(i,n),c=Math.max(s,r),d=Math.max(h,o);break;case"overlay":l=n<128?2*i*n/255:255-2*(255-i)*(255-n)/255,c=r<128?2*s*r/255:255-2*(255-s)*(255-r)/255,d=o<128?2*h*o/255:255-2*(255-h)*(255-o)/255;break;case"exclusion":l=n+i-2*n*i/255,c=r+s-2*r*s/255,d=o+h-2*o*h/255;break;case"tint":l=n+i*a,c=r+s*a,d=o+h*a}e[t]=l,e[t+1]=c,e[t+2]=d}}sendUniformData(t,e){const i=new Color(this.color).getSource();i[0]=this.alpha*i[0]/255,i[1]=this.alpha*i[1]/255,i[2]=this.alpha*i[2]/255,i[3]=this.alpha,t.uniform4fv(e.uColor,i)}}_defineProperty(BlendColor,"defaults",ss),_defineProperty(BlendColor,"type","BlendColor"),_defineProperty(BlendColor,"uniformLocations",["uColor"]),X.setClass(BlendColor);const ns={multiply:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform sampler2D uImage;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec4 color2 = texture2D(uImage, vTexCoord2);\n color.rgba *= color2.rgba;\n gl_FragColor = color;\n }\n ",mask:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform sampler2D uImage;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec4 color2 = texture2D(uImage, vTexCoord2);\n color.a = color2.a;\n gl_FragColor = color;\n }\n "},rs="\n attribute vec2 aPosition;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n uniform mat3 uTransformMatrix;\n void main() {\n vTexCoord = aPosition;\n vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\n gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n }\n ",os={mode:"multiply",alpha:1};class BlendImage extends BaseFilter{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return ns[this.mode]}getVertexSource(){return rs}applyToWebGL(t){const e=t.context,i=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,i,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:i}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/i,1]}applyTo2d(t){let{imageData:{data:e,width:i,height:s},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=createCanvasElement());const o=n.blendImage,a=o.getContext("2d");o.width!==i||o.height!==s?(o.width=i,o.height=s):a.clearRect(0,0,i,s),a.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),a.drawImage(r.getElement(),0,0,i,s);const h=a.getImageData(0,0,i,s).data;for(let t=0;t<e.length;t+=4){const i=e[t],s=e[t+1],n=e[t+2],r=e[t+3],o=h[t],a=h[t+1],l=h[t+2],c=h[t+3];switch(this.mode){case"multiply":e[t]=i*o/255,e[t+1]=s*a/255,e[t+2]=n*l/255,e[t+3]=r*c/255;break;case"mask":e[t+3]=c;break}}}sendUniformData(t,e){const i=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,i)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject(t,e){let{type:i,image:s,...n}=t;return FabricImage.fromObject(s,e).then(t=>new this({...n,image:t}))}}_defineProperty(BlendImage,"type","BlendImage"),_defineProperty(BlendImage,"defaults",os),_defineProperty(BlendImage,"uniformLocations",["uTransformMatrix","uImage"]),X.setClass(BlendImage);const as="\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n const float nSamples = 15.0;\n vec3 v3offset = vec3(12.9898, 78.233, 151.7182);\n float random(vec3 scale) {\n /* use the fragment position for a different seed per-pixel */\n return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n }\n void main() {\n vec4 color = vec4(0.0);\n float totalC = 0.0;\n float totalA = 0.0;\n float offset = random(v3offset);\n for (float t = -nSamples; t <= nSamples; t++) {\n float percent = (t + offset - 0.5) / nSamples;\n vec4 sample = texture2D(uTexture, vTexCoord + uDelta * percent);\n float weight = 1.0 - abs(percent);\n float alpha = weight * sample.a;\n color.rgb += sample.rgb * alpha;\n color.a += alpha;\n totalA += weight;\n totalC += alpha;\n }\n gl_FragColor.rgb = color.rgb / totalC;\n gl_FragColor.a = color.a / totalA;\n }\n ",hs={blur:0};class Blur extends BaseFilter{getFragmentSource(){return as}applyTo(t){isWebGLPipelineState(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:i,height:s}}=t;this.aspectRatio=i/s,this.horizontal=!0;let n=this.getBlurValue()*i;const r=new Uint8ClampedArray(e),o=15,a=4*i;for(let t=0;t<e.length;t+=4){let i=0,s=0,h=0,l=0,c=0;const d=t-t%a,u=d+a;for(let r=-14;r<o;r++){const a=r/o,g=4*Math.floor(n*a),f=1-Math.abs(a);let p=t+g;p<d?p=d:p>u&&(p=u);const m=e[p+3]*f;i+=e[p]*m,s+=e[p+1]*m,h+=e[p+2]*m,l+=m,c+=f}r[t]=i/l,r[t+1]=s/l,r[t+2]=h/l,r[t+3]=l/c}this.horizontal=!1,n=this.getBlurValue()*s;for(let t=0;t<r.length;t+=4){let i=0,s=0,h=0,l=0,c=0;const d=t%a,u=r.length-a+d;for(let e=-14;e<o;e++){const g=e/o,f=Math.floor(n*g)*a,p=1-Math.abs(g);let m=t+f;m<d?m=d:m>u&&(m=u);const y=r[m+3]*p;i+=r[m]*y,s+=r[m+1]*y,h+=r[m+2]*y,l+=y,c+=p}e[t]=i/l,e[t+1]=s/l,e[t+2]=h/l,e[t+3]=l/c}}sendUniformData(t,e){const i=this.chooseRightDelta();t.uniform2fv(e.uDelta,i)}isNeutralState(){return 0===this.blur}getBlurValue(){let t=1;const{horizontal:e,aspectRatio:i}=this;return e?i>1&&(t=1/i):i<1&&(t=i),t*this.blur*.12}chooseRightDelta(){const t=this.getBlurValue();return this.horizontal?[t,0]:[0,t]}}_defineProperty(Blur,"type","Blur"),_defineProperty(Blur,"defaults",hs),_defineProperty(Blur,"uniformLocations",["uDelta"]),X.setClass(Blur);const ls="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uBrightness;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color.rgb += uBrightness;\n gl_FragColor = color;\n }\n",cs={brightness:0};class Brightness extends BaseFilter{getFragmentSource(){return ls}applyTo2d(t){let{imageData:{data:e}}=t;const i=Math.round(255*this.brightness);for(let t=0;t<e.length;t+=4)e[t]+=i,e[t+1]+=i,e[t+2]+=i}isNeutralState(){return 0===this.brightness}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}_defineProperty(Brightness,"type","Brightness"),_defineProperty(Brightness,"defaults",cs),_defineProperty(Brightness,"uniformLocations",["uBrightness"]),X.setClass(Brightness);const ds="\n precision highp float;\n uniform sampler2D uTexture;\n varying vec2 vTexCoord;\n uniform mat4 uColorMatrix;\n uniform vec4 uConstants;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color *= uColorMatrix;\n color += uConstants;\n gl_FragColor = color;\n }",us={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class ColorMatrix extends BaseFilter{getFragmentSource(){return ds}applyTo2d(t){const e=undefined,i=t.imageData.data,s=this.matrix,n=this.colorsOnly;for(let t=0;t<i.length;t+=4){const e=i[t],r=i[t+1],o=i[t+2];if(i[t]=e*s[0]+r*s[1]+o*s[2]+255*s[4],i[t+1]=e*s[5]+r*s[6]+o*s[7]+255*s[9],i[t+2]=e*s[10]+r*s[11]+o*s[12]+255*s[14],!n){const n=i[t+3];i[t]+=n*s[3],i[t+1]+=n*s[8],i[t+2]+=n*s[13],i[t+3]=e*s[15]+r*s[16]+o*s[17]+n*s[18]+255*s[19]}}}sendUniformData(t,e){const i=this.matrix,s=[i[0],i[1],i[2],i[3],i[5],i[6],i[7],i[8],i[10],i[11],i[12],i[13],i[15],i[16],i[17],i[18]],n=[i[4],i[9],i[14],i[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,s),t.uniform4fv(e.uConstants,n)}toObject(){return{...super.toObject(),matrix:[...this.matrix]}}}function createColorMatrixFilter(t,e){var i;const s=(_defineProperty(i=class newClass extends ColorMatrix{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",t),_defineProperty(i,"defaults",{colorsOnly:!1,matrix:e}),i);return X.setClass(s,t),s}_defineProperty(ColorMatrix,"type","ColorMatrix"),_defineProperty(ColorMatrix,"defaults",us),_defineProperty(ColorMatrix,"uniformLocations",["uColorMatrix","uConstants"]),X.setClass(ColorMatrix);const gs=createColorMatrixFilter("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),fs=createColorMatrixFilter("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),ps=createColorMatrixFilter("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),ms=createColorMatrixFilter("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),ys=createColorMatrixFilter("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),xs=createColorMatrixFilter("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),vs=createColorMatrixFilter("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 Composed extends BaseFilter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){isWebGLPipelineState(t)&&(t.passes+=this.subFilters.length-1),this.subFilters.forEach(e=>{e.applyTo(t)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(t=>t.toObject())}}isNeutralState(){return!this.subFilters.some(t=>!t.isNeutralState())}static fromObject(t,e){return Promise.all((t.subFilters||[]).map(t=>X.getClass(t.type).fromObject(t,e))).then(t=>new this({subFilters:t}))}}_defineProperty(Composed,"type","Composed"),X.setClass(Composed);const _s="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uContrast;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\n color.rgb = contrastF * (color.rgb - 0.5) + 0.5;\n gl_FragColor = color;\n }",Cs={contrast:0};class Contrast extends BaseFilter{getFragmentSource(){return _s}isNeutralState(){return 0===this.contrast}applyTo2d(t){let{imageData:{data:e}}=t;const i=Math.floor(255*this.contrast),s=259*(i+255)/(255*(259-i));for(let t=0;t<e.length;t+=4)e[t]=s*(e[t]-128)+128,e[t+1]=s*(e[t+1]-128)+128,e[t+2]=s*(e[t+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}_defineProperty(Contrast,"type","Contrast"),_defineProperty(Contrast,"defaults",Cs),_defineProperty(Contrast,"uniformLocations",["uContrast"]),X.setClass(Contrast);const bs={Convolute_3_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[9];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 3.0; h+=1.0) {\n for (float w = 0.0; w < 3.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_3_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[9];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 3.0; h+=1.0) {\n for (float w = 0.0; w < 3.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_5_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[25];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 5.0; h+=1.0) {\n for (float w = 0.0; w < 5.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_5_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[25];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 5.0; h+=1.0) {\n for (float w = 0.0; w < 5.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_7_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[49];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 7.0; h+=1.0) {\n for (float w = 0.0; w < 7.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_7_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[49];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 7.0; h+=1.0) {\n for (float w = 0.0; w < 7.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_9_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[81];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 9.0; h+=1.0) {\n for (float w = 0.0; w < 9.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_9_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[81];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 9.0; h+=1.0) {\n for (float w = 0.0; w < 9.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n "},Ss={opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]};class Convolute extends BaseFilter{getCacheKey(){return`${this.type}_${Math.sqrt(this.matrix.length)}_${this.opaque?1:0}`}getFragmentSource(){return bs[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,i=e.data,s=this.matrix,n=Math.round(Math.sqrt(s.length)),r=Math.floor(n/2),o=e.width,a=e.height,h=t.ctx.createImageData(o,a),l=h.data,c=this.opaque?1:0;let d,u,g,f,p,m,y,x,v,_,C,b,S;for(C=0;C<a;C++)for(_=0;_<o;_++){for(p=4*(C*o+_),d=0,u=0,g=0,f=0,S=0;S<n;S++)for(b=0;b<n;b++)y=C+S-r,m=_+b-r,y<0||y>=a||m<0||m>=o||(x=4*(y*o+m),v=s[S*n+b],d+=i[x]*v,u+=i[x+1]*v,g+=i[x+2]*v,c||(f+=i[x+3]*v));l[p]=d,l[p+1]=u,l[p+2]=g,l[p+3]=c?i[p+3]:f}t.imageData=h}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return{...super.toObject(),opaque:this.opaque,matrix:[...this.matrix]}}}_defineProperty(Convolute,"type","Convolute"),_defineProperty(Convolute,"defaults",Ss),_defineProperty(Convolute,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),X.setClass(Convolute);const ws="\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec3 uGamma;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec3 correction = (1.0 / uGamma);\n color.r = pow(color.r, correction.r);\n color.g = pow(color.g, correction.g);\n color.b = pow(color.b, correction.b);\n gl_FragColor = color;\n gl_FragColor.rgb *= color.a;\n }\n",Ts="Gamma",Ps={gamma:[1,1,1]};class Gamma extends BaseFilter{getFragmentSource(){return ws}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const i=this.gamma,s=1/i[0],n=1/i[1],r=1/i[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const o=this.rgbValues;for(let t=0;t<256;t++)o.r[t]=255*Math.pow(t/255,s),o.g[t]=255*Math.pow(t/255,n),o.b[t]=255*Math.pow(t/255,r);for(let t=0;t<e.length;t+=4)e[t]=o.r[e[t]],e[t+1]=o.g[e[t+1]],e[t+2]=o.b[e[t+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return 1===t[0]&&1===t[1]&&1===t[2]}toObject(){return{type:Ts,gamma:this.gamma.concat()}}}_defineProperty(Gamma,"type",Ts),_defineProperty(Gamma,"defaults",Ps),_defineProperty(Gamma,"uniformLocations",["uGamma"]),X.setClass(Gamma);const Ms={average:"\n precision highp float;\n uniform sampler2D uTexture;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float average = (color.r + color.b + color.g) / 3.0;\n gl_FragColor = vec4(average, average, average, color.a);\n }\n ",lightness:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uMode;\n varying vec2 vTexCoord;\n void main() {\n vec4 col = texture2D(uTexture, vTexCoord);\n float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\n gl_FragColor = vec4(average, average, average, col.a);\n }\n ",luminosity:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uMode;\n varying vec2 vTexCoord;\n void main() {\n vec4 col = texture2D(uTexture, vTexCoord);\n float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\n gl_FragColor = vec4(average, average, average, col.a);\n }\n "},Os={mode:"average"};class Grayscale extends BaseFilter{applyTo2d(t){let{imageData:{data:e}}=t;for(let t=0,i;t<e.length;t+=4){const s=e[t],n=e[t+1],r=e[t+2];switch(this.mode){case"average":i=(s+n+r)/3;break;case"lightness":i=(Math.min(s,n,r)+Math.max(s,n,r))/2;break;case"luminosity":i=.21*s+.72*n+.07*r;break}e[t+2]=e[t+1]=e[t]=i}}getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Ms[this.mode]}sendUniformData(t,e){const i=1;t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}_defineProperty(Grayscale,"type","Grayscale"),_defineProperty(Grayscale,"defaults",Os),_defineProperty(Grayscale,"uniformLocations",["uMode"]),X.setClass(Grayscale);const ks={...us,rotation:0};class HueRotation extends ColorMatrix{calculateMatrix(){const t=this.rotation*Math.PI,e=cos(t),i=sin(t),s=1/3,n=Math.sqrt(s)*i,r=1-e;this.matrix=[e+r/3,s*r-n,s*r+n,0,0,s*r+n,e+s*r,s*r-n,0,0,s*r-n,s*r+n,e+s*r,0,0,0,0,0,1,0]}isNeutralState(){return 0===this.rotation}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}_defineProperty(HueRotation,"type","HueRotation"),_defineProperty(HueRotation,"defaults",ks),X.setClass(HueRotation);const Ds="\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uInvert;\n uniform int uAlpha;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n if (uInvert == 1) {\n if (uAlpha == 1) {\n gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,1.0 -color.a);\n } else {\n gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n }\n } else {\n gl_FragColor = color;\n }\n }\n",Es={alpha:!1,invert:!0};class Invert extends BaseFilter{applyTo2d(t){let{imageData:{data:e}}=t;for(let t=0;t<e.length;t+=4)e[t]=255-e[t],e[t+1]=255-e[t+1],e[t+2]=255-e[t+2],this.alpha&&(e[t+3]=255-e[t+3])}getFragmentSource(){return Ds}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}_defineProperty(Invert,"type","Invert"),_defineProperty(Invert,"defaults",Es),_defineProperty(Invert,"uniformLocations",["uInvert","uAlpha"]),X.setClass(Invert);const As="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uStepH;\n uniform float uNoise;\n uniform float uSeed;\n varying vec2 vTexCoord;\n float rand(vec2 co, float seed, float vScale) {\n return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n }\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\n gl_FragColor = color;\n }\n",Fs={noise:0};class Noise extends BaseFilter{getFragmentSource(){return As}applyTo2d(t){let{imageData:{data:e}}=t;const i=this.noise;for(let t=0;t<e.length;t+=4){const s=(.5-Math.random())*i;e[t]+=s,e[t+1]+=s,e[t+2]+=s}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return 0===this.noise}}_defineProperty(Noise,"type","Noise"),_defineProperty(Noise,"defaults",Fs),_defineProperty(Noise,"uniformLocations",["uNoise","uSeed"]),X.setClass(Noise);const Ls="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uBlocksize;\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n float blockW = uBlocksize * uStepW;\n float blockH = uBlocksize * uStepH;\n int posX = int(vTexCoord.x / blockW);\n int posY = int(vTexCoord.y / blockH);\n float fposX = float(posX);\n float fposY = float(posY);\n vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\n vec4 color = texture2D(uTexture, squareCoords);\n gl_FragColor = color;\n }\n",js={blocksize:4};class Pixelate extends BaseFilter{applyTo2d(t){let{imageData:{data:e,width:i,height:s}}=t;for(let t=0;t<s;t+=this.blocksize)for(let n=0;n<i;n+=this.blocksize){const r=4*t*i+4*n,o=e[r],a=e[r+1],h=e[r+2],l=e[r+3];for(let r=t;r<Math.min(t+this.blocksize,s);r++)for(let t=n;t<Math.min(n+this.blocksize,i);t++){const s=4*r*i+4*t;e[s]=o,e[s+1]=a,e[s+2]=h,e[s+3]=l}}}isNeutralState(){return 1===this.blocksize}getFragmentSource(){return Ls}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}_defineProperty(Pixelate,"type","Pixelate"),_defineProperty(Pixelate,"defaults",js),_defineProperty(Pixelate,"uniformLocations",["uBlocksize"]),X.setClass(Pixelate);const Is="\nprecision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\n gl_FragColor.a = 0.0;\n }\n}\n",Bs={color:"#FFFFFF",distance:.02,useAlpha:!1};class RemoveColor extends BaseFilter{getFragmentSource(){return Is}applyTo2d(t){let{imageData:{data:e}}=t;const i=255*this.distance,s=new Color(this.color).getSource(),n=[s[0]-i,s[1]-i,s[2]-i],r=[s[0]+i,s[1]+i,s[2]+i];for(let t=0;t<e.length;t+=4){const i=e[t],s=e[t+1],o=e[t+2];i>n[0]&&s>n[1]&&o>n[2]&&i<r[0]&&s<r[1]&&o<r[2]&&(e[t+3]=0)}}sendUniformData(t,e){const i=new Color(this.color).getSource(),s=this.distance,n=[0+i[0]/255-s,0+i[1]/255-s,0+i[2]/255-s,1],r=[i[0]/255+s,i[1]/255+s,i[2]/255+s,1];t.uniform4fv(e.uLow,n),t.uniform4fv(e.uHigh,r)}}_defineProperty(RemoveColor,"type","RemoveColor"),_defineProperty(RemoveColor,"defaults",Bs),_defineProperty(RemoveColor,"uniformLocations",["uLow","uHigh"]),X.setClass(RemoveColor);const Rs={resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3};class Resize extends BaseFilter{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,i=this.getFilterWindow(),s=new Array(i);for(let n=1;n<=i;n++)s[n-1]=t(n*e);return s}generateShader(t){const e=new Array(t);for(let i=1;i<=t;i++)e[i-1]=`${i}.0 * uDelta`;return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n uniform float uTaps[${t}];\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float sum = 1.0;\n ${e.map((t,e)=>`\n color += texture2D(uTexture, vTexCoord + ${t}) * uTaps[${e}] + texture2D(uTexture, vTexCoord - ${t}) * uTaps[${e}];\n sum += 2.0 * uTaps[${e}];\n `).join("\n")}\n gl_FragColor = color / sum;\n }\n `}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){isWebGLPipelineState(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return 1===this.scaleX&&1===this.scaleY}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;const i=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(i)/i}}applyTo2d(t){const e=t.imageData,i=this.scaleX,s=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/s;const n=e.width,r=e.height,o=Math.round(n*i),a=Math.round(r*s);let h;h="sliceHack"===this.resizeType?this.sliceByTwo(t,n,r,o,a):"hermite"===this.resizeType?this.hermiteFastResize(t,n,r,o,a):"bilinear"===this.resizeType?this.bilinearFiltering(t,n,r,o,a):"lanczos"===this.resizeType?this.lanczosResize(t,n,r,o,a):new ImageData(o,a),t.imageData=h}sliceByTwo(t,e,i,s,n){const r=t.imageData,o=.5;let a=!1,h=!1,l=e*o,c=i*o;const d=t.filterBackend.resources;let u=0,g=0;const f=e;let p=0;d.sliceByTwo||(d.sliceByTwo=createCanvasElement());const m=d.sliceByTwo;(m.width<1.5*e||m.height<i)&&(m.width=1.5*e,m.height=i);const y=m.getContext("2d");for(y.clearRect(0,0,1.5*e,i),y.putImageData(r,0,0),s=Math.floor(s),n=Math.floor(n);!a||!h;)e=l,i=c,s<Math.floor(l*o)?l=Math.floor(l*o):(l=s,a=!0),n<Math.floor(c*o)?c=Math.floor(c*o):(c=n,h=!0),y.drawImage(m,u,g,e,i,f,p,l,c),u=f,g=p,p+=c;return y.getImageData(u,g,s,n)}lanczosResize(t,e,i,s,n){function process(t){let x,v,_,C,b,S,w,T,P,M,O;for(m.x=(t+.5)*l,y.x=Math.floor(m.x),x=0;x<n;x++){for(m.y=(x+.5)*c,y.y=Math.floor(m.y),b=0,S=0,w=0,T=0,P=0,v=y.x-g;v<=y.x+g;v++)if(!(v<0||v>=e)){M=Math.floor(1e3*Math.abs(v-m.x)),p[M]||(p[M]={});for(let t=y.y-f;t<=y.y+f;t++)t<0||t>=i||(O=Math.floor(1e3*Math.abs(t-m.y)),p[M][O]||(p[M][O]=h(Math.sqrt(Math.pow(M*d,2)+Math.pow(O*u,2))/1e3)),_=p[M][O],_>0&&(C=4*(t*e+v),b+=_,S+=_*r[C],w+=_*r[C+1],T+=_*r[C+2],P+=_*r[C+3]))}C=4*(x*s+t),a[C]=S/b,a[C+1]=w/b,a[C+2]=T/b,a[C+3]=P/b}return++t<s?process(t):o}const r=t.imageData.data,o=t.ctx.createImageData(s,n),a=o.data,h=this.lanczosCreate(this.lanczosLobes),l=this.rcpScaleX,c=this.rcpScaleY,d=2/this.rcpScaleX,u=2/this.rcpScaleY,g=Math.ceil(l*this.lanczosLobes/2),f=Math.ceil(c*this.lanczosLobes/2),p={},m={x:0,y:0},y={x:0,y:0};return process(0)}bilinearFiltering(t,e,i,s,n){let r,o,a,h,l,c,d,u,g,f,p,m,y=0,x;const v=this.rcpScaleX,_=this.rcpScaleY,C=4*(e-1),b=undefined,S=t.imageData.data,w=t.ctx.createImageData(s,n),T=w.data;for(d=0;d<n;d++)for(u=0;u<s;u++)for(l=Math.floor(v*u),c=Math.floor(_*d),g=v*u-l,f=_*d-c,x=4*(c*e+l),p=0;p<4;p++)r=S[x+p],o=S[x+4+p],a=S[x+C+p],h=S[x+C+4+p],m=r*(1-g)*(1-f)+o*g*(1-f)+a*f*(1-g)+h*g*f,T[y++]=m;return w}hermiteFastResize(t,e,i,s,n){const r=this.rcpScaleX,o=this.rcpScaleY,a=Math.ceil(r/2),h=Math.ceil(o/2),l=undefined,c=t.imageData.data,d=t.ctx.createImageData(s,n),u=d.data;for(let t=0;t<n;t++)for(let i=0;i<s;i++){const n=4*(i+t*s);let l=0,d=0,g=0,f=0,p=0,m=0,y=0;const x=(t+.5)*o;for(let s=Math.floor(t*o);s<(t+1)*o;s++){const t=Math.abs(x-(s+.5))/h,n=(i+.5)*r,o=t*t;for(let t=Math.floor(i*r);t<(i+1)*r;t++){let i=Math.abs(n-(t+.5))/a;const r=Math.sqrt(o+i*i);r>1&&r<-1||(l=2*r*r*r-3*r*r+1,l>0&&(i=4*(t+s*e),y+=l*c[i+3],g+=l,c[i+3]<255&&(l=l*c[i+3]/250),f+=l*c[i],p+=l*c[i+1],m+=l*c[i+2],d+=l))}}u[n]=f/d,u[n+1]=p/d,u[n+2]=m/d,u[n+3]=y/g}return d}}_defineProperty(Resize,"type","Resize"),_defineProperty(Resize,"defaults",Rs),_defineProperty(Resize,"uniformLocations",["uDelta","uTaps"]),X.setClass(Resize);const Ws="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uSaturation;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float rgMax = max(color.r, color.g);\n float rgbMax = max(rgMax, color.b);\n color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\n color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\n color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\n gl_FragColor = color;\n }\n",Hs={saturation:0};class Saturation extends BaseFilter{getFragmentSource(){return Ws}applyTo2d(t){let{imageData:{data:e}}=t;const i=-this.saturation;for(let t=0;t<e.length;t+=4){const s=e[t],n=e[t+1],r=e[t+2],o=Math.max(s,n,r);e[t]+=o!==s?(o-s)*i:0,e[t+1]+=o!==n?(o-n)*i:0,e[t+2]+=o!==r?(o-r)*i:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return 0===this.saturation}}_defineProperty(Saturation,"type","Saturation"),_defineProperty(Saturation,"defaults",Hs),_defineProperty(Saturation,"uniformLocations",["uSaturation"]),X.setClass(Saturation);const Xs="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uVibrance;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float max = max(color.r, max(color.g, color.b));\n float avg = (color.r + color.g + color.b) / 3.0;\n float amt = (abs(max - avg) * 2.0) * uVibrance;\n color.r += max != color.r ? (max - color.r) * amt : 0.00;\n color.g += max != color.g ? (max - color.g) * amt : 0.00;\n color.b += max != color.b ? (max - color.b) * amt : 0.00;\n gl_FragColor = color;\n }\n",$s={vibrance:0};class Vibrance extends BaseFilter{getFragmentSource(){return Xs}applyTo2d(t){let{imageData:{data:e}}=t;const i=-this.vibrance;for(let t=0;t<e.length;t+=4){const s=e[t],n=e[t+1],r=e[t+2],o=Math.max(s,n,r),a=(s+n+r)/3,h=2*Math.abs(o-a)/255*i;e[t]+=o!==s?(o-s)*h:0,e[t+1]+=o!==n?(o-n)*h:0,e[t+2]+=o!==r?(o-r)*h:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return 0===this.vibrance}}_defineProperty(Vibrance,"type","Vibrance"),_defineProperty(Vibrance,"defaults",$s),_defineProperty(Vibrance,"uniformLocations",["uVibrance"]),X.setClass(Vibrance);var zs=Object.freeze({__proto__:null,BaseFilter:BaseFilter,BlackWhite:vs,BlendColor:BlendColor,BlendImage:BlendImage,Blur:Blur,Brightness:Brightness,Brownie:gs,ColorMatrix:ColorMatrix,Composed:Composed,Contrast:Contrast,Convolute:Convolute,Gamma:Gamma,Grayscale:Grayscale,HueRotation:HueRotation,Invert:Invert,Kodachrome:ps,Noise:Noise,Pixelate:Pixelate,Polaroid:ys,RemoveColor:RemoveColor,Resize:Resize,Saturation:Saturation,Sepia:xs,Technicolor:ms,Vibrance:Vibrance,Vintage:fs});t.ActiveSelection=ActiveSelection,t.BaseBrush=BaseBrush,t.BaseFabricObject=At,t.Canvas=Canvas,t.Canvas2dFilterBackend=Canvas2dFilterBackend,t.CanvasDOMManager=CanvasDOMManager,t.Circle=Circle,t.CircleBrush=CircleBrush,t.ClipPathLayout=ClipPathLayout,t.Color=Color,t.Control=Control,t.Ellipse=Ellipse,t.FabricImage=FabricImage,t.FabricObject=FabricObject,t.FabricText=FabricText,t.FitContentLayout=FitContentLayout,t.FixedLayout=FixedLayout,t.Frame=Frame,t.FrameLayout=FrameLayout,t.Gradient=Gradient,t.Group=Group,t.IText=IText,t.Image=FabricImage,t.InteractiveFabricObject=InteractiveFabricObject,t.Intersection=Intersection,t.LayoutManager=LayoutManager,t.LayoutStrategy=LayoutStrategy,t.Line=Line,t.Object=FabricObject,t.Observable=Observable,t.Path=Path,t.Pattern=Pattern,t.PatternBrush=PatternBrush,t.PencilBrush=PencilBrush,t.Point=Point,t.Polygon=Polygon,t.Polyline=Polyline,t.Rect=Rect,t.Shadow=Shadow,t.SprayBrush=SprayBrush,t.StaticCanvas=StaticCanvas,t.StaticCanvasDOMManager=StaticCanvasDOMManager,t.Text=FabricText,t.Textbox=Textbox,t.Triangle=Triangle,t.WebGLFilterBackend=WebGLFilterBackend,t.cache=n,t.classRegistry=X,t.config=e,t.controlsUtils=Ji,t.createCollectionMixin=createCollectionMixin,t.filters=zs,t.getEnv=getEnv,t.getFabricDocument=getFabricDocument,t.getFabricWindow=getFabricWindow,t.getFilterBackend=getFilterBackend,t.iMatrix=d,t.initFilterBackend=initFilterBackend,t.isPutImageFaster=isPutImageFaster,t.isWebGLPipelineState=isWebGLPipelineState,t.loadSVGFromString=loadSVGFromString,t.loadSVGFromURL=loadSVGFromURL,t.parseSVGDocument=parseSVGDocument,t.runningAnimations=$,t.setEnv=setEnv,t.setFilterBackend=setFilterBackend,t.util=Re,t.version=o});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).fabric={})}(this,function(t){"use strict";function _defineProperty(t,e,i){return(e=_toPropertyKey(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function _toPrimitive(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var s=i.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}function _toPropertyKey(t){var e=_toPrimitive(t,"string");return"symbol"==typeof e?e:e+""}class BaseConfiguration{constructor(){_defineProperty(this,"browserShadowBlurConstant",1),_defineProperty(this,"DPI",96),_defineProperty(this,"devicePixelRatio","undefined"!=typeof window?window.devicePixelRatio:1),_defineProperty(this,"perfLimitSizeTotal",2097152),_defineProperty(this,"maxCacheSideLimit",4096),_defineProperty(this,"minCacheSideLimit",256),_defineProperty(this,"disableStyleCopyPaste",!1),_defineProperty(this,"enableGLFiltering",!0),_defineProperty(this,"textureSize",4096),_defineProperty(this,"forceGLPutImageData",!1),_defineProperty(this,"cachesBoundsOfCurve",!1),_defineProperty(this,"fontPaths",{}),_defineProperty(this,"NUM_FRACTION_DIGITS",4)}}class Configuration extends BaseConfiguration{constructor(t){super(),this.configure(t)}configure(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,t)}addFonts(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.fontPaths={...this.fontPaths,...t}}removeFonts(){let t;(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).forEach(t=>{delete this.fontPaths[t]})}clearFonts(){this.fontPaths={}}restoreDefaults(t){const e=new BaseConfiguration,i=(null==t?void 0:t.reduce((t,i)=>(t[i]=e[i],t),{}))||e;this.configure(i)}}const e=new Configuration,log=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return console[t]("fabric",...i)};class FabricError extends Error{constructor(t,e){super(`fabric: ${t}`,e)}}class SignalAbortedError extends FabricError{constructor(t){super(`${t} 'options.signal' is in 'aborted' state`)}}class GLProbe{}class WebGLProbe extends GLProbe{testPrecision(t,e){const i=`precision ${e} float;\nvoid main(){}`,s=t.createShader(t.FRAGMENT_SHADER);return!!s&&(t.shaderSource(s,i),t.compileShader(s),!!t.getShaderParameter(s,t.COMPILE_STATUS))}queryWebGL(t){const e=t.getContext("webgl");e&&(this.maxTextureSize=e.getParameter(e.MAX_TEXTURE_SIZE),this.GLPrecision=["highp","mediump","lowp"].find(t=>this.testPrecision(e,t)),e.getExtension("WEBGL_lose_context").loseContext(),log("log",`WebGL: max texture size ${this.maxTextureSize}`))}isSupported(t){return!!this.maxTextureSize&&this.maxTextureSize>=t}}const i={},getEnv$1=()=>({document:document,window:window,isTouchSupported:"ontouchstart"in window||"ontouchstart"in document||window&&window.navigator&&window.navigator.maxTouchPoints>0,WebGLProbe:new WebGLProbe,dispose(){},copyPasteData:i});let s;const setEnv=t=>{s=t},getEnv=()=>s||(s=getEnv$1()),getFabricDocument=()=>getEnv().document,getFabricWindow=()=>getEnv().window,getDevicePixelRatio=()=>{var t;return Math.max(null!==(t=e.devicePixelRatio)&&void 0!==t?t:getFabricWindow().devicePixelRatio,1)};class Cache{constructor(){_defineProperty(this,"charWidthsCache",{}),_defineProperty(this,"boundsOfCurveCache",{})}getFontCache(t){let{fontFamily:e,fontStyle:i,fontWeight:s}=t;e=e.toLowerCase(),this.charWidthsCache[e]||(this.charWidthsCache[e]={});const n=this.charWidthsCache[e],r=`${i.toLowerCase()}_${(s+"").toLowerCase()}`;return n[r]||(n[r]={}),n[r]}clearFontCache(t){(t=(t||"").toLowerCase())?this.charWidthsCache[t]&&delete this.charWidthsCache[t]:this.charWidthsCache={}}limitDimsByArea(t){const{perfLimitSizeTotal:i}=e,s=Math.sqrt(i*t);return[Math.floor(s),Math.floor(i/s)]}}const n=new Cache;var r;const o="7.0.1-beta42";function noop(){}const a=Math.PI/2,h=Math.PI/4,l=2*Math.PI,c=Math.PI/180,d=Object.freeze([1,0,0,1,0,0]),u=16,g=2,f=.4477152502,p="center",m="left",y="top",x="bottom",v="right",_="none",C=/\r?\n/,b="moving",S="scaling",w="rotating",T="rotate",P="skewing",M="resizing",O="modifyPoly",k="modifyPath",D="changed",E="scale",A="scaleX",F="scaleY",L="skewX",j="skewY",I="fill",B="stroke",R="modified",W="json",H="svg";class ClassRegistry{constructor(){this[W]=new Map,this[H]=new Map}has(t){return this[W].has(t)}getClass(t){const e=this[W].get(t);if(!e)throw new FabricError(`No class registered for ${t}`);return e}setClass(t,e){e?this[W].set(e,t):(this[W].set(t.type,t),this[W].set(t.type.toLowerCase(),t))}getSVGClass(t){return this[H].get(t)}setSVGClass(t,e){this[H].set(null!=e?e:t.type.toLowerCase(),t)}}const X=new ClassRegistry;class AnimationRegistry extends Array{remove(t){const e=this.indexOf(t);e>-1&&this.splice(e,1)}cancelAll(){const t=this.splice(0);return t.forEach(t=>t.abort()),t}cancelByCanvas(t){if(!t)return[];const e=this.filter(e=>{var i;return e.target===t||"object"==typeof e.target&&(null===(i=e.target)||void 0===i?void 0:i.canvas)===t});return e.forEach(t=>t.abort()),e}cancelByTarget(t){if(!t)return[];const e=this.filter(e=>e.target===t);return e.forEach(t=>t.abort()),e}}const $=new AnimationRegistry;class Observable{constructor(){_defineProperty(this,"__eventListeners",{})}on(t,e){if(this.__eventListeners||(this.__eventListeners={}),"object"==typeof t)return Object.entries(t).forEach(t=>{let[e,i]=t;this.on(e,i)}),()=>this.off(t);if(e){const i=t;return this.__eventListeners[i]||(this.__eventListeners[i]=[]),this.__eventListeners[i].push(e),()=>this.off(i,e)}return()=>!1}once(t,e){if("object"==typeof t){const e=[];return Object.entries(t).forEach(t=>{let[i,s]=t;e.push(this.once(i,s))}),()=>e.forEach(t=>t())}if(e){const i=this.on(t,function onceHandler(){for(var t=arguments.length,s=new Array(t),n=0;n<t;n++)s[n]=arguments[n];e.call(this,...s),i()});return i}return()=>!1}_removeEventListener(t,e){if(this.__eventListeners[t])if(e){const i=this.__eventListeners[t],s=i.indexOf(e);s>-1&&i.splice(s,1)}else this.__eventListeners[t]=[]}off(t,e){if(this.__eventListeners)if(void 0===t)for(const t in this.__eventListeners)this._removeEventListener(t);else"object"==typeof t?Object.entries(t).forEach(t=>{let[e,i]=t;this._removeEventListener(e,i)}):this._removeEventListener(t,e)}fire(t,e){var i;if(!this.__eventListeners)return;const s=null===(i=this.__eventListeners[t])||void 0===i?void 0:i.concat();if(s)for(let t=0;t<s.length;t++)s[t].call(this,e||{})}}const removeFromArray=(t,e)=>{const i=t.indexOf(e);return-1!==i&&t.splice(i,1),t},cos=t=>{if(0===t)return 1;const e=undefined;switch(Math.abs(t)/a){case 1:case 3:return 0;case 2:return-1}return Math.cos(t)},sin=t=>{if(0===t)return 0;const e=t/a,i=Math.sign(t);switch(e){case 1:return i;case 2:return 0;case 3:return-i}return Math.sin(t)};class Point{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;"object"==typeof t?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e)}add(t){return new Point(this.x+t.x,this.y+t.y)}addEquals(t){return this.x+=t.x,this.y+=t.y,this}scalarAdd(t){return new Point(this.x+t,this.y+t)}scalarAddEquals(t){return this.x+=t,this.y+=t,this}subtract(t){return new Point(this.x-t.x,this.y-t.y)}subtractEquals(t){return this.x-=t.x,this.y-=t.y,this}scalarSubtract(t){return new Point(this.x-t,this.y-t)}scalarSubtractEquals(t){return this.x-=t,this.y-=t,this}multiply(t){return new Point(this.x*t.x,this.y*t.y)}scalarMultiply(t){return new Point(this.x*t,this.y*t)}scalarMultiplyEquals(t){return this.x*=t,this.y*=t,this}divide(t){return new Point(this.x/t.x,this.y/t.y)}scalarDivide(t){return new Point(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&&void 0!==arguments[1]?arguments[1]:.5;return e=Math.max(Math.min(1,e),0),new Point(this.x+(t.x-this.x)*e,this.y+(t.y-this.y)*e)}distanceFrom(t){const e=this.x-t.x,i=this.y-t.y;return Math.sqrt(e*e+i*i)}midPointFrom(t){return this.lerp(t)}min(t){return new Point(Math.min(this.x,t.x),Math.min(this.y,t.y))}max(t){return new Point(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,i=this.y;this.x=t.x,this.y=t.y,t.x=e,t.y=i}clone(){return new Point(this.x,this.y)}rotate(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:z;const i=sin(t),s=cos(t),n=this.subtract(e),r=undefined;return new Point(n.x*s-n.y*i,n.x*i+n.y*s).add(e)}transform(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return new Point(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 z=new Point(0,0),isCollection=t=>!!t&&Array.isArray(t._objects);function createCollectionMixin(t){class Collection extends t{constructor(){super(...arguments),_defineProperty(this,"_objects",[])}_onObjectAdded(t){}_onObjectRemoved(t){}_onStackOrderChanged(t){}add(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const s=this._objects.push(...e);return e.forEach(t=>this._onObjectAdded(t)),s}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return this._objects.splice(t,0,...i),i.forEach(t=>this._onObjectAdded(t)),this._objects.length}remove(){const t=this._objects,e=[];for(var i=arguments.length,s=new Array(i),n=0;n<i;n++)s[n]=arguments[n];return s.forEach(i=>{const s=t.indexOf(i);-1!==s&&(t.splice(s,1),e.push(i),this._onObjectRemoved(i))}),e}forEachObject(t){this.getObjects().forEach((e,i,s)=>t(e,i,s))}getObjects(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return 0===e.length?[...this._objects]:this._objects.filter(t=>t.isType(...e))}item(t){return this._objects[t]}isEmpty(){return 0===this._objects.length}size(){return this._objects.length}contains(t,e){return!!this._objects.includes(t)||!!e&&this._objects.some(e=>e instanceof Collection&&e.contains(t,!0))}complexity(){return this._objects.reduce((t,e)=>t+=e.complexity?e.complexity():0,0)}sendObjectToBack(t){return!(!t||t===this._objects[0])&&(removeFromArray(this._objects,t),this._objects.unshift(t),this._onStackOrderChanged(t),!0)}bringObjectToFront(t){return!(!t||t===this._objects[this._objects.length-1])&&(removeFromArray(this._objects,t),this._objects.push(t),this._onStackOrderChanged(t),!0)}sendObjectBackwards(t,e){if(!t)return!1;const i=this._objects.indexOf(t);if(0!==i){const s=this.findNewLowerIndex(t,i,e);return removeFromArray(this._objects,t),this._objects.splice(s,0,t),this._onStackOrderChanged(t),!0}return!1}bringObjectForward(t,e){if(!t)return!1;const i=this._objects.indexOf(t);if(i!==this._objects.length-1){const s=this.findNewUpperIndex(t,i,e);return removeFromArray(this._objects,t),this._objects.splice(s,0,t),this._onStackOrderChanged(t),!0}return!1}moveObjectTo(t,e){return t!==this._objects[e]&&(removeFromArray(this._objects,t),this._objects.splice(e,0,t),this._onStackOrderChanged(t),!0)}findNewLowerIndex(t,e,i){let s;if(i){s=e;for(let i=e-1;i>=0;--i)if(t.isOverlapping(this._objects[i])){s=i;break}}else s=e-1;return s}findNewUpperIndex(t,e,i){let s;if(i){s=e;for(let i=e+1;i<this._objects.length;++i)if(t.isOverlapping(this._objects[i])){s=i;break}}else s=e+1;return s}collectObjects(t){let{left:e,top:i,width:s,height:n}=t,{includeIntersecting:r=!0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=[],a=new Point(e,i),h=a.add(new Point(s,n));for(let t=this._objects.length-1;t>=0;t--){const e=this._objects[t];e.selectable&&e.visible&&(r&&e.intersectsWithRect(a,h)||e.isContainedWithinRect(a,h)||r&&e.containsPoint(a)||r&&e.containsPoint(h))&&o.push(e)}return o}}return Collection}class CommonMethods extends Observable{_setOptions(){let t=arguments.length>0&&void 0!==arguments[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"object"==typeof t?this._setObject(t):this._set(t,e),this}_set(t,e){this[t]=e}toggle(t){const e=this.get(t);return"boolean"==typeof e&&this.set(t,!e),this}get(t){return this[t]}}function requestAnimFrame(t){return getFabricWindow().requestAnimationFrame(t)}function cancelAnimFrame(t){return getFabricWindow().cancelAnimationFrame(t)}let Y=0;const uid=()=>Y++,createCanvasElement=()=>{const t=getFabricDocument().createElement("canvas");if(!t||void 0===t.getContext)throw new FabricError("Failed to create `canvas` element");return t},createImage=()=>getFabricDocument().createElement("img"),copyCanvasElement=t=>{var e;const i=createCanvasElementFor(t);return null===(e=i.getContext("2d"))||void 0===e||e.drawImage(t,0,0),i},createCanvasElementFor=t=>{const e=createCanvasElement();return e.width=t.width,e.height=t.height,e},toDataURL=(t,e,i)=>t.toDataURL(`image/${e}`,i),isHTMLCanvas=t=>!!t&&void 0!==t.getContext,toBlob=(t,e,i)=>new Promise((s,n)=>{t.toBlob(s,`image/${e}`,i)}),degreesToRadians=t=>t*c,radiansToDegrees=t=>t/c,isIdentityMatrix=t=>t.every((t,e)=>t===d[e]),transformPoint=(t,e,i)=>new Point(t).transform(e,i),invertTransform=t=>{const e=1/(t[0]*t[3]-t[1]*t[2]),i=[e*t[3],-e*t[1],-e*t[2],e*t[0],0,0],{x:s,y:n}=new Point(t[4],t[5]).transform(i,!0);return i[4]=-s,i[5]=-n,i},multiplyTransformMatrices=(t,e,i)=>[t[0]*e[0]+t[2]*e[1],t[1]*e[0]+t[3]*e[1],t[0]*e[2]+t[2]*e[3],t[1]*e[2]+t[3]*e[3],i?0:t[0]*e[4]+t[2]*e[5]+t[4],i?0:t[1]*e[4]+t[3]*e[5]+t[5]],multiplyTransformMatrixArray=(t,e)=>t.reduceRight((t,i)=>i&&t?multiplyTransformMatrices(i,t,e):i||t,void 0)||d.concat(),calcPlaneRotation=t=>{let[e,i]=t;return Math.atan2(i,e)},qrDecompose=t=>{const e=calcPlaneRotation(t),i=Math.pow(t[0],2)+Math.pow(t[1],2),s=Math.sqrt(i),n=(t[0]*t[3]-t[2]*t[1])/s,r=Math.atan2(t[0]*t[2]+t[1]*t[3],i);return{angle:radiansToDegrees(e),scaleX:s,scaleY:n,skewX:radiansToDegrees(r),skewY:0,translateX:t[4]||0,translateY:t[5]||0}},createTranslateMatrix=function(t){let e;return[1,0,0,1,t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0]};function createRotateMatrix(){let{angle:t=0}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{x:e=0,y:i=0}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=degreesToRadians(t),n=cos(s),r=sin(s);return[n,r,-r,n,e?e-(n*e-r*i):0,i?i-(r*e+n*i):0]}const createScaleMatrix=function(t){let e;return[t,0,0,arguments.length>1&&void 0!==arguments[1]?arguments[1]:t,0,0]},angleToSkew=t=>Math.tan(degreesToRadians(t)),createSkewXMatrix=t=>[1,0,angleToSkew(t),1,0,0],createSkewYMatrix=t=>[1,angleToSkew(t),0,1,0,0],calcDimensionsMatrix=t=>{let{scaleX:e=1,scaleY:i=1,flipX:s=!1,flipY:n=!1,skewX:r=0,skewY:o=0}=t,a=createScaleMatrix(s?-e:e,n?-i:i);return r&&(a=multiplyTransformMatrices(a,createSkewXMatrix(r),!0)),o&&(a=multiplyTransformMatrices(a,createSkewYMatrix(o),!0)),a},composeMatrix=t=>{const{translateX:e=0,translateY:i=0,angle:s=0}=t;let n=createTranslateMatrix(e,i);s&&(n=multiplyTransformMatrices(n,createRotateMatrix({angle:s})));const r=calcDimensionsMatrix(t);return isIdentityMatrix(r)||(n=multiplyTransformMatrices(n,r)),n},loadImage=function(t){let{signal:e,crossOrigin:i=null}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise(function(s,n){if(e&&e.aborted)return n(new SignalAbortedError("loadImage"));const r=createImage();let o;e&&(o=function(t){r.src="",n(t)},e.addEventListener("abort",o,{once:!0}));const done=function(){r.onload=r.onerror=null,o&&(null==e||e.removeEventListener("abort",o)),s(r)};t?(r.onload=done,r.onerror=function(){o&&(null==e||e.removeEventListener("abort",o)),n(new FabricError(`Error loading ${r.src}`))},i&&(r.crossOrigin=i),r.src=t):done()})},enlivenObjects=function(t){let{signal:e,reviver:i=noop}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((s,n)=>{const r=[];e&&e.addEventListener("abort",n,{once:!0}),Promise.all(t.map(t=>X.getClass(t.type).fromObject(t,{signal:e}).then(e=>(i(t,e),r.push(e),e)))).then(s).catch(t=>{r.forEach(t=>{t.dispose&&t.dispose()}),n(t)}).finally(()=>{e&&e.removeEventListener("abort",n)})})},enlivenObjectEnlivables=function(t){let{signal:e}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new Promise((i,s)=>{const n=[];e&&e.addEventListener("abort",s,{once:!0});const r=Object.values(t).map(t=>t&&t.type&&X.has(t.type)?enlivenObjects([t],{signal:e}).then(t=>{let[e]=t;return n.push(e),e}):t),o=Object.keys(t);Promise.all(r).then(t=>t.reduce((t,e,i)=>(t[o[i]]=e,t),{})).then(i).catch(t=>{n.forEach(t=>{t.dispose&&t.dispose()}),s(t)}).finally(()=>{e&&e.removeEventListener("abort",s)})})},pick=function(t){let e;return(arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]).reduce((e,i)=>(i in t&&(e[i]=t[i]),e),{})},pickBy=(t,e)=>Object.keys(t).reduce((i,s)=>(e(t[s],s,t)&&(i[s]=t[s]),i),{}),toFixed=(t,e)=>parseFloat(Number(t).toFixed(e)),matrixToSVG=t=>"matrix("+t.map(t=>toFixed(t,e.NUM_FRACTION_DIGITS)).join(" ")+")",isFiller=t=>!!t&&void 0!==t.toLive,isSerializableFiller=t=>!!t&&"function"==typeof t.toObject,isPattern=t=>!!t&&void 0!==t.offsetX&&"source"in t,isTextObject=t=>!!t&&"function"==typeof t._renderText,isPath=t=>!!t&&"function"==typeof t._renderPathCommands,isActiveSelection=t=>!!t&&"multiSelectionStacking"in t;function getScrollLeftTop(t){const e=t&&getDocumentFromElement(t);let i=0,s=0;if(!t||!e)return{left:i,top:s};let n=t;const r=e.documentElement,o=e.body||{scrollLeft:0,scrollTop:0};for(;n&&(n.parentNode||n.host)&&(n=n.parentNode||n.host,n===e?(i=o.scrollLeft||r.scrollLeft||0,s=o.scrollTop||r.scrollTop||0):(i+=n.scrollLeft||0,s+=n.scrollTop||0),1!==n.nodeType||"fixed"!==n.style.position););return{left:i,top:s}}const getDocumentFromElement=t=>t.ownerDocument||null,getWindowFromElement=t=>{var e;return(null===(e=t.ownerDocument)||void 0===e?void 0:e.defaultView)||null},setCanvasDimensions=function(t,e,i){let{width:s,height:n}=i,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;t.width=s,t.height=n,r>1&&(t.setAttribute("width",(s*r).toString()),t.setAttribute("height",(n*r).toString()),e.scale(r,r))},setCSSDimensions=(t,e)=>{let{width:i,height:s}=e;i&&(t.style.width="number"==typeof i?`${i}px`:i),s&&(t.style.height="number"==typeof s?`${s}px`:s)};function getElementOffset(t){var e;const i=t&&getDocumentFromElement(t),s={left:0,top:0};if(!i)return s;const n=(null===(e=getWindowFromElement(t))||void 0===e?void 0:e.getComputedStyle(t,null))||{};s.left+=parseInt(n.borderLeftWidth,10)||0,s.top+=parseInt(n.borderTopWidth,10)||0,s.left+=parseInt(n.paddingLeft,10)||0,s.top+=parseInt(n.paddingTop,10)||0;let r={left:0,top:0};const o=i.documentElement;void 0!==t.getBoundingClientRect&&(r=t.getBoundingClientRect());const a=getScrollLeftTop(t);return{left:r.left+a.left-(o.clientLeft||0)+s.left,top:r.top+a.top-(o.clientTop||0)+s.top}}function makeElementUnselectable(t){return void 0!==t.onselectstart&&(t.onselectstart=()=>!1),t.style.userSelect=_,t}class StaticCanvasDOMManager{constructor(t){_defineProperty(this,"_originalCanvasStyle",void 0),_defineProperty(this,"lower",void 0);const e=this.createLowerCanvas(t);this.lower={el:e,ctx:e.getContext("2d")}}createLowerCanvas(t){const e=isHTMLCanvas(t)?t:t&&getFabricDocument().getElementById(t)||createCanvasElement();if(e.hasAttribute("data-fabric"))throw new FabricError("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:i}=t;const{el:s}=this.lower;s.classList.remove("lower-canvas"),s.removeAttribute("data-fabric"),s.setAttribute("width",`${e}`),s.setAttribute("height",`${i}`),s.style.cssText=this._originalCanvasStyle||"",this._originalCanvasStyle=void 0}setDimensions(t,e){const{el:i,ctx:s}=this.lower;setCanvasDimensions(i,s,t,e)}setCSSDimensions(t){setCSSDimensions(this.lower.el,t)}calcOffset(){return getElementOffset(this.lower.el)}dispose(){getEnv().dispose(this.lower.el),delete this.lower}}const V={backgroundVpt:!0,backgroundColor:"",overlayVpt:!0,overlayColor:"",includeDefaultValues:!0,svgViewportTransformation:!0,renderOnAddRemove:!0,skipOffscreen:!0,enableRetinaScaling:!0,imageSmoothingEnabled:!0,controlsAboveOverlay:!1,allowTouchScrolling:!1,viewportTransform:[...d]};class StaticCanvas extends(createCollectionMixin(CommonMethods)){get lowerCanvasEl(){var t;return null===(t=this.elements.lower)||void 0===t?void 0:t.el}get contextContainer(){var t;return null===(t=this.elements.lower)||void 0===t?void 0:t.ctx}static getDefaults(){return StaticCanvas.ownDefaults}constructor(t){let e=arguments.length>1&&void 0!==arguments[1]?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 StaticCanvasDOMManager(t)}add(){const t=super.add(...arguments);return arguments.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];const n=super.insertAt(t,...i);return i.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),n}remove(){const t=super.remove(...arguments);return t.length>0&&this.renderOnAddRemove&&this.requestRenderAll(),t}_onObjectAdded(t){t.canvas&&t.canvas!==this&&(log("warn","Canvas is trying to add an object that belongs to a different canvas.\nResulting to default behavior: removing object from previous canvas and adding to new canvas"),t.canvas.remove(t)),t._set("canvas",this),t.setCoords(),this.fire("object:added",{target:t}),t.fire("added",{target:this})}_onObjectRemoved(t){t._set("canvas",void 0),this.fire("object:removed",{target:t}),t.fire("removed",{target:this})}_onStackOrderChanged(){this.renderOnAddRemove&&this.requestRenderAll()}getRetinaScaling(){return this.enableRetinaScaling?getDevicePixelRatio():1}calcOffset(){return this._offset=this.elements.calcOffset()}getWidth(){return this.width}getHeight(){return this.height}_setDimensionsImpl(t){let{cssOnly:e=!1,backstoreOnly:i=!1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e){const e={width:this.width,height:this.height,...t};this.elements.setDimensions(e,this.getRetinaScaling()),this.hasLostContext=!0,this.width=e.width,this.height=e.height}i||this.elements.setCSSDimensions(t),this.calcOffset()}setDimensions(t,e){this._setDimensionsImpl(t,e),e&&e.cssOnly||this.requestRenderAll()}getZoom(){return this.viewportTransform[0]}setViewportTransform(t){this.viewportTransform=t,this.calcViewportBoundaries(),this.renderOnAddRemove&&this.requestRenderAll()}zoomToPoint(t,e){const i=t,s=[...this.viewportTransform],n=transformPoint(t,invertTransform(s));s[0]=e,s[3]=e;const r=transformPoint(n,s);s[4]+=i.x-r.x,s[5]+=i.y-r.y,this.setViewportTransform(s)}setZoom(t){this.zoomToPoint(new Point(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 Point(-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=requestAnimFrame(()=>this.renderAndReset()))}calcViewportBoundaries(){const t=this.width,e=this.height,i=invertTransform(this.viewportTransform),s=transformPoint({x:0,y:0},i),n=transformPoint({x:t,y:e},i),r=s.min(n),o=s.max(n);return this.vptCoords={tl:r,tr:new Point(o.x,r.y),bl:new Point(r.x,o.y),br:o}}cancelRequestedRender(){this.nextRenderHandle&&(cancelAnimFrame(this.nextRenderHandle),this.nextRenderHandle=0)}drawControls(t){}renderCanvas(t,e){if(this.destroyed)return;const i=this.viewportTransform,s=this.clipPath;this.calcViewportBoundaries(),this.clearContext(t),t.imageSmoothingEnabled=this.imageSmoothingEnabled,t.patternQuality="best",this.fire("before:render",{ctx:t}),this._renderBackground(t),t.save(),t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this._renderObjects(t,e),t.restore(),this.controlsAboveOverlay||this.skipControlsDrawing||this.drawControls(t),s&&(s._set("canvas",this),s.shouldCache(),s._transformDone=!0,s.renderCache({forClipping:!0}),this.drawClipPathOnCanvas(t,s)),this._renderOverlay(t),this.controlsAboveOverlay&&!this.skipControlsDrawing&&this.drawControls(t),this.fire("after:render",{ctx:t}),this.__cleanupTask&&(this.__cleanupTask(),this.__cleanupTask=void 0)}drawClipPathOnCanvas(t,e){const i=this.viewportTransform;t.save(),t.transform(...i),t.globalCompositeOperation="destination-in",e.transform(t),t.scale(1/e.zoomX,1/e.zoomY),t.drawImage(e._cacheCanvas,-e.cacheTranslationX,-e.cacheTranslationY),t.restore()}_renderObjects(t,e){for(let i=0,s=e.length;i<s;++i)e[i]&&e[i].render(t)}_renderBackgroundOrOverlay(t,e){const i=this[`${e}Color`],s=this[`${e}Image`],n=this.viewportTransform,r=this[`${e}Vpt`];if(!i&&!s)return;const o=isFiller(i);if(i){if(t.save(),t.beginPath(),t.moveTo(0,0),t.lineTo(this.width,0),t.lineTo(this.width,this.height),t.lineTo(0,this.height),t.closePath(),t.fillStyle=o?i.toLive(t):i,r&&t.transform(...n),o){t.transform(1,0,0,1,i.offsetX||0,i.offsetY||0);const e=i.gradientTransform||i.patternTransform;e&&t.transform(...e)}t.fill(),t.restore()}if(s){t.save();const{skipOffscreen:e}=this;this.skipOffscreen=r,r&&t.transform(...n),s.render(t),this.skipOffscreen=e,t.restore()}}_renderBackground(t){this._renderBackgroundOrOverlay(t,"background")}_renderOverlay(t){this._renderBackgroundOrOverlay(t,"overlay")}getCenterPoint(){return new Point(this.width/2,this.height/2)}centerObjectH(t){return this._centerObject(t,new Point(this.getCenterPoint().x,t.getCenterPoint().y))}centerObjectV(t){return this._centerObject(t,new Point(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 Point(this.getVpCenter().x,t.getCenterPoint().y))}viewportCenterObjectV(t){return this._centerObject(t,new Point(t.getCenterPoint().x,this.getVpCenter().y))}getVpCenter(){return transformPoint(this.getCenterPoint(),invertTransform(this.viewportTransform))}_centerObject(t,e){t.setXY(e,p,p),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 i=this.clipPath,s=i&&!i.excludeFromExport?this._toObject(i,t,e):null;return{version:o,...pick(this,e),objects:this._objects.filter(t=>!t.excludeFromExport).map(i=>this._toObject(i,t,e)),...this.__serializeBgOverlay(t,e),...s?{clipPath:s}:null}}_toObject(t,e,i){let s;this.includeDefaultValues||(s=t.includeDefaultValues,t.includeDefaultValues=!1);const n=t[e](i);return this.includeDefaultValues||(t.includeDefaultValues=!!s),n}__serializeBgOverlay(t,e){const i={},s=this.backgroundImage,n=this.overlayImage,r=this.backgroundColor,o=this.overlayColor;return isFiller(r)?r.excludeFromExport||(i.background=r.toObject(e)):r&&(i.background=r),isFiller(o)?o.excludeFromExport||(i.overlay=o.toObject(e)):o&&(i.overlay=o),s&&!s.excludeFromExport&&(i.backgroundImage=this._toObject(s,t,e)),n&&!n.excludeFromExport&&(i.overlayImage=this._toObject(n,t,e)),i}toSVG(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1?arguments[1]:void 0;t.reviver=e;const i=[];return this._setSVGPreamble(i,t),this._setSVGHeader(i,t),this.clipPath&&i.push(`<g clip-path="url(#${this.clipPath.clipPathId})" >\n`),this._setSVGBgOverlayColor(i,"background"),this._setSVGBgOverlayImage(i,"backgroundImage",e),this._setSVGObjects(i,e),this.clipPath&&i.push("</g>\n"),this._setSVGBgOverlayColor(i,"overlay"),this._setSVGBgOverlayImage(i,"overlayImage",e),i.push("</svg>"),i.join("")}_setSVGPreamble(t,e){e.suppressPreamble||t.push('<?xml version="1.0" encoding="',e.encoding||"UTF-8",'" standalone="no" ?>\n','<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ','"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')}_setSVGHeader(t,i){const s=i.width||`${this.width}`,n=i.height||`${this.height}`,r=e.NUM_FRACTION_DIGITS,a=i.viewBox;let h;if(a)h=`viewBox="${a.x} ${a.y} ${a.width} ${a.height}" `;else if(this.svgViewportTransformation){const t=this.viewportTransform;h=`viewBox="${toFixed(-t[4]/t[0],r)} ${toFixed(-t[5]/t[3],r)} ${toFixed(this.width/t[0],r)} ${toFixed(this.height/t[3],r)}" `}else h=`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="',n,'" ',h,'xml:space="preserve">\n',"<desc>Created with Fabric.js ",o,"</desc>\n","<defs>\n",this.createSVGFontFacesMarkup(),this.createSVGRefElementsMarkup(),this.createSVGClipPathMarkup(i),"</defs>\n")}createSVGClipPathMarkup(t){const e=this.clipPath;return e?(e.clipPathId=`CLIPPATH_${uid()}`,`<clipPath id="${e.clipPathId}" >\n${e.toClipPathSVG(t.reviver)}</clipPath>\n`):""}createSVGRefElementsMarkup(){return["background","overlay"].map(t=>{const e=this[`${t}Color`];if(isFiller(e)){const i=this[`${t}Vpt`],s=this.viewportTransform,n={isType:()=>!1,width:this.width/(i?s[0]:1),height:this.height/(i?s[3]:1)};return e.toSVG(n,{additionalTransform:i?matrixToSVG(s):""})}}).join("")}createSVGFontFacesMarkup(){const t=[],i={},s=e.fontPaths;this._objects.forEach(function add(e){t.push(e),isCollection(e)&&e._objects.forEach(add)}),t.forEach(t=>{if(!isTextObject(t))return;const{styles:e,fontFamily:n}=t;!i[n]&&s[n]&&(i[n]=!0,e&&Object.values(e).forEach(t=>{Object.values(t).forEach(t=>{let{fontFamily:e=""}=t;!i[e]&&s[e]&&(i[e]=!0)})}))});const n=Object.keys(i).map(t=>`\t\t@font-face {\n\t\t\tfont-family: '${t}';\n\t\t\tsrc: url('${s[t]}');\n\t\t}\n`).join("");return n?`\t<style type="text/css"><![CDATA[\n${n}]]></style>\n`:""}_setSVGObjects(t,e){this.forEachObject(i=>{i.excludeFromExport||this._setSVGObject(t,i,e)})}_setSVGObject(t,e,i){t.push(e.toSVG(i))}_setSVGBgOverlayImage(t,e,i){const s=this[e];s&&!s.excludeFromExport&&s.toSVG&&t.push(s.toSVG(i))}_setSVGBgOverlayColor(t,e){const i=this[`${e}Color`];if(i)if(isFiller(i)){const s=i.repeat||"",n=this.width,r=this.height,o=undefined,a=this[`${e}Vpt`]?matrixToSVG(invertTransform(this.viewportTransform)):"";t.push(`<rect transform="${a} translate(${n/2},${r/2})" x="${i.offsetX-n/2}" y="${i.offsetY-r/2}" width="${"repeat-y"!==s&&"no-repeat"!==s||!isPattern(i)?n:i.source.width}" height="${"repeat-x"!==s&&"no-repeat"!==s||!isPattern(i)?r:i.source.height}" fill="url(#SVGID_${i.id})"></rect>\n`)}else t.push('<rect x="0" y="0" width="100%" height="100%" ','fill="',i,'"',"></rect>\n")}loadFromJSON(t,e){let{signal:i}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!t)return Promise.reject(new FabricError("`json` is undefined"));const s="string"==typeof t?JSON.parse(t):t,{objects:n=[],backgroundImage:r,background:o,overlayImage:a,overlay:h,clipPath:l}=s,c=this.renderOnAddRemove;return this.renderOnAddRemove=!1,Promise.all([enlivenObjects(n,{reviver:e,signal:i}),enlivenObjectEnlivables({backgroundImage:r,backgroundColor:o,overlayImage:a,overlayColor:h,clipPath:l},{signal:i})]).then(t=>{let[e,i]=t;return this.clear(),this.add(...e),this.set(s),this.set(i),this.renderOnAddRemove=c,this})}clone(t){const e=this.toObject(t),i=undefined;return this.cloneWithoutData().loadFromJSON(e)}cloneWithoutData(){const t=createCanvasElementFor(this);return new this.constructor(t)}toDataURL(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{format:e="png",quality:i=1,multiplier:s=1,enableRetinaScaling:n=!1}=t,r=s*(n?this.getRetinaScaling():1);return toDataURL(this.toCanvasElement(r,t),e,i)}toBlob(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const{format:e="png",quality:i=1,multiplier:s=1,enableRetinaScaling:n=!1}=t,r=s*(n?this.getRetinaScaling():1);return toBlob(this.toCanvasElement(r,t),e,i)}toCanvasElement(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,{width:e,height:i,left:s,top:n,filter:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const o=(e||this.width)*t,a=(i||this.height)*t,h=this.getZoom(),l=this.width,c=this.height,d=this.skipControlsDrawing,u=h*t,g=this.viewportTransform,f=undefined,p=undefined,m=[u,0,0,u,(g[4]-(s||0))*t,(g[5]-(n||0))*t],y=this.enableRetinaScaling,x=createCanvasElementFor({width:o,height:a}),v=r?this._objects.filter(t=>r(t)):this._objects;return this.enableRetinaScaling=!1,this.viewportTransform=m,this.width=o,this.height=a,this.skipControlsDrawing=!0,this.calcViewportBoundaries(),this.renderCanvas(x.getContext("2d"),v),this.viewportTransform=g,this.width=l,this.height=c,this.calcViewportBoundaries(),this.enableRetinaScaling=y,this.skipControlsDrawing=d,x}dispose(){return!this.disposed&&this.elements.cleanupDOM({width:this.width,height:this.height}),$.cancelByCanvas(this),this.disposed=!0,new Promise((t,e)=>{const task=()=>{this.destroy(),t(!0)};task.kill=e,this.__cleanupTask&&this.__cleanupTask.kill("aborted"),this.destroyed?t(!1):this.nextRenderHandle?this.__cleanupTask=task:task()})}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} }>`}}_defineProperty(StaticCanvas,"ownDefaults",V);const G=["touchstart","touchmove","touchend"];function getTouchInfo(t){const e=t.changedTouches;return e&&e[0]?e[0]:t}const getPointer=t=>{const e=undefined,i=getScrollLeftTop(t.target),s=getTouchInfo(t);return new Point(s.clientX+i.left,s.clientY+i.top)},isTouchEvent=t=>G.includes(t.type)||"touch"===t.pointerType,stopEvent=t=>{t.preventDefault(),t.stopPropagation()},makeBoundingBoxFromPoints=t=>{let e=0,i=0,s=0,n=0;for(let r=0,o=t.length;r<o;r++){const{x:o,y:a}=t[r];(o>s||!r)&&(s=o),(o<e||!r)&&(e=o),(a>n||!r)&&(n=a),(a<i||!r)&&(i=a)}return{left:e,top:i,width:s-e,height:n-i}},removeTransformFromObject=(t,e)=>{const i=invertTransform(e),s=multiplyTransformMatrices(i,t.calcOwnMatrix());applyTransformToObject(t,s)},addTransformToObject=(t,e)=>applyTransformToObject(t,multiplyTransformMatrices(e,t.calcOwnMatrix())),applyTransformToObject=(t,e)=>{const{translateX:i,translateY:s,scaleX:n,scaleY:r,...o}=qrDecompose(e),a=new Point(i,s);t.flipX=!1,t.flipY=!1,Object.assign(t,o),t.set({scaleX:n,scaleY:r}),t.setPositionByOrigin(a,p,p)},resetObjectTransform=t=>{t.scaleX=1,t.scaleY=1,t.skewX=0,t.skewY=0,t.flipX=!1,t.flipY=!1,t.rotate(0)},saveObjectTransform=t=>({scaleX:t.scaleX,scaleY:t.scaleY,skewX:t.skewX,skewY:t.skewY,angle:t.angle,left:t.left,flipX:t.flipX,flipY:t.flipY,top:t.top}),sizeAfterTransform=(t,e,i)=>{const s=t/2,n=e/2,r=[new Point(-s,-n),new Point(s,-n),new Point(-s,n),new Point(s,n)].map(t=>t.transform(i)),o=makeBoundingBoxFromPoints(r);return new Point(o.width,o.height)},calcPlaneChangeMatrix=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:d,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d;return multiplyTransformMatrices(invertTransform(e),t)},sendPointToPlane=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d;return t.transform(calcPlaneChangeMatrix(e,i))},sendVectorToPlane=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:d,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:d;return t.transform(calcPlaneChangeMatrix(e,i),!0)},sendObjectToPlane=(t,e,i)=>{const s=calcPlaneChangeMatrix(e,i);return applyTransformToObject(t,multiplyTransformMatrices(s,t.calcOwnMatrix())),s},fireEvent=(t,e)=>{var i;const{transform:{target:s}}=e;null===(i=s.canvas)||void 0===i||i.fire(`object:${t}`,{...e,target:s}),s.fire(t,e)},N={left:-.5,top:-.5,center:0,bottom:.5,right:.5},resolveOrigin=t=>"string"==typeof t?N[t]:t-.5,U=new Point(1,0),q=new Point,rotateVector=(t,e)=>t.rotate(e),createVector=(t,e)=>new Point(e).subtract(t),magnitude=t=>t.distanceFrom(q),calcAngleBetweenVectors=(t,e)=>Math.atan2(crossProduct(t,e),dotProduct(t,e)),calcVectorRotation=t=>calcAngleBetweenVectors(U,t),getUnitVector=t=>t.eq(q)?t:t.scalarDivide(magnitude(t)),getOrthonormalVector=function(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return getUnitVector(new Point(-t.y,t.x).scalarMultiply(e?1:-1))},crossProduct=(t,e)=>t.x*e.y-t.y*e.x,dotProduct=(t,e)=>t.x*e.x+t.y*e.y,isBetweenVectors=(t,e,i)=>{if(t.eq(e)||t.eq(i))return!0;const s=crossProduct(e,i),n=crossProduct(e,t),r=crossProduct(i,t);return s>=0?n>=0&&r<=0:!(n<=0&&r>=0)},K="not-allowed",getActionFromCorner=(t,e,i,s)=>{if(!e||!t)return"drag";const n=s.controls[e];return n.getActionName(i,n,s)};function isTransformCentered(t){return resolveOrigin(t.originX)===resolveOrigin(p)&&resolveOrigin(t.originY)===resolveOrigin(p)}function invertOrigin(t){return.5-resolveOrigin(t)}const isLocked=(t,e)=>t[e],commonEventInfo=(t,e,i,s)=>({e:t,transform:e,pointer:new Point(i,s)});function findCornerQuadrant(t,e,i){const s=i,n=sendPointToPlane(t.getCenterPoint(),t.canvas.viewportTransform,void 0),r=calcVectorRotation(createVector(n,s))+l;return Math.round(r%l/h)}function normalizePoint(t,e,i,s){const n=t.getRelativeCenterPoint(),r=void 0!==i&&void 0!==s?t.translateToGivenOrigin(n,p,p,i,s):new Point(t.left,t.top),o=undefined;return(t.angle?e.rotate(-degreesToRadians(t.angle),n):e).subtract(r)}function getLocalPoint(t,e,i,s,n){var r;let{target:o,corner:a}=t;const h=o.controls[a],l=(null===(r=o.canvas)||void 0===r?void 0:r.getZoom())||1,c=o.padding/l,d=normalizePoint(o,new Point(s,n),e,i);return d.x>=c&&(d.x-=c),d.x<=-c&&(d.x+=c),d.y>=c&&(d.y-=c),d.y<=c&&(d.y+=c),d.x-=h.offsetX,d.y-=h.offsetY,d}const dragHandler=(t,e,i,s)=>{const{target:n,offsetX:r,offsetY:o}=e,a=i-r,h=s-o,l=!isLocked(n,"lockMovementX")&&n.left!==a,c=!isLocked(n,"lockMovementY")&&n.top!==h;return l&&n.set(m,a),c&&n.set(y,h),(l||c)&&fireEvent(b,commonEventInfo(t,e,i,s)),l||c},J={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"},reRGBa=()=>/^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,reHSLa=()=>/^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,reHex=()=>/^#?(([0-9a-f]){3,4}|([0-9a-f]{2}){3,4})$/i,hue2rgb=(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t),rgb2Hsl=(t,e,i,s)=>{t/=255,e/=255,i/=255;const n=Math.max(t,e,i),r=Math.min(t,e,i);let o,a;const h=(n+r)/2;if(n===r)o=a=0;else{const s=n-r;switch(a=h>.5?s/(2-n-r):s/(n+r),n){case t:o=(e-i)/s+(e<i?6:0);break;case e:o=(i-t)/s+2;break;case i:o=(t-e)/s+4;break}o/=6}return[Math.round(360*o),Math.round(100*a),Math.round(100*h),s]},fromAlphaToFloat=function(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"1";return parseFloat(t)/(t.endsWith("%")?100:1)},hexify=t=>Math.min(Math.round(t),255).toString(16).toUpperCase().padStart(2,"0"),greyAverage=t=>{let[e,i,s,n=1]=t;const r=Math.round(.3*e+.59*i+.11*s);return[r,r,r,n]};class Color{constructor(t){if(_defineProperty(this,"isUnrecognised",!1),t)if(t instanceof Color)this.setSource([...t._source]);else if(Array.isArray(t)){const[e,i,s,n=1]=t;this.setSource([e,i,s,n])}else this.setSource(this._tryParsingColor(t));else this.setSource([0,0,0,1])}_tryParsingColor(t){return(t=t.toLowerCase())in J&&(t=J[t]),"transparent"===t?[255,255,255,0]:Color.sourceFromHex(t)||Color.sourceFromRgb(t)||Color.sourceFromHsl(t)||(this.isUnrecognised=!0)&&[0,0,0,1]}getSource(){return this._source}setSource(t){this._source=t}toRgb(){const[t,e,i]=this.getSource();return`rgb(${t},${e},${i})`}toRgba(){return`rgba(${this.getSource().join(",")})`}toHsl(){const[t,e,i]=rgb2Hsl(...this.getSource());return`hsl(${t},${e}%,${i}%)`}toHsla(){const[t,e,i,s]=rgb2Hsl(...this.getSource());return`hsla(${t},${e}%,${i}%,${s})`}toHex(){const t=undefined;return this.toHexa().slice(0,6)}toHexa(){const[t,e,i,s]=this.getSource();return`${hexify(t)}${hexify(e)}${hexify(i)}${hexify(Math.round(255*s))}`}getAlpha(){return this.getSource()[3]}setAlpha(t){return this._source[3]=t,this}toGrayscale(){return this.setSource(greyAverage(this.getSource())),this}toBlackWhite(t){const[e,,,i]=greyAverage(this.getSource()),s=e<(t||127)?0:255;return this.setSource([s,s,s,i]),this}overlayWith(t){t instanceof Color||(t=new Color(t));const e=this.getSource(),i=.5,s=t.getSource(),[n,r,o]=e.map((t,e)=>Math.round(.5*t+s[e]*i));return this.setSource([n,r,o,e[3]]),this}static fromRgb(t){return Color.fromRgba(t)}static fromRgba(t){return new Color(Color.sourceFromRgb(t))}static sourceFromRgb(t){const e=t.match(/^rgba?\(\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d{0,3}(?:\.\d+)?%?)\s*)?\)$/i);if(e){const[t,i,s]=e.slice(1,4).map(t=>{const e=parseFloat(t);return t.endsWith("%")?Math.round(2.55*e):e});return[t,i,s,fromAlphaToFloat(e[4])]}}static fromHsl(t){return Color.fromHsla(t)}static fromHsla(t){return new Color(Color.sourceFromHsl(t))}static sourceFromHsl(t){const e=t.match(/^hsla?\(\s*([+-]?\d{0,3}(?:\.\d+)?(?:deg|turn|rad)?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*[\s|,]\s*(\d{0,3}(?:\.\d+)?%?)\s*(?:\s*[,/]\s*(\d*(?:\.\d+)?%?)\s*)?\)$/i);if(!e)return;const i=undefined,s=(Color.parseAngletoDegrees(e[1])%360+360)%360/360,n=parseFloat(e[2])/100,r=parseFloat(e[3])/100;let o,a,h;if(0===n)o=a=h=r;else{const t=r<=.5?r*(n+1):r+n-r*n,e=2*r-t;o=hue2rgb(e,t,s+1/3),a=hue2rgb(e,t,s),h=hue2rgb(e,t,s-1/3)}return[Math.round(255*o),Math.round(255*a),Math.round(255*h),fromAlphaToFloat(e[4])]}static fromHex(t){return new Color(Color.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),i=undefined;let s;s=e.length<=4?e.split("").map(t=>t+t):e.match(/.{2}/g);const[n,r,o,a=255]=s.map(t=>parseInt(t,16));return[n,r,o,a/255]}}static parseAngletoDegrees(t){const e=t.toLowerCase(),i=parseFloat(e);return e.includes("rad")?radiansToDegrees(i):e.includes("turn")?360*i:i}}const getSvgAttributes=t=>{const e=["instantiated_by_use","style","id","class"];switch(t){case"linearGradient":return e.concat(["x1","y1","x2","y2","gradientUnits","gradientTransform"]);case"radialGradient":return e.concat(["gradientUnits","gradientTransform","cx","cy","r","fx","fy","fr"]);case"stop":return e.concat(["offset","stop-color","stop-opacity"])}return e},parseUnit=function(t){let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:u;const s=/\D{0,2}$/.exec(t),n=parseFloat(t),r=e.DPI;switch(null==s?void 0:s[0]){case"mm":return n*r/25.4;case"cm":return n*r/2.54;case"in":return n*r;case"pt":return n*r/72;case"pc":return n*r/72*12;case"em":return n*i;default:return n}},parseAlign=t=>t&&t!==_?[t.slice(1,4),t.slice(5,8)]:t===_?[t,t]:["Mid","Mid"],parsePreserveAspectRatioAttribute=t=>{const[e,i]=t.trim().split(" "),[s,n]=parseAlign(e);return{meetOrSlice:i||"meet",alignX:s,alignY:n}},colorPropToSVG=function(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2],s,n;if(e)if(e.toLive)s=`url(#SVGID_${e.id})`;else{const t=new Color(e),i=t.getAlpha();s=t.toRgb(),1!==i&&(n=i.toString())}else s="none";return i?`${t}: ${s}; ${n?`${t}-opacity: ${n}; `:""}`:`${t}="${s}" ${n?`${t}-opacity="${n}" `:""}`},createSVGRect=function(t,i){let{left:s,top:n,width:r,height:o}=i,a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.NUM_FRACTION_DIGITS;const h=colorPropToSVG(I,t,!1),[l,c,d,u]=[s,n,r,o].map(t=>toFixed(t,a));return`<rect ${h} x="${l}" y="${c}" width="${d}" height="${u}"></rect>`};class FabricObjectSVGExportMixin{getSvgStyles(t){const e=this.fillRule?this.fillRule:"nonzero",i=this.strokeWidth?this.strokeWidth:"0",s=this.strokeDashArray?this.strokeDashArray.join(" "):_,n=this.strokeDashOffset?this.strokeDashOffset:"0",r=this.strokeLineCap?this.strokeLineCap:"butt",o=this.strokeLineJoin?this.strokeLineJoin:"miter",a=this.strokeMiterLimit?this.strokeMiterLimit:"4",h=void 0!==this.opacity?this.opacity:"1",l=this.visible?"":" visibility: hidden;",c=t?"":this.getSvgFilter(),d=colorPropToSVG(I,this.fill),u=undefined;return[colorPropToSVG(B,this.stroke),"stroke-width: ",i,"; ","stroke-dasharray: ",s,"; ","stroke-linecap: ",r,"; ","stroke-dashoffset: ",n,"; ","stroke-linejoin: ",o,"; ","stroke-miterlimit: ",a,"; ",d,"fill-rule: ",e,"; ","opacity: ",h,";",c,l].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&&void 0!==arguments[1]?arguments[1]:"";const i=t?this.calcTransformMatrix():this.calcOwnMatrix(),s=undefined;return`${`transform="${matrixToSVG(i)}`}${e}" `}_toSVG(t){return[""]}toSVG(t){return this._createBaseSVGMarkup(this._toSVG(t),{reviver:t})}toClipPathSVG(t){return"\t"+this._createBaseClipPathSVGMarkup(this._toSVG(t),{reviver:t})}_createBaseClipPathSVGMarkup(t){let{reviver:e,additionalTransform:i=""}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=[this.getSvgTransform(!0,i),this.getSvgCommons()].join(""),n=t.indexOf("COMMON_PARTS");return t[n]=s,e?e(t.join("")):t.join("")}_createBaseSVGMarkup(t){let{noStyle:e,reviver:i,withShadow:s,additionalTransform:n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=e?"":`style="${this.getSvgStyles()}" `,o=s?`style="${this.getSvgFilter()}" `:"",a=this.clipPath,h=this.strokeUniform?'vector-effect="non-scaling-stroke" ':"",l=a&&a.absolutePositioned,c=this.stroke,d=this.fill,u=this.shadow,g=[],f=t.indexOf("COMMON_PARTS");let p;a&&(a.clipPathId=`CLIPPATH_${uid()}`,p=`<clipPath id="${a.clipPathId}" >\n${a.toClipPathSVG(i)}</clipPath>\n`),l&&g.push("<g ",o,this.getSvgCommons()," >\n"),g.push("<g ",this.getSvgTransform(!1),l?"":o+this.getSvgCommons()," >\n");const m=[r,h,e?"":this.addPaintOrder()," ",n?`transform="${n}" `:""].join("");return t[f]=m,isFiller(d)&&g.push(d.toSVG(this)),isFiller(c)&&g.push(c.toSVG(this)),u&&g.push(u.toSVG(this)),a&&g.push(p),g.push(t.join("")),g.push("</g>\n"),l&&g.push("</g>\n"),i?i(g.join("")):g.join("")}addPaintOrder(){return this.paintFirst!==I?` paint-order="${this.paintFirst}" `:""}}function getSvgRegex(t){return new RegExp("^("+t.join("|")+")\\b","i")}const Z="textDecorationThickness",Q=["fontSize","fontWeight","fontFamily","fontStyle"],tt=["underline","overline","linethrough"],et=[...Q,"lineHeight","text","charSpacing","textAlign","styles","path","pathStartOffset","pathSide","pathAlign","wrap","ellipsis","letterSpacing","enableAdvancedLayout","verticalAlign","kashida"],it=[...et,...tt,"textBackgroundColor","direction",Z,"useOverlayEditing"],st=[...Q,...tt,B,"strokeWidth",I,"deltaY","textBackgroundColor",Z],nt={_reNewline:C,_reSpacesAndTabs:/[ \t\r]/g,_reSpaceAndTab:/[ \t\r]/,_reWords:/\S+/g,fontSize:40,fontWeight:"normal",fontFamily:"Times New Roman",underline:!1,overline:!1,linethrough:!1,textAlign:m,fontStyle:"normal",lineHeight:1.16,textBackgroundColor:"",stroke:null,shadow:null,path:void 0,pathStartOffset:0,pathSide:m,pathAlign:"baseline",charSpacing:0,deltaY:0,direction:"ltr",wrap:"word",ellipsis:!1,letterSpacing:0,enableAdvancedLayout:!1,verticalAlign:"top",kashida:"none",useOverlayEditing:!1,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,[Z]:66.667},rt="justify",ot="justify-left",at="justify-right",ht="justify-center",lt=String.raw`[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?`,ct=String.raw`(?:\s*,?\s+|\s*,\s*)`,dt="http://www.w3.org/2000/svg",ut=new RegExp("(normal|italic)?\\s*(normal|small-caps)?\\s*(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900)?\\s*("+lt+"(?:px|cm|mm|em|pt|pc|in)*)(?:\\/(normal|"+lt+"))?\\s+(.*)"),gt=undefined,ft=["symbol","image","marker","pattern","view","svg"],pt=["pattern","defs","symbol","metadata","clipPath","mask","desc"],mt=["symbol","g","a","svg","clipPath","defs"],yt={cx:m,x:m,r:"radius",cy:y,y:y,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":Z},xt="font-size",vt="clip-path",_t=getSvgRegex(["path","circle","polygon","polyline","ellipse","rect","line","image","text"]),Ct=getSvgRegex(ft),bt=getSvgRegex(mt),St=new RegExp(String.raw`^\s*(${lt})${ct}(${lt})${ct}(${lt})${ct}(${lt})\s*$`),wt="(-?\\d+(?:\\.\\d*)?(?:px)?(?:\\s?|$))?",Tt=new RegExp("(?:\\s|^)"+wt+wt+"("+lt+"?(?:px)?)?(?:\\s?|$)(?:$|\\s)"),Pt={color:"rgb(0,0,0)",blur:0,offsetX:0,offsetY:0,affectStroke:!1,includeDefaultValues:!0,nonScaling:!1};class Shadow{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e="string"==typeof t?Shadow.parseShadow(t):t;Object.assign(this,Shadow.ownDefaults,e),this.id=uid()}static parseShadow(t){const e=t.trim(),[,i=0,s=0,n=0]=(Tt.exec(e)||[]).map(t=>parseFloat(t)||0),r=undefined;return{color:(e.replace(Tt,"")||"rgb(0,0,0)").trim(),offsetX:i,offsetY:s,blur:n}}toString(){return[this.offsetX,this.offsetY,this.blur,this.color].join("px ")}toSVG(t){const i=rotateVector(new Point(this.offsetX,this.offsetY),degreesToRadians(-t.angle)),s=20,n=new Color(this.color);let r=40,o=40;return t.width&&t.height&&(r=100*toFixed((Math.abs(i.x)+this.blur)/t.width,e.NUM_FRACTION_DIGITS)+s,o=100*toFixed((Math.abs(i.y)+this.blur)/t.height,e.NUM_FRACTION_DIGITS)+s),t.flipX&&(i.x*=-1),t.flipY&&(i.y*=-1),`<filter id="SVGID_${this.id}" y="-${o}%" height="${100+2*o}%" x="-${r}%" width="${100+2*r}%" >\n\t<feGaussianBlur in="SourceAlpha" stdDeviation="${toFixed(this.blur?this.blur/2:0,e.NUM_FRACTION_DIGITS)}"></feGaussianBlur>\n\t<feOffset dx="${toFixed(i.x,e.NUM_FRACTION_DIGITS)}" dy="${toFixed(i.y,e.NUM_FRACTION_DIGITS)}" result="oBlur" ></feOffset>\n\t<feFlood flood-color="${n.toRgb()}" flood-opacity="${n.getAlpha()}"/>\n\t<feComposite in2="oBlur" operator="in" />\n\t<feMerge>\n\t\t<feMergeNode></feMergeNode>\n\t\t<feMergeNode in="SourceGraphic"></feMergeNode>\n\t</feMerge>\n</filter>\n`}toObject(){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=Shadow.ownDefaults;return this.includeDefaultValues?t:pickBy(t,(t,i)=>t!==e[i])}static async fromObject(t){return new this(t)}}_defineProperty(Shadow,"ownDefaults",Pt),_defineProperty(Shadow,"type","shadow"),X.setClass(Shadow,"shadow");const capValue=(t,e,i)=>Math.max(t,Math.min(e,i)),Mt=[y,m,A,F,"flipX","flipY","originX","originY","angle","opacity","globalCompositeOperation","shadow","visible",L,j],Ot=[I,B,"strokeWidth","strokeDashArray","width","height","paintFirst","strokeUniform","strokeLineCap","strokeDashOffset","strokeLineJoin","strokeMiterLimit","backgroundColor","clipPath"],kt={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:m,originY:y,strokeWidth:1,strokeUniform:!1,padding:0,opacity:1,paintFirst:I,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},Dt={noScaleCache:!0,lockMovementX:!1,lockMovementY:!1,lockRotation:!1,lockScalingX:!1,lockScalingY:!1,lockSkewingX:!1,lockSkewingY:!1,lockScalingFlip:!1,cornerSize:10,touchCornerSize:24,transparentCorners:!1,cornerColor:"#ffffff",cornerStrokeColor:"#0d99ff",cornerStyle:"circle",cornerDashArray:null,hasControls:!0,borderColor:"#0d99ff",borderDashArray:null,borderOpacityWhenMoving:.6,borderScaleFactor:1,hasBorders:!0,selectionBackgroundColor:"",selectable:!0,evented:!0,perPixelTargetFind:!1,activeOn:"down",hoverCursor:null,moveCursor:null},normalize=(t,e,i,s)=>(t<Math.abs(e)?(t=e,s=i/4):s=0===e&&0===t?i/l*Math.asin(1):i/l*Math.asin(e/t),{a:t,c:e,p:i,s:s}),elastic=(t,e,i,s,n)=>t*Math.pow(2,10*(s-=1))*Math.sin((s*n-e)*l/i),defaultEasing=(t,e,i,s)=>-i*Math.cos(t/s*a)+i+e,easeInCubic=(t,e,i,s)=>i*(t/s)**3+e,easeOutCubic=(t,e,i,s)=>i*((t/s-1)**3+1)+e,easeInOutCubic=(t,e,i,s)=>(t/=s/2)<1?i/2*t**3+e:i/2*((t-2)**3+2)+e,easeInQuart=(t,e,i,s)=>i*(t/=s)*t**3+e,easeOutQuart=(t,e,i,s)=>-i*((t=t/s-1)*t**3-1)+e,easeInOutQuart=(t,e,i,s)=>(t/=s/2)<1?i/2*t**4+e:-i/2*((t-=2)*t**3-2)+e,easeInQuint=(t,e,i,s)=>i*(t/s)**5+e,easeOutQuint=(t,e,i,s)=>i*((t/s-1)**5+1)+e,easeInOutQuint=(t,e,i,s)=>(t/=s/2)<1?i/2*t**5+e:i/2*((t-2)**5+2)+e,easeInSine=(t,e,i,s)=>-i*Math.cos(t/s*a)+i+e,easeOutSine=(t,e,i,s)=>i*Math.sin(t/s*a)+e,easeInOutSine=(t,e,i,s)=>-i/2*(Math.cos(Math.PI*t/s)-1)+e,easeInExpo=(t,e,i,s)=>0===t?e:i*2**(10*(t/s-1))+e,easeOutExpo=(t,e,i,s)=>t===s?e+i:i*-(2**(-10*t/s)+1)+e,easeInOutExpo=(t,e,i,s)=>0===t?e:t===s?e+i:(t/=s/2)<1?i/2*2**(10*(t-1))+e:i/2*-(2**(-10*--t)+2)+e,easeInCirc=(t,e,i,s)=>-i*(Math.sqrt(1-(t/=s)*t)-1)+e,easeOutCirc=(t,e,i,s)=>i*Math.sqrt(1-(t=t/s-1)*t)+e,easeInOutCirc=(t,e,i,s)=>(t/=s/2)<1?-i/2*(Math.sqrt(1-t**2)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e,easeInElastic=(t,e,i,s)=>{const n=1.70158,r=i;let o=0;if(0===t)return e;if(1===(t/=s))return e+i;o||(o=.3*s);const{a:a,s:h,p:l}=normalize(r,i,o,n);return-elastic(a,h,l,t,s)+e},easeOutElastic=(t,e,i,s)=>{const n=1.70158,r=i;let o=0;if(0===t)return e;if(1===(t/=s))return e+i;o||(o=.3*s);const{a:a,s:h,p:c,c:d}=normalize(r,i,o,n);return a*2**(-10*t)*Math.sin((t*s-h)*l/c)+d+e},easeInOutElastic=(t,e,i,s)=>{const n=1.70158,r=i;let o=0;if(0===t)return e;if(2===(t/=s/2))return e+i;o||(o=s*(.3*1.5));const{a:a,s:h,p:c,c:d}=normalize(r,i,o,n);return t<1?-.5*elastic(a,h,c,t,s)+e:a*Math.pow(2,-10*(t-=1))*Math.sin((t*s-h)*l/c)*.5+d+e},easeInBack=function(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return i*(t/=s)*t*((n+1)*t-n)+e},easeOutBack=function(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return i*((t=t/s-1)*t*((n+1)*t+n)+1)+e},easeInOutBack=function(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1.70158;return(t/=s/2)<1?i/2*(t*t*((1+(n*=1.525))*t-n))+e:i/2*((t-=2)*t*((1+(n*=1.525))*t+n)+2)+e},easeOutBounce=(t,e,i,s)=>(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e,easeInBounce=(t,e,i,s)=>i-easeOutBounce(s-t,0,i,s)+e,easeInOutBounce=(t,e,i,s)=>t<s/2?.5*easeInBounce(2*t,0,i,s)+e:.5*easeOutBounce(2*t-s,0,i,s)+.5*i+e,easeInQuad=(t,e,i,s)=>i*(t/=s)*t+e,easeOutQuad=(t,e,i,s)=>-i*(t/=s)*(t-2)+e,easeInOutQuad=(t,e,i,s)=>(t/=s/2)<1?i/2*t**2+e:-i/2*(--t*(t-2)-1)+e;var Et=Object.freeze({__proto__:null,defaultEasing:defaultEasing,easeInBack:easeInBack,easeInBounce:easeInBounce,easeInCirc:easeInCirc,easeInCubic:easeInCubic,easeInElastic:easeInElastic,easeInExpo:easeInExpo,easeInOutBack:easeInOutBack,easeInOutBounce:easeInOutBounce,easeInOutCirc:easeInOutCirc,easeInOutCubic:easeInOutCubic,easeInOutElastic:easeInOutElastic,easeInOutExpo:easeInOutExpo,easeInOutQuad:easeInOutQuad,easeInOutQuart:easeInOutQuart,easeInOutQuint:easeInOutQuint,easeInOutSine:easeInOutSine,easeInQuad:easeInQuad,easeInQuart:easeInQuart,easeInQuint:easeInQuint,easeInSine:easeInSine,easeOutBack:easeOutBack,easeOutBounce:easeOutBounce,easeOutCirc:easeOutCirc,easeOutCubic:easeOutCubic,easeOutElastic:easeOutElastic,easeOutExpo:easeOutExpo,easeOutQuad:easeOutQuad,easeOutQuart:easeOutQuart,easeOutQuint:easeOutQuint,easeOutSine:easeOutSine});const defaultAbort=()=>!1;class AnimationBase{constructor(t){let{startValue:e,byValue:i,duration:s=500,delay:n=0,easing:r=defaultEasing,onStart:o=noop,onChange:a=noop,onComplete:h=noop,abort:l=defaultAbort,target:c}=t;_defineProperty(this,"_state","pending"),_defineProperty(this,"durationProgress",0),_defineProperty(this,"valueProgress",0),this.tick=this.tick.bind(this),this.duration=s,this.delay=n,this.easing=r,this._onStart=o,this._onChange=a,this._onComplete=h,this._abort=l,this.target=c,this.startValue=e,this.byValue=i,this.value=this.startValue,this.endValue=Object.freeze(this.calculate(this.duration).value)}get state(){return this._state}isDone(){return"aborted"===this._state||"completed"===this._state}start(){const firstTick=t=>{"pending"===this._state&&(this.startTime=t||+new Date,this._state="running",this._onStart(),this.tick(this.startTime))};this.register(),this.delay>0?setTimeout(()=>requestAnimFrame(firstTick),this.delay):requestAnimFrame(firstTick)}tick(t){const e=(t||+new Date)-this.startTime,i=Math.min(e,this.duration);this.durationProgress=i/this.duration;const{value:s,valueProgress:n}=this.calculate(i);this.value=Object.freeze(s),this.valueProgress=n,"aborted"!==this._state&&(this._abort(this.value,this.valueProgress,this.durationProgress)?(this._state="aborted",this.unregister()):e>=this.duration?(this.durationProgress=this.valueProgress=1,this._onChange(this.endValue,this.valueProgress,this.durationProgress),this._state="completed",this._onComplete(this.endValue,this.valueProgress,this.durationProgress),this.unregister()):(this._onChange(this.value,this.valueProgress,this.durationProgress),requestAnimFrame(this.tick)))}register(){$.push(this)}unregister(){$.remove(this)}abort(){this._state="aborted",this.unregister()}}class ValueAnimation extends AnimationBase{constructor(t){let{startValue:e=0,endValue:i=100,...s}=t;super({...s,startValue:e,byValue:i-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 ArrayAnimation extends AnimationBase{constructor(t){let{startValue:e=[0],endValue:i=[100],...s}=t;super({...s,startValue:e,byValue:i.map((t,i)=>t-e[i])})}calculate(t){const e=this.startValue.map((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i));return{value:e,valueProgress:Math.abs((e[0]-this.startValue[0])/this.byValue[0])}}}const defaultColorEasing=(t,e,i,s)=>{const n=undefined;return e+i*(1-Math.cos(t/s*a))},wrapColorCallback=t=>t&&((e,i,s)=>t(new Color(e).toRgba(),i,s));class ColorAnimation extends AnimationBase{constructor(t){let{startValue:e,endValue:i,easing:s=defaultColorEasing,onChange:n,onComplete:r,abort:o,...a}=t;const h=new Color(e).getSource(),l=new Color(i).getSource();super({...a,startValue:h,byValue:l.map((t,e)=>t-h[e]),easing:s,onChange:wrapColorCallback(n),onComplete:wrapColorCallback(r),abort:wrapColorCallback(o)})}calculate(t){const[e,i,s,n]=this.startValue.map((e,i)=>this.easing(t,e,this.byValue[i],this.duration,i)),r=[...[e,i,s].map(Math.round),capValue(0,n,1)];return{value:r,valueProgress:r.map((t,e)=>0!==this.byValue[e]?Math.abs((t-this.startValue[e])/this.byValue[e]):0).find(t=>0!==t)||0}}}const isArrayAnimation=t=>Array.isArray(t.startValue)||Array.isArray(t.endValue);function animate(t){const e=isArrayAnimation(t)?new ArrayAnimation(t):new ValueAnimation(t);return e.start(),e}function animateColor(t){const e=new ColorAnimation(t);return e.start(),e}class Intersection{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),i=0;i<t;i++)e[i]=arguments[i];return this.points=this.points.concat(e.filter(t=>!this.includes(t))),this}static isPointContained(t,e,i){let s=arguments.length>3&&void 0!==arguments[3]&&arguments[3];if(e.eq(i))return t.eq(e);if(e.x===i.x)return t.x===e.x&&(s||t.y>=Math.min(e.y,i.y)&&t.y<=Math.max(e.y,i.y));if(e.y===i.y)return t.y===e.y&&(s||t.x>=Math.min(e.x,i.x)&&t.x<=Math.max(e.x,i.x));{const n=createVector(e,i),r=undefined,o=createVector(e,t).divide(n);return s?Math.abs(o.x)===Math.abs(o.y):o.x===o.y&&o.x>=0&&o.x<=1}}static isPointInPolygon(t,e){const i=new Point(t).setX(Math.min(t.x-1,...e.map(t=>t.x)));let s=0;for(let n=0;n<e.length;n++){const r=this.intersectSegmentSegment(e[n],e[(n+1)%e.length],t,i);if(r.includes(t))return!0;s+=Number("Intersection"===r.status)}return s%2==1}static intersectLineLine(t,e,i,s){let n=!(arguments.length>4&&void 0!==arguments[4])||arguments[4],r=!(arguments.length>5&&void 0!==arguments[5])||arguments[5];const o=e.x-t.x,a=e.y-t.y,h=s.x-i.x,l=s.y-i.y,c=t.x-i.x,d=t.y-i.y,u=h*d-l*c,g=o*d-a*c,f=l*o-h*a;if(0!==f){const e=u/f,i=g/f;return(n||0<=e&&e<=1)&&(r||0<=i&&i<=1)?new Intersection("Intersection").append(new Point(t.x+e*o,t.y+e*a)):new Intersection}if(0===u||0===g){const o=n||r||Intersection.isPointContained(t,i,s)||Intersection.isPointContained(e,i,s)||Intersection.isPointContained(i,t,e)||Intersection.isPointContained(s,t,e);return new Intersection(o?"Coincident":void 0)}return new Intersection("Parallel")}static intersectSegmentLine(t,e,i,s){return Intersection.intersectLineLine(t,e,i,s,!1,!0)}static intersectSegmentSegment(t,e,i,s){return Intersection.intersectLineLine(t,e,i,s,!1,!1)}static intersectLinePolygon(t,e,i){let s=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];const n=new Intersection,r=i.length;for(let o=0,a,h,l;o<r;o++){if(a=i[o],h=i[(o+1)%r],l=Intersection.intersectLineLine(t,e,a,h,s,!1),"Coincident"===l.status)return l;n.append(...l.points)}return n.points.length>0&&(n.status="Intersection"),n}static intersectSegmentPolygon(t,e,i){return Intersection.intersectLinePolygon(t,e,i,!1)}static intersectPolygonPolygon(t,e){const i=new Intersection,s=t.length,n=[];for(let r=0;r<s;r++){const o=t[r],a=t[(r+1)%s],h=Intersection.intersectSegmentPolygon(o,a,e);"Coincident"===h.status?(n.push(h),i.append(o,a)):i.append(...h.points)}return n.length>0&&n.length===t.length?new Intersection("Coincident"):(i.points.length>0&&(i.status="Intersection"),i)}static intersectPolygonRectangle(t,e,i){const s=e.min(i),n=e.max(i),r=new Point(n.x,s.y),o=new Point(s.x,n.y);return Intersection.intersectPolygonPolygon(t,[s,r,n,o])}}class ObjectGeometry extends CommonMethods{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?transformPoint(t,this.group.calcTransformMatrix()):t}setXY(t,e,i){this.group&&(t=transformPoint(t,invertTransform(this.group.calcTransformMatrix()))),this.setRelativeXY(t,e,i)}getRelativeXY(){return new Point(this.left,this.top)}setRelativeXY(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.originX,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.originY;this.setPositionByOrigin(t,e,i)}isStrokeAccountedForInDimensions(){return!1}getCoords(){const{tl:t,tr:e,br:i,bl:s}=this.aCoords||(this.aCoords=this.calcACoords()),n=[t,e,i,s];if(this.group){const t=this.group.calcTransformMatrix();return n.map(e=>transformPoint(e,t))}return n}intersectsWithRect(t,e){const i=undefined;return"Intersection"===Intersection.intersectPolygonRectangle(this.getCoords(),t,e).status}intersectsWithObject(t){const e=Intersection.intersectPolygonPolygon(this.getCoords(),t.getCoords());return"Intersection"===e.status||"Coincident"===e.status||t.isContainedWithinObject(this)||this.isContainedWithinObject(t)}isContainedWithinObject(t){const e=undefined;return this.getCoords().every(e=>t.containsPoint(e))}isContainedWithinRect(t,e){const{left:i,top:s,width:n,height:r}=this.getBoundingRect();return i>=t.x&&i+n<=e.x&&s>=t.y&&s+r<=e.y}isOverlapping(t){return this.intersectsWithObject(t)||this.isContainedWithinObject(t)||t.isContainedWithinObject(this)}containsPoint(t){return Intersection.isPointInPolygon(t,this.getCoords())}isOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords,i=undefined;return!!this.getCoords().some(i=>i.x<=e.x&&i.x>=t.x&&i.y<=e.y&&i.y>=t.y)||(!!this.intersectsWithRect(t,e)||this.containsPoint(t.midPointFrom(e)))}isPartiallyOnScreen(){if(!this.canvas)return!1;const{tl:t,br:e}=this.canvas.vptCoords;if(this.intersectsWithRect(t,e))return!0;const i=undefined;return this.getCoords().every(i=>(i.x>=e.x||i.x<=t.x)&&(i.y>=e.y||i.y<=t.y))&&this.containsPoint(t.midPointFrom(e))}getBoundingRect(){return makeBoundingBoxFromPoints(this.getCoords())}getScaledWidth(){return this._getTransformedDimensions().x}getScaledHeight(){return this._getTransformedDimensions().y}scale(t){this._set(A,t),this._set(F,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(null===(t=this.canvas)||void 0===t?void 0:t.getRetinaScaling())||1}getTotalAngle(){return this.group?radiansToDegrees(calcPlaneRotation(this.calcTransformMatrix())):this.angle}getViewportTransform(){var t;return(null===(t=this.canvas)||void 0===t?void 0:t.viewportTransform)||d.concat()}calcACoords(){const t=createRotateMatrix({angle:this.angle}),{x:e,y:i}=this.getRelativeCenterPoint(),s=createTranslateMatrix(e,i),n=multiplyTransformMatrices(s,t),r=this._getTransformedDimensions(),o=r.x/2,a=r.y/2;return{tl:transformPoint({x:-o,y:-a},n),tr:transformPoint({x:o,y:-a},n),bl:transformPoint({x:-o,y:a},n),br:transformPoint({x:o,y:a},n)}}setCoords(){this.aCoords=this.calcACoords()}transformMatrixKey(){let t=arguments.length>0&&void 0!==arguments[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,resolveOrigin(this.originX),resolveOrigin(this.originY)),e}calcTransformMatrix(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=this.calcOwnMatrix();if(t||!this.group)return e;const i=this.transformMatrixKey(t),s=this.matrixCache;return s&&s.key.every((t,e)=>t===i[e])?s.value:(this.group&&(e=multiplyTransformMatrices(this.group.calcTransformMatrix(!1),e)),this.matrixCache={key:i,value:e},e)}calcOwnMatrix(){const t=this.transformMatrixKey(!0),e=this.ownMatrixCache;if(e&&e.key===t)return e.value;const i=this.getRelativeCenterPoint(),s={angle:this.angle,translateX:i.x,translateY:i.y,scaleX:this.scaleX,scaleY:this.scaleY,skewX:this.skewX,skewY:this.skewY,flipX:this.flipX,flipY:this.flipY},n=composeMatrix(s);return this.ownMatrixCache={key:t,value:n},n}_getNonTransformedDimensions(){return new Point(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&&void 0!==arguments[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},i=e.strokeWidth;let s=i,n=0;this.strokeUniform&&(s=0,n=i);const r=e.width+s,o=e.height+s,a=undefined;let h;return h=0===e.skewX&&0===e.skewY?new Point(r*e.scaleX,o*e.scaleY):sizeAfterTransform(r,o,calcDimensionsMatrix(e)),h.scalarAdd(n)}translateToGivenOrigin(t,e,i,s,n){let r=t.x,o=t.y;const a=resolveOrigin(s)-resolveOrigin(e),h=resolveOrigin(n)-resolveOrigin(i);if(a||h){const t=this._getTransformedDimensions();r+=a*t.x,o+=h*t.y}return new Point(r,o)}translateToCenterPoint(t,e,i){if(e===p&&i===p)return t;const s=this.translateToGivenOrigin(t,e,i,p,p);return this.angle?s.rotate(degreesToRadians(this.angle),t):s}translateToOriginPoint(t,e,i){const s=this.translateToGivenOrigin(t,p,p,e,i);return this.angle?s.rotate(degreesToRadians(this.angle),t):s}getCenterPoint(){const t=this.getRelativeCenterPoint();return this.group?transformPoint(t,this.group.calcTransformMatrix()):t}getRelativeCenterPoint(){return this.translateToCenterPoint(new Point(this.left,this.top),this.originX,this.originY)}getPointByOrigin(t,e){return this.translateToOriginPoint(this.getRelativeCenterPoint(),t,e)}setPositionByOrigin(t,e,i){const s=this.translateToCenterPoint(t,e,i),n=this.translateToOriginPoint(s,this.originX,this.originY);this.set({left:n.x,top:n.y})}_getLeftTopCoords(){return this.translateToOriginPoint(this.getRelativeCenterPoint(),m,y)}}let At=class FabricObject extends ObjectGeometry{static getDefaults(){return FabricObject.ownDefaults}get type(){const t=this.constructor.type;return"FabricObject"===t?"object":t.toLowerCase()}set type(t){log("warn","Setting type has no effect",t)}constructor(t){super(),_defineProperty(this,"_cacheContext",null),Object.assign(this,FabricObject.ownDefaults),this.setOptions(t)}_createCacheCanvas(){this._cacheCanvas=createCanvasElement(),this._cacheContext=this._cacheCanvas.getContext("2d"),this._updateCacheCanvas(),this.dirty=!0}_limitCacheSize(t){const i=t.width,s=t.height,r=e.maxCacheSideLimit,o=e.minCacheSideLimit;if(i<=r&&s<=r&&i*s<=e.perfLimitSizeTotal)return i<o&&(t.width=o),s<o&&(t.height=o),t;const a=i/s,[h,l]=n.limitDimsByArea(a),c=capValue(o,h,r),d=capValue(o,l,r);return i>c&&(t.zoomX/=i/c,t.width=c,t.capped=!0),s>d&&(t.zoomY/=s/d,t.height=d,t.capped=!0),t}_getCacheCanvasDimensions(){const t=this.getTotalObjectScaling(),e=this._getTransformedDimensions({skewX:0,skewY:0}),i=e.x*t.x/this.scaleX,s=e.y*t.y/this.scaleY;return{width:Math.ceil(i+2),height:Math.ceil(s+2),zoomX:t.x,zoomY:t.y,x:i,y:s}}_updateCacheCanvas(){const t=this._cacheCanvas,e=this._cacheContext,{width:i,height:s,zoomX:n,zoomY:r,x:o,y:a}=this._limitCacheSize(this._getCacheCanvasDimensions()),h=i!==t.width||s!==t.height,l=this.zoomX!==n||this.zoomY!==r;if(!t||!e)return!1;const c=undefined;if(h||l){i!==t.width||s!==t.height?(t.width=i,t.height=s):(e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,t.width,t.height));const h=o/2,l=a/2;return this.cacheTranslationX=Math.round(t.width/2-h)+h,this.cacheTranslationY=Math.round(t.height/2-l)+l,e.translate(this.cacheTranslationX,this.cacheTranslationY),e.scale(n,r),this.zoomX=n,this.zoomY=r,!0}return!1}setOptions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this._setOptions(t)}transform(t){const e=this.group&&!this.group._transformDone||this.group&&this.canvas&&t===this.canvas.contextTop,i=this.calcTransformMatrix(!e);t.transform(i[0],i[1],i[2],i[3],i[4],i[5])}getObjectScaling(){if(!this.group)return new Point(Math.abs(this.scaleX),Math.abs(this.scaleY));const t=qrDecompose(this.calcTransformMatrix());return new Point(Math.abs(t.scaleX),Math.abs(t.scaleY))}getTotalObjectScaling(){const t=this.getObjectScaling();if(this.canvas){const e=this.canvas.getZoom(),i=this.getCanvasRetinaScaling();return t.scalarMultiply(e*i)}return t}getObjectOpacity(){let t=this.opacity;return this.group&&(t*=this.group.getObjectOpacity()),t}_constrainScale(t){return Math.abs(t)<this.minScaleLimit?t<0?-this.minScaleLimit:this.minScaleLimit:0===t?1e-4:t}_set(t,e){t!==A&&t!==F||(e=this._constrainScale(e)),t===A&&e<0?(this.flipX=!this.flipX,e*=-1):"scaleY"===t&&e<0?(this.flipY=!this.flipY,e*=-1):"shadow"!==t||!e||e instanceof Shadow||(e=new Shadow(e));const i=this[t]!==e;return this[t]=e,i&&this.constructor.cacheProperties.includes(t)&&(this.dirty=!0),this.parent&&(this.dirty||i&&this.constructor.stateProperties.includes(t))&&this.parent._set("dirty",!0),this}isNotVisible(){return 0===this.opacity||!this.width&&!this.height&&0===this.strokeWidth||!this.visible}render(t){this.isNotVisible()||this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(t.save(),this._setupCompositeOperation(t),this.drawSelectionBackground(t),this.transform(t),this._setOpacity(t),this._setShadow(t),this.shouldCache()?(this.renderCache(),this.drawCacheOnCanvas(t)):(this._removeCacheCanvas(),this.drawObject(t,!1,{}),this.dirty=!1),t.restore())}drawSelectionBackground(t){}renderCache(t){if(t=t||{},this._cacheCanvas&&this._cacheContext||this._createCacheCanvas(),this.isCacheDirty()&&this._cacheContext){const{zoomX:e,zoomY:i,cacheTranslationX:s,cacheTranslationY:n}=this,{width:r,height:o}=this._cacheCanvas;this.drawObject(this._cacheContext,t.forClipping,{zoomX:e,zoomY:i,cacheTranslationX:s,cacheTranslationY:n,width:r,height:o,parentClipPaths:[]}),this.dirty=!1}}_removeCacheCanvas(){this._cacheCanvas=void 0,this._cacheContext=null}hasStroke(){return!!this.stroke&&"transparent"!==this.stroke&&0!==this.strokeWidth}hasFill(){return!!this.fill&&"transparent"!==this.fill}needsItsOwnCache(){return!!(this.paintFirst===B&&this.hasFill()&&this.hasStroke()&&this.shadow)||!!this.clipPath}shouldCache(){return this.ownCaching=this.objectCaching&&(!this.parent||!this.parent.isOnACache())||this.needsItsOwnCache(),this.ownCaching}willDrawShadow(){return!!this.shadow&&(0!==this.shadow.offsetX||0!==this.shadow.offsetY)}drawClipPathOnCache(t,e,i){t.save(),e.inverted?t.globalCompositeOperation="destination-out":t.globalCompositeOperation="destination-in",t.setTransform(1,0,0,1,0,0),t.drawImage(i,0,0),t.restore()}drawObject(t,e,i){const s=this.fill,n=this.stroke;e?(this.fill="black",this.stroke="",this._setClippingProperties(t)):this._renderBackground(t),this._render(t),this._drawClipPath(t,this.clipPath,i),this.fill=s,this.stroke=n}createClipPathLayer(t,e){const i=createCanvasElementFor(e),s=i.getContext("2d");if(s.translate(e.cacheTranslationX,e.cacheTranslationY),s.scale(e.zoomX,e.zoomY),t._cacheCanvas=i,e.parentClipPaths.forEach(t=>{t.transform(s)}),e.parentClipPaths.push(t),t.absolutePositioned){const t=invertTransform(this.calcTransformMatrix());s.transform(t[0],t[1],t[2],t[3],t[4],t[5])}return t.transform(s),t.drawObject(s,!0,e),i}_drawClipPath(t,e,i){if(!e)return;e._transformDone=!0;const s=this.createClipPathLayer(e,i);this.drawClipPathOnCache(t,e,s)}drawCacheOnCanvas(t){t.scale(1/this.zoomX,1/this.zoomY),t.drawImage(this._cacheCanvas,-this.cacheTranslationX,-this.cacheTranslationY)}isCacheDirty(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.isNotVisible())return!1;const e=this._cacheCanvas,i=this._cacheContext;return!(!e||!i||t||!this._updateCacheCanvas())||!!(this.dirty||this.clipPath&&this.clipPath.absolutePositioned)&&(e&&i&&!t&&(i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,e.width,e.height),i.restore()),!0)}_renderBackground(t){if(!this.backgroundColor)return;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 i=e.stroke;i&&(t.lineWidth=e.strokeWidth,t.lineCap=e.strokeLineCap,t.lineDashOffset=e.strokeDashOffset,t.lineJoin=e.strokeLineJoin,t.miterLimit=e.strokeMiterLimit,isFiller(i)?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?this._applyPatternForTransformedGradient(t,i):(t.strokeStyle=i.toLive(t),this._applyPatternGradientTransform(t,i)):t.strokeStyle=e.stroke)}_setFillStyles(t,e){let{fill:i}=e;i&&(isFiller(i)?(t.fillStyle=i.toLive(t),this._applyPatternGradientTransform(t,i)):t.fillStyle=i)}_setClippingProperties(t){t.globalAlpha=1,t.strokeStyle="transparent",t.fillStyle="#000000"}_setLineDash(t,e){e&&0!==e.length&&t.setLineDash(e)}_setShadow(t){if(!this.shadow)return;const i=this.shadow,s=this.canvas,n=this.getCanvasRetinaScaling(),[r,,,o]=(null==s?void 0:s.viewportTransform)||d,a=r*n,h=o*n,l=i.nonScaling?new Point(1,1):this.getObjectScaling();t.shadowColor=i.color,t.shadowBlur=i.blur*e.browserShadowBlurConstant*(a+h)*(l.x+l.y)/4,t.shadowOffsetX=i.offsetX*a*l.x,t.shadowOffsetY=i.offsetY*h*l.y}_removeShadow(t){this.shadow&&(t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0)}_applyPatternGradientTransform(t,e){if(!isFiller(e))return{offsetX:0,offsetY:0};const i=e.gradientTransform||e.patternTransform,s=-this.width/2+e.offsetX||0,n=-this.height/2+e.offsetY||0;return"percentage"===e.gradientUnits?t.transform(this.width,0,0,this.height,s,n):t.transform(1,0,0,1,s,n),i&&t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),{offsetX:s,offsetY:n}}_renderPaintInOrder(t){this.paintFirst===B?(this._renderStroke(t),this._renderFill(t)):(this._renderFill(t),this._renderStroke(t))}_render(t){}_renderFill(t){this.fill&&(t.save(),this._setFillStyles(t,this),"evenodd"===this.fillRule?t.fill("evenodd"):t.fill(),t.restore())}_renderStroke(t){if(this.stroke&&0!==this.strokeWidth){if(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this.strokeUniform){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 i;const s=this._limitCacheSize(this._getCacheCanvasDimensions()),n=this.getCanvasRetinaScaling(),r=s.x/this.scaleX/n,o=s.y/this.scaleY/n,a=createCanvasElementFor({width:Math.ceil(r),height:Math.ceil(o)}),h=a.getContext("2d");h&&(h.beginPath(),h.moveTo(0,0),h.lineTo(r,0),h.lineTo(r,o),h.lineTo(0,o),h.closePath(),h.translate(r/2,o/2),h.scale(s.zoomX/this.scaleX/n,s.zoomY/this.scaleY/n),this._applyPatternGradientTransform(h,e),h.fillStyle=e.toLive(t),h.fill(),t.translate(-this.width/2-this.strokeWidth/2,-this.height/2-this.strokeWidth/2),t.scale(n*this.scaleX/s.zoomX,n*this.scaleY/s.zoomY),t.strokeStyle=null!==(i=h.createPattern(a,"no-repeat"))&&void 0!==i?i:"")}_findCenterFromElement(){return new Point(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),i=undefined;return new(X.getClass("image"))(e)}toCanvasElement(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const e=saveObjectTransform(this),i=this.group,s=this.shadow,n=Math.abs,r=t.enableRetinaScaling?getDevicePixelRatio():1,o=(t.multiplier||1)*r,a=t.canvasProvider||(t=>new StaticCanvas(t,{enableRetinaScaling:!1,renderOnAddRemove:!1,skipOffscreen:!1}));delete this.group,t.withoutTransform&&resetObjectTransform(this),t.withoutShadow&&(this.shadow=null),t.viewportTransform&&sendObjectToPlane(this,this.getViewportTransform()),this.setCoords();const h=createCanvasElement(),l=this.getBoundingRect(),c=this.shadow,d=new Point;if(c){const t=c.blur,e=c.nonScaling?new Point(1,1):this.getObjectScaling();d.x=2*Math.round(n(c.offsetX)+t)*n(e.x),d.y=2*Math.round(n(c.offsetY)+t)*n(e.y)}const u=l.width+d.x,g=l.height+d.y;h.width=Math.ceil(u),h.height=Math.ceil(g);const f=a(h);"jpeg"===t.format&&(f.backgroundColor="#fff"),this.setPositionByOrigin(new Point(f.width/2,f.height/2),p,p);const m=this.canvas;f._objects=[this],this.set("canvas",f),this.setCoords();const y=f.toCanvasElement(o||1,t);return this.set("canvas",m),this.shadow=s,i&&(this.group=i),this.set(e),this.setCoords(),f._objects=[],f.destroy(),y}toDataURL(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return toDataURL(this.toCanvasElement(t),t.format||"png",t.quality||1)}toBlob(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return toBlob(this.toCanvasElement(t),t.format||"png",t.quality||1)}isType(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return e.includes(this.constructor.type)||e.includes(this.type)}complexity(){return 1}toJSON(){return this.toObject()}rotate(t){const{centeredRotation:e,originX:i,originY:s}=this;if(e){const{x:t,y:e}=this.getRelativeCenterPoint();this.originX=p,this.originY=p,this.left=t,this.top=e}if(this.set("angle",t),e){const{x:t,y:e}=this.translateToOriginPoint(this.getRelativeCenterPoint(),i,s);this.left=t,this.top=e,this.originX=i,this.originY=s}}setOnGroup(){}_setupCompositeOperation(t){this.globalCompositeOperation&&(t.globalCompositeOperation=this.globalCompositeOperation)}dispose(){$.cancelByTarget(this),this.off(),this._set("canvas",void 0),this._cacheCanvas&&getEnv().dispose(this._cacheCanvas),this._cacheCanvas=void 0,this._cacheContext=null}animate(t,e){return Object.entries(t).reduce((t,i)=>{let[s,n]=i;return t[s]=this._animate(s,n,e),t},{})}_animate(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const s=t.split("."),n=this.constructor.colorProperties.includes(s[s.length-1]),{abort:r,startValue:o,onChange:a,onComplete:h}=i,l={...i,target:this,startValue:null!=o?o:s.reduce((t,e)=>t[e],this),endValue:e,abort:null==r?void 0:r.bind(this),onChange:(t,e,i)=>{s.reduce((e,i,n)=>(n===s.length-1&&(e[i]=t),e[i]),this),a&&a(t,e,i)},onComplete:(t,e,i)=>{this.setCoords(),h&&h(t,e,i)}};return n?animateColor(l):animate(l)}isDescendantOf(t){const{parent:e,group:i}=this;return e===t||i===t||!!e&&e.isDescendantOf(t)||!!i&&i!==e&&i.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(),i=t.getAncestors();if(0===e.length&&i.length>0&&this===i[i.length-1])return{fork:[],otherFork:[t,...i.slice(0,i.length-1)],common:[this]};for(let s=0,n;s<e.length;s++){if(n=e[s],n===t)return{fork:[this,...e.slice(0,s)],otherFork:[],common:e.slice(s)};for(let r=0;r<i.length;r++){if(this===i[r])return{fork:[],otherFork:[t,...i.slice(0,r)],common:[this,...e]};if(n===i[r])return{fork:[this,...e.slice(0,s)],otherFork:[t,...i.slice(0,r)],common:e.slice(s)}}}return{fork:[this,...e],otherFork:[t,...i],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 i=e.common[0]||this.canvas;if(!i)return;const s=e.fork.pop(),n=e.otherFork.pop(),r=i._objects.indexOf(s),o=i._objects.indexOf(n);return r>-1&&r>o}toObject(){let t;const i=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:[]).concat(FabricObject.customProperties,this.constructor.customProperties||[]);let s;const n=e.NUM_FRACTION_DIGITS,{clipPath:r,fill:a,stroke:h,shadow:l,strokeDashArray:c,left:d,top:u,originX:g,originY:f,width:p,height:m,strokeWidth:y,strokeLineCap:x,strokeDashOffset:v,strokeLineJoin:_,strokeUniform:C,strokeMiterLimit:b,scaleX:S,scaleY:w,angle:T,flipX:P,flipY:M,opacity:O,visible:k,backgroundColor:D,fillRule:E,paintFirst:A,globalCompositeOperation:F,skewX:L,skewY:j}=this;r&&!r.excludeFromExport&&(s=r.toObject(i.concat("inverted","absolutePositioned")));const toFixedBound=t=>toFixed(t,n),I={...pick(this,i),type:this.constructor.type,version:o,originX:g,originY:f,left:toFixedBound(d),top:toFixedBound(u),width:toFixedBound(p),height:toFixedBound(m),fill:isSerializableFiller(a)?a.toObject():a,stroke:isSerializableFiller(h)?h.toObject():h,strokeWidth:toFixedBound(y),strokeDashArray:c?c.concat():c,strokeLineCap:x,strokeDashOffset:v,strokeLineJoin:_,strokeUniform:C,strokeMiterLimit:toFixedBound(b),scaleX:toFixedBound(S),scaleY:toFixedBound(w),angle:toFixedBound(T),flipX:P,flipY:M,opacity:toFixedBound(O),shadow:l?l.toObject():l,visible:k,backgroundColor:D,fillRule:E,paintFirst:A,globalCompositeOperation:F,skewX:toFixedBound(L),skewY:toFixedBound(j),...s?{clipPath:s}:null};return this.includeDefaultValues?I:this._removeDefaultValues(I)}toDatalessObject(t){return this.toObject(t)}_removeDefaultValues(t){const e=this.constructor.getDefaults(),i=undefined,s=Object.keys(e).length>0?e:Object.getPrototypeOf(this);return pickBy(t,(t,e)=>{if(e===m||e===y||"type"===e)return!0;const i=s[e];return t!==i&&!(Array.isArray(t)&&Array.isArray(i)&&0===t.length&&0===i.length)})}toString(){return`#<${this.constructor.type}>`}static _fromObject(t){let{type:e,...i}=t,{extraParam:s,...n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return enlivenObjectEnlivables(i,n).then(t=>s?(delete t[s],new this(i[s],t)):new this(t))}static fromObject(t,e){return this._fromObject(t,e)}};_defineProperty(At,"stateProperties",Mt),_defineProperty(At,"cacheProperties",Ot),_defineProperty(At,"ownDefaults",kt),_defineProperty(At,"type","FabricObject"),_defineProperty(At,"colorProperties",[I,B,"backgroundColor"]),_defineProperty(At,"customProperties",[]),X.setClass(At),X.setClass(At,"object");const wrapWithFireEvent=(t,e,i)=>(s,n,r,o)=>{const a=e(s,n,r,o);return a&&fireEvent(t,{...commonEventInfo(s,n,r,o),...i}),a};function wrapWithFixedAnchor(t){return(e,i,s,n)=>{const{target:r,originX:o,originY:a}=i,h=r.getRelativeCenterPoint(),l=r.translateToOriginPoint(h,o,a),c=t(e,i,s,n);return r.setPositionByOrigin(l,i.originX,i.originY),c}}const changeObjectWidth=(t,e,i,s)=>{const n=getLocalPoint(e,e.originX,e.originY,i,s);if(resolveOrigin(e.originX)===resolveOrigin(p)||resolveOrigin(e.originX)===resolveOrigin(v)&&n.x<0||resolveOrigin(e.originX)===resolveOrigin(m)&&n.x>0){const{target:t}=e,i=t.strokeWidth/(t.strokeUniform?t.scaleX:1),s=isTransformCentered(e)?2:1,r=t.width,o=Math.abs(n.x*s/t.scaleX)-i;return t.set("width",Math.max(o,1)),r!==t.width}return!1},Ft=wrapWithFireEvent(M,wrapWithFixedAnchor(changeObjectWidth)),Lt=6,jt=20,It=3;function renderCircleControl(t,e,i,s,n){s=s||{};const r=this.sizeX||s.cornerSize||n.cornerSize,o=this.sizeY||s.cornerSize||n.cornerSize,a=void 0!==s.transparentCorners?s.transparentCorners:n.transparentCorners,h=a?B:I,c=!a&&(s.cornerStrokeColor||n.cornerStrokeColor);let d=e,u=i,g;t.save(),t.fillStyle=s.cornerColor||n.cornerColor||"",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"",r>o?(g=r,t.scale(1,o/r),u=i*r/o):o>r?(g=o,t.scale(r/o,1),d=e*o/r):g=r,t.beginPath(),t.arc(d,u,g/2,0,l,!1),t[h](),c&&t.stroke(),t.restore()}function renderSquareControl(t,e,i,s,n){s=s||{};const r=this.sizeX||s.cornerSize||n.cornerSize,o=this.sizeY||s.cornerSize||n.cornerSize,a=void 0!==s.transparentCorners?s.transparentCorners:n.transparentCorners,h=a?B:I,l=!a&&(s.cornerStrokeColor||n.cornerStrokeColor),c=r/2,d=o/2;t.save(),t.fillStyle=s.cornerColor||n.cornerColor||"",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"",t.translate(e,i);const u=n.getTotalAngle();t.rotate(degreesToRadians(u)),t[`${h}Rect`](-c,-d,r,o),l&&t.strokeRect(-c,-d,r,o),t.restore()}function renderHorizontalPillControl(t,e,i,s,n){s=s||{};const r=6,o=jt,a=3;t.save(),t.translate(e,i);const h=n.getTotalAngle();t.rotate(degreesToRadians(h)),t.fillStyle=s.cornerColor||n.cornerColor||"#ffffff",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"#0d99ff",t.lineWidth=1.5,t.beginPath(),t.roundRect(-3,-10,6,o,3),t.fill(),t.stroke(),t.restore()}function renderVerticalPillControl(t,e,i,s,n){s=s||{};const r=jt,o=6,a=3;t.save(),t.translate(e,i);const h=n.getTotalAngle();t.rotate(degreesToRadians(h)),t.fillStyle=s.cornerColor||n.cornerColor||"#ffffff",t.strokeStyle=s.cornerStrokeColor||n.cornerStrokeColor||"#0d99ff",t.lineWidth=1.5,t.beginPath(),t.roundRect(-10,-3,r,6,3),t.fill(),t.stroke(),t.restore()}class Control{constructor(t){_defineProperty(this,"visible",!0),_defineProperty(this,"actionName",E),_defineProperty(this,"angle",0),_defineProperty(this,"x",0),_defineProperty(this,"y",0),_defineProperty(this,"offsetX",0),_defineProperty(this,"offsetY",0),_defineProperty(this,"sizeX",0),_defineProperty(this,"sizeY",0),_defineProperty(this,"touchSizeX",0),_defineProperty(this,"touchSizeY",0),_defineProperty(this,"cursorStyle","crosshair"),_defineProperty(this,"withConnection",!1),Object.assign(this,t)}shouldActivate(t,e,i,s){var n;let{tl:r,tr:o,br:a,bl:h}=s;return(null===(n=e.canvas)||void 0===n?void 0:n.getActiveObject())===e&&e.isControlVisible(t)&&Intersection.isPointInPolygon(i,[r,o,a,h])}getActionHandler(t,e,i){return this.actionHandler}getMouseDownHandler(t,e,i){return this.mouseDownHandler}getMouseUpHandler(t,e,i){return this.mouseUpHandler}cursorStyleHandler(t,e,i,s){return e.cursorStyle}getActionName(t,e,i){return e.actionName}getVisibility(t,e){var i,s;return null!==(i=null===(s=t._controlsVisibility)||void 0===s?void 0:s[e])&&void 0!==i?i:this.visible}setVisibility(t,e,i){this.visible=t}positionHandler(t,e,i,s){return new Point(this.x*t.x+this.offsetX,this.y*t.y+this.offsetY).transform(e)}calcCornerCoords(t,e,i,s,n,r){const o=multiplyTransformMatrixArray([createTranslateMatrix(i,s),createRotateMatrix({angle:t}),createScaleMatrix((n?this.touchSizeX:this.sizeX)||e,(n?this.touchSizeY:this.sizeY)||e)]);return{tl:new Point(-.5,-.5).transform(o),tr:new Point(.5,-.5).transform(o),br:new Point(.5,.5).transform(o),bl:new Point(-.5,.5).transform(o)}}render(t,e,i,s,n){s=s||{};const r=undefined;if(!(0!==this.x&&0!==this.y||0===this.x&&0===this.y)&&!s.cornerStyle){if(0===this.y&&0!==this.x)return void renderHorizontalPillControl.call(this,t,e,i,s,n);if(0===this.x&&0!==this.y)return void renderVerticalPillControl.call(this,t,e,i,s,n)}switch(s.cornerStyle||n.cornerStyle){case"circle":renderCircleControl.call(this,t,e,i,s,n);break;default:renderSquareControl.call(this,t,e,i,s,n)}}}const rotationStyleHandler=(t,e,i)=>i.lockRotation?K:e.cursorStyle,Bt=undefined,Rt=wrapWithFireEvent(w,wrapWithFixedAnchor((t,e,i,s)=>{let{target:n,ex:r,ey:o,theta:a,originX:h,originY:l}=e;const c=n.translateToOriginPoint(n.getRelativeCenterPoint(),h,l);if(isLocked(n,"lockRotation"))return!1;const d=Math.atan2(o-c.y,r-c.x),u=Math.atan2(s-c.y,i-c.x);let g=radiansToDegrees(u-d+a);if(n.snapAngle&&n.snapAngle>0){const t=n.snapAngle,e=n.snapThreshold||t,i=Math.ceil(g/t)*t,s=Math.floor(g/t)*t;Math.abs(g-s)<e?g=s:Math.abs(g-i)<e&&(g=i)}g<0&&(g=360+g),g%=360;const f=n.angle!==g;return n.angle=g,f}));function scaleIsProportional(t,e){const i=e.canvas,s=t[i.uniScaleKey];return i.uniformScaling&&!s||!i.uniformScaling&&s}function scalingIsForbidden(t,e,i){const s=isLocked(t,"lockScalingX"),n=isLocked(t,"lockScalingY");if(s&&n)return!0;if(!e&&(s||n)&&i)return!0;if(s&&"x"===e)return!0;if(n&&"y"===e)return!0;const{width:r,height:o,strokeWidth:a}=t;return 0===r&&0===a&&"y"!==e||0===o&&0===a&&"x"!==e}const Wt=["e","se","s","sw","w","nw","n","ne","e"],scaleCursorStyleHandler=(t,e,i,s)=>{const n=scaleIsProportional(t,i),r=undefined;if(scalingIsForbidden(i,0!==e.x&&0===e.y?"x":0===e.x&&0!==e.y?"y":"",n))return K;const o=findCornerQuadrant(i,e,s);return`${Wt[o]}-resize`};function scaleObject(t,e,i,s){let n=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};const r=e.target,o=n.by,a=scaleIsProportional(t,r),h=undefined;let l,c,d,u,g,f;if(scalingIsForbidden(r,o,a))return!1;if(e.gestureScale)c=e.scaleX*e.gestureScale,d=e.scaleY*e.gestureScale;else{if(l=getLocalPoint(e,e.originX,e.originY,i,s),g="y"!==o?Math.sign(l.x||e.signX||1):1,f="x"!==o?Math.sign(l.y||e.signY||1):1,e.signX||(e.signX=g),e.signY||(e.signY=f),isLocked(r,"lockScalingFlip")&&(e.signX!==g||e.signY!==f))return!1;if(u=r._getTransformedDimensions(),a&&!o){const t=Math.abs(l.x)+Math.abs(l.y),{original:i}=e,s=undefined,n=t/(Math.abs(u.x*i.scaleX/r.scaleX)+Math.abs(u.y*i.scaleY/r.scaleY));c=i.scaleX*n,d=i.scaleY*n}else c=Math.abs(l.x*r.scaleX/u.x),d=Math.abs(l.y*r.scaleY/u.y);isTransformCentered(e)&&(c*=2,d*=2),e.signX!==g&&"y"!==o&&(e.originX=invertOrigin(e.originX),c*=-1,e.signX=g),e.signY!==f&&"x"!==o&&(e.originY=invertOrigin(e.originY),d*=-1,e.signY=f)}const p=r.scaleX,m=r.scaleY;return o?("x"===o&&r.set(A,c),"y"===o&&r.set(F,d)):(!isLocked(r,"lockScalingX")&&r.set(A,c),!isLocked(r,"lockScalingY")&&r.set(F,d)),p!==r.scaleX||m!==r.scaleY}const scaleObjectFromCorner=(t,e,i,s)=>scaleObject(t,e,i,s),scaleObjectX=(t,e,i,s)=>scaleObject(t,e,i,s,{by:"x"}),scaleObjectY=(t,e,i,s)=>scaleObject(t,e,i,s,{by:"y"}),Ht=wrapWithFireEvent(S,wrapWithFixedAnchor(scaleObjectFromCorner)),Xt=wrapWithFireEvent(S,wrapWithFixedAnchor(scaleObjectX)),$t=wrapWithFireEvent(S,wrapWithFixedAnchor(scaleObjectY)),zt={x:{counterAxis:"y",scale:A,skew:L,lockSkewing:"lockSkewingX",origin:"originX",flip:"flipX"},y:{counterAxis:"x",scale:F,skew:j,lockSkewing:"lockSkewingY",origin:"originY",flip:"flipY"}},Yt=["ns","nesw","ew","nwse"],skewCursorStyleHandler=(t,e,i,s)=>{if(0!==e.x&&isLocked(i,"lockSkewingY"))return K;if(0!==e.y&&isLocked(i,"lockSkewingX"))return K;const n=findCornerQuadrant(i,e,s)%4;return`${Yt[n]}-resize`};function skewObject(t,e,i){let{target:s,ex:n,ey:r,skewingSide:o,...a}=e;const{skew:h}=zt[t],l=i.subtract(new Point(n,r)).divide(new Point(s.scaleX,s.scaleY))[t],c=s[h],d=a[h],u=Math.tan(degreesToRadians(d)),g="y"===t?s._getTransformedDimensions({scaleX:1,scaleY:1,skewX:0}).x:s._getTransformedDimensions({scaleX:1,scaleY:1}).y,f=2*l*o/Math.max(g,1)+u,p=radiansToDegrees(Math.atan(f));s.set(h,p);const m=c!==s[h];if(m&&"y"===t){const{skewX:t,scaleX:e}=s,i=s._getTransformedDimensions({skewY:c}),n=s._getTransformedDimensions(),r=0!==t?i.x/n.x:1;1!==r&&s.set(A,r*e)}return m}function skewHandler(t,e,i,s,n){const{target:r}=i,{counterAxis:o,origin:a,lockSkewing:h,skew:l,flip:c}=zt[t];if(isLocked(r,h))return!1;const{origin:d,flip:u}=zt[o],g=resolveOrigin(i[d])*(r[u]?-1:1),f=-Math.sign(g)*(r[c]?-1:1),m=undefined,y=.5*-((0===r[l]&&getLocalPoint(i,p,p,s,n)[t]>0||r[l]>0?1:-1)*f)+.5,x=wrapWithFireEvent(P,wrapWithFixedAnchor((e,i,s,n)=>skewObject(t,i,new Point(s,n))));return x(e,{...i,[a]:y,skewingSide:f},s,n)}const skewHandlerX=(t,e,i,s)=>skewHandler("x",t,e,i,s),skewHandlerY=(t,e,i,s)=>skewHandler("y",t,e,i,s);function isAltAction(t,e){return t[e.canvas.altActionKey]}const scaleOrSkewActionName=(t,e,i)=>{const s=isAltAction(t,i);return 0===e.x?s?L:F:0===e.y?s?j:A:""},scaleSkewCursorStyleHandler=(t,e,i,s)=>isAltAction(t,i)?skewCursorStyleHandler(t,e,i,s):scaleCursorStyleHandler(t,e,i,s),scalingXOrSkewingY=(t,e,i,s)=>isAltAction(t,e.target)?skewHandlerY(t,e,i,s):Xt(t,e,i,s),scalingYOrSkewingX=(t,e,i,s)=>isAltAction(t,e.target)?skewHandlerX(t,e,i,s):$t(t,e,i,s),createObjectDefaultControls=()=>({ml:new Control({x:-.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingXOrSkewingY,getActionName:scaleOrSkewActionName,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mr:new Control({x:.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingXOrSkewingY,getActionName:scaleOrSkewActionName,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mb:new Control({x:0,y:.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingYOrSkewingX,getActionName:scaleOrSkewActionName,render:renderVerticalPillControl,sizeX:20,sizeY:6}),mt:new Control({x:0,y:-.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:scalingYOrSkewingX,getActionName:scaleOrSkewActionName,render:renderVerticalPillControl,sizeX:20,sizeY:6}),tl:new Control({x:-.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),tr:new Control({x:.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),bl:new Control({x:-.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),br:new Control({x:.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),mtr:new Control({x:0,y:-.5,actionHandler:Rt,cursorStyleHandler:rotationStyleHandler,offsetY:-40,withConnection:!0,actionName:T})}),createResizeControls=()=>({mr:new Control({x:.5,y:0,actionHandler:Ft,cursorStyleHandler:scaleSkewCursorStyleHandler,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),ml:new Control({x:-.5,y:0,actionHandler:Ft,cursorStyleHandler:scaleSkewCursorStyleHandler,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20})}),createTextboxDefaultControls=()=>{const{mt:t,mb:e,...i}={...createObjectDefaultControls(),...createResizeControls()};return i},Vt="#ffffff",Gt="#8b5cf6",Nt="rgba(139, 92, 246, 0.1)",Ut="#8b5cf6",qt=[6,4],Kt=6,Jt=20,Zt=10,Qt=2,createDefaultExpansion=()=>({expandLeft:0,expandRight:0,expandTop:0,expandBottom:0});function getExpansion(t){return t.expansion||(t.expansion={expandLeft:0,expandRight:0,expandTop:0,expandBottom:0}),t.expansion}function setExpansion(t,e){const i=getExpansion(t);Object.assign(i,e)}class ExpandControl extends Control{constructor(t){super(t),this.expandDirections=t.expandDirections,this.actionName="expand"}positionHandler(t,e,i,s){const n=getExpansion(i),{expandLeft:r,expandRight:o,expandTop:a,expandBottom:h}=n,l=i.width||1,c=i.height||1,d=r/l,u=o/l,g=a/c,f=h/c;let p=this.x,m=this.y;return this.x<0?p=this.x-d:this.x>0&&(p=this.x+u),this.y<0?m=this.y-g:this.y>0&&(m=this.y+f),new Point(p*t.x+this.offsetX,m*t.y+this.offsetY).transform(e)}render(t,e,i,s,n){t.save(),t.translate(e,i);const r=n.getTotalAngle();t.rotate(degreesToRadians(r)),t.shadowColor="rgba(0, 0, 0, 0.2)",t.shadowBlur=3,t.shadowOffsetX=0,t.shadowOffsetY=1,t.fillStyle=Vt,t.strokeStyle=Gt,t.lineWidth=2;const o=undefined;0!==this.x&&0!==this.y?(t.beginPath(),t.arc(0,0,5,0,2*Math.PI),t.fill(),t.stroke()):0===this.y?(t.beginPath(),t.roundRect(-3,-10,6,Jt,2),t.fill(),t.stroke()):(t.beginPath(),t.roundRect(-10,-3,Jt,6,2),t.fill(),t.stroke()),t.restore()}}const expandLeftHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleX||1,h=undefined,l=n._getTransformedDimensions().x/2,c=undefined,d=Math.max(0,-l-o.x)/a;var u;return Math.abs(d-r.expandLeft)>.5&&(r.expandLeft=d,n.setCoords(),null===(u=n.canvas)||void 0===u||u.requestRenderAll(),!0)},expandRightHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleX||1,h=n.width*a/2,l=undefined,c=Math.max(0,o.x-h)/a;var d;return Math.abs(c-r.expandRight)>.5&&(r.expandRight=c,n.setCoords(),null===(d=n.canvas)||void 0===d||d.requestRenderAll(),!0)},expandTopHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleY||1,h=n.height*a/2,l=undefined,c=Math.max(0,-h-o.y)/a;var d;return Math.abs(c-r.expandTop)>.5&&(r.expandTop=c,n.setCoords(),null===(d=n.canvas)||void 0===d||d.requestRenderAll(),!0)},expandBottomHandler=(t,e,i,s)=>{const{target:n}=e,r=getExpansion(n),o=getLocalPoint(e,p,p,i,s),a=n.scaleY||1,h=n.height*a/2,l=undefined,c=Math.max(0,o.y-h)/a;var d;return Math.abs(c-r.expandBottom)>.5&&(r.expandBottom=c,n.setCoords(),null===(d=n.canvas)||void 0===d||d.requestRenderAll(),!0)};function createCornerExpandHandler(t,e){return(i,s,n,r)=>{const o=t(i,s,n,r),a=e(i,s,n,r);return o||a}}function expandCursorStyleHandler(t,e,i){const s=undefined,n=e.expandDirections;return n.includes("left")&&n.includes("right")?"ew-resize":n.includes("top")&&n.includes("bottom")?"ns-resize":n.includes("left")||n.includes("right")?"ew-resize":n.includes("top")||n.includes("bottom")?"ns-resize":2===n.length?n.includes("left")&&n.includes("top")||n.includes("right")&&n.includes("bottom")?"nwse-resize":"nesw-resize":"move"}function createExpandControls(){return{ml:new ExpandControl({x:-.5,y:0,expandDirections:["left"],actionHandler:expandLeftHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:6,sizeY:Jt}),mr:new ExpandControl({x:.5,y:0,expandDirections:["right"],actionHandler:expandRightHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:6,sizeY:Jt}),mt:new ExpandControl({x:0,y:-.5,expandDirections:["top"],actionHandler:expandTopHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:Jt,sizeY:6}),mb:new ExpandControl({x:0,y:.5,expandDirections:["bottom"],actionHandler:expandBottomHandler,cursorStyleHandler:expandCursorStyleHandler,sizeX:Jt,sizeY:6}),tl:new ExpandControl({x:-.5,y:-.5,expandDirections:["left","top"],actionHandler:createCornerExpandHandler(expandLeftHandler,expandTopHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt}),tr:new ExpandControl({x:.5,y:-.5,expandDirections:["right","top"],actionHandler:createCornerExpandHandler(expandRightHandler,expandTopHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt}),bl:new ExpandControl({x:-.5,y:.5,expandDirections:["left","bottom"],actionHandler:createCornerExpandHandler(expandLeftHandler,expandBottomHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt}),br:new ExpandControl({x:.5,y:.5,expandDirections:["right","bottom"],actionHandler:createCornerExpandHandler(expandRightHandler,expandBottomHandler),cursorStyleHandler:expandCursorStyleHandler,sizeX:Zt,sizeY:Zt})}}class InteractiveFabricObject extends At{static getDefaults(){return{...super.getDefaults(),...InteractiveFabricObject.ownDefaults}}constructor(t){super(),Object.assign(this,this.constructor.createControls(),InteractiveFabricObject.ownDefaults),this.setOptions(t),this.expandMode=!1,this.expansion={expandLeft:0,expandRight:0,expandTop:0,expandBottom:0}}static createControls(){return{controls:createObjectDefaultControls()}}_updateCacheCanvas(){const t=this.canvas;if(this.noScaleCache&&t&&t._currentTransform){const e=t._currentTransform,i=e.target,s=e.action;if(this===i&&s&&s.startsWith(E))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&&void 0!==arguments[1]&&arguments[1];if(!this.hasControls||!this.canvas)return;this.__corner=void 0;const i=Object.entries(this.oCoords);for(let s=i.length-1;s>=0;s--){const[n,r]=i[s],o=this.controls[n];if(o.shouldActivate(n,this,t,e?r.touchCorner:r.corner))return this.__corner=n,{key:n,control:o,coord:this.oCoords[n]}}}calcOCoords(){const t=this.getViewportTransform(),e=this.getCenterPoint(),i=createTranslateMatrix(e.x,e.y),s=createRotateMatrix({angle:this.getTotalAngle()-(this.group&&this.flipX?180:0)}),n=multiplyTransformMatrices(i,s),r=multiplyTransformMatrices(t,n),o=multiplyTransformMatrices(r,[1/t[0],0,0,1/t[3],0,0]),a=this.group?qrDecompose(this.calcTransformMatrix()):void 0;a&&(a.scaleX=Math.abs(a.scaleX),a.scaleY=Math.abs(a.scaleY));const h=this._calculateCurrentDimensions(a),l={};return this.forEachControl((t,e)=>{const i=t.positionHandler(h,o,this,t);l[e]=Object.assign(i,this._calcCornerCoords(t,i))}),l}_calcCornerCoords(t,e){const i=this.getTotalAngle(),s=undefined,n=undefined;return{corner:t.calcCornerCoords(i,this.cornerSize,e.x,e.y,!1,this),touchCorner:t.calcCornerCoords(i,this.touchCornerSize,e.x,e.y,!0,this)}}setCoords(){super.setCoords(),this.canvas&&(this.oCoords=this.calcOCoords())}forEachControl(t){for(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(),i=this._calculateCurrentDimensions(),s=this.getViewportTransform();t.translate(e.x,e.y),t.scale(1/s[0],1/s[3]),t.rotate(degreesToRadians(this.angle)),t.fillStyle=this.selectionBackgroundColor,t.fillRect(-i.x/2,-i.y/2,i.x,i.y),t.restore()}strokeBorders(t,e){t.strokeRect(-e.x/2,-e.y/2,e.x,e.y)}_drawBorders(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const s={hasControls:this.hasControls,borderColor:this.borderColor,borderDashArray:this.borderDashArray,...i};t.save(),t.strokeStyle=s.borderColor,this._setLineDash(t,s.borderDashArray),this.strokeBorders(t,e),s.hasControls&&this.drawControlsConnectingLines(t,e),t.restore()}_renderControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{hasBorders:i,hasControls:s}=this,n={hasBorders:i,hasControls:s,...e},r=this.getViewportTransform(),o=n.hasBorders,a=n.hasControls,h=multiplyTransformMatrices(r,this.calcTransformMatrix()),l=qrDecompose(h);t.save(),t.translate(l.translateX,l.translateY),t.lineWidth=this.borderScaleFactor,this.group===this.parent&&(t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1),this.flipX&&(l.angle-=180),t.rotate(degreesToRadians(this.group?l.angle:this.angle)),o&&this.drawBorders(t,l,e),a&&this.drawControls(t,e),t.restore()}drawBorders(t,e,i){let s;if(i&&i.forActiveSelection||this.group){const t=sizeAfterTransform(this.width,this.height,calcDimensionsMatrix(e)),i=this.isStrokeAccountedForInDimensions()?z:(this.strokeUniform?(new Point).scalarAdd(this.canvas?this.canvas.getZoom():1):new Point(e.scaleX,e.scaleY)).scalarMultiply(this.strokeWidth);s=t.add(i).scalarAdd(this.borderScaleFactor).scalarAdd(2*this.padding)}else s=this._calculateCurrentDimensions().scalarAdd(this.borderScaleFactor);this.expandMode&&this.drawExpandPreview(t,s,e),this._drawBorders(t,s,i)}drawControlsConnectingLines(t,e){let i=!1;t.beginPath(),this.forEachControl((s,n)=>{s.withConnection&&s.getVisibility(this,n)&&(i=!0,t.moveTo(s.x*e.x,s.y*e.y),t.lineTo(s.x*e.x+s.offsetX,s.y*e.y+s.offsetY))}),i&&t.stroke()}drawControls(t){var e;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=null===(e=this.canvas)||void 0===e?void 0:e._currentTransform,n=undefined;if(s&&s.target===this&&this.isMoving){const e=s.corner;if(!e)return;const n=this.controls[e];if(n&&n.getVisibility(this,e)){t.save();const s=this.getCanvasRetinaScaling(),{cornerStrokeColor:r,cornerDashArray:o,cornerColor:a}=this,h={cornerStrokeColor:r,cornerDashArray:o,cornerColor:a,...i};t.setTransform(s,0,0,s,0,0),t.strokeStyle=t.fillStyle=h.cornerColor,this.transparentCorners||(t.strokeStyle=h.cornerStrokeColor),this._setLineDash(t,h.cornerDashArray);const l=this.oCoords[e];n.render(t,l.x,l.y,h,this),t.restore()}return}t.save();const r=this.getCanvasRetinaScaling(),{cornerStrokeColor:o,cornerDashArray:a,cornerColor:h}=this,l={cornerStrokeColor:o,cornerDashArray:a,cornerColor:h,...i};t.setTransform(r,0,0,r,0,0),t.strokeStyle=t.fillStyle=l.cornerColor,this.transparentCorners||(t.strokeStyle=l.cornerStrokeColor),this._setLineDash(t,l.cornerDashArray),this.forEachControl((e,i)=>{if(e.getVisibility(this,i)){const s=this.oCoords[i];e.render(t,s.x,s.y,l,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&&void 0!==arguments[0]?arguments[0]:{};Object.entries(t).forEach(t=>{let[e,i]=t;return this.setControlVisible(e,i)})}clearContextTop(t){if(!this.canvas)return;const e=this.canvas.contextTop;if(!e)return;const i=this.canvas.viewportTransform;e.save(),e.transform(i[0],i[1],i[2],i[3],i[4],i[5]),this.transform(e);const s=this.width+4,n=this.height+4;return e.clearRect(-s/2,-n/2,s,n),t||e.restore(),e}onDeselect(t){return!1}onSelect(t){return!1}shouldStartDragging(t){return!1}onDragStart(t){return!1}canDrop(t){return!1}renderDragSourceEffect(t){}renderDropTargetEffect(t){}enterExpandMode(){var t;this.expandMode||(this._savedControls=this.controls,this._savedLockMovementX=this.lockMovementX,this._savedLockMovementY=this.lockMovementY,this._savedLockScalingX=this.lockScalingX,this._savedLockScalingY=this.lockScalingY,this.lockMovementX=!0,this.lockMovementY=!0,this.lockScalingX=!0,this.lockScalingY=!0,this.controls=createExpandControls(),this.expandMode=!0,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}exitExpandMode(){var t;this.expandMode&&(this._savedControls?(this.controls=this._savedControls,this._savedControls=void 0):this.controls=createObjectDefaultControls(),void 0!==this._savedLockMovementX&&(this.lockMovementX=this._savedLockMovementX,this._savedLockMovementX=void 0),void 0!==this._savedLockMovementY&&(this.lockMovementY=this._savedLockMovementY,this._savedLockMovementY=void 0),void 0!==this._savedLockScalingX&&(this.lockScalingX=this._savedLockScalingX,this._savedLockScalingX=void 0),void 0!==this._savedLockScalingY&&(this.lockScalingY=this._savedLockScalingY,this._savedLockScalingY=void 0),this.expandMode=!1,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}toggleExpandMode(){this.expandMode?this.exitExpandMode():this.enterExpandMode()}getExpansion(){return{...this.expansion}}setExpansion(t){var e;Object.assign(this.expansion,t),this.setCoords(),null===(e=this.canvas)||void 0===e||e.requestRenderAll()}resetExpansion(){var t;this.expansion={expandLeft:0,expandRight:0,expandTop:0,expandBottom:0},this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()}hasExpansion(){const{expandLeft:t,expandRight:e,expandTop:i,expandBottom:s}=this.expansion;return t>0||e>0||i>0||s>0}getExpandedDimensions(){const{expandLeft:t,expandRight:e,expandTop:i,expandBottom:s}=this.expansion;return{expandedWidth:this.width+t+e,expandedHeight:this.height+i+s}}drawExpandPreview(t,e,i){if(!this.expandMode)return;const s=this.borderScaleFactor||1,n=2*(this.padding||0),r=e.x-s-n,o=e.y-s-n,a=r/(this.width||1),h=o/(this.height||1),{expandLeft:l,expandRight:c,expandTop:d,expandBottom:u}=this.expansion,g=l*a,f=c*a,p=d*h,m=u*h,y=r+g+f,x=o+p+m,v=(f-g)/2,_=(m-p)/2;t.save(),t.fillStyle=Nt,t.fillRect(-y/2+v,-x/2+_,y,x),t.strokeStyle=Ut,t.lineWidth=1,t.setLineDash(qt),t.strokeRect(-y/2+v,-x/2+_,y,x),t.restore()}}function applyMixins(t,e){return e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i)||Object.create(null))})}),t}_defineProperty(InteractiveFabricObject,"ownDefaults",Dt);class FabricObject extends InteractiveFabricObject{}applyMixins(FabricObject,[FabricObjectSVGExportMixin]),X.setClass(FabricObject),X.setClass(FabricObject,"object");const isTransparent=(t,e,i,s)=>{const n=2*(s=Math.round(s))+1,{data:r}=t.getImageData(e-s,i-s,n,n);for(let t=3;t<r.length;t+=4){const e=undefined;if(r[t]>0)return!1}return!0},findIndexRight=(t,e)=>{for(let i=t.length-1;i>=0;i--)if(e(t[i],i,t))return i;return-1};class StrokeProjectionsBase{constructor(t){this.options=t,this.strokeProjectionMagnitude=this.options.strokeWidth/2,this.scale=new Point(this.options.scaleX,this.options.scaleY),this.strokeUniformScalar=this.options.strokeUniform?new Point(1/this.options.scaleX,1/this.options.scaleY):new Point(1,1)}createSideVector(t,e){const i=createVector(t,e);return this.options.strokeUniform?i.multiply(this.scale):i}projectOrthogonally(t,e,i){return this.applySkew(t.add(this.calcOrthogonalProjection(t,e,i)))}isSkewed(){return 0!==this.options.skewX||0!==this.options.skewY}applySkew(t){const e=new Point(t);return e.y+=e.x*Math.tan(degreesToRadians(this.options.skewY)),e.x+=e.y*Math.tan(degreesToRadians(this.options.skewX)),e}scaleUnitVector(t,e){return t.multiply(this.strokeUniformScalar).scalarMultiply(e)}}const te=new Point;class StrokeLineJoinProjections extends StrokeProjectionsBase{static getOrthogonalRotationFactor(t,e){const i=e?calcAngleBetweenVectors(t,e):calcVectorRotation(t);return Math.abs(i)<a?-1:1}constructor(t,e,i,s){super(s),_defineProperty(this,"AB",void 0),_defineProperty(this,"AC",void 0),_defineProperty(this,"alpha",void 0),_defineProperty(this,"bisector",void 0),this.A=new Point(t),this.B=new Point(e),this.C=new Point(i),this.AB=this.createSideVector(this.A,this.B),this.AC=this.createSideVector(this.A,this.C),this.alpha=calcAngleBetweenVectors(this.AB,this.AC),this.bisector=getUnitVector(rotateVector(this.AB.eq(te)?this.AC:this.AB,this.alpha/2))}calcOrthogonalProjection(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.strokeProjectionMagnitude;const s=this.createSideVector(t,e),n=getOrthonormalVector(s),r=StrokeLineJoinProjections.getOrthogonalRotationFactor(n,this.bisector);return this.scaleUnitVector(n,i*r)}projectBevel(){const t=[];return(this.alpha%l===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),i=1/Math.sin(e/2),s=this.scaleUnitVector(this.bisector,-this.strokeProjectionMagnitude*i),n=this.options.strokeUniform?magnitude(this.scaleUnitVector(this.bisector,this.options.strokeMiterLimit)):this.options.strokeMiterLimit;return magnitude(s)/this.strokeProjectionMagnitude<=n&&t.push(this.applySkew(this.A.add(s))),t.push(...this.projectBevel()),t}projectRoundNoSkew(t,e){const i=[],s=new Point(StrokeLineJoinProjections.getOrthogonalRotationFactor(this.bisector),StrokeLineJoinProjections.getOrthogonalRotationFactor(new Point(this.bisector.y,this.bisector.x))),n=undefined,r=undefined;return[new Point(1,0).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(s),new Point(0,1).scalarMultiply(this.strokeProjectionMagnitude).multiply(this.strokeUniformScalar).multiply(s)].forEach(s=>{isBetweenVectors(s,t,e)&&i.push(this.A.add(s))}),i}projectRoundWithSkew(t,e){const i=[],{skewX:s,skewY:n,scaleX:r,scaleY:o,strokeUniform:a}=this.options,h=new Point(Math.tan(degreesToRadians(s)),Math.tan(degreesToRadians(n))),l=this.strokeProjectionMagnitude,c=a?l/o/Math.sqrt(1/o**2+1/r**2*h.y**2):l/Math.sqrt(1+h.y**2),d=new Point(Math.sqrt(Math.max(l**2-c**2,0)),c),u=a?l/Math.sqrt(1+h.x**2*(1/o)**2/(1/r+1/r*h.x*h.y)**2):l/Math.sqrt(1+h.x**2/(1+h.x*h.y)**2),g=new Point(u,Math.sqrt(Math.max(l**2-u**2,0)));return[g,g.scalarMultiply(-1),d,d.scalarMultiply(-1)].map(t=>this.applySkew(a?t.multiply(this.strokeUniformScalar):t)).forEach(s=>{isBetweenVectors(s,t,e)&&i.push(this.applySkew(this.A).add(s))}),i}projectRound(){const t=[];t.push(...this.projectBevel());const e=this.alpha%l===0,i=this.applySkew(this.A),s=t[e?0:2].subtract(i),n=t[e?1:0].subtract(i),r=e?this.applySkew(this.AB.scalarMultiply(-1)):this.applySkew(this.bisector.multiply(this.strokeUniformScalar).scalarMultiply(-1)),o=crossProduct(s,r)>0,a=o?s:n,h=o?n:s;return this.isSkewed()?t.push(...this.projectRoundWithSkew(a,h)):t.push(...this.projectRoundNoSkew(a,h)),t}projectPoints(){switch(this.options.strokeLineJoin){case"miter":return this.projectMiter();case"round":return this.projectRound();default:return this.projectBevel()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t,angle:this.alpha,bisector:this.bisector}))}}class StrokeLineCapProjections extends StrokeProjectionsBase{constructor(t,e,i){super(i),this.A=new Point(t),this.T=new Point(e)}calcOrthogonalProjection(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.strokeProjectionMagnitude;const s=this.createSideVector(t,e);return this.scaleUnitVector(getOrthonormalVector(s),i)}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 Point(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 StrokeLineJoinProjections(this.A,this.T,this.T,this.options).projectRound());return t}projectSquare(){const t=[];if(this.A.eq(this.T)){const e=new Point(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),i=this.scaleUnitVector(getUnitVector(this.createSideVector(this.A,this.T)),-this.strokeProjectionMagnitude),s=this.A.add(i);t.push(s.add(e),s.subtract(e))}return t.map(t=>this.applySkew(t))}projectPoints(){switch(this.options.strokeLineCap){case"round":return this.projectRound();case"square":return this.projectSquare();default:return this.projectButt()}}project(){return this.projectPoints().map(t=>({originPoint:this.A,projectedPoint:t}))}}const projectStrokeOnPoints=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const s=[];if(0===t.length)return s;const n=t.reduce((t,e)=>(t[t.length-1].eq(e)||t.push(new Point(e)),t),[new Point(t[0])]);if(1===n.length)i=!0;else if(!i){const t=n[0],e=findIndexRight(n,e=>!e.eq(t));n.splice(e+1)}return n.forEach((t,n,r)=>{let o,a;0===n?(a=r[1],o=i?t:r[r.length-1]):n===r.length-1?(o=r[n-1],a=i?t:r[0]):(o=r[n-1],a=r[n+1]),i&&1===r.length?s.push(...new StrokeLineCapProjections(t,t,e).project()):!i||0!==n&&n!==r.length-1?s.push(...new StrokeLineJoinProjections(t,o,a,e).project()):s.push(...new StrokeLineCapProjections(t,0===n?a:o,e).project())}),s},cloneStyles=t=>{const e={};return Object.keys(t).forEach(i=>{e[i]={},Object.keys(t[i]).forEach(s=>{e[i][s]={...t[i][s]}})}),e},capitalize=function(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return`${t.charAt(0).toUpperCase()}${e?t.slice(1):t.slice(1).toLowerCase()}`},escapeXml=t=>t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;");let ee;const getSegmenter=()=>(ee||(ee="Intl"in getFabricWindow()&&"Segmenter"in Intl&&new Intl.Segmenter(void 0,{granularity:"grapheme"})),ee),graphemeSplit=t=>{if(ee||getSegmenter(),ee){const e=ee.segment(t);return Array.from(e).map(t=>{let{segment:e}=t;return e})}return graphemeSplitImpl(t)},graphemeSplitImpl=t=>{const e=[];for(let i=0,s;i<t.length;i++)!1!==(s=getWholeChar(t,i))&&e.push(s);return e},getWholeChar=(t,e)=>{const i=t.charCodeAt(e);if(isNaN(i))return"";if(i<55296||i>57343)return t.charAt(e);if(55296<=i&&i<=56319){if(t.length<=e+1)throw"High surrogate without following low surrogate";const i=t.charCodeAt(e+1);if(56320>i||i>57343)throw"High surrogate without following low surrogate";return t.charAt(e)+t.charAt(e+1)}if(0===e)throw"Low surrogate without preceding high surrogate";const s=t.charCodeAt(e-1);if(55296>s||s>56319)throw"Low surrogate without preceding high surrogate";return!1};var ie=Object.freeze({__proto__:null,capitalize:capitalize,escapeXml:escapeXml,graphemeSplit:graphemeSplit});const hasStyleChanged=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return t.fill!==e.fill||t.stroke!==e.stroke||t.strokeWidth!==e.strokeWidth||t.fontSize!==e.fontSize||t.fontFamily!==e.fontFamily||t.fontWeight!==e.fontWeight||t.fontStyle!==e.fontStyle||t.textDecorationThickness!==e.textDecorationThickness||t.textBackgroundColor!==e.textBackgroundColor||t.deltaY!==e.deltaY||i&&(t.overline!==e.overline||t.underline!==e.underline||t.linethrough!==e.linethrough)},stylesToArray=(t,e)=>{const i=e.split("\n"),s=[];let n=-1,r={};t=cloneStyles(t);for(let e=0;e<i.length;e++){const o=graphemeSplit(i[e]);if(t[e])for(let i=0;i<o.length;i++){n++;const o=t[e][i];o&&Object.keys(o).length>0&&(hasStyleChanged(r,o,!0)?s.push({start:n,end:n+1,style:o}):s[s.length-1].end++),r=o||{}}else n+=o.length,r={}}return s},stylesFromArray=(t,e)=>{if(!Array.isArray(t))return cloneStyles(t);const i=e.split(C),s={};let n=-1,r=0;for(let e=0;e<i.length;e++){const o=graphemeSplit(i[e]);for(let i=0;i<o.length;i++)n++,t[r]&&t[r].start<=n&&n<t[r].end&&(s[e]=s[e]||{},s[e][i]={...t[r].style},n===t[r].end-1&&r++)}return s},se=["display","transform",I,"fill-opacity","fill-rule","opacity",B,"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 selectorMatches(t,e){const i=t.nodeName,s=t.getAttribute("class"),n=t.getAttribute("id"),r="(?![a-zA-Z\\-]+)";let o;if(o=new RegExp("^"+i,"i"),e=e.replace(o,""),n&&e.length&&(o=new RegExp("#"+n+r,"i"),e=e.replace(o,"")),s&&e.length){const t=s.split(" ");for(let i=t.length;i--;)o=new RegExp("\\."+t[i]+r,"i"),e=e.replace(o,"")}return 0===e.length}function doesSomeParentMatch(t,e){let i,s=!0;for(;t.parentElement&&1===t.parentElement.nodeType&&e.length;)s&&(i=e.pop()),s=selectorMatches(t=t.parentElement,i);return 0===e.length}function elementMatchesRule(t,e){let i=!0;const s=selectorMatches(t,e.pop());return s&&e.length&&(i=doesSomeParentMatch(t,e)),s&&i&&0===e.length}function getGlobalStylesForElement(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i={};for(const s in e)elementMatchesRule(t,s.split(" "))&&(i={...i,...e[s]});return i}const normalizeAttr=t=>{var e;return null!==(e=yt[t])&&void 0!==e?e:t},ne=new RegExp(`(${lt})`,"gi"),cleanupSvgAttribute=t=>t.replace(ne," $1 ").replace(/,/gi," ").replace(/\s+/gi," "),re=`(${lt})`,oe=String.raw`(skewX)\(${re}\)`,ae=String.raw`(skewY)\(${re}\)`,he=String.raw`(rotate)\(${re}(?: ${re} ${re})?\)`,le=String.raw`(scale)\(${re}(?: ${re})?\)`,ce=String.raw`(translate)\(${re}(?: ${re})?\)`,de=undefined,ue=`(?:${String.raw`(matrix)\(${re} ${re} ${re} ${re} ${re} ${re}\)`}|${ce}|${he}|${le}|${oe}|${ae})`,ge=`(?:${ue}*)`,fe=String.raw`^\s*(?:${ge}?)\s*$`,pe=new RegExp(fe),me=new RegExp(ue),ye=new RegExp(ue,"g");function parseTransformAttribute(t){const e=[];if(!(t=cleanupSvgAttribute(t).replace(/\s*([()])\s*/gi,"$1"))||t&&!pe.test(t))return[...d];for(const i of t.matchAll(ye)){const t=me.exec(i[0]);if(!t)continue;let s=d;const n=t.filter(t=>!!t),[,r,...o]=n,[a,h,l,c,u,g]=o.map(t=>parseFloat(t));switch(r){case"translate":s=createTranslateMatrix(a,h);break;case T:s=createRotateMatrix({angle:a},{x:h,y:l});break;case E:s=createScaleMatrix(a,h);break;case L:s=createSkewXMatrix(a);break;case j:s=createSkewYMatrix(a);break;case"matrix":s=[a,h,l,c,u,g];break}e.push(s)}return multiplyTransformMatrixArray(e)}function normalizeValue(t,e,i,s){const n=Array.isArray(e);let r,o=e;if(t!==I&&t!==B||e!==_){if("strokeUniform"===t)return"non-scaling-stroke"===e;if("strokeDashArray"===t)o=e===_?null:e.replace(/,/g," ").split(/\s+/).map(parseFloat);else if("transformMatrix"===t)o=i&&i.transformMatrix?multiplyTransformMatrices(i.transformMatrix,parseTransformAttribute(e)):parseTransformAttribute(e);else if("visible"===t)o=e!==_&&"hidden"!==e,i&&!1===i.visible&&(o=!1);else if("opacity"===t)o=parseFloat(e),i&&void 0!==i.opacity&&(o*=i.opacity);else if("textAnchor"===t)o="start"===e?m:"end"===e?v:p;else if("charSpacing"===t||t===Z)r=parseUnit(e,s)/s*1e3;else if("paintFirst"===t){const t=e.indexOf(I),i=e.indexOf(B);o=I,(t>-1&&i>-1&&i<t||-1===t&&i>-1)&&(o=B)}else{if("href"===t||"xlink:href"===t||"font"===t||"id"===t)return e;if("imageSmoothing"===t)return"optimizeQuality"===e;r=n?e.map(parseUnit):parseUnit(e,s)}}else o="";return!n&&isNaN(r)?o:r}function parseFontDeclaration(t,e){const i=t.match(ut);if(!i)return;const s=i[1],n=i[3],r=i[4],o=i[5],a=i[6];s&&(e.fontStyle=s),n&&(e.fontWeight=isNaN(parseFloat(n))?n:parseFloat(n)),r&&(e.fontSize=parseUnit(r)),a&&(e.fontFamily=a),o&&(e.lineHeight="normal"===o?1:o)}function parseStyleObject(t,e){Object.entries(t).forEach(t=>{let[i,s]=t;void 0!==s&&(e[i.toLowerCase()]=s)})}function parseStyleString(t,e){t.replace(/;\s*$/,"").split(";").forEach(t=>{if(!t)return;const[i,s]=t.split(":");e[i.trim().toLowerCase()]=s.trim()})}function parseStyleAttribute(t){const e={},i=t.getAttribute("style");return i?("string"==typeof i?parseStyleString(i,e):parseStyleObject(i,e),e):e}const xe={stroke:"strokeOpacity",fill:"fillOpacity"};function setStrokeFillOpacity(t){const e=FabricObject.getDefaults();return Object.entries(xe).forEach(i=>{let[s,n]=i;if(void 0===t[n]||""===t[s])return;if(void 0===t[s]){if(!e[s])return;t[s]=e[s]}if(0===t[s].indexOf("url("))return;const r=new Color(t[s]);t[s]=r.setAlpha(toFixed(r.getAlpha()*t[n],2)).toRgba()}),t}function parseAttributes(t,e,i){if(!t)return{};let s={},n,r=u;t.parentNode&&bt.test(t.parentNode.nodeName)&&(s=parseAttributes(t.parentElement,e,i),s.fontSize&&(n=r=parseUnit(s.fontSize)));const o={...e.reduce((e,i)=>{const s=t.getAttribute(i);return s&&(e[i]=s),e},{}),...getGlobalStylesForElement(t,i),...parseStyleAttribute(t)};o[vt]&&t.setAttribute(vt,o[vt]),o[xt]&&(n=parseUnit(o[xt],r),o[xt]=`${n}`);const a={};for(const t in o){const e=normalizeAttr(t),i=normalizeValue(e,o[t],s,n);a[e]=i}a&&a.font&&parseFontDeclaration(a.font,a);const h={...s,...a};return bt.test(t.nodeName)?h:setStrokeFillOpacity(h)}const ve={rx:0,ry:0},_e=["rx","ry"];class Rect extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Rect.ownDefaults}}constructor(t){super(),Object.assign(this,Rect.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:i}=this,s=-e/2,n=-i/2,r=this.rx?Math.min(this.rx,e/2):0,o=this.ry?Math.min(this.ry,i/2):0,a=0!==r||0!==o;t.beginPath(),t.moveTo(s+r,n),t.lineTo(s+e-r,n),a&&t.bezierCurveTo(s+e-f*r,n,s+e,n+f*o,s+e,n+o),t.lineTo(s+e,n+i-o),a&&t.bezierCurveTo(s+e,n+i-f*o,s+e-f*r,n+i,s+e-r,n+i),t.lineTo(s+r,n+i),a&&t.bezierCurveTo(s+f*r,n+i,s,n+i-f*o,s,n+i-o),t.lineTo(s,n+o),a&&t.bezierCurveTo(s,n+f*o,s+f*r,n,s+r,n),t.closePath(),this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([..._e,...t])}_toSVG(){const{width:t,height:e,rx:i,ry:s}=this;return["<rect ","COMMON_PARTS",`x="${-t/2}" y="${-e/2}" rx="${i}" ry="${s}" width="${t}" height="${e}" />\n`]}static async fromElement(t,e,i){const{left:s=0,top:n=0,width:r=0,height:o=0,visible:a=!0,...h}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this({...e,...h,left:s,top:n,width:r,height:o,visible:Boolean(a&&r&&o)})}}_defineProperty(Rect,"type","Rect"),_defineProperty(Rect,"cacheProperties",[...Ot,..._e]),_defineProperty(Rect,"ownDefaults",ve),_defineProperty(Rect,"ATTRIBUTE_NAMES",[...se,"x","y","rx","ry","width","height"]),X.setClass(Rect),X.setSVGClass(Rect);const Ce="initialization",be="added",Se="removed",we="imperative",Te="object_modified",Pe="object_modifying",getObjectBounds=(t,e)=>{const{strokeUniform:i,strokeWidth:s,width:n,height:r,group:o}=e,a=o&&o!==t?calcPlaneChangeMatrix(o.calcTransformMatrix(),t.calcTransformMatrix()):null,h=a?e.getRelativeCenterPoint().transform(a):e.getRelativeCenterPoint(),l=!e.isStrokeAccountedForInDimensions(),c=i&&l?sendVectorToPlane(new Point(s,s),void 0,t.calcTransformMatrix()):z,d=!i&&l?s:0,u=sizeAfterTransform(n+d,r+d,multiplyTransformMatrixArray([a,e.calcOwnMatrix()],!0)).add(c).scalarDivide(2);return[h.subtract(u),h.add(u)]};class LayoutStrategy{calcLayoutResult(t,e){if(this.shouldPerformLayout(t))return this.calcBoundingBox(e,t)}shouldPerformLayout(t){let{type:e,prevStrategy:i,strategy:s}=t;return e===Ce||e===we||!!i&&s!==i}shouldLayoutClipPath(t){let{type:e,target:{clipPath:i}}=t;return e!==Ce&&i&&!i.absolutePositioned}getInitialSize(t,e){return e.size}calcBoundingBox(t,e){const{type:i,target:s}=e;if(i===we&&e.overrides)return e.overrides;if(0===t.length)return;const{left:n,top:r,width:o,height:a}=makeBoundingBoxFromPoints(t.map(t=>getObjectBounds(s,t)).reduce((t,e)=>t.concat(e),[])),h=new Point(o,a),l=undefined,c=new Point(n,r).add(h.scalarDivide(2));if(i===Ce){const t=this.getInitialSize(e,{size:h,center:c});return{center:c,relativeCorrection:new Point(0,0),size:t}}{const t=undefined;return{center:c.transform(s.calcOwnMatrix()),size:h}}}}_defineProperty(LayoutStrategy,"type","strategy");class FitContentLayout extends LayoutStrategy{shouldPerformLayout(t){return!0}}_defineProperty(FitContentLayout,"type","fit-content"),X.setClass(FitContentLayout);const Me="layoutManager";class LayoutManager{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new FitContentLayout;_defineProperty(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 i=this.getLayoutResult(e);i&&this.commitLayout(e,i),this.onAfterLayout(e,i),this._prevLayoutStrategy=e.strategy}attachHandlers(t,e){const{target:i}=e;return[R,b,M,w,S,P,D,O,k].map(e=>t.on(e,t=>this.performLayout(e===R?{type:Te,trigger:e,e:t,target:i}:{type:Pe,trigger:e,e:t,target:i})))}subscribe(t,e){this.unsubscribe(t,e);const i=this.attachHandlers(t,e);this._subscriptions.set(t,i)}unsubscribe(t,e){(this._subscriptions.get(t)||[]).forEach(t=>t()),this._subscriptions.delete(t)}unsubscribeTargets(t){t.targets.forEach(e=>this.unsubscribe(e,t))}subscribeTargets(t){t.targets.forEach(e=>this.subscribe(e,t))}onBeforeLayout(t){const{target:e,type:i}=t,{canvas:s}=e;if(i===Ce||i===be?this.subscribeTargets(t):i===Se&&this.unsubscribeTargets(t),e.fire("layout:before",{context:t}),s&&s.fire("object:layout:before",{target:e,context:t}),i===we&&t.deep){const{strategy:i,...s}=t;e.forEachObject(t=>t.layoutManager&&t.layoutManager.performLayout({...s,bubbles:!1,target:t}))}}getLayoutResult(t){const{target:e,strategy:i,type:s}=t,n=i.calcLayoutResult(t,e.getObjects());if(!n)return;const r=s===Ce?new Point:e.getRelativeCenterPoint(),{center:o,correction:a=new Point,relativeCorrection:h=new Point}=n,l=r.subtract(o).add(a).transform(s===Ce?d:invertTransform(e.calcOwnMatrix()),!0).add(h);return{result:n,prevCenter:r,nextCenter:o,offset:l}}commitLayout(t,e){const{target:i}=t,{result:{size:s},nextCenter:n}=e;var r,o;(i.set({width:s.x,height:s.y}),this.layoutObjects(t,e),t.type===Ce)?i.set({left:null!==(r=t.x)&&void 0!==r?r:n.x+s.x*resolveOrigin(i.originX),top:null!==(o=t.y)&&void 0!==o?o:n.y+s.y*resolveOrigin(i.originY)}):(i.setPositionByOrigin(n,p,p),i.setCoords(),i.set("dirty",!0))}layoutObjects(t,e){const{target:i}=t;i.forEachObject(s=>{s.group===i&&this.layoutObject(t,e,s)}),t.strategy.shouldLayoutClipPath(t)&&this.layoutObject(t,e,i.clipPath)}layoutObject(t,e,i){let{offset:s}=e;i.set({left:i.left+s.x,top:i.top+s.y})}onAfterLayout(t,e){const{target:i,strategy:s,bubbles:n,prevStrategy:r,...o}=t,{canvas:a}=i;i.fire("layout:after",{context:t,result:e}),a&&a.fire("object:layout:after",{context:t,result:e,target:i});const h=i.parent;n&&null!=h&&h.layoutManager&&((o.path||(o.path=[])).push(i),h.layoutManager.performLayout({...o,target:h})),i.set("dirty",!0)}dispose(){const{_subscriptions:t}=this;t.forEach(t=>t.forEach(t=>t())),t.clear()}toObject(){return{type:Me,strategy:this.strategy.constructor.type}}toJSON(){return this.toObject()}}X.setClass(LayoutManager,Me);class NoopLayoutManager extends LayoutManager{performLayout(){}}const Oe={strokeWidth:0,subTargetCheck:!1,interactive:!1};class Group extends(createCollectionMixin(FabricObject)){static getDefaults(){return{...super.getDefaults(),...Group.ownDefaults}}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_defineProperty(this,"_activeObjects",[]),_defineProperty(this,"__objectSelectionTracker",void 0),_defineProperty(this,"__objectSelectionDisposer",void 0),Object.assign(this,Group.ownDefaults),this.setOptions(e),this.groupInit(t,e)}groupInit(t,e){var i;this._objects=[...t],this.__objectSelectionTracker=this.__objectSelectionMonitor.bind(this,!0),this.__objectSelectionDisposer=this.__objectSelectionMonitor.bind(this,!1),this.forEachObject(t=>{this.enterGroup(t,!1)}),this.layoutManager=null!==(i=e.layoutManager)&&void 0!==i?i:new LayoutManager,this.layoutManager.performLayout({type:Ce,target:this,targets:[...t],x:e.left,y:e.top})}canEnterGroup(t){return t===this||this.isDescendantOf(t)?(log("error","Group: circular object trees are not supported, this call has no effect"),!1):-1===this._objects.indexOf(t)||(log("error","Group: duplicate objects are not supported inside group, this call has no effect"),!1)}_filterObjectsBeforeEnteringGroup(t){return t.filter((t,e,i)=>this.canEnterGroup(t)&&i.indexOf(t)===e)}add(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];const s=this._filterObjectsBeforeEnteringGroup(e),n=super.add(...s);return this._onAfterObjectsChange(be,s),n}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];const n=this._filterObjectsBeforeEnteringGroup(i),r=super.insertAt(t,...n);return this._onAfterObjectsChange(be,n),r}remove(){const t=super.remove(...arguments);return this._onAfterObjectsChange(Se,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 i=this[t];return super._set(t,e),"canvas"===t&&i!==e&&(this._objects||[]).forEach(i=>{i._set(t,e)}),this}_shouldSetNestedCoords(){return this.subTargetCheck}removeAll(){return this._activeObjects=[],this.remove(...this._objects)}__objectSelectionMonitor(t,e){let{target:i}=e;const s=this._activeObjects;if(t)s.push(i),this._set("dirty",!0);else if(s.length>0){const t=s.indexOf(i);t>-1&&(s.splice(t,1),this._set("dirty",!0))}}_watchObject(t,e){t&&this._watchObject(!1,e),t?(e.on("selected",this.__objectSelectionTracker),e.on("deselected",this.__objectSelectionDisposer)):(e.off("selected",this.__objectSelectionTracker),e.off("deselected",this.__objectSelectionDisposer))}enterGroup(t,e){t.group&&t.group.remove(t),t._set("parent",this),this._enterGroup(t,e)}_enterGroup(t,e){e&&applyTransformToObject(t,multiplyTransformMatrices(invertTransform(this.calcTransformMatrix()),t.calcTransformMatrix())),this._shouldSetNestedCoords()&&t.setCoords(),t._set("group",this),t._set("canvas",this.canvas),this._watchObject(!0,t);const i=this.canvas&&this.canvas.getActiveObject&&this.canvas.getActiveObject();i&&(i===t||t.isDescendantOf(i))&&this._activeObjects.push(t)}exitGroup(t,e){this._exitGroup(t,e),t._set("parent",void 0),t._set("canvas",void 0)}_exitGroup(t,e){t._set("group",void 0),e||(applyTransformToObject(t,multiplyTransformMatrices(this.calcTransformMatrix(),t.calcTransformMatrix())),t.setCoords()),this._watchObject(!1,t);const i=this._activeObjects.length>0?this._activeObjects.indexOf(t):-1;i>-1&&this._activeObjects.splice(i,1)}shouldCache(){const t=FabricObject.prototype.shouldCache.call(this);if(t)for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return this.ownCaching=!1,!1;return t}willDrawShadow(){if(super.willDrawShadow())return!0;for(let t=0;t<this._objects.length;t++)if(this._objects[t].willDrawShadow())return!0;return!1}isOnACache(){return this.ownCaching||!!this.parent&&this.parent.isOnACache()}drawObject(t,e,i){this._renderBackground(t);for(let e=0;e<this._objects.length;e++){var s;const i=this._objects[e];null!==(s=this.canvas)&&void 0!==s&&s.preserveObjectStacking&&i.group!==this?(t.save(),t.transform(...invertTransform(this.calcTransformMatrix())),i.render(t),t.restore()):i.group===this&&i.render(t)}this._drawClipPath(t,this.clipPath,i)}setCoords(){super.setCoords(),this._shouldSetNestedCoords()&&this.forEachObject(t=>t.setCoords())}triggerLayout(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.layoutManager.performLayout({target:this,type:we,...t})}render(t){this._transformDone=!0,super.render(t),this._transformDone=!1}__serializeObjects(t,e){const i=this.includeDefaultValues;return this._objects.filter(function(t){return!t.excludeFromExport}).map(function(s){const n=s.includeDefaultValues;s.includeDefaultValues=i;const r=s[t||"toObject"](e);return s.includeDefaultValues=n,r})}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=this.layoutManager.toObject();return{...super.toObject(["subTargetCheck","interactive",...t]),..."fit-content"!==e.strategy||this.includeDefaultValues?{layoutManager:e}:{},objects:this.__serializeObjects("toObject",t)}}toString(){return`#<Group: (${this.complexity()})>`}dispose(){this.layoutManager.unsubscribeTargets({targets:this.getObjects(),target:this}),this._activeObjects=[],this.forEachObject(t=>{this._watchObject(!1,t),t.dispose()}),super.dispose()}_createSVGBgRect(t){if(!this.backgroundColor)return"";const e=Rect.prototype._toSVG.call(this),i=e.indexOf("COMMON_PARTS");e[i]='for="group" ';const s=e.join("");return t?t(s):s}_toSVG(t){const e=["<g ","COMMON_PARTS"," >\n"],i=this._createSVGBgRect(t);i&&e.push("\t\t",i);for(let i=0;i<this._objects.length;i++)e.push("\t\t",this._objects[i].toSVG(t));return e.push("</g>\n"),e}getSvgStyles(){const t=void 0!==this.opacity&&1!==this.opacity?`opacity: ${this.opacity};`:"",e=this.visible?"":" visibility: hidden;";return[t,this.getSvgFilter(),e].join("")}toClipPathSVG(t){const e=[],i=this._createSVGBgRect(t);i&&e.push("\t",i);for(let i=0;i<this._objects.length;i++)e.push("\t",this._objects[i].toClipPathSVG(t));return this._createBaseClipPathSVGMarkup(e,{reviver:t})}static fromObject(t,e){let{type:i,objects:s=[],layoutManager:n,...r}=t;return Promise.all([enlivenObjects(s,e),enlivenObjectEnlivables(r,e)]).then(t=>{let[e,i]=t;const s=new this(e,{...r,...i,layoutManager:new NoopLayoutManager});if(n){const t=X.getClass(n.type),e=X.getClass(n.strategy);s.layoutManager=new t(new e)}else s.layoutManager=new LayoutManager;return s.layoutManager.subscribeTargets({type:Ce,target:s,targets:s.getObjects()}),s.setCoords(),s})}}_defineProperty(Group,"type","Group"),_defineProperty(Group,"ownDefaults",Oe),X.setClass(Group);const groupSVGElements=(t,e)=>t&&1===t.length?t[0]:new Group(t,e),findScaleToFit=(t,e)=>Math.min(e.width/t.width,e.height/t.height),findScaleToCover=(t,e)=>Math.max(e.width/t.width,e.height/t.height),ke="\\s*,?\\s*",De=`${ke}(${lt})`,Ee=`${De}${De}${De}${ke}([01])${ke}([01])${De}${De}`,Ae=undefined,Fe={m:"l",M:"L"},segmentToBezier=(t,e,i,s,n,r,o,a,h,l,c)=>{const d=cos(t),u=sin(t),g=cos(e),f=sin(e),p=i*n*g-s*r*f+o,m=s*n*g+i*r*f+a,y=undefined,x=undefined,v=undefined,_=undefined;return["C",l+h*(-i*n*u-s*r*d),c+h*(-s*n*u+i*r*d),p+h*(i*n*f+s*r*g),m+h*(s*n*f-i*r*g),p,m]},arcToSegments=(t,e,i,s,n,r,o)=>{if(0===i||0===s)return[];let a=0,h=0,l=0;const d=Math.PI,u=o*c,g=sin(u),f=cos(u),p=.5*(-f*t-g*e),m=.5*(-f*e+g*t),y=i**2,x=s**2,v=m**2,_=p**2,C=y*x-y*v-x*_;let b=Math.abs(i),S=Math.abs(s);if(C<0){const t=Math.sqrt(1-C/(y*x));b*=t,S*=t}else l=(n===r?-1:1)*Math.sqrt(C/(y*v+x*_));const w=l*b*m/S,T=-l*S*p/b,P=f*w-g*T+.5*t,M=g*w+f*T+.5*e;let O=calcVectorAngle(1,0,(p-w)/b,(m-T)/S),k=calcVectorAngle((p-w)/b,(m-T)/S,(-p-w)/b,(-m-T)/S);0===r&&k>0?k-=2*d:1===r&&k<0&&(k+=2*d);const D=Math.ceil(Math.abs(k/d*2)),E=[],A=k/D,F=8/3*Math.sin(A/4)*Math.sin(A/4)/Math.sin(A/2);let L=O+A;for(let t=0;t<D;t++)E[t]=segmentToBezier(O,L,f,g,b,S,P,M,F,a,h),a=E[t][5],h=E[t][6],O=L,L+=A;return E},calcVectorAngle=(t,e,i,s)=>{const n=Math.atan2(e,t),r=Math.atan2(s,i);return r>=n?r-n:2*Math.PI-(n-r)},CB1=t=>t**3,CB2=t=>3*t**2*(1-t),CB3=t=>3*t*(1-t)**2,CB4=t=>(1-t)**3;function getBoundsOfCurve(t,i,s,r,o,a,h,l){let c;if(e.cachesBoundsOfCurve&&(c=[...arguments].join(),n.boundsOfCurveCache[c]))return n.boundsOfCurveCache[c];const d=Math.sqrt,u=Math.abs,g=[],f=[[0,0],[0,0]];let p=6*t-12*s+6*o,m=-3*t+9*s-9*o+3*h,y=3*s-3*t;for(let t=0;t<2;++t){if(t>0&&(p=6*i-12*r+6*a,m=-3*i+9*r-9*a+3*l,y=3*r-3*i),u(m)<1e-12){if(u(p)<1e-12)continue;const t=-y/p;0<t&&t<1&&g.push(t);continue}const e=p*p-4*y*m;if(e<0)continue;const s=d(e),n=(-p+s)/(2*m);0<n&&n<1&&g.push(n);const o=(-p-s)/(2*m);0<o&&o<1&&g.push(o)}let x=g.length;const v=x,_=getPointOnCubicBezierIterator(t,i,s,r,o,a,h,l);for(;x--;){const{x:t,y:e}=_(g[x]);f[0][x]=t,f[1][x]=e}f[0][v]=t,f[1][v]=i,f[0][v+1]=h,f[1][v+1]=l;const C=[new Point(Math.min(...f[0]),Math.min(...f[1])),new Point(Math.max(...f[0]),Math.max(...f[1]))];return e.cachesBoundsOfCurve&&(n.boundsOfCurveCache[c]=C),C}const fromArcToBeziers=(t,e,i)=>{let[s,n,r,o,a,h,l,c]=i;const d=arcToSegments(l-t,c-e,n,r,a,h,o);for(let i=0,s=d.length;i<s;i++)d[i][1]+=t,d[i][2]+=e,d[i][3]+=t,d[i][4]+=e,d[i][5]+=t,d[i][6]+=e;return d},makePathSimpler=t=>{let e=0,i=0,s=0,n=0;const r=[];let o,a=0,h=0;for(const l of t){const t=[...l];let c;switch(t[0]){case"l":t[1]+=e,t[2]+=i;case"L":e=t[1],i=t[2],c=["L",e,i];break;case"h":t[1]+=e;case"H":e=t[1],c=["L",e,i];break;case"v":t[1]+=i;case"V":i=t[1],c=["L",e,i];break;case"m":t[1]+=e,t[2]+=i;case"M":e=t[1],i=t[2],s=t[1],n=t[2],c=["M",e,i];break;case"c":t[1]+=e,t[2]+=i,t[3]+=e,t[4]+=i,t[5]+=e,t[6]+=i;case"C":a=t[3],h=t[4],e=t[5],i=t[6],c=["C",t[1],t[2],a,h,e,i];break;case"s":t[1]+=e,t[2]+=i,t[3]+=e,t[4]+=i;case"S":"C"===o?(a=2*e-a,h=2*i-h):(a=e,h=i),e=t[3],i=t[4],c=["C",a,h,t[1],t[2],e,i],a=c[3],h=c[4];break;case"q":t[1]+=e,t[2]+=i,t[3]+=e,t[4]+=i;case"Q":a=t[1],h=t[2],e=t[3],i=t[4],c=["Q",a,h,e,i];break;case"t":t[1]+=e,t[2]+=i;case"T":"Q"===o?(a=2*e-a,h=2*i-h):(a=e,h=i),e=t[1],i=t[2],c=["Q",a,h,e,i];break;case"a":t[6]+=e,t[7]+=i;case"A":fromArcToBeziers(e,i,t).forEach(t=>r.push(t)),e=t[6],i=t[7];break;case"z":case"Z":e=s,i=n,c=["Z"];break}c?(r.push(c),o=c[0]):o=""}return r},calcLineLength=(t,e,i,s)=>Math.sqrt((i-t)**2+(s-e)**2),getPointOnCubicBezierIterator=(t,e,i,s,n,r,o,a)=>h=>{const l=CB1(h),c=CB2(h),d=CB3(h),u=CB4(h);return new Point(o*l+n*c+i*d+t*u,a*l+r*c+s*d+e*u)},QB1=t=>t**2,QB2=t=>2*t*(1-t),QB3=t=>(1-t)**2,getTangentCubicIterator=(t,e,i,s,n,r,o,a)=>h=>{const l=QB1(h),c=QB2(h),d=QB3(h),u=3*(d*(i-t)+c*(n-i)+l*(o-n)),g=3*(d*(s-e)+c*(r-s)+l*(a-r));return Math.atan2(g,u)},getPointOnQuadraticBezierIterator=(t,e,i,s,n,r)=>o=>{const a=QB1(o),h=QB2(o),l=QB3(o);return new Point(n*a+i*h+t*l,r*a+s*h+e*l)},getTangentQuadraticIterator=(t,e,i,s,n,r)=>o=>{const a=1-o,h=2*(a*(i-t)+o*(n-i)),l=2*(a*(s-e)+o*(r-s));return Math.atan2(l,h)},pathIterator=(t,e,i)=>{let s=new Point(e,i),n=0;for(let e=1;e<=100;e+=1){const i=t(e/100);n+=calcLineLength(s.x,s.y,i.x,i.y),s=i}return n},findPercentageForDistance=(t,e)=>{let i=0,s=0,n={x:t.x,y:t.y},r={...n},o,a=.01,h=0;const l=t.iterator,c=t.angleFinder;for(;s<e&&a>1e-4;)r=l(i),h=i,o=calcLineLength(n.x,n.y,r.x,r.y),o+s>e?(i-=a,a/=2):(n=r,i+=a,s+=o);return{...r,angle:c(h)}},getPathSegmentsInfo=t=>{let e=0,i=0,s=0,n=0,r=0,o,a;const h=[];for(const l of t){const t={x:i,y:s,command:l[0],length:0};switch(l[0]){case"M":a=t,a.x=n=i=l[1],a.y=r=s=l[2];break;case"L":a=t,a.length=calcLineLength(i,s,l[1],l[2]),i=l[1],s=l[2];break;case"C":o=getPointOnCubicBezierIterator(i,s,l[1],l[2],l[3],l[4],l[5],l[6]),a=t,a.iterator=o,a.angleFinder=getTangentCubicIterator(i,s,l[1],l[2],l[3],l[4],l[5],l[6]),a.length=pathIterator(o,i,s),i=l[5],s=l[6];break;case"Q":o=getPointOnQuadraticBezierIterator(i,s,l[1],l[2],l[3],l[4]),a=t,a.iterator=o,a.angleFinder=getTangentQuadraticIterator(i,s,l[1],l[2],l[3],l[4]),a.length=pathIterator(o,i,s),i=l[3],s=l[4];break;case"Z":a=t,a.destX=n,a.destY=r,a.length=calcLineLength(i,s,n,r),i=n,s=r;break}e+=a.length,h.push(a)}return h.push({length:e,x:i,y:s}),h},getPointOnPath=function(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:getPathSegmentsInfo(t),s=0;for(;e-i[s].length>0&&s<i.length-2;)e-=i[s].length,s++;const n=i[s],r=e/n.length,o=t[s];switch(n.command){case"M":return{x:n.x,y:n.y,angle:0};case"Z":return{...new Point(n.x,n.y).lerp(new Point(n.destX,n.destY),r),angle:Math.atan2(n.destY-n.y,n.destX-n.x)};case"L":return{...new Point(n.x,n.y).lerp(new Point(o[1],o[2]),r),angle:Math.atan2(o[2]-n.y,o[1]-n.x)};case"C":return findPercentageForDistance(n,e);case"Q":return findPercentageForDistance(n,e)}},Le=new RegExp("[mzlhvcsqta][^mzlhvcsqta]*","gi"),je=new RegExp(Ee,"g"),Ie=new RegExp(lt,"gi"),Be={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7},parsePath=t=>{var e;const i=[],s=null!==(e=t.match(Le))&&void 0!==e?e:[];for(const t of s){const e=t[0];if("z"===e||"Z"===e){i.push([e]);continue}const s=Be[e.toLowerCase()];let n=[];if("a"===e||"A"===e){je.lastIndex=0;for(let e=null;e=je.exec(t);)n.push(...e.slice(1))}else n=t.match(Ie)||[];for(let t=0;t<n.length;t+=s){const r=new Array(s),o=Fe[e];r[0]=t>0&&o?o:e;for(let e=0;e<s;e++)r[e+1]=parseFloat(n[t+e]);i.push(r)}}return i},getSmoothPathFromPoints=function(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,i=new Point(t[0]),s=new Point(t[1]),n=1,r=0;const o=[],a=t.length,h=a>2;let l;for(h&&(n=t[2].x<s.x?-1:t[2].x===s.x?0:1,r=t[2].y<s.y?-1:t[2].y===s.y?0:1),o.push(["M",i.x-n*e,i.y-r*e]),l=1;l<a;l++){if(!i.eq(s)){const t=i.midPointFrom(s);o.push(["Q",i.x,i.y,t.x,t.y])}i=t[l],l+1<t.length&&(s=t[l+1])}return h&&(n=i.x>t[l-2].x?1:i.x===t[l-2].x?0:-1,r=i.y>t[l-2].y?1:i.y===t[l-2].y?0:-1),o.push(["L",i.x+n*e,i.y+r*e]),o},transformPath=(t,e,i)=>(i&&(e=multiplyTransformMatrices(e,[1,0,0,1,-i.x,-i.y])),t.map(t=>{const i=[...t];for(let s=1;s<t.length-1;s+=2){const{x:n,y:r}=transformPoint({x:t[s],y:t[s+1]},e);i[s]=n,i[s+1]=r}return i})),getRegularPolygonPath=(t,e)=>{const i=2*Math.PI/t;let s=-a;t%2==0&&(s+=i/2);const n=new Array(t+1);for(let r=0;r<t;r++){const t=r*i+s,{x:o,y:a}=new Point(cos(t),sin(t)).scalarMultiply(e);n[r]=[0===r?"M":"L",o,a]}return n[t]=["Z"],n},joinPath=(t,e)=>t.map(t=>t.map((t,i)=>0===i||void 0===e?t:toFixed(t,e)).join(" ")).join(" "),mergeClipPaths=(t,e)=>{var i;let s=t,n=e;s.inverted&&!n.inverted&&(s=e,n=t),sendObjectToPlane(n,null===(i=n.group)||void 0===i?void 0:i.calcTransformMatrix(),s.calcTransformMatrix());const r=s.inverted&&n.inverted;return r&&(s.inverted=n.inverted=!1),new Group([s],{clipPath:n,inverted:r})},getRandomInt=(t,e)=>Math.floor(Math.random()*(e-t+1))+t,_assignTransformMatrixProps=t=>{if(t.transformMatrix){const{scaleX:e,scaleY:i,angle:s,skewX:n}=qrDecompose(t.transformMatrix);t.flipX=!1,t.flipY=!1,t.set(A,e),t.set(F,i),t.angle=s,t.skewX=n,t.skewY=0}},removeTransformMatrixForSvgParsing=(t,e)=>{let i=t._findCenterFromElement();t.transformMatrix&&(_assignTransformMatrixProps(t),i=i.transform(t.transformMatrix)),delete t.transformMatrix,e&&(t.scaleX*=e.scaleX,t.scaleY*=e.scaleY,t.cropX=e.cropX,t.cropY=e.cropY,i.x+=e.offsetLeft,i.y+=e.offsetTop,t.width=e.width,t.height=e.height),t.setPositionByOrigin(i,p,p)};var Re=Object.freeze({__proto__:null,addTransformToObject:addTransformToObject,animate:animate,animateColor:animateColor,applyTransformToObject:applyTransformToObject,calcAngleBetweenVectors:calcAngleBetweenVectors,calcDimensionsMatrix:calcDimensionsMatrix,calcPlaneChangeMatrix:calcPlaneChangeMatrix,calcVectorRotation:calcVectorRotation,cancelAnimFrame:cancelAnimFrame,capValue:capValue,composeMatrix:composeMatrix,copyCanvasElement:copyCanvasElement,cos:cos,createCanvasElement:createCanvasElement,createImage:createImage,createRotateMatrix:createRotateMatrix,createScaleMatrix:createScaleMatrix,createSkewXMatrix:createSkewXMatrix,createSkewYMatrix:createSkewYMatrix,createTranslateMatrix:createTranslateMatrix,createVector:createVector,crossProduct:crossProduct,degreesToRadians:degreesToRadians,dotProduct:dotProduct,ease:Et,enlivenObjectEnlivables:enlivenObjectEnlivables,enlivenObjects:enlivenObjects,findScaleToCover:findScaleToCover,findScaleToFit:findScaleToFit,getBoundsOfCurve:getBoundsOfCurve,getOrthonormalVector:getOrthonormalVector,getPathSegmentsInfo:getPathSegmentsInfo,getPointOnPath:getPointOnPath,getPointer:getPointer,getRandomInt:getRandomInt,getRegularPolygonPath:getRegularPolygonPath,getSmoothPathFromPoints:getSmoothPathFromPoints,getSvgAttributes:getSvgAttributes,getUnitVector:getUnitVector,groupSVGElements:groupSVGElements,hasStyleChanged:hasStyleChanged,invertTransform:invertTransform,isBetweenVectors:isBetweenVectors,isIdentityMatrix:isIdentityMatrix,isTouchEvent:isTouchEvent,isTransparent:isTransparent,joinPath:joinPath,loadImage:loadImage,magnitude:magnitude,makeBoundingBoxFromPoints:makeBoundingBoxFromPoints,makePathSimpler:makePathSimpler,matrixToSVG:matrixToSVG,mergeClipPaths:mergeClipPaths,multiplyTransformMatrices:multiplyTransformMatrices,multiplyTransformMatrixArray:multiplyTransformMatrixArray,parsePath:parsePath,parsePreserveAspectRatioAttribute:parsePreserveAspectRatioAttribute,parseUnit:parseUnit,pick:pick,projectStrokeOnPoints:projectStrokeOnPoints,qrDecompose:qrDecompose,radiansToDegrees:radiansToDegrees,removeFromArray:removeFromArray,removeTransformFromObject:removeTransformFromObject,removeTransformMatrixForSvgParsing:removeTransformMatrixForSvgParsing,requestAnimFrame:requestAnimFrame,resetObjectTransform:resetObjectTransform,rotateVector:rotateVector,saveObjectTransform:saveObjectTransform,sendObjectToPlane:sendObjectToPlane,sendPointToPlane:sendPointToPlane,sendVectorToPlane:sendVectorToPlane,sin:sin,sizeAfterTransform:sizeAfterTransform,string:ie,stylesFromArray:stylesFromArray,stylesToArray:stylesToArray,toBlob:toBlob,toDataURL:toDataURL,toFixed:toFixed,transformPath:transformPath,transformPoint:transformPoint});function setStyle(t,e){const i=t.style;i&&Object.entries(e).forEach(t=>{let[e,s]=t;return i.setProperty(e,s)})}class CanvasDOMManager extends StaticCanvasDOMManager{constructor(t){let{allowTouchScrolling:e=!1,containerClass:i=""}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(t),_defineProperty(this,"upper",void 0),_defineProperty(this,"container",void 0);const{el:s}=this.lower,n=this.createUpperCanvas();this.upper={el:n,ctx:n.getContext("2d")},this.applyCanvasStyle(s,{allowTouchScrolling:e}),this.applyCanvasStyle(n,{allowTouchScrolling:e,styles:{position:"absolute",left:"0",top:"0"}});const r=this.createContainerElement();r.classList.add(i),s.parentNode&&s.parentNode.replaceChild(r,s),r.append(s,n),this.container=r}createUpperCanvas(){const{el:t}=this.lower,e=createCanvasElement();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=getFabricDocument().createElement("div");return t.setAttribute("data-fabric","wrapper"),setStyle(t,{position:"relative"}),makeElementUnselectable(t),t}applyCanvasStyle(t,e){const{styles:i,allowTouchScrolling:s}=e;setStyle(t,{...i,"touch-action":s?"manipulation":_}),makeElementUnselectable(t)}setDimensions(t,e){super.setDimensions(t,e);const{el:i,ctx:s}=this.upper;setCanvasDimensions(i,s,t,e)}setCSSDimensions(t){super.setCSSDimensions(t),setCSSDimensions(this.upper.el,t),setCSSDimensions(this.container,t)}cleanupDOM(t){const e=this.container,{el:i}=this.lower,{el:s}=this.upper;super.cleanupDOM(t),e.removeChild(s),e.removeChild(i),e.parentNode&&e.parentNode.replaceChild(i,e)}dispose(){super.dispose(),getEnv().dispose(this.upper.el),delete this.upper,delete this.container}}const We={uniformScaling:!0,uniScaleKey:"shiftKey",centeredScaling:!1,centeredRotation:!1,centeredKey:"altKey",altActionKey:"shiftKey",selection:!0,selectionKey:"shiftKey",selectionColor:"rgba(100, 100, 255, 0.3)",selectionDashArray:[],selectionBorderColor:"rgba(255, 255, 255, 0.3)",selectionLineWidth:1,selectionFullyContained:!1,hoverCursor:"move",moveCursor:"move",defaultCursor:"default",freeDrawingCursor:"crosshair",notAllowedCursor:"not-allowed",perPixelTargetFind:!1,targetFindTolerance:0,skipTargetFind:!1,stopContextMenu:!1,fireRightClick:!1,fireMiddleClick:!1,enablePointerEvents:!1,containerClass:"canvas-container",preserveObjectStacking:!0};class SelectableCanvas extends StaticCanvas{constructor(){super(...arguments),_defineProperty(this,"_hoveredTargets",[]),_defineProperty(this,"_objectsToRender",void 0),_defineProperty(this,"_currentTransform",null),_defineProperty(this,"_groupSelector",null),_defineProperty(this,"contextTopDirty",!1)}static getDefaults(){return{...super.getDefaults(),...SelectableCanvas.ownDefaults}}get upperCanvasEl(){var t;return null===(t=this.elements.upper)||void 0===t?void 0:t.el}get contextTop(){var t;return null===(t=this.elements.upper)||void 0===t?void 0:t.ctx}get wrapperEl(){return this.elements.container}initElements(t){this.elements=new CanvasDOMManager(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(),i=Math.ceil((2*t+1)*e);this.pixelFindCanvasEl.width=this.pixelFindCanvasEl.height=i,this.pixelFindContext.scale(e,e)}isTargetTransparent(t,e,i){const s=this.targetFindTolerance,n=this.pixelFindContext;this.clearContext(n),n.save(),n.translate(-e+s,-i+s),n.transform(...this.viewportTransform);const r=t.selectionBackgroundColor;t.selectionBackgroundColor="",t.render(n),t.selectionBackgroundColor=r,n.restore();const o=Math.round(s*this.getRetinaScaling());return isTransparent(n,o,o,o)}_isSelectionKeyPressed(t){const e=this.selectionKey;return!!e&&(Array.isArray(e)?!!e.find(e=>!!e&&!0===t[e]):t[e])}_shouldClearSelection(t,e){const i=this.getActiveObjects(),s=this._activeObject;return!!(!e||e&&s&&i.length>1&&-1===i.indexOf(e)&&s!==e&&!this._isSelectionKeyPressed(t)||e&&!e.evented||e&&!e.selectable&&s&&s!==e)}_shouldCenterTransform(t,e,i){if(!t)return;let s;return e===E||e===A||e===F||e===M?s=this.centeredScaling||t.centeredScaling:e===T&&(s=this.centeredRotation||t.centeredRotation),s?!i:i}_getOriginFromCorner(t,e){const i={x:t.originX,y:t.originY};return e?(["ml","tl","bl"].includes(e)?i.x=v:["mr","tr","br"].includes(e)&&(i.x=m),["tl","mt","tr"].includes(e)?i.y=x:["bl","mb","br"].includes(e)&&(i.y=y),i):i}_setupCurrentTransform(t,e,i){var s;const n=e.group?sendPointToPlane(this.getScenePoint(t),void 0,e.group.calcTransformMatrix()):this.getScenePoint(t),{key:r="",control:o}=e.getActiveControl()||{},a=i&&o?null===(s=o.getActionHandler(t,e,o))||void 0===s?void 0:s.bind(o):dragHandler,h=getActionFromCorner(i,r,t,e),l=t[this.centeredKey],c=this._shouldCenterTransform(e,h,l)?{x:p,y:p}:this._getOriginFromCorner(e,r),d={target:e,action:h,actionHandler:a,actionPerformed:!1,corner:r,scaleX:e.scaleX,scaleY:e.scaleY,skewX:e.skewX,skewY:e.skewY,offsetX:n.x-e.left,offsetY:n.y-e.top,originX:c.x,originY:c.y,ex:n.x,ey:n.y,lastX:n.x,lastY:n.y,theta:degreesToRadians(e.angle),width:e.width,height:e.height,shiftKey:t.shiftKey,altKey:l,original:{...saveObjectTransform(e),originX:c.x,originY:c.y}};this._currentTransform=d,this.fire("before:transform",{e:t,transform:d})}setCursor(t){this.upperCanvasEl.style.cursor=t}_drawSelection(t){const{x:e,y:i,deltaX:s,deltaY:n}=this._groupSelector,r=new Point(e,i).transform(this.viewportTransform),o=new Point(e+s,i+n).transform(this.viewportTransform),a=this.selectionLineWidth/2;let h=Math.min(r.x,o.x),l=Math.min(r.y,o.y),c=Math.max(r.x,o.x),d=Math.max(r.y,o.y);this.selectionColor&&(t.fillStyle=this.selectionColor,t.fillRect(h,l,c-h,d-l)),this.selectionLineWidth&&this.selectionBorderColor&&(t.lineWidth=this.selectionLineWidth,t.strokeStyle=this.selectionBorderColor,h+=a,l+=a,c-=a,d-=a,FabricObject.prototype._setLineDash.call(this,t,this.selectionDashArray),t.strokeRect(h,l,c-h,d-l))}findTarget(t){if(this._targetInfo)return this._targetInfo;if(this.skipTargetFind)return{subTargets:[],currentSubTargets:[]};const e=this.getScenePoint(t),i=this._activeObject,s=this.getActiveObjects(),n=this.searchPossibleTargets(this._objects,e),{subTargets:r,container:o,target:a}=n,h={...n,currentSubTargets:r,currentContainer:o,currentTarget:a};if(!i)return h;const l={...this.searchPossibleTargets([i],e),currentSubTargets:r,currentContainer:o,currentTarget:a},c=undefined;if(i.findControl(this.getViewportPoint(t),isTouchEvent(t)))return{...l,target:i};if(l.target){if(s.length>1)return l;if(!this.preserveObjectStacking)return l;if(this.preserveObjectStacking&&t[this.altSelectionKey])return l}return h}_pointIsInObjectSelectionArea(t,e){let i=t.getCoords();const s=this.getZoom(),n=t.padding/s;if(n){const[t,e,s,r]=i,o=Math.atan2(e.y-t.y,e.x-t.x),a=cos(o)*n,h=sin(o)*n,l=a+h,c=a-h;i=[new Point(t.x-c,t.y-l),new Point(e.x+l,e.y-c),new Point(s.x+c,s.y+l),new Point(r.x-l,r.y+c)]}return Intersection.isPointInPolygon(e,i)}_checkTarget(t,e){if(t&&t.visible&&t.evented&&this._pointIsInObjectSelectionArea(t,e)){if(!this.perPixelTargetFind&&!t.perPixelTargetFind||t.isEditing)return!0;{const i=e.transform(this.viewportTransform);if(!this.isTargetTransparent(t,i.x,i.y))return!0}}return!1}_searchPossibleTargets(t,e,i){let s=t.length;for(;s--;){const n=t[s];if(this._checkTarget(n,e)){if(isCollection(n)&&n.subTargetCheck){const{target:t}=this._searchPossibleTargets(n._objects,e,i);t&&i.push(t)}return{target:n,subTargets:i}}}return{subTargets:[]}}searchPossibleTargets(t,e){const i=this._searchPossibleTargets(t,e,[]);i.container=i.target;const{container:s,subTargets:n}=i;if(s&&isCollection(s)&&s.interactive&&n[0]){for(let t=n.length-1;t>0;t--){const e=n[t];if(!isCollection(e)||!e.interactive)return i.target=e,i}return i.target=n[0],i}return i}getViewportPoint(t){return this._viewportPoint?this._viewportPoint:this._getPointerImpl(t,!0)}getScenePoint(t){return this._scenePoint?this._scenePoint:this._getPointerImpl(t)}_getPointerImpl(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];const i=this.upperCanvasEl,s=i.getBoundingClientRect();let n=getPointer(t),r=s.width||0,o=s.height||0;r&&o||(y in s&&x in s&&(o=Math.abs(s.top-s.bottom)),v in s&&m in s&&(r=Math.abs(s.right-s.left))),this.calcOffset(),n.x=n.x-this._offset.left,n.y=n.y-this._offset.top,e||(n=sendPointToPlane(n,void 0,this.viewportTransform));const a=this.getRetinaScaling();1!==a&&(n.x/=a,n.y/=a);const h=0===r||0===o?new Point(1,1):new Point(i.width/r,i.height/o);return n.multiply(h)}_setDimensionsImpl(t,e){this._resetTransformEventData(),super._setDimensionsImpl(t,e),this._isCurrentlyDrawing&&this.freeDrawingBrush&&this.freeDrawingBrush._setBrushStyles(this.contextTop)}_createCacheCanvas(){this.pixelFindCanvasEl=createCanvasElement(),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 isActiveSelection(t)?t.getObjects():t?[t]:[]}_fireSelectionEvents(t,e){let i=!1,s=!1;const n=this.getActiveObjects(),r=[],o=[];t.forEach(t=>{n.includes(t)||(i=!0,t.fire("deselected",{e:e,target:t}),o.push(t))}),n.forEach(s=>{t.includes(s)||(i=!0,s.fire("selected",{e:e,target:s}),r.push(s))}),t.length>0&&n.length>0?(s=!0,i&&this.fire("selection:updated",{e:e,selected:r,deselected:o})):n.length>0?(s=!0,this.fire("selection:created",{e:e,selected:r})):t.length>0&&(s=!0,this.fire("selection:cleared",{e:e,deselected:o})),s&&(this._objectsToRender=void 0)}setActiveObject(t,e){const i=this.getActiveObjects(),s=this._setActiveObject(t,e);return this._fireSelectionEvents(i,e),s}_setActiveObject(t,e){const i=this._activeObject;return i!==t&&(!(!this._discardActiveObject(e,t)&&this._activeObject)&&(!t.onSelect({e:e})&&(this._activeObject=t,isActiveSelection(t)&&i!==t&&t.set("canvas",this),t.setCoords(),!0)))}_discardActiveObject(t,e){const i=this._activeObject;return!!i&&(!i.onDeselect({e:t,object:e})&&(this._currentTransform&&this._currentTransform.target===i&&this.endCurrentTransform(t),isActiveSelection(i)&&i===this._hoveredTarget&&(this._hoveredTarget=void 0),this._activeObject=void 0,!0))}discardActiveObject(t){const e=this.getActiveObjects(),i=this.getActiveObject();e.length&&this.fire("before:selection:cleared",{e:t,deselected:[i]});const s=this._discardActiveObject(t);return this._fireSelectionEvents(e,t),s}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,i=e.target,s={e:t,target:i,transform:e,action:e.action};i._scaling&&(i._scaling=!1),i.setCoords(),e.actionPerformed&&(this.fire("object:modified",s),i.fire(R,s))}setViewportTransform(t){super.setViewportTransform(t);const e=this._activeObject;e&&e.setCoords()}destroy(){const t=this._activeObject;isActiveSelection(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,i){const s=this._realizeGroupTransformOnObject(t),n=super._toObject(t,e,i);return t.set(s),n}_realizeGroupTransformOnObject(t){const{group:e}=t;if(e&&isActiveSelection(e)&&this._activeObject===e){const i=undefined,s=pick(t,["angle","flipX","flipY",m,A,F,L,j,y]);return addTransformToObject(t,e.calcOwnMatrix()),s}return{}}_setSVGObject(t,e,i){const s=this._realizeGroupTransformOnObject(e);super._setSVGObject(t,e,i),e.set(s)}}_defineProperty(SelectableCanvas,"ownDefaults",We);class TextEditingManager{constructor(t){_defineProperty(this,"targets",[]),_defineProperty(this,"__disposer",void 0);const cb=()=>{const{hiddenTextarea:e}=t.getActiveObject()||{};e&&e.focus()},e=t.upperCanvasEl;e.addEventListener("click",cb),this.__disposer=()=>e.removeEventListener("click",cb)}exitTextEditing(){this.target=void 0,this.targets.forEach(t=>{t.isEditing&&t.exitEditing()})}add(t){this.targets.push(t)}remove(t){this.unregister(t),removeFromArray(this.targets,t)}register(t){this.target=t}unregister(t){t===this.target&&(this.target=void 0)}onMouseMove(t){var e;(null===(e=this.target)||void 0===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 He={passive:!1},getEventPoints=(t,e)=>{const i=undefined,s=undefined;return{viewportPoint:t.getViewportPoint(e),scenePoint:t.getScenePoint(e)}},addListener=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return t.addEventListener(...i)},removeListener=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];return t.removeEventListener(...i)},Xe={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 Canvas extends SelectableCanvas{constructor(t){let e;super(t,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}),_defineProperty(this,"_isClick",void 0),_defineProperty(this,"textEditingManager",new TextEditingManager(this)),["_onMouseDown","_onTouchStart","_onMouseMove","_onMouseUp","_onTouchEnd","_onResize","_onMouseWheel","_onMouseOut","_onMouseEnter","_onContextMenu","_onClick","_onDragStart","_onDragEnd","_onDragProgress","_onDragOver","_onDragEnter","_onDragLeave","_onDrop"].forEach(t=>{this[t]=this[t].bind(this)}),this.addOrRemove(addListener,"add")}_getEventPrefix(){return this.enablePointerEvents?"pointer":"mouse"}addOrRemove(t,e){const i=this.upperCanvasEl,s=this._getEventPrefix();t(getWindowFromElement(i),"resize",this._onResize),t(i,s+"down",this._onMouseDown),t(i,`${s}move`,this._onMouseMove,He),t(i,`${s}out`,this._onMouseOut),t(i,`${s}enter`,this._onMouseEnter),t(i,"wheel",this._onMouseWheel,{passive:!1}),t(i,"contextmenu",this._onContextMenu),t(i,"click",this._onClick),t(i,"dblclick",this._onClick),t(i,"dragstart",this._onDragStart),t(i,"dragend",this._onDragEnd),t(i,"dragover",this._onDragOver),t(i,"dragenter",this._onDragEnter),t(i,"dragleave",this._onDragLeave),t(i,"drop",this._onDrop),this.enablePointerEvents||t(i,"touchstart",this._onTouchStart,He)}removeListeners(){this.addOrRemove(removeListener,"remove");const t=this._getEventPrefix(),e=getDocumentFromElement(this.upperCanvasEl);removeListener(e,`${t}up`,this._onMouseUp),removeListener(e,"touchend",this._onTouchEnd,He),removeListener(e,`${t}move`,this._onMouseMove,He),removeListener(e,"touchmove",this._onMouseMove,He),clearTimeout(this._willAddMouseDown)}_onMouseWheel(t){this._cacheTransformEventData(t),this._handleEvent(t,"wheel"),this._resetTransformEventData()}_onMouseOut(t){const e=this._hoveredTarget,i={e:t,...getEventPoints(this,t)};this.fire("mouse:out",{...i,target:e}),this._hoveredTarget=void 0,e&&e.fire("mouseout",{...i}),this._hoveredTargets.forEach(t=>{this.fire("mouse:out",{...i,target:t}),t&&t.fire("mouseout",{...i})}),this._hoveredTargets=[]}_onMouseEnter(t){const{target:e}=this.findTarget(t);this._currentTransform||e||(this.fire("mouse:over",{e:t,...getEventPoints(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 i={e:t,target:e};return this.fire("dragstart",i),e.fire("dragstart",i),void addListener(this.upperCanvasEl,"drag",this._onDragProgress)}stopEvent(t)}_renderDragEffects(t,e,i){let s=!1;const n=this._dropTarget;n&&n!==e&&n!==i&&(n.clearContextTop(),s=!0),null==e||e.clearContextTop(),i!==e&&(null==i||i.clearContextTop());const r=this.contextTop;r.save(),r.transform(...this.viewportTransform),e&&(r.save(),e.transform(r),e.renderDragSourceEffect(t),r.restore(),s=!0),i&&(r.save(),i.transform(r),i.renderDropTargetEffect(t),r.restore(),s=!0),r.restore(),s&&(this.contextTopDirty=!0)}_onDragEnd(t){const{currentSubTargets:e}=this.findTarget(t),i=!!t.dataTransfer&&t.dataTransfer.dropEffect!==_,s=i?this._activeObject:void 0,n={e:t,target:this._dragSource,subTargets:e,dragSource:this._dragSource,didDrop:i,dropTarget:s};removeListener(this.upperCanvasEl,"drag",this._onDragProgress),this.fire("dragend",n),this._dragSource&&this._dragSource.fire("dragend",n),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:i,currentSubTargets:s}=this.findTarget(t),n=this._dragSource,r={e:t,target:i,subTargets:s,dragSource:n,canDrop:!1,dropTarget:void 0};let o;this.fire(e,r),this._fireEnterLeaveEvents(t,i,r),i&&(i.canDrop(t)&&(o=i),i.fire(e,r));for(let i=0;i<s.length;i++){const n=s[i];n.canDrop(t)&&(o=n),n.fire(e,r)}this._renderDragEffects(t,n,o),this._dropTarget=o}_onDragEnter(t){const{currentContainer:e,currentSubTargets:i}=this.findTarget(t),s={e:t,target:e,subTargets:i,dragSource:this._dragSource};this.fire("dragenter",s),this._fireEnterLeaveEvents(t,e,s)}_onDragLeave(t){const{currentSubTargets:e}=this.findTarget(t),i={e:t,target:this._draggedoverTarget,subTargets:e,dragSource:this._dragSource};this.fire("dragleave",i),this._fireEnterLeaveEvents(t,void 0,i),this._renderDragEffects(t,this._dragSource),this._dropTarget=void 0,this._hoveredTargets=[]}_onDrop(t){const{currentContainer:e,currentSubTargets:i}=this.findTarget(t),s=this._basicEventHandler("drop:before",{e:t,target:e,subTargets:i,dragSource:this._dragSource,...getEventPoints(this,t)});s.didDrop=!1,s.dropTarget=void 0,this._basicEventHandler("drop",s),this.fire("drop:after",s)}_onContextMenu(t){const{target:e,subTargets:i}=this.findTarget(t),s=this._basicEventHandler("contextmenu:before",{e:t,target:e,subTargets:i});return this.stopContextMenu&&stopEvent(t),this._basicEventHandler("contextmenu",s),!1}_onClick(t){const e=t.detail;e>3||e<2||(this._cacheTransformEventData(t),2==e&&"dblclick"===t.type&&this._handleEvent(t,"dblclick"),3==e&&this._handleEvent(t,"tripleclick"),this._resetTransformEventData())}getPointerId(t){const e=t.changedTouches;return e?e[0]&&e[0].identifier:this.enablePointerEvents?t.pointerId:-1}_isMainEvent(t){return!0===t.isPrimary||!1!==t.isPrimary&&("touchend"===t.type&&0===t.touches.length||(!t.changedTouches||t.changedTouches[0].identifier===this.mainTouchId))}_onTouchStart(t){this._cacheTransformEventData(t);let e=!this.allowTouchScrolling;const i=this._activeObject;void 0===this.mainTouchId&&(this.mainTouchId=this.getPointerId(t)),this.__onMouseDown(t);const{target:s}=this.findTarget(t);(this.isDrawingMode||i&&s===i)&&(e=!0),e&&t.preventDefault();const n=this.upperCanvasEl,r=this._getEventPrefix(),o=getDocumentFromElement(n);addListener(o,"touchend",this._onTouchEnd,He),e&&addListener(o,"touchmove",this._onMouseMove,He),removeListener(n,`${r}down`,this._onMouseDown),this._resetTransformEventData()}_onMouseDown(t){this._cacheTransformEventData(t),this.__onMouseDown(t);const e=this.upperCanvasEl,i=this._getEventPrefix();removeListener(e,`${i}move`,this._onMouseMove,He);const s=getDocumentFromElement(e);addListener(s,`${i}up`,this._onMouseUp),addListener(s,`${i}move`,this._onMouseMove,He),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(),i=getDocumentFromElement(this.upperCanvasEl);removeListener(i,"touchend",this._onTouchEnd,He),removeListener(i,"touchmove",this._onMouseMove,He),this._willAddMouseDown&&clearTimeout(this._willAddMouseDown),this._willAddMouseDown=setTimeout(()=>{addListener(this.upperCanvasEl,`${e}down`,this._onMouseDown),this._willAddMouseDown=0},400)}_onMouseUp(t){this._cacheTransformEventData(t),this.__onMouseUp(t);const e=this.upperCanvasEl,i=this._getEventPrefix();if(this._isMainEvent(t)){const t=getDocumentFromElement(this.upperCanvasEl);removeListener(t,`${i}up`,this._onMouseUp),removeListener(t,`${i}move`,this._onMouseMove,He),addListener(e,`${i}move`,this._onMouseMove,He)}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 i=this._currentTransform,s=this._isClick,{target:n}=this.findTarget(t),{button:r}=t;if(r)return void((this.fireMiddleClick&&1===r||this.fireRightClick&&2===r)&&this._handleEvent(t,"up"));if(this.isDrawingMode&&this._isCurrentlyDrawing)return void this._onMouseUpInDrawingMode(t);if(!this._isMainEvent(t))return;let o=!1,a,h;if(i&&(this._finalizeCurrentTransform(t),o=i.actionPerformed),!s){const e=n===this._activeObject;this.handleSelection(t),o||(o=this._shouldRender(n)||!e&&n===this._activeObject)}if(n){const e=n.findControl(this.getViewportPoint(t),isTouchEvent(t)),{key:s,control:r}=e||{};if(h=s,n.selectable&&n!==this._activeObject&&"up"===n.activeOn)this.setActiveObject(n,t),o=!0;else if(r){const e=r.getMouseUpHandler(t,n,r);e&&(a=this.getScenePoint(t),e.call(r,t,i,a.x,a.y))}n.isMoving=!1}if(i&&(i.target!==n||i.corner!==h)){const e=i.target&&i.target.controls[i.corner],s=e&&e.getMouseUpHandler(t,i.target,e);a=a||this.getScenePoint(t),s&&s.call(e,t,i,a.x,a.y)}this._setCursorFromEvent(t,n),this._handleEvent(t,"up"),this._groupSelector=null,this._currentTransform=null,n&&(n.__corner=void 0),o?this.requestRenderAll():s||null!==(e=this._activeObject)&&void 0!==e&&e.isEditing||this.renderTop()}_basicEventHandler(t,e){const{target:i,subTargets:s=[]}=e;this.fire(t,e),i&&i.fire(t,e);for(let n=0;n<s.length;n++)s[n]!==i&&s[n].fire(t,e);return e}_handleEvent(t,e,i){const{target:s,subTargets:n}=this.findTarget(t),r={e:t,target:s,subTargets:n,...getEventPoints(this,t),transform:this._currentTransform,..."down:before"===e||"down"===e?i:{}};"up:before"!==e&&"up"!==e||(r.isClick=this._isClick),this.fire(`mouse:${e}`,r),s&&s.fire(`mouse${e}`,r);for(let t=0;t<n.length;t++)n[t]!==s&&n[t].fire(`mouse${e}`,r)}_onMouseDownInDrawingMode(t){this._isCurrentlyDrawing=!0,this.getActiveObject()&&(this.discardActiveObject(t),this.requestRenderAll());const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseDown(e,{e:t,pointer:e}),this._handleEvent(t,"down",{alreadySelected:!1})}_onMouseMoveInDrawingMode(t){if(this._isCurrentlyDrawing){const e=this.getScenePoint(t);this.freeDrawingBrush&&this.freeDrawingBrush.onMouseMove(e,{e:t,pointer:e})}this.setCursor(this.freeDrawingCursor),this._handleEvent(t,"move")}_onMouseUpInDrawingMode(t){const e=this.getScenePoint(t);this.freeDrawingBrush?this._isCurrentlyDrawing=!!this.freeDrawingBrush.onMouseUp({e:t,pointer:e}):this._isCurrentlyDrawing=!1,this._handleEvent(t,"up")}__onMouseDown(t){this._isClick=!0,this._handleEvent(t,"down:before");let{target:e}=this.findTarget(t),i=!!e&&e===this._activeObject;const{button:s}=t;if(s)return void((this.fireMiddleClick&&1===s||this.fireRightClick&&2===s)&&this._handleEvent(t,"down",{alreadySelected:i}));if(this.isDrawingMode)return void this._onMouseDownInDrawingMode(t);if(!this._isMainEvent(t))return;if(this._currentTransform)return;let n=this._shouldRender(e),r=!1;if(this.handleMultiSelection(t,e)?(e=this._activeObject,r=!0,n=!0):this._shouldClearSelection(t,e)&&this.discardActiveObject(t),this.selection&&(!e||!e.selectable&&!e.isEditing&&e!==this._activeObject)){const e=this.getScenePoint(t);this._groupSelector={x:e.x,y:e.y,deltaY:0,deltaX:0}}if(i=!!e&&e===this._activeObject,e){e.selectable&&"down"===e.activeOn&&this.setActiveObject(e,t);const s=e.findControl(this.getViewportPoint(t),isTouchEvent(t));if(e===this._activeObject&&(s||!r)){this._setupCurrentTransform(t,e,i);const n=s?s.control:void 0,r=this.getScenePoint(t),o=n&&n.getMouseDownHandler(t,e,n);o&&o.call(n,t,this._currentTransform,r.x,r.y)}}n&&(this._objectsToRender=void 0),this._handleEvent(t,"down",{alreadySelected:i}),n&&this.requestRenderAll()}_resetTransformEventData(){this._targetInfo=this._viewportPoint=this._scenePoint=void 0}_cacheTransformEventData(t){this._resetTransformEventData(),this._viewportPoint=this.getViewportPoint(t),this._scenePoint=sendPointToPlane(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 i=this.getScenePoint(t);e.deltaX=i.x-e.x,e.deltaY=i.y-e.y,this.renderTop()}else if(this._currentTransform)this._transformObject(t);else{const{target:e}=this.findTarget(t);this._setCursorFromEvent(t,e),this._fireOverOutEvents(t,e)}this.textEditingManager.onMouseMove(t),this._handleEvent(t,"move")}_fireOverOutEvents(t,e){const i=this._hoveredTarget,s=this._hoveredTargets,{subTargets:n}=this.findTarget(t),r=Math.max(s.length,n.length);this.fireSyntheticInOutEvents("mouse",{e:t,target:e,oldTarget:i,fireCanvas:!0});for(let e=0;e<r;e++)this.fireSyntheticInOutEvents("mouse",{e:t,target:n[e],oldTarget:s[e]});this._hoveredTarget=e,this._hoveredTargets=n}_fireEnterLeaveEvents(t,e,i){const s=this._draggedoverTarget,n=this._hoveredTargets,{subTargets:r}=this.findTarget(t),o=Math.max(n.length,r.length);this.fireSyntheticInOutEvents("drag",{...i,target:e,oldTarget:s,fireCanvas:!0});for(let t=0;t<o;t++)this.fireSyntheticInOutEvents("drag",{...i,target:r[t],oldTarget:n[t]});this._draggedoverTarget=e}fireSyntheticInOutEvents(t,e){let{target:i,oldTarget:s,fireCanvas:n,e:r,...o}=e;const{targetIn:a,targetOut:h,canvasIn:l,canvasOut:c}=Xe[t],d=s!==i;if(s&&d){const t={...o,e:r,target:s,nextTarget:i,...getEventPoints(this,r)};n&&this.fire(c,t),s.fire(h,t)}if(i&&d){const t={...o,e:r,target:i,previousTarget:s,...getEventPoints(this,r)};n&&this.fire(l,t),i.fire(a,t)}}_transformObject(t){const e=this.getScenePoint(t),i=this._currentTransform,s=i.target,n=s.group?sendPointToPlane(e,void 0,s.group.calcTransformMatrix()):e;i.shiftKey=t.shiftKey,i.altKey=!!this.centeredKey&&t[this.centeredKey],this._performTransformAction(t,i,n),i.actionPerformed&&this.requestRenderAll()}_performTransformAction(t,e,i){const{action:s,actionHandler:n,target:r}=e,o=!!n&&n(t,e,i.x,i.y);o&&r.setCoords(),"drag"===s&&o&&(e.target.isMoving=!0,this.setCursor(e.target.moveCursor||this.moveCursor)),e.actionPerformed=e.actionPerformed||o}_setCursorFromEvent(t,e){if(!e)return void this.setCursor(this.defaultCursor);let i=e.hoverCursor||this.hoverCursor;const s=isActiveSelection(this._activeObject)?this._activeObject:null,n=(!s||e.group!==s)&&e.findControl(this.getViewportPoint(t));if(n){const{control:i,coord:s}=n;this.setCursor(i.cursorStyleHandler(t,i,e,s))}else{if(e.subTargetCheck){const{subTargets:e}=this.findTarget(t);e.concat().reverse().forEach(t=>{i=t.hoverCursor||i})}this.setCursor(i)}}handleMultiSelection(t,e){const i=this._activeObject,s=isActiveSelection(i);if(i&&this._isSelectionKeyPressed(t)&&this.selection&&e&&e.selectable&&(i!==e||s)&&(s||!e.isDescendantOf(i)&&!i.isDescendantOf(e))&&!e.onSelect({e:t})&&!i.getActiveControl()){if(s){const s=i.getObjects();let n=[];if(e===i){const i=this.getScenePoint(t);let r=this.searchPossibleTargets(s,i);if(r.target?(e=r.target,n=r.subTargets):(r=this.searchPossibleTargets(this._objects,i),e=r.target,n=r.subTargets),!e||!e.selectable)return!1}e.group===i?(i.remove(e),this._hoveredTarget=e,this._hoveredTargets=n,1===i.size()&&this._setActiveObject(i.item(0),t)):(i.multiSelectAdd(e),this._hoveredTarget=i,this._hoveredTargets=n),this._fireSelectionEvents(s,t)}else{i.isEditing&&i.exitEditing();const s=undefined,n=new(X.getClass("ActiveSelection"))([],{canvas:this});n.multiSelectAdd(i,e),this._hoveredTarget=n,this._setActiveObject(n,t),this._fireSelectionEvents([i],t)}return!0}return!1}handleSelection(t){if(!this.selection||!this._groupSelector)return!1;const{x:e,y:i,deltaX:s,deltaY:n}=this._groupSelector,r=new Point(e,i),o=r.add(new Point(s,n)),a=r.min(o),h=undefined,l=r.max(o).subtract(a),c=this.collectObjects({left:a.x,top:a.y,width:l.x,height:l.y},{includeIntersecting:!this.selectionFullyContained}),d=r.eq(o)?c[0]?[c[0]]:[]:c.length>1?c.filter(e=>!e.onSelect({e:t})).reverse():c;if(1===d.length)this.setActiveObject(d[0],t);else if(d.length>1){const e=X.getClass("ActiveSelection");this.setActiveObject(new e(d,{canvas:this}),t)}return this._groupSelector=null,!0}clear(){this.textEditingManager.clear(),super.clear()}destroy(){this.removeListeners(),this.textEditingManager.dispose(),super.destroy()}}const $e={x1:0,y1:0,x2:0,y2:0},ze={...$e,r1:0,r2:0},ifNaN=(t,e)=>isNaN(t)&&"number"==typeof e?e:t,Ye=/^(\d+\.\d+)%|(\d+)%$/;function isPercent(t){return t&&Ye.test(t)}function parsePercent(t,e){const i="number"==typeof t?t:"string"==typeof t?parseFloat(t)/(isPercent(t)?100:1):NaN;return capValue(0,ifNaN(i,e),1)}const Ve=/\s*;\s*/,Ge=/\s*:\s*/;function parseColorStop(t,e){let i,s;const n=t.getAttribute("style");if(n){const t=n.split(Ve);""===t[t.length-1]&&t.pop();for(let e=t.length;e--;){const[n,r]=t[e].split(Ge).map(t=>t.trim());"stop-color"===n?i=r:"stop-opacity"===n&&(s=r)}}i=i||t.getAttribute("stop-color")||"rgb(0,0,0)",s=ifNaN(parseFloat(s||t.getAttribute("stop-opacity")||""),1);const r=new Color(i);return r.setAlpha(r.getAlpha()*s*e),{offset:parsePercent(t.getAttribute("offset"),0),color:r.toRgba()}}function parseColorStops(t,e){const i=[],s=t.getElementsByTagName("stop"),n=parsePercent(e,1);for(let t=s.length;t--;)i.push(parseColorStop(s[t],n));return i}function parseType(t){return"linearGradient"===t.nodeName||"LINEARGRADIENT"===t.nodeName?"linear":"radial"}function parseGradientUnits(t){return"userSpaceOnUse"===t.getAttribute("gradientUnits")?"pixels":"percentage"}function convertPercentUnitsToValues(t,e){let{width:i,height:s,gradientUnits:n}=e,r;return Object.keys(t).reduce((e,o)=>{const a=t[o];return"Infinity"===a?r=1:"-Infinity"===a?r=0:(r="string"==typeof a?parseFloat(a):a,"string"==typeof a&&isPercent(a)&&(r*=.01,"pixels"===n&&("x1"!==o&&"x2"!==o&&"r2"!==o||(r*=i),"y1"!==o&&"y2"!==o||(r*=s)))),e[o]=r,e},{})}function getValue(t,e){return t.getAttribute(e)}function parseLinearCoords(t){return{x1:getValue(t,"x1")||0,y1:getValue(t,"y1")||0,x2:getValue(t,"x2")||"100%",y2:getValue(t,"y2")||0}}function parseRadialCoords(t){return{x1:getValue(t,"fx")||getValue(t,"cx")||"50%",y1:getValue(t,"fy")||getValue(t,"cy")||"50%",r1:0,x2:getValue(t,"cx")||"50%",y2:getValue(t,"cy")||"50%",r2:getValue(t,"r")||"50%"}}function parseCoords(t,e){return convertPercentUnitsToValues("linear"===parseType(t)?parseLinearCoords(t):parseRadialCoords(t),{...e,gradientUnits:parseGradientUnits(t)})}class Gradient{constructor(t){const{type:e="linear",gradientUnits:i="pixels",coords:s={},colorStops:n=[],offsetX:r=0,offsetY:o=0,gradientTransform:a,id:h}=t||{};Object.assign(this,{type:e,gradientUnits:i,coords:{..."radial"===e?ze:$e,...s},colorStops:n,offsetX:r,offsetY:o,gradientTransform:a,id:h?`${h}_${uid()}`:uid()})}addColorStop(t){for(const e in t)this.colorStops.push({offset:parseFloat(e),color:t[e]});return this}toObject(t){return{...pick(this,t),type:this.type,coords:{...this.coords},colorStops:this.colorStops.map(t=>({...t})),offsetX:this.offsetX,offsetY:this.offsetY,gradientUnits:this.gradientUnits,gradientTransform:this.gradientTransform?[...this.gradientTransform]:void 0}}toSVG(t){let{additionalTransform:e}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i=[],s=this.gradientTransform?this.gradientTransform.concat():d.concat(),n="pixels"===this.gradientUnits?"userSpaceOnUse":"objectBoundingBox",r=this.colorStops.map(t=>({...t})).sort((t,e)=>t.offset-e.offset);let o=-this.offsetX,a=-this.offsetY;"objectBoundingBox"===n?(o/=t.width,a/=t.height):(o+=t.width/2,a+=t.height/2),isPath(t)&&"percentage"!==this.gradientUnits&&(o-=t.pathOffset.x,a-=t.pathOffset.y),s[4]-=o,s[5]-=a;const h=[`id="SVGID_${this.id}"`,`gradientUnits="${n}"`,`gradientTransform="${e?e+" ":""}${matrixToSVG(s)}"`,""].join(" ");if("linear"===this.type){const{x1:t,y1:e,x2:s,y2:n}=this.coords;i.push("<linearGradient ",h,' x1="',t,'" y1="',e,'" x2="',s,'" y2="',n,'">\n')}else if("radial"===this.type){const{x1:t,y1:e,x2:s,y2:n,r1:o,r2:a}=this.coords,l=o>a;i.push("<radialGradient ",h,' cx="',l?t:s,'" cy="',l?e:n,'" r="',l?o:a,'" fx="',l?s:t,'" fy="',l?n:e,'">\n'),l&&(r.reverse(),r.forEach(t=>{t.offset=1-t.offset}));const c=Math.min(o,a);if(c>0){const t=undefined,e=c/Math.max(o,a);r.forEach(t=>{t.offset+=e*(1-t.offset)})}}return r.forEach(t=>{let{color:e,offset:s}=t;i.push(`<stop offset="${100*s}%" style="stop-color:${e};"/>\n`)}),i.push("linear"===this.type?"</linearGradient>":"</radialGradient>","\n"),i.join("")}toLive(t){const{x1:e,y1:i,x2:s,y2:n,r1:r,r2:o}=this.coords,a="linear"===this.type?t.createLinearGradient(e,i,s,n):t.createRadialGradient(e,i,r,s,n,o);return this.colorStops.forEach(t=>{let{color:e,offset:i}=t;a.addColorStop(i,e)}),a}static async fromObject(t){const{colorStops:e,gradientTransform:i}=t;return new this({...t,colorStops:e?e.map(t=>({...t})):void 0,gradientTransform:i?[...i]:void 0})}static fromElement(t,e,i){const s=parseGradientUnits(t),n=e._findCenterFromElement();return new this({id:t.getAttribute("id")||void 0,type:parseType(t),coords:parseCoords(t,{width:i.viewBoxWidth||i.width,height:i.viewBoxHeight||i.height}),colorStops:parseColorStops(t,i.opacity),gradientUnits:s,gradientTransform:parseTransformAttribute(t.getAttribute("gradientTransform")||""),..."pixels"===s?{offsetX:e.width/2-n.x,offsetY:e.height/2-n.y}:{offsetX:0,offsetY:0}})}}_defineProperty(Gradient,"type","Gradient"),X.setClass(Gradient,"gradient"),X.setClass(Gradient,"linear"),X.setClass(Gradient,"radial");class Pattern{get type(){return"pattern"}set type(t){log("warn","Setting type has no effect",t)}constructor(t){_defineProperty(this,"repeat","repeat"),_defineProperty(this,"offsetX",0),_defineProperty(this,"offsetY",0),_defineProperty(this,"crossOrigin",""),this.id=uid(),Object.assign(this,t)}isImageSource(){return!!this.source&&"string"==typeof this.source.src}isCanvasSource(){return!!this.source&&!!this.source.toDataURL}sourceToString(){return this.isImageSource()?this.source.src:this.isCanvasSource()?this.source.toDataURL():""}toLive(t){return this.source&&(!this.isImageSource()||this.source.complete&&0!==this.source.naturalWidth&&0!==this.source.naturalHeight)?t.createPattern(this.source,this.repeat):null}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const{repeat:i,crossOrigin:s}=this;return{...pick(this,t),type:"pattern",source:this.sourceToString(),repeat:i,crossOrigin:s,offsetX:toFixed(this.offsetX,e.NUM_FRACTION_DIGITS),offsetY:toFixed(this.offsetY,e.NUM_FRACTION_DIGITS),patternTransform:this.patternTransform?[...this.patternTransform]:null}}toSVG(t){let{width:e,height:i}=t;const{source:s,repeat:n,id:r}=this,o=ifNaN(this.offsetX/e,0),a=ifNaN(this.offsetY/i,0),h=undefined,l=undefined;return[`<pattern id="SVGID_${r}" x="${o}" y="${a}" width="${"repeat-y"===n||"no-repeat"===n?1+Math.abs(o||0):ifNaN(s.width/e,0)}" height="${"repeat-x"===n||"no-repeat"===n?1+Math.abs(a||0):ifNaN(s.height/i,0)}">`,`<image x="0" y="0" width="${s.width}" height="${s.height}" xlink:href="${this.sourceToString()}"></image>`,"</pattern>",""].join("\n")}static async fromObject(t,e){let{type:i,source:s,patternTransform:n,...r}=t;const o=await loadImage(s,{...e,crossOrigin:r.crossOrigin});return new this({...r,patternTransform:n&&n.slice(0),source:o})}}_defineProperty(Pattern,"type","Pattern"),X.setClass(Pattern),X.setClass(Pattern,"pattern");class BaseBrush{constructor(t){_defineProperty(this,"color","rgb(0, 0, 0)"),_defineProperty(this,"width",1),_defineProperty(this,"shadow",null),_defineProperty(this,"strokeLineCap","round"),_defineProperty(this,"strokeLineJoin","round"),_defineProperty(this,"strokeMiterLimit",10),_defineProperty(this,"strokeDashArray",null),_defineProperty(this,"limitedToCanvasSize",!1),this.canvas=t}_setBrushStyles(t){t.strokeStyle=this.color,t.lineWidth=this.width,t.lineCap=this.strokeLineCap,t.miterLimit=this.strokeMiterLimit,t.lineJoin=this.strokeLineJoin,t.setLineDash(this.strokeDashArray||[])}_saveAndTransform(t){const e=this.canvas.viewportTransform;t.save(),t.transform(e[0],e[1],e[2],e[3],e[4],e[5])}needsFullRender(){const t=undefined;return new Color(this.color).getAlpha()<1||!!this.shadow}_setShadow(){if(!this.shadow||!this.canvas)return;const t=this.canvas,e=this.shadow,i=t.contextTop,s=t.getZoom()*t.getRetinaScaling();i.shadowColor=e.color,i.shadowBlur=e.blur*s,i.shadowOffsetX=e.offsetX*s,i.shadowOffsetY=e.offsetY*s}_resetShadow(){const t=this.canvas.contextTop;t.shadowColor="",t.shadowBlur=t.shadowOffsetX=t.shadowOffsetY=0}_isOutSideCanvas(t){return t.x<0||t.x>this.canvas.getWidth()||t.y<0||t.y>this.canvas.getHeight()}}class Path extends FabricObject{constructor(t){let{path:e,left:i,top:s,...n}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,Path.ownDefaults),this.setOptions(n),this._setPath(t||[],!0),"number"==typeof i&&this.set(m,i),"number"==typeof s&&this.set(y,s)}_setPath(t,e){this.path=makePathSimpler(Array.isArray(t)?t:parsePath(t)),this.setBoundingBox(e)}_findCenterFromElement(){const t=this._calcBoundsFromPath();return new Point(t.left+t.width/2,t.top+t.height/2)}_renderPathCommands(t){const e=-this.pathOffset.x,i=-this.pathOffset.y;t.beginPath();for(const s of this.path)switch(s[0]){case"L":t.lineTo(s[1]+e,s[2]+i);break;case"M":t.moveTo(s[1]+e,s[2]+i);break;case"C":t.bezierCurveTo(s[1]+e,s[2]+i,s[3]+e,s[4]+i,s[5]+e,s[6]+i);break;case"Q":t.quadraticCurveTo(s[1]+e,s[2]+i,s[3]+e,s[4]+i);break;case"Z":t.closePath();break}}_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&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject(t),path:this.path.map(t=>t.slice())}}toDatalessObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=this.toObject(t);return this.sourcePath&&(delete e.path,e.sourcePath=this.sourcePath),e}_toSVG(){const t=undefined;return["<path ","COMMON_PARTS",`d="${joinPath(this.path,e.NUM_FRACTION_DIGITS)}" stroke-linecap="round" />\n`]}_getOffsetTransform(){const t=e.NUM_FRACTION_DIGITS;return` translate(${toFixed(-this.pathOffset.x,t)}, ${toFixed(-this.pathOffset.y,t)})`}toClipPathSVG(t){const e=this._getOffsetTransform();return"\t"+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:i,pathOffset:s}=this._calcDimensions();this.set({width:e,height:i,pathOffset:s}),t&&this.setPositionByOrigin(s,p,p)}_calcBoundsFromPath(){const t=[];let e=0,i=0,s=0,n=0;for(const r of this.path)switch(r[0]){case"L":s=r[1],n=r[2],t.push({x:e,y:i},{x:s,y:n});break;case"M":s=r[1],n=r[2],e=s,i=n;break;case"C":t.push(...getBoundsOfCurve(s,n,r[1],r[2],r[3],r[4],r[5],r[6])),s=r[5],n=r[6];break;case"Q":t.push(...getBoundsOfCurve(s,n,r[1],r[2],r[1],r[2],r[3],r[4])),s=r[3],n=r[4];break;case"Z":s=e,n=i;break}return makeBoundingBoxFromPoints(t)}_calcDimensions(){const t=this._calcBoundsFromPath();return{...t,pathOffset:new Point(t.left+t.width/2,t.top+t.height/2)}}static fromObject(t){return this._fromObject(t,{extraParam:"path"})}static async fromElement(t,e,i){const{d:s,...n}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this(s,{...n,...e,left:void 0,top:void 0})}}function isEmptySVGPath(t){return"M 0 0 Q 0 0 0 0 L 0 0"===joinPath(t)}_defineProperty(Path,"type","Path"),_defineProperty(Path,"cacheProperties",[...Ot,"path","fillRule"]),_defineProperty(Path,"ATTRIBUTE_NAMES",[...se,"d"]),X.setClass(Path),X.setSVGClass(Path);class PencilBrush extends BaseBrush{constructor(t){super(t),_defineProperty(this,"decimate",.4),_defineProperty(this,"drawStraightLine",!1),_defineProperty(this,"straightLineKey","shiftKey"),this._points=[],this._hasStraightLine=!1}needsFullRender(){return super.needsFullRender()||this._hasStraightLine}static drawSegment(t,e,i){const s=e.midPointFrom(i);return t.quadraticCurveTo(e.x,e.y,s.x,s.y),s}onMouseDown(t,e){let{e:i}=e;this.canvas._isMainEvent(i)&&(this.drawStraightLine=!!this.straightLineKey&&i[this.straightLineKey],this._prepareForDrawing(t),this._addPoint(t),this._render())}onMouseMove(t,e){let{e:i}=e;if(this.canvas._isMainEvent(i)&&(this.drawStraightLine=!!this.straightLineKey&&i[this.straightLineKey],(!0!==this.limitedToCanvasSize||!this._isOutSideCanvas(t))&&this._addPoint(t)&&this._points.length>1))if(this.needsFullRender())this.canvas.clearContext(this.canvas.contextTop),this._render();else{const t=this._points,e=t.length,i=this.canvas.contextTop;this._saveAndTransform(i),this.oldEnd&&(i.beginPath(),i.moveTo(this.oldEnd.x,this.oldEnd.y)),this.oldEnd=PencilBrush.drawSegment(i,t[e-2],t[e-1]),i.stroke(),i.restore()}}onMouseUp(t){let{e:e}=t;return!this.canvas._isMainEvent(e)||(this.drawStraightLine=!1,this.oldEnd=void 0,this._finalizeAndAddPath(),!1)}_prepareForDrawing(t){this._reset(),this._addPoint(t),this.canvas.contextTop.moveTo(t.x,t.y)}_addPoint(t){return!(this._points.length>1&&t.eq(this._points[this._points.length-1]))&&(this.drawStraightLine&&this._points.length>1&&(this._hasStraightLine=!0,this._points.pop()),this._points.push(t),!0)}_reset(){this._points=[],this._setBrushStyles(this.canvas.contextTop),this._setShadow(),this._hasStraightLine=!1}_render(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.canvas.contextTop,e=this._points[0],i=this._points[1];if(this._saveAndTransform(t),t.beginPath(),2===this._points.length&&e.x===i.x&&e.y===i.y){const t=this.width/1e3;e.x-=t,i.x+=t}t.moveTo(e.x,e.y);for(let s=1;s<this._points.length;s++)PencilBrush.drawSegment(t,e,i),e=this._points[s],i=this._points[s+1];t.lineTo(e.x,e.y),t.stroke(),t.restore()}convertPointsToSVGPath(t){const e=this.width/1e3;return getSmoothPathFromPoints(t,e)}createPath(t){const e=new Path(t,{fill:null,stroke:this.color,strokeWidth:this.width,strokeLineCap:this.strokeLineCap,strokeMiterLimit:this.strokeMiterLimit,strokeLineJoin:this.strokeLineJoin,strokeDashArray:this.strokeDashArray});return this.shadow&&(this.shadow.affectStroke=!0,e.shadow=new Shadow(this.shadow)),e}decimatePoints(t,e){if(t.length<=2)return t;let i=t[0],s;const n=this.canvas.getZoom(),r=Math.pow(e/n,2),o=t.length-1,a=[i];for(let e=1;e<o-1;e++)s=Math.pow(i.x-t[e].x,2)+Math.pow(i.y-t[e].y,2),s>=r&&(i=t[e],a.push(i));return a.push(t[o]),a}_finalizeAndAddPath(){const t=undefined;this.canvas.contextTop.closePath(),this.decimate&&(this._points=this.decimatePoints(this._points,this.decimate));const e=this.convertPointsToSVGPath(this._points);if(isEmptySVGPath(e))return void this.canvas.requestRenderAll();const i=this.createPath(e);this.canvas.clearContext(this.canvas.contextTop),this.canvas.fire("before:path:created",{path:i}),this.canvas.add(i),this.canvas.requestRenderAll(),i.setCoords(),this._resetShadow(),this.canvas.fire("path:created",{path:i})}}const Ne=["radius","startAngle","endAngle","counterClockwise"],Ue={radius:0,startAngle:0,endAngle:360,counterClockwise:!1};class Circle extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Circle.ownDefaults}}constructor(t){super(),Object.assign(this,Circle.ownDefaults),this.setOptions(t)}_set(t,e){return super._set(t,e),"radius"===t&&this.setRadius(e),this}_render(t){t.beginPath(),t.arc(0,0,this.radius,degreesToRadians(this.startAngle),degreesToRadians(this.endAngle),this.counterClockwise),this._renderPaintInOrder(t)}getRadiusX(){return this.get("radius")*this.get(A)}getRadiusY(){return this.get("radius")*this.get(F)}setRadius(t){this.radius=t,this.set({width:2*t,height:2*t})}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...Ne,...t])}_toSVG(){const t=(this.endAngle-this.startAngle)%360;if(0===t)return["<circle ","COMMON_PARTS",'cx="0" cy="0" ','r="',`${this.radius}`,'" />\n'];{const{radius:e}=this,i=degreesToRadians(this.startAngle),s=degreesToRadians(this.endAngle),n=cos(i)*e,r=sin(i)*e,o=cos(s)*e,a=sin(s)*e,h=undefined,l=undefined;return[`<path d="M ${n} ${r} A ${e} ${e} 0 ${t>180?1:0} ${this.counterClockwise?0:1} ${o} ${a}" `,"COMMON_PARTS"," />\n"]}}static async fromElement(t,e,i){const{left:s=0,top:n=0,radius:r=0,...o}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this({...o,radius:r,left:s-r,top:n-r})}static fromObject(t){return super._fromObject(t)}}_defineProperty(Circle,"type","Circle"),_defineProperty(Circle,"cacheProperties",[...Ot,...Ne]),_defineProperty(Circle,"ownDefaults",Ue),_defineProperty(Circle,"ATTRIBUTE_NAMES",["cx","cy","r",...se]),X.setClass(Circle),X.setSVGClass(Circle);class CircleBrush extends BaseBrush{constructor(t){super(t),_defineProperty(this,"width",10),this.points=[]}drawDot(t){const e=this.addPoint(t),i=this.canvas.contextTop;this._saveAndTransform(i),this.dot(i,e),i.restore()}dot(t,e){t.fillStyle=e.fill,t.beginPath(),t.arc(e.x,e.y,e.radius,0,2*Math.PI,!1),t.closePath(),t.fill()}onMouseDown(t){this.points=[],this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.drawDot(t)}_render(){const t=this.canvas.contextTop,e=this.points;this._saveAndTransform(t);for(let i=0;i<e.length;i++)this.dot(t,e[i]);t.restore()}onMouseMove(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.needsFullRender()?(this.canvas.clearContext(this.canvas.contextTop),this.addPoint(t),this._render()):this.drawDot(t))}onMouseUp(){const t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;const e=[];for(let t=0;t<this.points.length;t++){const i=this.points[t],s=new Circle({radius:i.radius,left:i.x,top:i.y,originX:p,originY:p,fill:i.fill});this.shadow&&(s.shadow=new Shadow(this.shadow)),e.push(s)}const i=new Group(e,{canvas:this.canvas});this.canvas.fire("before:path:created",{path:i}),this.canvas.add(i),this.canvas.fire("path:created",{path:i}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()}addPoint(t){let{x:e,y:i}=t;const s={x:e,y:i,radius:getRandomInt(Math.max(0,this.width-20),this.width+20)/2,fill:new Color(this.color).setAlpha(getRandomInt(0,100)/100).toRgba()};return this.points.push(s),s}}function getUniqueRects(t){const e={},i=[];for(let s=0,n;s<t.length;s++)n=`${t[s].left}${t[s].top}`,e[n]||(e[n]=!0,i.push(t[s]));return i}class SprayBrush extends BaseBrush{constructor(t){super(t),_defineProperty(this,"width",10),_defineProperty(this,"density",20),_defineProperty(this,"dotWidth",1),_defineProperty(this,"dotWidthVariance",1),_defineProperty(this,"randomOpacity",!1),_defineProperty(this,"optimizeOverlapping",!0),this.sprayChunks=[],this.sprayChunk=[]}onMouseDown(t){this.sprayChunks=[],this.canvas.clearContext(this.canvas.contextTop),this._setShadow(),this.addSprayChunk(t),this.renderChunck(this.sprayChunk)}onMouseMove(t){!0===this.limitedToCanvasSize&&this._isOutSideCanvas(t)||(this.addSprayChunk(t),this.renderChunck(this.sprayChunk))}onMouseUp(){const t=this.canvas.renderOnAddRemove;this.canvas.renderOnAddRemove=!1;const e=[];for(let t=0;t<this.sprayChunks.length;t++){const i=this.sprayChunks[t];for(let t=0;t<i.length;t++){const s=i[t],n=new Rect({width:s.width,height:s.width,left:s.x+1,top:s.y+1,originX:p,originY:p,fill:this.color});e.push(n)}}const i=new Group(this.optimizeOverlapping?getUniqueRects(e):e,{objectCaching:!0,subTargetCheck:!1,interactive:!1});this.shadow&&i.set("shadow",new Shadow(this.shadow)),this.canvas.fire("before:path:created",{path:i}),this.canvas.add(i),this.canvas.fire("path:created",{path:i}),this.canvas.clearContext(this.canvas.contextTop),this._resetShadow(),this.canvas.renderOnAddRemove=t,this.canvas.requestRenderAll()}renderChunck(t){const e=this.canvas.contextTop;e.fillStyle=this.color,this._saveAndTransform(e);for(let i=0;i<t.length;i++){const s=t[i];e.globalAlpha=s.opacity,e.fillRect(s.x,s.y,s.width,s.width)}e.restore()}_render(){const t=this.canvas.contextTop;t.fillStyle=this.color,this._saveAndTransform(t);for(let t=0;t<this.sprayChunks.length;t++)this.renderChunck(this.sprayChunks[t]);t.restore()}addSprayChunk(t){this.sprayChunk=[];const e=this.width/2;for(let i=0;i<this.density;i++)this.sprayChunk.push({x:getRandomInt(t.x-e,t.x+e),y:getRandomInt(t.y-e,t.y+e),width:this.dotWidthVariance?getRandomInt(Math.max(1,this.dotWidth-this.dotWidthVariance),this.dotWidth+this.dotWidthVariance):this.dotWidth,opacity:this.randomOpacity?getRandomInt(0,100)/100:1});this.sprayChunks.push(this.sprayChunk)}}class PatternBrush extends PencilBrush{constructor(t){super(t)}getPatternSrc(){const t=20,e=5,i=createCanvasElement(),s=i.getContext("2d");return i.width=i.height=25,s&&(s.fillStyle=this.color,s.beginPath(),s.arc(10,10,10,0,2*Math.PI,!1),s.closePath(),s.fill()),i}getPattern(t){return t.createPattern(this.source||this.getPatternSrc(),"repeat")}_setBrushStyles(t){super._setBrushStyles(t);const e=this.getPattern(t);e&&(t.strokeStyle=e)}createPath(t){const e=super.createPath(t),i=e._getLeftTopCoords().scalarAdd(e.strokeWidth/2);return e.stroke=new Pattern({source:this.source||this.getPatternSrc(),offsetX:-i.x,offsetY:-i.y}),e}}const qe=["x1","x2","y1","y2"];class Line extends FabricObject{constructor(){let[t,e,i,s]=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[0,0,100,0],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_defineProperty(this,"hitStrokeWidth","auto"),_defineProperty(this,"_updatingEndpoints",!1),_defineProperty(this,"_useEndpointCoords",!0),_defineProperty(this,"_exportingSVG",!1),this.setOptions(n),this.x1=t,this.x2=i,this.y1=e,this.y2=s,void 0!==n.hitStrokeWidth&&(this.hitStrokeWidth=n.hitStrokeWidth),this.hasBorders=!1,this.hasControls=!0,this.selectable=!0,this.hoverCursor="move",this.perPixelTargetFind=!1,this.strokeLineCap="butt",this._setWidthHeight();const{left:r,top:o}=n;"number"==typeof r&&this.set(m,r),"number"==typeof o&&this.set(y,o),this._setupLineControls()}_setupLineControls(){this.controls={p1:new Control({x:0,y:0,cursorStyle:"move",actionHandler:this._endpointActionHandler.bind(this),positionHandler:this._p1PositionHandler.bind(this),render:this._renderEndpointControl.bind(this),sizeX:12,sizeY:12}),p2:new Control({x:0,y:0,cursorStyle:"move",actionHandler:this._endpointActionHandler.bind(this),positionHandler:this._p2PositionHandler.bind(this),render:this._renderEndpointControl.bind(this),sizeX:12,sizeY:12})}}_p1PositionHandler(){return new Point(this.x1,this.y1).transform(this.getViewportTransform())}_p2PositionHandler(){return new Point(this.x2,this.y2).transform(this.getViewportTransform())}_renderEndpointControl(t,e,i){const s=12;t.save(),t.fillStyle="#007bff",t.strokeStyle="#ffffff",t.lineWidth=2,t.beginPath(),t.arc(e,i,6,0,2*Math.PI),t.fill(),t.stroke(),t.restore()}drawBorders(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this._useEndpointCoords?(this._drawLineBorders(t,e),this):super.drawBorders(t,e,{})}_drawLineBorders(t){var e;let i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const s=(null===(e=this.canvas)||void 0===e?void 0:e.viewportTransform)||[1,0,0,1,0,0];t.save(),t.setTransform(s[0],s[1],s[2],s[3],s[4],s[5]),t.strokeStyle=i.borderColor||this.borderColor||"rgba(100, 200, 200, 0.5)",t.lineWidth=(this.strokeWidth||1)+5,t.lineCap=this.strokeLineCap||"butt",t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,t.beginPath(),t.moveTo(this.x1,this.y1),t.lineTo(this.x2,this.y2),t.stroke(),t.restore()}_renderControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1,this.drawControls(t,e),t.restore()}getBoundingRect(){if(this._useEndpointCoords){const{x1:t,y1:e,x2:i,y2:s}=this,n="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth,r=Math.max(n/2+5,10);return{left:Math.min(t,i)-r,top:Math.min(e,s)-r,width:Math.abs(i-t)+2*r||2*r,height:Math.abs(s-e)+2*r||2*r}}return super.getBoundingRect()}setCoords(){if(this._useEndpointCoords){const t="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth,e=Math.max(t/2+5,10);if(this.width=Math.abs(this.x2-this.x1)+2*e,this.height=Math.abs(this.y2-this.y1)+2*e,0===this.left&&0===this.top){const t=this._findCenterFromElement();this.left=t.x,this.top=t.y}}super.setCoords()}getCoords(){if(this._useEndpointCoords){const t=this.x2-this.x1,e=this.y2-this.y1,i=Math.sqrt(t*t+e*e);if(0===i)return super.getCoords();const s="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth,n=Math.max(s/2+2,5),r=-e/i,o=t/i;return[new Point(this.x1+r*n,this.y1+o*n),new Point(this.x2+r*n,this.y2+o*n),new Point(this.x2-r*n,this.y2-o*n),new Point(this.x1-r*n,this.y1-o*n)]}return super.getCoords()}containsPoint(t){if(this._useEndpointCoords){var e;if((null===(e=this.canvas)||void 0===e?void 0:e.getActiveObject())===this)return super.containsPoint(t);const i=this._distanceToLineSegment(t.x,t.y),s="auto"===this.hitStrokeWidth?this.strokeWidth:this.hitStrokeWidth||1,n=undefined;return i<=Math.max(s/2+2,5)}return super.containsPoint(t)}_distanceToLineSegment(t,e){const i=this.x1,s=this.y1,n=this.x2,r=this.y2,o=(i-n)*(i-n)+(s-r)*(s-r);if(0===o)return Math.sqrt((t-i)*(t-i)+(e-s)*(e-s));const a=((t-i)*(n-i)+(e-s)*(r-s))/o;let h,l;return a<0?(h=i,l=s):a>1?(h=n,l=r):(h=i+a*(n-i),l=s+a*(r-s)),Math.sqrt((t-h)*(t-h)+(e-l)*(e-l))}_endpointActionHandler(t,e,i,s){var n;const r=e.corner,o=new Point(i,s);let a=o.x,h=o.y;if(t.shiftKey){const t="p1"===r?"p2":"p1",e=this["p1"===t?"x1":"x2"],i=this["p1"===t?"y1":"y2"],s=this._snapToAngle(e,i,a,h);a=s.x,h=s.y}var l;return this._useEndpointCoords?("p1"===r?(this.x1=a,this.y1=h):"p2"===r&&(this.x2=a,this.y2=h),this.stroke instanceof Gradient&&!this._exportingSVG&&(this.stroke.coords.x1=this.x1,this.stroke.coords.y1=this.y1,this.stroke.coords.x2=this.x2,this.stroke.coords.y2=this.y2),this.dirty=!0,this.setCoords(),null===(l=this.canvas)||void 0===l||l.requestRenderAll(),!0):(this._updatingEndpoints=!0,"p1"===r?(this.x1=a,this.y1=h):"p2"===r&&(this.x2=a,this.y2=h),this._setWidthHeight(),this.dirty=!0,this._updatingEndpoints=!1,null===(n=this.canvas)||void 0===n||n.requestRenderAll(),this.fire("modified",{transform:e,target:this,e:t}),!0)}_snapToAngle(t,e,i,s){const n=i-t,r=s-e,o=Math.sqrt(n*n+r*r);if(0===o)return{x:i,y:s};let a=Math.atan2(r,n)*(180/Math.PI);const h=15,l=undefined,c=Math.round(a/h)*h*(Math.PI/180);return{x:t+Math.cos(c)*o,y:e+Math.sin(c)*o}}_setWidthHeight(){let t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.width=Math.abs(this.x2-this.x1)||1,this.height=Math.abs(this.y2-this.y1)||1,!t&&!this._updatingEndpoints){const{left:t,top:e,width:i,height:s}=makeBoundingBoxFromPoints([{x:this.x1,y:this.y1},{x:this.x2,y:this.y2}]);this.setPositionByOrigin(new Point(t+i/2,e+s/2),p,p)}}_set(t,e){const i=this.left,s=this.top;if(super._set(t,e),qe.includes(t)&&(this._setWidthHeight(),this.dirty=!0,this.stroke instanceof Gradient&&!this._exportingSVG&&(this.stroke.coords.x1=this.x1,this.stroke.coords.y1=this.y1,this.stroke.coords.x2=this.x2,this.stroke.coords.y2=this.y2)),("left"===t||"top"===t)&&this.canvas&&!this._updatingEndpoints){const t=this.left-i,e=this.top-s;0===t&&0===e||(this._updatingEndpoints=!0,this.x1+=t,this.y1+=e,this.x2+=t,this.y2+=e,this.stroke instanceof Gradient&&(this.stroke.coords.x1=this.x1,this.stroke.coords.y1=this.y1,this.stroke.coords.x2=this.x2,this.stroke.coords.y2=this.y2),this._updatingEndpoints=!1)}return this}render(t){this._useEndpointCoords?this._renderDirectly(t):super.render(t)}_renderDirectly(t){if(!this.visible)return;t.save(),t.globalAlpha=this.opacity,t.lineWidth=this.strokeWidth,t.lineCap=this.strokeLineCap||"butt",t.beginPath(),t.moveTo(this.x1,this.y1),t.lineTo(this.x2,this.y2);const e=t.strokeStyle;var i;isFiller(this.stroke)?t.strokeStyle=this.stroke.toLive(t):t.strokeStyle=(null===(i=this.stroke)||void 0===i?void 0:i.toString())||"#000";t.stroke(),t.strokeStyle=e,t.restore()}_render(t){if(this._useEndpointCoords)return;t.beginPath();const e=this.calcLinePoints();t.moveTo(e.x1,e.y1),t.lineTo(e.x2,e.y2),t.lineWidth=this.strokeWidth;const i=t.strokeStyle;isFiller(this.stroke)&&(t.strokeStyle=this.stroke.toLive(t)),this.stroke&&this._renderStroke(t),t.strokeStyle=i}_findCenterFromElement(){return new Point((this.x1+this.x2)/2,(this.y1+this.y2)/2)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return this._useEndpointCoords?{...super.toObject(t),x1:this.x1,y1:this.y1,x2:this.x2,y2:this.y2}:{...super.toObject(t),...this.calcLinePoints()}}_getNonTransformedDimensions(){const t=super._getNonTransformedDimensions();return"round"===this.strokeLineCap&&(t.x+=this.strokeWidth,t.y+=this.strokeWidth),t}calcLinePoints(){if(this._updatingEndpoints){const t=(this.x1+this.x2)/2,e=(this.y1+this.y2)/2;return{x1:this.x1-t,y1:this.y1-e,x2:this.x2-t,y2:this.y2-e}}const{x1:t,x2:e,y1:i,y2:s,width:n,height:r}=this,o=t<=e?-1:1,a=i<=s?-1:1;return{x1:o*n/2,y1:a*r/2,x2:o*-n/2,y2:a*-r/2}}_toSVG(){if(this._useEndpointCoords){let t="";return t=this.stroke instanceof Gradient?`stroke="url(#${this.stroke.id})"`:`stroke="${this.stroke||"none"}"`,[`<line ${t} stroke-width="${this.strokeWidth}" stroke-linecap="${this.strokeLineCap}" `,`stroke-dasharray="${this.strokeDashArray?this.strokeDashArray.join(" "):"none"}" `,`stroke-dashoffset="${this.strokeDashOffset}" stroke-linejoin="${this.strokeLineJoin}" `,`stroke-miterlimit="${this.strokeMiterLimit}" fill="${this.fill||"none"}" `,`fill-rule="${this.fillRule}" opacity="${this.opacity}" `,`x1="${this.x1}" y1="${this.y1}" x2="${this.x2}" y2="${this.y2}" />\n`]}{const{x1:t,x2:e,y1:i,y2:s}=this.calcLinePoints();return["<line ","COMMON_PARTS",`x1="${t}" y1="${i}" x2="${e}" y2="${s}" />\n`]}}toSVG(t){if(this._useEndpointCoords){const e=this.left,i=this.top;this.left=(this.x1+this.x2)/2,this.top=(this.y1+this.y2)/2;const s=super.toSVG(t);this.left=e,this.top=i;const n=undefined;return s.replace(/<g transform="[^"]*"[^>]*>/g,"").replace(/<\/g>/g,"").replace(/x1="[^"]*"/g,`x1="${this.x1}"`).replace(/y1="[^"]*"/g,`y1="${this.y1}"`).replace(/x2="[^"]*"/g,`x2="${this.x2}"`).replace(/y2="[^"]*"/g,`y2="${this.y2}"`)}return super.toSVG(t)}static async fromElement(t,e,i){const{x1:s=0,y1:n=0,x2:r=0,y2:o=0,...a}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this([s,n,r,o],a)}static fromObject(t){let{x1:e,y1:i,x2:s,y2:n,...r}=t;return this._fromObject({...r,points:[e,i,s,n]},{extraParam:"points"})}}function pointDistance(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function normalizeVector(t){const e=Math.sqrt(t.x*t.x+t.y*t.y);return 0===e?{x:0,y:0}:{x:t.x/e,y:t.y/e}}function getMaxRadius(t,e,i){const s=pointDistance(t,e),n=pointDistance(e,i);return Math.min(s,n)/2}function calculateRoundedCorner(t,e,i,s){const n={x:e.x-t.x,y:e.y-t.y},r={x:i.x-e.x,y:i.y-e.y},o=normalizeVector(n),a=normalizeVector(r),h=getMaxRadius(t,e,i),l=Math.min(s,h),c={x:e.x-o.x*l,y:e.y-o.y*l},d={x:e.x+a.x*l,y:e.y+a.y*l},u=l*f,g=undefined,p=undefined;return{corner:e,start:c,end:d,cp1:{x:c.x+o.x*u,y:c.y+o.y*u},cp2:{x:d.x-a.x*u,y:d.y-a.y*u},actualRadius:l}}function applyCornerRadiusToPolygon(t,e){let i=arguments.length>2&&void 0!==arguments[2]&&arguments[2];if(t.length<3)throw new Error("Polygon must have at least 3 points");let s=e;if(i){const i=Math.min(...t.map(t=>t.x)),n=Math.max(...t.map(t=>t.x)),r=Math.min(...t.map(t=>t.y)),o=Math.max(...t.map(t=>t.y)),a=n-i,h=o-r,l=undefined;s=e/100*Math.min(a,h)}const n=[];for(let e=0;e<t.length;e++){const i=(e-1+t.length)%t.length,r=(e+1)%t.length,o=undefined,a=undefined,h=undefined,l=calculateRoundedCorner(t[i],t[e],t[r],s);n.push(l)}return n}function renderRoundedPolygon(t,e){let i=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(0===e.length)return;t.beginPath();const s=e[0];t.moveTo(s.start.x,s.start.y);for(let s=0;s<e.length;s++){const n=e[s],r=undefined,o=e[(s+1)%e.length];t.bezierCurveTo(n.cp1.x,n.cp1.y,n.cp2.x,n.cp2.y,n.end.x,n.end.y),(s<e.length-1||i)&&t.lineTo(o.start.x,o.start.y)}i&&t.closePath()}function generateRoundedPolygonPath(t){let e=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(0===t.length)return"";const i=[],s=t[0];i.push(`M ${s.start.x} ${s.start.y}`);for(let s=0;s<t.length;s++){const n=t[s],r=undefined,o=t[(s+1)%t.length];i.push(`C ${n.cp1.x} ${n.cp1.y} ${n.cp2.x} ${n.cp2.y} ${n.end.x} ${n.end.y}`),(s<t.length-1||e)&&i.push(`L ${o.start.x} ${o.start.y}`)}return e&&i.push("Z"),i.join(" ")}_defineProperty(Line,"type","Line"),_defineProperty(Line,"cacheProperties",[...Ot,...qe]),_defineProperty(Line,"ATTRIBUTE_NAMES",se.concat(qe)),X.setClass(Line),X.setSVGClass(Line);const Ke={width:100,height:100,cornerRadius:0},Je=["cornerRadius"];class Triangle extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Triangle.ownDefaults}}constructor(t){super(),Object.assign(this,Triangle.ownDefaults),this.setOptions(t)}_getTrianglePoints(){const t=this.width/2,e=this.height/2;return[{x:-t,y:e},{x:0,y:-e},{x:t,y:e}]}_render(t){if(this.cornerRadius>0){const e=undefined,i=undefined;renderRoundedPolygon(t,applyCornerRadiusToPolygon(this._getTrianglePoints(),this.cornerRadius),!0)}else{const e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,i),t.lineTo(0,-i),t.lineTo(e,i),t.closePath()}this._renderPaintInOrder(t)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...Je,...t])}_toSVG(){if(this.cornerRadius>0){const t=undefined,e=undefined,i=undefined;return["<path ","COMMON_PARTS",`d="${generateRoundedPolygonPath(applyCornerRadiusToPolygon(this._getTrianglePoints(),this.cornerRadius),!0)}" />`]}{const t=this.width/2,e=this.height/2,i=undefined;return["<polygon ","COMMON_PARTS",'points="',`${-t} ${e},0 ${-e},${t} ${e}`,'" />']}}}_defineProperty(Triangle,"type","Triangle"),_defineProperty(Triangle,"cacheProperties",[...Ot,...Je]),_defineProperty(Triangle,"ownDefaults",Ke),X.setClass(Triangle),X.setSVGClass(Triangle);const Ze={rx:0,ry:0},Qe=["rx","ry"];class Ellipse extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Ellipse.ownDefaults}}constructor(t){super(),Object.assign(this,Ellipse.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);break}return this}getRx(){return this.get("rx")*this.get(A)}getRy(){return this.get("ry")*this.get(F)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject([...Qe,...t])}_toSVG(){return["<ellipse ","COMMON_PARTS",`cx="0" cy="0" rx="${this.rx}" ry="${this.ry}" />\n`]}_render(t){t.beginPath(),t.save(),t.transform(1,0,0,this.ry/this.rx,0,0),t.arc(0,0,this.rx,0,l,!1),t.restore(),this._renderPaintInOrder(t)}static async fromElement(t,e,i){const s=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return s.left=(s.left||0)-s.rx,s.top=(s.top||0)-s.ry,new this(s)}}function parsePointsAttribute(t){if(!t)return[];const e=t.replace(/,/g," ").trim().split(/\s+/),i=[];for(let t=0;t<e.length;t+=2)i.push({x:parseFloat(e[t]),y:parseFloat(e[t+1])});return i}_defineProperty(Ellipse,"type","Ellipse"),_defineProperty(Ellipse,"cacheProperties",[...Ot,...Qe]),_defineProperty(Ellipse,"ownDefaults",Ze),_defineProperty(Ellipse,"ATTRIBUTE_NAMES",[...se,"cx","cy","rx","ry"]),X.setClass(Ellipse),X.setSVGClass(Ellipse);const ti={exactBoundingBox:!1,cornerRadius:0};class Polyline extends FabricObject{static getDefaults(){return{...super.getDefaults(),...Polyline.ownDefaults}}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),_defineProperty(this,"strokeDiff",void 0),Object.assign(this,Polyline.ownDefaults),this.setOptions(e),this.points=t;const{left:i,top:s}=e;this.initialized=!0,this.setBoundingBox(!0),"number"==typeof i&&this.set(m,i),"number"==typeof s&&this.set(y,s)}isOpen(){return!0}_projectStrokeOnPoints(t){return projectStrokeOnPoints(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(t=>t.projectedPoint):this.points;if(0===e.length)return{left:0,top:0,width:0,height:0,pathOffset:new Point,strokeOffset:new Point,strokeDiff:new Point};const i=makeBoundingBoxFromPoints(e),s=calcDimensionsMatrix({...t,scaleX:1,scaleY:1}),n=makeBoundingBoxFromPoints(this.points.map(t=>transformPoint(t,s,!0))),r=new Point(this.scaleX,this.scaleY);let o=i.left+i.width/2,a=i.top+i.height/2;return this.exactBoundingBox&&(o-=a*Math.tan(degreesToRadians(this.skewX)),a-=o*Math.tan(degreesToRadians(this.skewY))),{...i,pathOffset:new Point(o,a),strokeOffset:new Point(n.left,n.top).subtract(new Point(i.left,i.top)).multiply(r),strokeDiff:new Point(i.width,i.height).subtract(new Point(n.width,n.height)).multiply(r)}}_findCenterFromElement(){const t=makeBoundingBoxFromPoints(this.points);return new Point(t.left+t.width/2,t.top+t.height/2)}setDimensions(){this.setBoundingBox()}setBoundingBox(t){const{left:e,top:i,width:s,height:n,pathOffset:r,strokeOffset:o,strokeDiff:a}=this._calcDimensions();this.set({width:s,height:n,pathOffset:r,strokeOffset:o,strokeDiff:a}),t&&this.setPositionByOrigin(new Point(e+s/2,i+n/2),p,p)}isStrokeAccountedForInDimensions(){return this.exactBoundingBox}_getNonTransformedDimensions(){return this.exactBoundingBox?new Point(this.width,this.height):super._getNonTransformedDimensions()}_getTransformedDimensions(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(this.exactBoundingBox){let r;if(Object.keys(t).some(t=>this.strokeUniform||this.constructor.layoutProperties.includes(t))){var e,i;const{width:s,height:n}=this._calcDimensions(t);r=new Point(null!==(e=t.width)&&void 0!==e?e:s,null!==(i=t.height)&&void 0!==i?i:n)}else{var s,n;r=new Point(null!==(s=t.width)&&void 0!==s?s:this.width,null!==(n=t.height)&&void 0!==n?n:this.height)}return r.multiply(new Point(t.scaleX||this.scaleX,t.scaleY||this.scaleY))}return super._getTransformedDimensions(t)}_set(t,e){const i=this.initialized&&this[t]!==e,s=super._set(t,e);return this.exactBoundingBox&&i&&((t===A||t===F)&&this.strokeUniform&&this.constructor.layoutProperties.includes("strokeUniform")||this.constructor.layoutProperties.includes(t))&&this.setDimensions(),s}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject(["cornerRadius",...t]),points:this.points.map(t=>{let{x:e,y:i}=t;return{x:e,y:i}})}}_toSVG(){if(this.cornerRadius>0&&this.points.length>=3){const t=this.pathOffset.x,e=this.pathOffset.y,i=undefined,s=undefined,n=undefined;return["<path ","COMMON_PARTS",`d="${generateRoundedPolygonPath(applyCornerRadiusToPolygon(this.points.map(i=>({x:i.x-t,y:i.y-e})),this.cornerRadius),!this.isOpen())}" />\n`]}{const t=[],i=this.pathOffset.x,s=this.pathOffset.y,n=e.NUM_FRACTION_DIGITS;for(let e=0,r=this.points.length;e<r;e++)t.push(toFixed(this.points[e].x-i,n),",",toFixed(this.points[e].y-s,n)," ");return[`<${this.constructor.type.toLowerCase()} `,"COMMON_PARTS",`points="${t.join("")}" />\n`]}}_render(t){const e=this.points.length,i=this.pathOffset.x,s=this.pathOffset.y;if(e&&!isNaN(this.points[e-1].y)){if(this.cornerRadius>0&&e>=3){const e=undefined,n=undefined;renderRoundedPolygon(t,applyCornerRadiusToPolygon(this.points.map(t=>({x:t.x-i,y:t.y-s})),this.cornerRadius),!this.isOpen())}else{t.beginPath(),t.moveTo(this.points[0].x-i,this.points[0].y-s);for(let n=0;n<e;n++){const e=this.points[n];t.lineTo(e.x-i,e.y-s)}!this.isOpen()&&t.closePath()}this._renderPaintInOrder(t)}}complexity(){return this.points.length}static async fromElement(t,e,i){const s=parsePointsAttribute(t.getAttribute("points")),{left:n,top:r,...o}=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return new this(s,{...o,...e})}static fromObject(t){return this._fromObject(t,{extraParam:"points"})}}_defineProperty(Polyline,"ownDefaults",ti),_defineProperty(Polyline,"type","Polyline"),_defineProperty(Polyline,"layoutProperties",[L,j,"strokeLineCap","strokeLineJoin","strokeMiterLimit","strokeWidth","strokeUniform","points"]),_defineProperty(Polyline,"cacheProperties",[...Ot,"points","cornerRadius"]),_defineProperty(Polyline,"ATTRIBUTE_NAMES",[...se]),X.setClass(Polyline),X.setSVGClass(Polyline);class Polygon extends Polyline{isOpen(){return!1}}_defineProperty(Polygon,"ownDefaults",ti),_defineProperty(Polygon,"type","Polygon"),X.setClass(Polygon),X.setSVGClass(Polygon);class StyledText extends FabricObject{isEmptyStyles(t){if(!this.styles)return!0;if(void 0!==t&&!this.styles[t])return!0;const e=void 0===t?this.styles:{line:this.styles[t]};for(const t in e)for(const i in e[t])for(const s in e[t][i])return!1;return!0}styleHas(t,e){if(!this.styles)return!1;if(void 0!==e&&!this.styles[e])return!1;const i=void 0===e?this.styles:{0:this.styles[e]};for(const e in i)for(const s in i[e])if(void 0!==i[e][s][t])return!0;return!1}cleanStyle(t){if(!this.styles)return!1;const e=this.styles;let i=0,s,n,r=!0,o=0;for(const o in e){s=0;for(const a in e[o]){const h=e[o][a]||{},l=undefined;i++,void 0!==h[t]?(n?h[t]!==n&&(r=!1):n=h[t],h[t]===this[t]&&delete h[t]):r=!1,0!==Object.keys(h).length?s++:delete e[o][a]}0===s&&delete e[o]}for(let t=0;t<this._textLines.length;t++)o+=this._textLines[t].length;r&&i===o&&(this[t]=n,this.removeStyle(t))}removeStyle(t){if(!this.styles)return;const e=this.styles;let i,s,n;for(s in e){for(n in i=e[s],i)delete i[n][t],0===Object.keys(i[n]).length&&delete i[n];0===Object.keys(i).length&&delete e[s]}}_extendStyles(t,e){const{lineIndex:i,charIndex:s}=this.get2DCursorLocation(t);this._getLineStyle(i)||this._setLineStyle(i);const n=pickBy({...this._getStyleDeclaration(i,s),...e},t=>void 0!==t);this._setStyleDeclaration(i,s,n)}getSelectionStyles(t,e,i){const s=[];for(let n=t;n<(e||t);n++)s.push(this.getStyleAtPosition(n,i));return s}getStyleAtPosition(t,e){const{lineIndex:i,charIndex:s}=this.get2DCursorLocation(t);return e?this.getCompleteStyleDeclaration(i,s):this._getStyleDeclaration(i,s)}setSelectionStyles(t,e,i){for(let s=e;s<(i||e);s++)this._extendStyles(s,t);this._forceClearCache=!0}_getStyleDeclaration(t,e){var i;const s=this.styles&&this.styles[t];return s&&null!==(i=s[e])&&void 0!==i?i:{}}getCompleteStyleDeclaration(t,e){return{...pick(this,this.constructor._styleProperties),...this._getStyleDeclaration(t,e)}}_setStyleDeclaration(t,e,i){this.styles[t][e]=i}_deleteStyleDeclaration(t,e){delete this.styles[t][e]}_getLineStyle(t){return!!this.styles[t]}_setLineStyle(t){this.styles[t]={}}_deleteLineStyle(t){delete this.styles[t]}}_defineProperty(StyledText,"_styleProperties",st);let ei=null;function getMeasurementContext(){if(!ei){const t=createCanvasElementFor({width:0,height:0});ei=t.getContext("2d")}return ei}function measureGrapheme(t,e,i){const s=ii.get(t,e);if(s)return s;const n=i||getMeasurementContext();applyFontStyle(n,e);const r=n.measureText(t),o=getFontMetrics(e),a={width:r.width,height:o.lineHeight,ascent:o.ascent,descent:o.descent,baseline:o.ascent};return ii.set(t,e,a),a}function measureGraphemeWithKerning(t,e,i,s){const n=measureGrapheme(t,i,s);if(!e)return{...n,kernedWidth:n.width};const r=`${e}${t}`,o=si.get(r,i);if(o)return{...n,kernedWidth:o};const a=getMeasurementContext();applyFontStyle(a,i);const h=undefined,l=undefined,c=a.measureText(e+t).width-measureGrapheme(e,i,a).width;return si.set(r,i,c),{...n,kernedWidth:c}}function getRepresentativeCharacter(t){const e=getMeasurementContext();if("undefined"!=typeof document&&"fonts"in document)try{if(!document.fonts.check(`16px ${t}`))return"M"}catch(t){return"M"}const i=[{char:"م",script:"Arabic"},{char:"א",script:"Hebrew"},{char:"अ",script:"Devanagari"},{char:"ا",script:"Urdu"},{char:"ک",script:"Persian"},{char:"த",script:"Tamil"},{char:"ก",script:"Thai"},{char:"М",script:"Cyrillic"},{char:"Ω",script:"Greek"},{char:"M",script:"Latin"}];e.font=`16px ${t}`;const s=e.measureText("M").width;for(const t of i){const i=e.measureText(t.char);if(i.width>0&&Math.abs(i.width-s)>.1)return t.char}return"M"}function getFontMetrics(t){var e,i,s,n;const r=getFontDeclaration(t),o=ni.get(r);if(o)return o;const a=getMeasurementContext();applyFontStyle(a,t);const h=getRepresentativeCharacter(t.fontFamily),l=a.measureText(h),c=t.fontSize,d=null!==(e=l.fontBoundingBoxAscent)&&void 0!==e?e:.91*c,u=null!==(i=l.fontBoundingBoxDescent)&&void 0!==i?i:.21*c,g=undefined,f=undefined,p={ascent:d,descent:u,lineHeight:c,baseline:"alphabetic",fontBoundingBoxAscent:d,fontBoundingBoxDescent:u,actualBoundingBoxAscent:null!==(s=l.actualBoundingBoxAscent)&&void 0!==s?s:.716*c,actualBoundingBoxDescent:null!==(n=l.actualBoundingBoxDescent)&&void 0!==n?n:0};return ni.set(r,p),p}function applyFontStyle(t,e){const i=getFontDeclaration(e);t.font=i,e.letterSpacing&&"letterSpacing"in t&&(t.letterSpacing=`${e.letterSpacing}px`),e.direction&&(t.direction=e.direction),t.textBaseline="alphabetic"}function getFontDeclaration(t){const{fontStyle:e,fontWeight:i,fontSize:s,fontFamily:n}=t;let r;return`${e} ${i} ${s}px ${!n.includes(" ")||n.includes('"')||n.includes("'")?n:`"${n}"`}`}class LRUCache{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1e3;_defineProperty(this,"cache",new Map),_defineProperty(this,"maxSize",void 0),_defineProperty(this,"hits",0),_defineProperty(this,"misses",0),this.maxSize=t}get(t){const e=this.cache.get(t);if(e)return e.timestamp=Date.now(),this.hits++,e.value;this.misses++}set(t,e){if(this.cache.size>=this.maxSize){const t=this.findOldestKey();t&&this.cache.delete(t)}this.cache.set(t,{value:e,timestamp:Date.now()})}findOldestKey(){let t,e=1/0;for(const[i,s]of this.cache.entries())s.timestamp<e&&(e=s.timestamp,t=i);return t}clear(){this.cache.clear(),this.hits=0,this.misses=0}getStats(){const t=this.hits+this.misses;return{size:this.cache.size,hitRate:t>0?this.hits/t:0,hits:this.hits,misses:this.misses}}}class MeasurementCache{constructor(){_defineProperty(this,"cache",new LRUCache(1e3))}getCacheKey(t,e){const i=undefined,s=undefined;return`${getFontDeclaration(e)}|${t}|${e.letterSpacing||0}`}get(t,e){const i=this.getCacheKey(t,e);return this.cache.get(i)}set(t,e,i){const s=this.getCacheKey(t,e);this.cache.set(s,i)}clear(){this.cache.clear()}getStats(){return this.cache.getStats()}}class KerningCache{constructor(){_defineProperty(this,"cache",new LRUCache(5e3))}getCacheKey(t,e){const i=undefined;return`${getFontDeclaration(e)}|${t}`}get(t,e){const i=this.getCacheKey(t,e);return this.cache.get(i)}set(t,e,i){const s=this.getCacheKey(t,e);this.cache.set(s,i)}clear(){this.cache.clear()}getStats(){return this.cache.getStats()}}class FontMetricsCache{constructor(){_defineProperty(this,"cache",new Map)}get(t){return this.cache.get(t)}set(t,e){this.cache.set(t,e)}clear(){this.cache.clear()}getStats(){return{size:this.cache.size}}}const ii=new MeasurementCache,si=new KerningCache,ni=new FontMetricsCache;function clearAllCaches(){ii.clear(),si.clear(),ni.clear()}function fontLacksEnglishGlyphs(t){if("undefined"==typeof document)return!1;const e=["stv","arabic","naskh","thuluth","kufi","diwani","nastaliq","kufic","hijazi","madinah","makkah"],i=t.toLowerCase();if(e.some(t=>i.includes(t)))return!0;const s=getMeasurementContext();s.font=`16px ${t}`;const n=["A","B","C","a","b","c","M","W"],r="Arial, sans-serif",o=n.map(t=>s.measureText(t).width);s.font=`16px ${r}`;const a=n.map(t=>s.measureText(t).width);let h=0;for(let t=0;t<n.length;t++)Math.abs(o[t]-a[t])<.5&&h++;const l=undefined,c=undefined;return h>=.7*n.length}"undefined"!=typeof document&&"fonts"in document&&document.fonts.addEventListener("loadingdone",()=>{clearAllCaches()});const ri=new Map;function fontLacksEnglishGlyphsCached(t){if(ri.has(t))return ri.get(t);const e=fontLacksEnglishGlyphs(t);return ri.set(t,e),e}const oi={L:/[\u0041-\u005A\u0061-\u007A\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]/,R:/[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F4\u0608\u060B\u060D]/,AL:/[\u0627\u0629-\u063A\u0641-\u064A\u066D-\u066F\u0671-\u06D3\u06D5]/,EN:/[\u0030-\u0039\u00B2\u00B3\u00B9\u06F0-\u06F9]/,AN:/[\u0660-\u0669\u066B\u066C]/};function segmentGraphemes(t){if("undefined"!=typeof Intl&&"Segmenter"in Intl)try{const e=undefined,i=new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(t);return Array.from(i,t=>t.segment)}catch(t){}return graphemeSplit(t)}function analyzeBiDi(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"ltr";if(!t)return[];const i=[],s=Array.from(t);let n=null;for(let t=0;t<s.length;t++){const r=s[t],o=getBidiDirection(r,e);n&&n.direction===o?(n.text+=r,n.end=t+1):(n&&i.push(n),n={text:r,direction:o,level:"rtl"===o?1:0,start:t,end:t+1})}return n&&i.push(n),i.length>0?i:[{text:t,direction:e,level:"rtl"===e?1:0,start:0,end:t.length}]}function isWhitespace(t){return/\s/.test(t)}function getBidiDirection(t,e){return oi.R.test(t)||oi.AL.test(t)?"rtl":oi.L.test(t)?"ltr":(oi.EN.test(t)||oi.AN.test(t),e)}const ai="ـ",hi=new Set(["ا","د","ذ","ر","ز","و","ة","ء","آ","أ","إ","ٲ","ٳ","ٵ","ڈ","ډ","ڊ","ڋ","ڌ","ڍ","ڎ","ڏ","ڐ","ڑ","ڒ","ړ","ڔ","ڕ","ږ","ڗ","ژ","ڙ","ۄ","ۅ","ۆ","ۇ","ۈ","ۉ","ۊ","ۋ","ۍ","ۏ"]);function isArabicLetter(t){if(!t)return!1;const e=t.charCodeAt(0);return e>=1568&&e<=1610||e>=1646&&e<=1747||e>=1872&&e<=1919||e>=2208&&e<=2303}const li=new Set(["ا","أ","إ","آ","ٱ"]),ci="ل";function canInsertKashida(t,e){return!(!t||!e)&&(!/\s/.test(t)&&!/\s/.test(e)&&(!(!isArabicLetter(t)||!isArabicLetter(e))&&(!hi.has(t)&&(t!==ci||!li.has(e)))))}function findKashidaPoints(t){const e=[];for(let i=0;i<t.length-1;i++){const s=undefined,n=undefined;if(canInsertKashida(t[i],t[i+1])){let s=1,n=i,r=i+1;for(;n>0&&!isWhitespace(t[n-1]);)n--;for(;r<t.length&&!isWhitespace(t[r]);)r++;const o=r-n,a=i-n,h=undefined;s=Math.min(a,o-1-a)+1,o>4&&(s+=1),o>6&&(s+=1),e.push({charIndex:i,priority:s})}}return e.sort((t,e)=>e.priority-t.priority),e}function applyEllipsis(t,e){const{maxWidth:i,maxHeight:s,ellipsisChar:n,measureFn:r}=e;if(!t)return{truncatedText:"",isTruncated:!1,truncationIndex:0,ellipsisWidth:0,originalLength:0};const o="number"==typeof r(n)?r(n):r(n).width,a=r(t),h="number"==typeof a?a:a.width,l="number"==typeof a?0:a.height;let c=!1;if(i&&h>i&&(c=!0),s&&l>s&&(c=!0),!c)return{truncatedText:t,isTruncated:!1,truncationIndex:segmentGraphemes(t).length,ellipsisWidth:o,originalLength:segmentGraphemes(t).length};if(i){const e=undefined;return{...truncateByWidth(t,i,n,o,r),ellipsisWidth:o,originalLength:segmentGraphemes(t).length}}if(s){const e=undefined;return{...truncateByHeight(t,s,n,r),ellipsisWidth:o,originalLength:segmentGraphemes(t).length}}return{truncatedText:t,isTruncated:!1,truncationIndex:segmentGraphemes(t).length,ellipsisWidth:o,originalLength:segmentGraphemes(t).length}}function truncateByWidth(t,e,i,s,n){const r=segmentGraphemes(t),o=e-s;let a=0,h=r.length,l=0;for(;a<=h;){const t=Math.floor((a+h)/2),e=undefined,i=n(r.slice(0,t).join("")),s=undefined;("number"==typeof i?i:i.width)<=o?(l=t,a=t+1):h=t-1}if(0===l)return{truncatedText:i,isTruncated:!0,truncationIndex:0};if(l===r.length)return{truncatedText:t,isTruncated:!1,truncationIndex:r.length};const c=undefined;return{truncatedText:r.slice(0,l).join("")+i,isTruncated:!0,truncationIndex:l}}function truncateByHeight(t,e,i,s){var n;const r=t.split("\n");let o="",a=0;for(a=0;a<r.length;a++){const i=0===a?r[a]:o+"\n"+r[a],n=s(i),h=undefined;if(("number"==typeof n?0:n.height)>e&&o)break;if(o=i,a===r.length-1)return{truncatedText:t,isTruncated:!1,truncationIndex:segmentGraphemes(t).length}}if(a>0){const t=r[a-1],e=t+i,s=segmentGraphemes(o);return{truncatedText:o.replace(/[^\n]*$/,e),isTruncated:!0,truncationIndex:s.length-segmentGraphemes(t).length+segmentGraphemes(e).length-1}}const h="function"==typeof s&&(null===(n=s(r[0]))||void 0===n?void 0:n.width)||1e3;return truncateByWidth(r[0],h,i,0,s)}function layoutText(t){var e;const{text:i,width:s,height:n,wrap:r,align:o,ellipsis:a,direction:h,padding:l=0,verticalAlign:c="top"}=t;if(!i)return{lines:[],totalWidth:0,totalHeight:0,isTruncated:!1,graphemeCount:0};const d=s?s-2*l:1/0,u=n?n-2*l:1/0,g=i.split("\n"),f=[];let p=0,m=0,y=0,x;for(let e=0;e<g.length;e++){const i=g[e],s=e===g.length-1,r=layoutParagraph(i,{...t,width:d,isLastParagraph:s});for(const e of r){if(n&&p+e.height>u){const i=handleHeightOverflow(f,e,u-p,t);return{lines:i.lines,totalWidth:Math.max(m,...i.lines.map(t=>t.width)),totalHeight:u,isTruncated:!0,graphemeCount:y+i.addedGraphemes,ellipsisApplied:i.ellipsisResult}}e===r[r.length-1]&&(e.isLastInParagraph=!0),f.push(e),p+=e.height,m=Math.max(m,e.width),y+=e.graphemes.length}}if(a&&s)for(const e of f)if(e.width>d&&(x=applyEllipsis(e.text,{maxWidth:d,maxHeight:1/0,ellipsisChar:"string"==typeof a?a:"…",measureFn:e=>measureLineWidth(e,t)}),x.isTruncated)){const i=layoutSingleLine(x.truncatedText,t);Object.assign(e,i);break}const v=applyAlignment(f,o,m,t),_=calculateVerticalOffset(p,n||p,c);return v.forEach(t=>{t.bounds.forEach(t=>{t.y+=_})}),{lines:v,totalWidth:m,totalHeight:p,isTruncated:!(null===(e=x)||void 0===e||!e.isTruncated),graphemeCount:y,ellipsisApplied:x}}function layoutParagraph(t,e){const{wrap:i,width:s}=e;if(!t)return[createEmptyLine(e)];if("none"===i||s===1/0)return[layoutSingleLine(t,e,0)];const n=[];"word"===i?n.push(...wrapByWords(t,s,e)):"char"===i&&n.push(...wrapByCharacters(t,s,e));let r=0;const o=undefined;return n.map(t=>{const i=layoutSingleLine(t,e,r);return r+=t.length+1,i})}function layoutSingleLine(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;const s=segmentGraphemes(t),n=[],r=createMeasurementOptions(e);let o=0,a=0,h=0,l=i;for(let t=0;t<s.length;t++){const c=s[t],d=undefined,u=measureGraphemeWithKerning(c,t>0?s[t-1]:void 0,r),g=undefined,f=undefined,p=(e.letterSpacing||0)+(e.charSpacing?e.fontSize*e.charSpacing/1e3:0),m=u.kernedWidth+p;n.push({grapheme:c,x:o,y:0,width:u.width,height:u.height,kernedWidth:u.kernedWidth,left:o,baseline:u.baseline,charIndex:l,graphemeIndex:i+t}),l+=c.length,o+=m,a+=m,h=Math.max(h,u.height)}n.length>0&&(e.letterSpacing,e.charSpacing&&(e.fontSize,e.charSpacing));const c=1.13,d=h*e.lineHeight*c;return{text:t,graphemes:s,width:a,height:d,bounds:n,isWrapped:!1,isLastInParagraph:!1,baseline:.8*d}}function wrapByWords(t,e,i){const s=[],n=t.split(/(\s+)/);let r="";for(let t=0;t<n.length;t++){const o=n[t],a=measureLineWidth(o,i),h=r?r+o:o,l=undefined;if(measureLineWidth(h,i)>e&&r)s.push(r.trim()),r=o;else if(a>e&&!r){const t=wrapByCharacters(o,e,i);s.push(...t.slice(0,-1)),r=t[t.length-1],measureLineWidth(r,i)}else r=h}return r&&s.push(r.trim()),s.length>0?s:[""]}function wrapByCharacters(t,e,i){const s=[],n=segmentGraphemes(t);let r="";for(const t of n){const n=r+t,o=undefined;measureLineWidth(n,i)>e&&r?(s.push(r),r=t):r=n}return r&&s.push(r),s.length>0?s:[""]}function applyBiDiVisualReordering(t,e){const i="inherit"===e.direction?"ltr":e.direction,s=analyzeBiDi(t.text,i),n=undefined;if(!(s.length>1||1===s.length&&s[0].direction!==i))return"rtl"===i&&t.bounds.forEach(e=>{e.x=t.width-e.left-e.kernedWidth}),t;const r=[];let o=0;for(let t=0;t<s.length;t++){const e=undefined,i=segmentGraphemes(s[t].text);for(let e=0;e<i.length;e++)r.push(t);o+=i.length}const a=[],h=[];let l=0;for(const i of s){h.push(l);const s=segmentGraphemes(i.text);let n=0;for(let i=0;i<s.length;i++)if(l+i<t.bounds.length){const s=e.letterSpacing||0,r=e.charSpacing?e.fontSize*e.charSpacing/1e3:0;n+=t.bounds[l+i].kernedWidth+s+r}a.push(n),l+=s.length}const c=s.map((t,e)=>e);"rtl"===i&&c.reverse();const d=new Array(s.length);let u=0;for(const t of c)d[t]=u,u+=a[t];for(let i=0;i<t.bounds.length;i++){const n=r[i];if(void 0===n)continue;const o=s[n],l=h[n],c=undefined,u=undefined,g=(e.letterSpacing||0)+(e.charSpacing?e.fontSize*e.charSpacing/1e3:0);let f=0;for(let e=l;e<i;e++)f+=t.bounds[e].kernedWidth+g;const p=t.bounds[i].kernedWidth+g;"rtl"===o.direction?t.bounds[i].x=d[n]+a[n]-f-p:t.bounds[i].x=d[n]+f}return t}function applyAlignment(t,e,i,s){return t.map(t=>{applyBiDiVisualReordering(t,s);let n=0;switch(e){case"center":n=(i-t.width)/2;break;case"right":n=i-t.width;break;case"justify":if(!t.isLastInParagraph&&t.graphemes.length>1)return applyJustification(t,i,s);break;case"left":default:n=0;break}return 0!==n&&t.bounds.forEach(t=>{t.x+=n,t.left+=n}),t})}function applyJustification(t,e,i){const s=t.graphemes.filter(t=>/\s/.test(t)).length;if(0===s)return t;const n=undefined,r=(e-t.width)/s;let o=0;return t.bounds.forEach(t=>{t.x+=o,t.left+=o,/\s/.test(t.grapheme)&&(t.kernedWidth+=r,t.width+=r,o+=r)}),t.width=e,t.justifyRatio=1+r/(.25*i.fontSize),t}function calculateVerticalOffset(t,e,i){switch(i){case"middle":return(e-t)/2;case"bottom":return e-t;case"top":default:return 0}}function handleHeightOverflow(t,e,i,s){if(s.ellipsis&&i>0){const n="string"==typeof s.ellipsis?s.ellipsis:"…",r=s.width||1/0,o=applyEllipsis(e.text,{maxWidth:r,maxHeight:i,ellipsisChar:n,measureFn:t=>measureLineWidth(t,s)});if(o.isTruncated){const e=layoutSingleLine(o.truncatedText,s);return e.isLastInParagraph=!0,{lines:[...t,e],addedGraphemes:e.graphemes.length,ellipsisResult:o}}}return{lines:t,addedGraphemes:0}}function createEmptyLine(t){const e=1.13,i=t.fontSize*t.lineHeight*e;return{text:"",graphemes:[],width:0,height:i,bounds:[],isWrapped:!1,isLastInParagraph:!0,baseline:.8*i}}function measureLineWidth(t,e){const i=segmentGraphemes(t),s=createMeasurementOptions(e);let n=0;for(let t=0;t<i.length;t++){const r=undefined,o=undefined,a=measureGraphemeWithKerning(i[t],t>0?i[t-1]:void 0,s),h=e.letterSpacing||0,l=e.charSpacing?e.fontSize*e.charSpacing/1e3:0;n+=a.kernedWidth+h+l}return n}function createMeasurementOptions(t){return{fontFamily:t.fontFamily,fontSize:t.fontSize,fontStyle:t.fontStyle,fontWeight:t.fontWeight,letterSpacing:t.letterSpacing,direction:"inherit"===t.direction?"ltr":t.direction}}const di=/ +/g,ui=/"/g;function createSVGInlineRect(t,e,i,s,n){return`\t\t${createSVGRect(t,{left:e,top:i,width:s,height:n})}\n`}class TextSVGExportMixin extends FabricObjectSVGExportMixin{_toSVG(){const t=this._getSVGLeftTopOffsets(),e=this._getSVGTextAndBg(t.textTop,t.textLeft);return this._wrapSVGTextAndBg(e)}toSVG(t){const e=this._createBaseSVGMarkup(this._toSVG(),{reviver:t,noStyle:!0,withShadow:!0}),i=this.path;return i?e+i._createBaseSVGMarkup(i._toSVG(),{reviver:t,withShadow:!0,additionalTransform:matrixToSVG(this.calcOwnMatrix())}):e}_getSVGLeftTopOffsets(){return{textLeft:-this.width/2,textTop:-this.height/2,lineTop:this.getHeightOfLine(0)}}_wrapSVGTextAndBg(t){let{textBgRects:e,textSpans:i}=t;const s=!0,n=this.getSvgTextDecoration(this);return[e.join(""),'\t\t<text xml:space="preserve" ',`font-family="${this.fontFamily.replace(ui,"'")}" `,`font-size="${this.fontSize}" `,this.fontStyle?`font-style="${this.fontStyle}" `:"",this.fontWeight?`font-weight="${this.fontWeight}" `:"",n?`text-decoration="${n}" `:"","rtl"===this.direction?`direction="${this.direction}" `:"",'style="',this.getSvgStyles(s),'"',this.addPaintOrder()," >",i.join(""),"</text>\n"]}_getSVGTextAndBg(t,e){const i=[],s=[];let n=t,r;this.backgroundColor&&s.push(...createSVGInlineRect(this.backgroundColor,-this.width/2,-this.height/2,this.width,this.height));for(let t=0,o=this._textLines.length;t<o;t++)r=this._getLineLeftOffset(t),"rtl"===this.direction&&(r+=this.width),(this.textBackgroundColor||this.styleHas("textBackgroundColor",t))&&this._setSVGTextLineBg(s,t,e+r,n),this._setSVGTextLineText(i,t,e+r,n),n+=this.getHeightOfLine(t);return{textSpans:i,textBgRects:s}}_createTextCharSpan(t,i,s,n,r){const o=e.NUM_FRACTION_DIGITS,a=this.getSvgSpanStyles(i,t!==t.trim()||!!t.match(di)),h=a?`style="${a}"`:"",l=i.deltaY,c=l?` dy="${toFixed(l,o)}" `:"",{angle:d,renderLeft:u,renderTop:g,width:f}=r;let p="";if(void 0!==u){const t=f/2;d&&(p=` rotate="${toFixed(radiansToDegrees(d),o)}"`);const e=createRotateMatrix({angle:radiansToDegrees(d)});e[4]=u,e[5]=g;const i=new Point(-t,0).transform(e);s=i.x,n=i.y}return`<tspan x="${toFixed(s,o)}" y="${toFixed(n,o)}" ${c}${p}${h}>${escapeXml(t)}</tspan>`}_setSVGTextLineText(t,e,i,s){const n=this.getHeightOfLine(e),r=this.textAlign.includes(rt),o=this._textLines[e];let a,h,l="",c,d,u=0,g;s+=n*(1-this._fontSizeFraction)/this.lineHeight;for(let n=0,f=o.length-1;n<=f;n++)g=n===f||this.charSpacing||this.path,l+=o[n],c=this.__charBounds[e][n],0===u?(i+=c.kernedWidth-c.width,u+=c.width):u+=c.kernedWidth,r&&!g&&this._reSpaceAndTab.test(o[n])&&(g=!0),g||(a=a||this.getCompleteStyleDeclaration(e,n),h=this.getCompleteStyleDeclaration(e,n+1),g=hasStyleChanged(a,h,!0)),g&&(d=this._getStyleDeclaration(e,n),t.push(this._createTextCharSpan(l,d,i,s,c)),l="",a=h,"rtl"===this.direction?i-=u:i+=u,u=0)}_setSVGTextLineBg(t,e,i,s){const n=this._textLines[e],r=this.getHeightOfLine(e)/this.lineHeight;let o=0,a=0,h,l=this.getValueOfPropertyAt(e,0,"textBackgroundColor");for(let c=0;c<n.length;c++){const{left:n,width:d,kernedWidth:u}=this.__charBounds[e][c];h=this.getValueOfPropertyAt(e,c,"textBackgroundColor"),h!==l?(l&&t.push(...createSVGInlineRect(l,i+a,s,o,r)),a=n,o=d,l=h):o+=u}h&&t.push(...createSVGInlineRect(l,i+a,s,o,r))}getSvgStyles(t){return`${super.getSvgStyles(t)} text-decoration-thickness: ${toFixed(this.textDecorationThickness*this.getObjectScaling().y/10,e.NUM_FRACTION_DIGITS)}%; white-space: pre;`}getSvgSpanStyles(t,i){const{fontFamily:s,strokeWidth:n,stroke:r,fill:o,fontSize:a,fontStyle:h,fontWeight:l,deltaY:c,textDecorationThickness:d,linethrough:u,overline:g,underline:f}=t,p=this.getSvgTextDecoration({underline:null!=f?f:this.underline,overline:null!=g?g:this.overline,linethrough:null!=u?u:this.linethrough}),m=d||this.textDecorationThickness;return[r?colorPropToSVG(B,r):"",n?`stroke-width: ${n}; `:"",s?`font-family: ${s.includes("'")||s.includes('"')?s:`'${s}'`}; `:"",a?`font-size: ${a}px; `:"",h?`font-style: ${h}; `:"",l?`font-weight: ${l}; `:"",p?`text-decoration: ${p}; text-decoration-thickness: ${toFixed(m*this.getObjectScaling().y/10,e.NUM_FRACTION_DIGITS)}%; `:"",o?colorPropToSVG(I,o):"",c?`baseline-shift: ${-c}; `:"",i?"white-space: pre; ":""].join("")}getSvgTextDecoration(t){return["overline","underline","line-through"].filter(e=>t[e.replace("-","")]).join(" ")}}function segmentIntoGraphemes(t){if("undefined"!=typeof Intl&&Intl.Segmenter){const e=new Intl.Segmenter(void 0,{granularity:"grapheme"});return Array.from(e.segment(t),t=>t.segment)}return Array.from(t)}function extractLinesFromDOM(t){const e=t.value;if(!e)return{lines:[],totalWidth:0,totalHeight:0};const i=getComputedStyle(t),s=t.parentElement;if(!s)throw new Error("Textarea must be in DOM to extract lines");const n=document.createElement("div");n.style.position="absolute",n.style.left="-9999px",n.style.top="-9999px",n.style.visibility="hidden",n.style.pointerEvents="none";const r=undefined;["fontSize","fontFamily","fontWeight","fontStyle","lineHeight","letterSpacing","wordSpacing","textAlign","textTransform","whiteSpace","overflowWrap","wordBreak","direction","unicodeBidi","width","height","maxWidth","maxHeight","minWidth","minHeight","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","border","borderTop","borderRight","borderBottom","borderLeft","boxSizing"].forEach(t=>{n.style[t]=i[t]}),n.style.overflow="hidden",n.style.resize="none",s.appendChild(n);try{const t=segmentIntoGraphemes(e),i=[];t.forEach((t,e)=>{const s=document.createElement("span");s.textContent=t,s.setAttribute("data-index",e.toString()),n.appendChild(s),i.push(s)});const s=new Map;i.forEach((t,e)=>{const i=t.offsetTop;s.has(i)||s.set(i,{spans:[],indices:[]}),s.get(i).spans.push(t),s.get(i).indices.push(e)});const r=[],o=undefined;Array.from(s.keys()).sort((t,e)=>t-e).forEach(e=>{const i=undefined,n=s.get(e).indices.sort((t,e)=>t-e),o=n[0],a=n[n.length-1]+1,h=t.slice(o,a).join("");r.push({text:h,start:o,end:a})});const a=Math.max(...i.map(t=>t.offsetLeft+t.offsetWidth)),h=i.length>0?Math.max(...i.map(t=>t.offsetTop+t.offsetHeight)):0;return{lines:r,totalWidth:a,totalHeight:h}}finally{s.removeChild(n)}}function createLayoutHash(t){const e=undefined;return[t.text,t.width,t.height,t.fontFamily,t.fontSize,t.fontWeight,t.fontStyle,t.lineHeight,t.charSpacing,t.textAlign,t.direction].map(t=>String(t)).join("|")}function areBrowserLinesValid(t,e){if(!e||!t.__lastBrowserLines)return!1;const i=undefined;return createLayoutHash(t)===e}function storeBrowserLines(t,e,i){t.__lastBrowserLines=e,t.__lastBrowserLinesHash=createLayoutHash(t)}function clearBrowserLines(t){delete t.__lastBrowserLines,delete t.__lastBrowserLinesHash}function getBrowserLines(t){const e=t.__lastBrowserLines,i=t.__lastBrowserLinesHash;return e&&areBrowserLinesValid(t,i)?e:null}let gi;function getMeasuringContext(){if(!gi){const t=createCanvasElementFor({width:0,height:0});gi=t.getContext("2d")}return gi}class FabricText extends StyledText{static getDefaults(){return{...super.getDefaults(),...FabricText.ownDefaults}}constructor(t,e){super(),_defineProperty(this,"__charBounds",[]),_defineProperty(this,"__kashidaInfo",[]),Object.assign(this,FabricText.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=getPathSegmentsInfo(t.path))}_splitText(){const t=getBrowserLines(this);if(t&&this.useOverlayEditing)return this._splitTextFromBrowserLines(t);const e=this._splitTextIntoLines(this.text);return this.textLines=e.lines,this._textLines=e.graphemeLines,this._unwrappedTextLines=e._unwrappedLines,this._text=e.graphemeText,e}_splitTextFromBrowserLines(t){const e=[],i=[],s=[];let n=[];for(const r of t){e.push(r.text);const o=this.graphemeSplit(r.text);i.push(o),s.push(o),n=n.concat(o),r!==t[t.length-1]&&n.push("\n")}const r={lines:e,graphemeLines:i,graphemeText:n,_unwrappedLines:s};return this.textLines=r.lines,this._textLines=r.graphemeLines,this._unwrappedTextLines=r._unwrappedLines,this._text=r.graphemeText,r}initDimensions(){const t=undefined;if(this._isFontReady()||this.initialized||this._scheduleInitAfterFontLoad(),this.enableAdvancedLayout&&!this.path)return this.initDimensionsAdvanced();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(rt)&&this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces()}enlargeSpaces(){const t=undefined,e={none:0,short:.25,medium:.5,long:.75,stylistic:1}[this.kashida]||0;this.__kashidaInfo=[];for(let t=0,i=this._textLines.length;t<i;t++){this.__kashidaInfo[t]=[];const s=this._textLines.slice(t+1).some(t=>{const e=Array.isArray(t)?t.join(""):t;return/\S/.test(e)}),n=!s,r=t===i-1||this.isEndOfWrapping(t)||n,o=undefined;if(!(this.textAlign.includes("justify")&&!r))continue;const a=this._textLines[t],h=this.getLineWidth(t),l=this.width-h;if(l<=0)continue;const c=this.textLines[t].match(this._reSpacesAndTabs),d=c?c.length:0,u=e>0?findKashidaPoints(a):[],g=u.length>0;let f=0;g&&e>0&&(f=l*e);const p=g?f/u.length:0;if(g&&p>0){const e=[...u].sort((t,e)=>e.charIndex-t.charIndex),i=getMeasuringContext();if(i){i.font=this._getFontDeclaration();const s=i.measureText(ai).width;if(s>0){const i=[...a];for(const n of e){const e=Math.max(1,Math.round(p/s));for(let t=0;t<e;t++)i.splice(n.charIndex+1,0,ai);this.__kashidaInfo[t].push({charIndex:n.charIndex,width:p,tatweelCount:e})}this._textLines[t]=i,this.textLines&&void 0!==this.textLines[t]&&(this.textLines[t]=i.join("")),this.__charBounds[t]=[],this.__lineWidths[t]=void 0,this._measureLine(t)}}}const m=this.getLineWidth(t),y=this.width-m;if(y>0&&d>0){const e=y/d;let i=0;for(let s=0;s<this._textLines[t].length;s++){const n=this.__charBounds[t][s];n&&(n.left+=i,this._reSpaceAndTab.test(this._textLines[t][s])&&(n.width+=e,n.kernedWidth+=e,i+=e))}}}}_layoutTextAdvanced(){const t=undefined;return layoutText(this._getAdvancedLayoutOptions())}_getAdvancedLayoutOptions(){return{text:this.text,width:this.width,height:this.ellipsis?this.height:void 0,wrap:this.wrap||"word",align:this._mapTextAlignToAlign(this.textAlign),ellipsis:this.ellipsis||!1,fontSize:this.fontSize,lineHeight:this.lineHeight,letterSpacing:this.letterSpacing||0,charSpacing:this.charSpacing,direction:"inherit"===this.direction?"ltr":this.direction,fontFamily:this.fontFamily,fontStyle:this.fontStyle,fontWeight:this.fontWeight,verticalAlign:this.verticalAlign||"top"}}_mapTextAlignToAlign(t){switch(t){case"center":case p:return"center";case"right":case v:return"right";case"justify":case rt:case ot:case at:case ht:return"justify";default:return"left"}}initDimensionsAdvanced(){if(!this.enableAdvancedLayout)return this.initDimensions();const t=this._layoutTextAdvanced();this.width=t.totalWidth||this.MIN_TEXT_WIDTH,this.height=t.totalHeight,this._convertLayoutToLegacyFormat(t),this.textAlign.includes(rt)&&this.kashida&&"none"!==this.kashida&&this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces(),this.dirty=!0}_convertLayoutToLegacyFormat(t){this._textLines=t.lines.map(t=>t.graphemes),this.textLines=t.lines.map(t=>t.text),this._text=t.lines.flatMap(t=>t.graphemes),this.__charBounds=t.lines.map(t=>t.bounds.map(t=>({left:t.left,top:t.y,width:t.width,height:t.height,kernedWidth:t.kernedWidth,deltaY:t.deltaY||0,renderLeft:t.x}))),this.__lineWidths=t.lines.map(t=>t.width),t.lines.length>0&&(this._unwrappedTextLines=t.lines.map(t=>t.graphemes))}isEndOfWrapping(t){return t===this._textLines.length-1}missingNewlineOffset(t){return 1}get2DCursorLocation(t,e){const i=e?this._unwrappedTextLines:this._textLines;let s;for(s=0;s<i.length;s++){if(t<=i[s].length)return{lineIndex:s,charIndex:t};t-=i[s].length+this.missingNewlineOffset(s,e)}return{lineIndex:s-1,charIndex:i[s-1].length<t?i[s-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.__overlayEditor||(this.paintFirst===B?(this._renderTextStroke(t),this._renderTextFill(t)):(this._renderTextFill(t),this._renderTextStroke(t)))}_setTextStyles(t,e,i){if(t.textBaseline="alphabetic",this.path)switch(this.pathAlign){case p:t.textBaseline="middle";break;case"ascender":t.textBaseline=y;break;case"descender":t.textBaseline=x;break}t.font=this._getFontDeclaration(e,i)}calcTextWidth(){let t=this.getLineWidth(0);for(let e=1,i=this._textLines.length;e<i;e++){const i=this.getLineWidth(e);i>t&&(t=i)}return t}_renderTextLine(t,e,i,s,n,r){this._renderChars(t,e,i,s,n,r)}_buildKashidaDisplayLines(){if("none"===this.kashida||!this.__kashidaInfo)return this._textLines;const t=[];for(let e=0;e<this._textLines.length;e++){const i=this._textLines[e],s=this.__kashidaInfo[e];if(!s||0===s.length){t.push([...i]);continue}const n=[...s].sort((t,e)=>e.charIndex-t.charIndex),r=[...i];for(const{charIndex:t,width:e}of n){if(e<=0||t>=r.length)continue;const i=Math.max(1,Math.round(e/3)),s=ai.repeat(i);r.splice(t+1,0,s)}t.push(r)}return t}_renderTextLinesBackground(t){if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor"))return;const e=t.fillStyle,i=this._getLeftOffset();let s=this._getTopOffset();for(let e=0,n=this._textLines.length;e<n;e++){const n=this.getHeightOfLine(e);if(!this.textBackgroundColor&&!this.styleHas("textBackgroundColor",e)){s+=n;continue}const r=this._textLines[e].length,o=this._getLineLeftOffset(e);let a=0,h=0,l,c,d=this.getValueOfPropertyAt(e,0,"textBackgroundColor");for(let u=0;u<r;u++){const r=this.__charBounds[e][u];c=this.getValueOfPropertyAt(e,u,"textBackgroundColor"),this.path?(t.save(),t.translate(r.renderLeft,r.renderTop),t.rotate(r.angle),t.fillStyle=c,c&&t.fillRect(-r.width/2,-n/this.lineHeight*(1-this._fontSizeFraction),r.width,n/this.lineHeight),t.restore()):c!==d?(l=i+o+h,"rtl"===this.direction&&(l=this.width-l-a),t.fillStyle=d,d&&t.fillRect(l,s,a,n/this.lineHeight),h=r.left,a=r.width,d=c):a+=r.kernedWidth}c&&!this.path&&(l=i+o+h,"rtl"===this.direction&&(l=this.width-l-a),t.fillStyle=c,t.fillRect(l,s,a,n/this.lineHeight)),s+=n}t.fillStyle=e,this._removeShadow(t)}_measureChar(t,e,i,s){const r=n.getFontCache(e),o=this._getFontDeclaration(e),a=i+t,h="ـ"===i,l=i&&!h&&o===this._getFontDeclaration(s),c=e.fontSize/this.CACHE_FONT_SIZE;let d,u,g,f;if(i&&!h&&void 0!==r[i]&&(g=r[i]),void 0!==r[t]&&(f=d=r[t]),l&&void 0!==r[a]&&(u=r[a],f=u-g),void 0===d||void 0===g||void 0===u){const s=getMeasuringContext();this._setTextStyles(s,e,!0),void 0===d&&(f=d=s.measureText(t).width,r[t]=d),void 0===g&&l&&i&&!h&&(g=s.measureText(i).width,r[i]=g),l&&void 0===u&&!h&&(u=s.measureText(a).width,r[a]=u,f=u-g)}return{width:d*c,kernedWidth:f*c}}getHeightOfChar(t,e){return this.getValueOfPropertyAt(t,e,"fontSize")}measureLine(t){const e=this._measureLine(t);return 0!==this.charSpacing&&(e.width-=this._getWidthOfCharSpacing()),e.width<0&&(e.width=0),e}_measureLine(t){this._justifyApplied;let e=0,i,s;const n=this.pathSide===v,r=this.path,o=this._textLines[t],a=o.length,h=new Array(a);this.__charBounds[t]=h;for(let n=0;n<a;n++){const r=o[n];s=this._getGraphemeBox(r,t,n,i),h[n]=s,e+=s.kernedWidth,i=r}if(h[a]={left:s?s.left+s.width:0,width:0,kernedWidth:0,height:this.fontSize,deltaY:0},r&&r.segmentsInfo){let t=0;const i=r.segmentsInfo[r.segmentsInfo.length-1].length;switch(this.textAlign){case m:t=n?i-e:0;break;case p:t=(i-e)/2;break;case v:t=n?0:i-e;break}t+=this.pathStartOffset*(n?-1:1);for(let e=n?a-1:0;n?e>=0:e<a;n?e--:e++)s=h[e],t>i?t%=i:t<0&&(t+=i),this._setGraphemeOnPath(t,s),t+=s.kernedWidth}return{width:e,numOfSpaces:0}}_setGraphemeOnPath(t,e){const i=t+e.kernedWidth/2,s=this.path,n=getPointOnPath(s.path,i,s.segmentsInfo);e.renderLeft=n.x-s.pathOffset.x,e.renderTop=n.y-s.pathOffset.y,e.angle=n.angle+(this.pathSide===v?Math.PI:0)}_getGraphemeBox(t,e,i,s,n){const r=this.getCompleteStyleDeclaration(e,i),o=s?this.getCompleteStyleDeclaration(e,i-1):{},a=this._measureChar(t,r,s,o);let h=a.kernedWidth,l=a.width,c;0!==this.charSpacing&&(c=this._getWidthOfCharSpacing(),l+=c,h+=c);const d={width:l,left:0,height:r.fontSize,kernedWidth:h,deltaY:r.deltaY};if(i>0&&!n){const t=this.__charBounds[e][i-1];d.left=t.left+t.width+a.kernedWidth-a.width}return d}getHeightOfLine(t){if(this.__lineHeights[t])return this.__lineHeights[t];let e=this.getHeightOfChar(t,0);for(let i=1,s=this._textLines[t].length;i<s;i++)e=Math.max(this.getHeightOfChar(t,i),e);return this.__lineHeights[t]=e*this.lineHeight*this._fontSizeMult}calcTextHeight(){let t,e=0;for(let i=0,s=this._textLines.length;i<s;i++)t=this.getHeightOfLine(i),e+=i===s-1?t/this.lineHeight:t;return e}_getLeftOffset(){return"ltr"===this.direction?-this.width/2:this.width/2}_getTopOffset(){return-this.height/2}_renderTextCommon(t,e){var i;t.save();let s=0;const n=this._getLeftOffset(),r=this._getTopOffset();"fillText"===e&&null!==(i=this.textAlign)&&void 0!==i&&i.includes("justify");for(let i=0,a=this._textLines.length;i<a;i++){var o;const a=this.getHeightOfLine(i),h=a/this.lineHeight,l=this._getLineLeftOffset(i);"fillText"===e&&null!==(o=this.textAlign)&&void 0!==o&&o.includes("justify")&&this.getLineWidth(i),this._renderTextLine(e,t,this._textLines[i],n+l,r+s+h,i),s+=a}t.restore()}_renderTextFill(t){(this.fill||this.styleHas(I))&&this._renderTextCommon(t,"fillText")}_renderTextStroke(t){(this.stroke&&0!==this.strokeWidth||!this.isEmptyStyles())&&(this.shadow&&!this.shadow.affectStroke&&this._removeShadow(t),t.save(),this._setLineDash(t,this.strokeDashArray),t.beginPath(),this._renderTextCommon(t,"strokeText"),t.closePath(),t.restore())}_renderChars(t,e,i,s,n,r){const o=this.getHeightOfLine(r),a=this.textAlign.includes(rt),h=this.path,l="ltr"===this.direction,c="ltr"===this.direction?1:-1,d=e.direction,u=this.__charBounds[r];this.enableAdvancedLayout&&(null==u?void 0:u.length)>0&&u[0].renderLeft;const g=!a&&0===this.charSpacing&&this.isEmptyStyles(r)&&!h;let f,p,y="",x,_=0,C,b;if(e.save(),d!==this.direction&&(e.canvas.setAttribute("dir",l?"ltr":"rtl"),e.direction=l?"ltr":"rtl",e.textAlign=l?m:v),n-=o*this._fontSizeFraction/this.lineHeight,g)return this._renderChar(t,e,r,0,i.join(""),s,n),void e.restore();if(a&&0===r&&"fillText"===t){const t=this.__charBounds[r];null==t||t.reduce((t,e)=>t+((null==e?void 0:e.kernedWidth)||0),0);const e=undefined;[3,9,15,23,31].forEach(e=>{var i;const s=null==t?void 0:t[e];s&&console.log(` Space at idx ${e}: kernedWidth=${null===(i=s.kernedWidth)||void 0===i?void 0:i.toFixed(2)}`)})}for(let o=0,d=i.length-1;o<=d;o++)C=o===d||this.charSpacing||h,y+=i[o],x=this.__charBounds[r][o],0===_&&l?(s+=c*(x.kernedWidth-x.width),_+=x.width):_+=x.kernedWidth,a&&!C&&this._reSpaceAndTab.test(i[o])&&(C=!0),C||(f=f||this.getCompleteStyleDeclaration(r,o),p=this.getCompleteStyleDeclaration(r,o+1),C=hasStyleChanged(f,p,!1)),C&&(h?(e.save(),e.translate(x.renderLeft,x.renderTop),e.rotate(x.angle),this._renderChar(t,e,r,o,y,-_/2,0),e.restore()):(b=s,this._renderChar(t,e,r,o,y,b,n)),y="",f=p,s+=c*_,_=0);e.restore()}_applyPatternGradientTransformText(t){const e=this.width+this.strokeWidth,i=this.height+this.strokeWidth,s=createCanvasElementFor({width:e,height:i}),n=s.getContext("2d");return s.width=e,s.height=i,n.beginPath(),n.moveTo(0,0),n.lineTo(e,0),n.lineTo(e,i),n.lineTo(0,i),n.closePath(),n.translate(e/2,i/2),n.fillStyle=t.toLive(n),this._applyPatternGradientTransform(n,t),n.fill(),n.createPattern(s,"no-repeat")}handleFiller(t,e,i){let s,n;return isFiller(i)?"percentage"===i.gradientUnits||i.gradientTransform||i.patternTransform?(s=-this.width/2,n=-this.height/2,t.translate(s,n),t[e]=this._applyPatternGradientTransformText(i),{offsetX:s,offsetY:n}):(t[e]=i.toLive(t),this._applyPatternGradientTransform(t,i)):(t[e]=i,{offsetX:0,offsetY:0})}_setStrokeStyles(t,e){let{stroke:i,strokeWidth:s}=e;return t.lineWidth=s,t.lineCap=this.strokeLineCap,t.lineDashOffset=this.strokeDashOffset,t.lineJoin=this.strokeLineJoin,t.miterLimit=this.strokeMiterLimit,this.handleFiller(t,"strokeStyle",i)}_setFillStyles(t,e){let{fill:i}=e;return this.handleFiller(t,"fillStyle",i)}_renderChar(t,e,i,s,n,r,o){const a=this._getStyleDeclaration(i,s),h=this.getCompleteStyleDeclaration(i,s),l="fillText"===t&&h.fill,c="strokeText"===t&&h.stroke&&h.strokeWidth;if(c||l){if(e.save(),e.font=this._getFontDeclaration(h),a.textBackgroundColor&&this._removeShadow(e),a.deltaY&&(o+=a.deltaY),l){const t=this._setFillStyles(e,h);e.fillText(n,r-t.offsetX,o-t.offsetY)}if(c){const t=this._setStrokeStyles(e,h);e.strokeText(n,r-t.offsetX,o-t.offsetY)}e.restore()}}setSuperscript(t,e){this._setScript(t,e,this.superscript)}setSubscript(t,e){this._setScript(t,e,this.subscript)}_setScript(t,e,i){const s=this.get2DCursorLocation(t,!0),n=this.getValueOfPropertyAt(s.lineIndex,s.charIndex,"fontSize"),r=this.getValueOfPropertyAt(s.lineIndex,s.charIndex,"deltaY"),o={fontSize:n*i.size,deltaY:r+n*i.baseline};this.setSelectionStyles(o,t,e)}_getLineLeftOffset(t){const e=this.getLineWidth(t),i=this.width-e,s=this.textAlign,n=this.direction,r=this.isEndOfWrapping(t),o=undefined,a=!this._textLines.slice(t+1).some(t=>{const e=Array.isArray(t)?t.join(""):t;return/\S/.test(e)});let h=0;const l=undefined;return s===rt||s===ht&&!r&&!a||s===at&&!r&&!a||s===ot&&!r&&!a?0:(s===p||s===ht?h=i/2:s!==v&&s!==at||(h=i),"rtl"===n&&(s===v||s===rt||s===at?h=0:s===m||s===ot?h=-i:s!==p&&s!==ht||(h=-i/2),i<=0&&(h=0)),h)}_clearCache(){this._forceClearCache=!1,this.__lineWidths=[],this.__lineHeights=[],this.__charBounds=[],this.__kashidaInfo=[],this._justifyApplied=!1,this._lastDimensionState=null}_displayToOriginalIndex(t,e){var i;const s=null===(i=this.__kashidaInfo)||void 0===i?void 0:i[t];if(!s||0===s.length)return e;const n=[...s].sort((t,e)=>t.charIndex-e.charIndex);let r=0;for(const t of n){const i=t.tatweelCount||0,s=t.charIndex+1+r,n=s+i;if(e<s)break;if(e<n)return t.charIndex+1;r+=i}const o=undefined;return e-r}_originalToDisplayIndex(t,e){var i;const s=null===(i=this.__kashidaInfo)||void 0===i?void 0:i[t];if(!s||0===s.length)return e;const n=[...s].sort((t,e)=>t.charIndex-e.charIndex);let r=0;for(const t of n){const i=t.tatweelCount||0;if(!(e>t.charIndex))break;r+=i}return e+r}_isTatweelAtDisplayIndex(t,e){var i;const s=null===(i=this.__kashidaInfo)||void 0===i?void 0:i[t];if(!s||0===s.length)return!1;const n=[...s].sort((t,e)=>t.charIndex-e.charIndex);let r=0;for(const t of n){const i=t.tatweelCount||0,s=t.charIndex+1+r,n=undefined;if(e>=s&&e<s+i)return!0;r+=i}return!1}_getTatweelCountForLine(t){var e;const i=null===(e=this.__kashidaInfo)||void 0===e?void 0:e[t];return i&&0!==i.length?i.reduce((t,e)=>t+(e.tatweelCount||0),0):0}_getOriginalLineLength(t){var e;const i=undefined;return((null===(e=this._textLines[t])||void 0===e?void 0:e.length)||0)-this._getTatweelCountForLine(t)}getLineWidth(t){if(void 0!==this.__lineWidths[t])return this.__lineWidths[t];const{width:e}=this.measureLine(t);return this.__lineWidths[t]=e,e}_getWidthOfCharSpacing(){return 0!==this.charSpacing?this.fontSize*this.charSpacing/1e3:0}getValueOfPropertyAt(t,e,i){var s;const n=undefined;return null!==(s=this._getStyleDeclaration(t,e)[i])&&void 0!==s?s:this[i]}_renderTextDecoration(t,e){if(!this[e]&&!this.styleHas(e))return;let i=this._getTopOffset();const s=this._getLeftOffset(),n=this.path,r=this._getWidthOfCharSpacing(),o="linethrough"===e?.5:"overline"===e?1:0,a=this.offsets[e];for(let h=0,l=this._textLines.length;h<l;h++){const l=this.getHeightOfLine(h);if(!this[e]&&!this.styleHas(e,h)){i+=l;continue}const c=this._textLines[h],d=l/this.lineHeight,u=this._getLineLeftOffset(h);let g=0,f=0,p=this.getValueOfPropertyAt(h,0,e),m=this.getValueOfPropertyAt(h,0,I),y=this.getValueOfPropertyAt(h,0,Z),x=p,v=m,_=y;const C=i+d*(1-this._fontSizeFraction);let b=this.getHeightOfChar(h,0),S=this.getValueOfPropertyAt(h,0,"deltaY");for(let i=0,r=c.length;i<r;i++){const r=this.__charBounds[h][i];x=this.getValueOfPropertyAt(h,i,e),v=this.getValueOfPropertyAt(h,i,I),_=this.getValueOfPropertyAt(h,i,Z);const l=this.getHeightOfChar(h,i),c=this.getValueOfPropertyAt(h,i,"deltaY");if(n&&x&&v){const e=this.fontSize*_/1e3;t.save(),t.fillStyle=m,t.translate(r.renderLeft,r.renderTop),t.rotate(r.angle),t.fillRect(-r.kernedWidth/2,a*l+c-o*e,r.kernedWidth,e),t.restore()}else if((x!==p||v!==m||l!==b||_!==y||c!==S)&&f>0){const e=this.fontSize*y/1e3;let i=s+u+g;"rtl"===this.direction&&(i=this.width-i-f),p&&m&&y&&(t.fillStyle=m,t.fillRect(i,C+a*b+S-o*e,f,e)),g=r.left,f=r.width,p=x,y=_,m=v,b=l,S=c}else f+=r.kernedWidth}let w=s+u+g;"rtl"===this.direction&&(w=this.width-w-f),t.fillStyle=v;const T=this.fontSize*_/1e3;x&&v&&_&&t.fillRect(w,C+a*b+S-o*T,f-r,T),i+=l}this._removeShadow(t)}_getFontDeclaration(){let{fontFamily:t=this.fontFamily,fontStyle:e=this.fontStyle,fontWeight:i=this.fontWeight,fontSize:s=this.fontSize}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments.length>1?arguments[1]:void 0,r=t.includes("'")||t.includes('"')||t.includes(",")||FabricText.genericFonts.includes(t.toLowerCase())?t:`"${t}"`;return n||t.includes(",")||!(t.toLowerCase().includes("stv")||t.toLowerCase().includes("arabic")||t.toLowerCase().includes("naskh")||t.toLowerCase().includes("kufi"))||(r=`${r}, "Arial Unicode MS", Arial, sans-serif`),[e,i,`${n?this.CACHE_FONT_SIZE:s}px`,r].join(" ")}render(t){this.visible&&(this.canvas&&this.canvas.skipOffscreen&&!this.group&&!this.isOnScreen()||(this._forceClearCache&&this.initDimensions(),super.render(t)))}graphemeSplit(t){return graphemeSplit(t)}_splitTextIntoLines(t){const e=t.split(this._reNewline),i=new Array(e.length),s=["\n"];let n=[];for(let t=0;t<e.length;t++)"rtl"===this.direction||this._containsArabicText(e[t])?i[t]=segmentGraphemes(e[t]):i[t]=this.graphemeSplit(e[t]),n=n.concat(i[t],s);return n.pop(),{_unwrappedLines:i,lines:e,graphemeText:n,graphemeLines:i}}_containsArabicText(t){return/[\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(t)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject([...it,...t]),styles:stylesToArray(this.styles,this.text),...this.path?{path:this.path.toObject()}:{}}}set(t,e){const{textLayoutProperties:i}=this.constructor;super.set(t,e);let s=!1,n=!1;if("object"==typeof t)for(const e in t)"path"===e&&this.setPathInfo(),s=s||i.includes(e),n=n||"path"===e;else s=i.includes(t),n="path"===t;return n&&this.setPathInfo(),s&&this.initialized&&(clearBrowserLines(this),this.initDimensions(),this.setCoords()),this}complexity(){return 1}static async fromElement(t,e,i){const s=parseAttributes(t,FabricText.ATTRIBUTE_NAMES,i),{textAnchor:n=m,textDecoration:r="",dx:o=0,dy:a=0,top:h=0,left:l=0,fontSize:c=u,strokeWidth:d=1,...g}={...e,...s},f=undefined,y=new this((t.textContent||"").replace(/^\s+|\s+$|\n+/g,"").replace(/\s+/g," "),{left:l+o,top:h+a,underline:r.includes("underline"),overline:r.includes("overline"),linethrough:r.includes("line-through"),strokeWidth:0,fontSize:c,...g}),x=y.getScaledHeight()/y.height,_=undefined,C=((y.height+y.strokeWidth)*y.lineHeight-y.height)*x,b=y.getScaledHeight()+C;let S=0;return n===p&&(S=y.getScaledWidth()/2),n===v&&(S=y.getScaledWidth()),y.set({left:y.left-S,top:y.top-(b-y.fontSize*(.07+y._fontSizeFraction))/y.lineHeight,strokeWidth:d}),y}_isFontReady(){if("undefined"==typeof document||!("fonts"in document))return!0;try{return document.fonts.check(`${this.fontSize}px ${this.fontFamily}`)}catch(t){return!0}}_scheduleInitAfterFontLoad(){if("undefined"==typeof document||!("fonts"in document))return;if(this._fontLoadScheduled)return;this._fontLoadScheduled=!0;const t=`${this.fontSize}px ${this.fontFamily}`;document.fonts.load(t).then(()=>{var t;(this._fontLoadScheduled=!1,this.initDimensions(),this.textAlign&&this.textAlign.includes(rt))?setTimeout(()=>{var t;this.enlargeSpaces&&this.enlargeSpaces(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()},10):null===(t=this.canvas)||void 0===t||t.requestRenderAll()}).catch(()=>{this._fontLoadScheduled=!1})}forceTextReinitialization(){this._clearCache(),this.dirty=!0,this._splitText(),this.initDimensions(),this.textAlign&&this.textAlign.includes(rt)&&setTimeout(()=>{var t;this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces&&(this.enlargeSpaces(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())},10)}static fromObject(t){return this._fromObject({...t,styles:stylesFromArray(t.styles||{},t.text)},{extraParam:"text"}).then(t=>{t.initialized=!0,t._clearCache&&t._clearCache(),t.dirty=!0;const e=`${t.fontSize}px ${t.fontFamily}`;return"undefined"!=typeof document&&"fonts"in document&&"Arial"!==t.fontFamily&&"Times New Roman"!==t.fontFamily?document.fonts.load(e).then(()=>{var e;t.initialized=!0;const i=undefined;if(null===(e=t.fontFamily)||void 0===e?void 0:e.toLowerCase().includes("stv")){t._browserWrapCache=null,t._lastDimensionState=null,t._browserWrapInitialized=!1,t._usingBrowserWrapping=!0,t.useOverlayEditing=!0;const reinitWithDelay=e=>{t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions(),t.width<50&&e<3&&setTimeout(()=>reinitWithDelay(e+1),100*e)};reinitWithDelay(0)}else t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions();return t}).catch(()=>(t.initialized=!0,t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions(),t)):(t.initialized=!0,t.forceTextReinitialization?t.forceTextReinitialization():t.initDimensions(),t)})}}_defineProperty(FabricText,"textLayoutProperties",et),_defineProperty(FabricText,"cacheProperties",[...Ot,...it]),_defineProperty(FabricText,"ownDefaults",nt),_defineProperty(FabricText,"type","Text"),_defineProperty(FabricText,"genericFonts",["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong"]),_defineProperty(FabricText,"ATTRIBUTE_NAMES",se.concat("x","y","dx","dy","font-family","font-style","font-weight","font-size","letter-spacing","text-decoration","text-anchor")),applyMixins(FabricText,[TextSVGExportMixin]),X.setClass(FabricText),X.setSVGClass(FabricText);class DraggableTextDelegate{constructor(t){_defineProperty(this,"target",void 0),_defineProperty(this,"__mouseDownInPlace",!1),_defineProperty(this,"__dragStartFired",!1),_defineProperty(this,"__isDraggingOver",!1),_defineProperty(this,"__dragStartSelection",void 0),_defineProperty(this,"__dragImageDisposer",void 0),_defineProperty(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(t=>t()),this._dispose=void 0}}isPointerOverSelection(t){const e=this.target,i=e.getSelectionStartFromPointer(t);return e.isEditing&&i>=e.selectionStart&&i<=e.selectionEnd&&e.selectionStart<e.selectionEnd}start(t){return this.__mouseDownInPlace=this.isPointerOverSelection(t)}isActive(){return this.__mouseDownInPlace}end(t){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 i;let{selectionStart:s,selectionEnd:n}=e;const r=this.target,o=r.canvas,a=new Point(r.flipX?-1:1,r.flipY?-1:1),h=r._getCursorBoundaries(s),l=undefined,c=new Point(h.left+h.leftOffset,h.top+h.topOffset).multiply(a).transform(r.calcTransformMatrix()),d=undefined,u=o.getScenePoint(t).subtract(c),g=r.getCanvasRetinaScaling(),f=r.getBoundingRect(),p=c.subtract(new Point(f.left,f.top)),m=o.viewportTransform,y=p.add(u).transform(m,!0),x=r.backgroundColor,v=cloneStyles(r.styles);r.backgroundColor="";const C={stroke:"transparent",fill:"transparent",textBackgroundColor:"transparent"};r.setSelectionStyles(C,0,s),r.setSelectionStyles(C,n,r.text.length),r.dirty=!0;const b=r.toCanvasElement({enableRetinaScaling:o.enableRetinaScaling,viewportTransform:!0});r.backgroundColor=x,r.styles=v,r.dirty=!0,setStyle(b,{position:"fixed",left:-b.width+"px",border:_,width:b.width/g+"px",height:b.height/g+"px"}),this.__dragImageDisposer&&this.__dragImageDisposer(),this.__dragImageDisposer=()=>{b.remove()},getDocumentFromElement(t.target||this.target.hiddenTextarea).body.appendChild(b),null===(i=t.dataTransfer)||void 0===i||i.setDragImage(b,y.x,y.y)}onDragStart(t){this.__dragStartFired=!0;const e=this.target,i=this.isActive();if(i&&t.dataTransfer){const i=this.__dragStartSelection={selectionStart:e.selectionStart,selectionEnd:e.selectionEnd},s=e._text.slice(i.selectionStart,i.selectionEnd).join(""),n={text:e.text,value:s,...i};t.dataTransfer.setData("text/plain",s),t.dataTransfer.setData("application/fabric",JSON.stringify({value:s,styles:e.getSelectionStyles(i.selectionStart,i.selectionEnd,!0)})),t.dataTransfer.effectAllowed="copyMove",this.setDragImage(t,n)}return e.abortCursorAnimation(),i}canDrop(t){if(this.target.editable&&!this.target.getActiveControl()&&!t.defaultPrevented){if(this.isActive()&&this.__dragStartSelection){const e=this.target.getSelectionStartFromPointer(t),i=this.__dragStartSelection;return e<i.selectionStart||e>i.selectionEnd}return!0}return!1}targetCanDrop(t){return this.target.canDrop(t)}dragEnterHandler(t){let{e:e}=t;const i=this.targetCanDrop(e);!this.__isDraggingOver&&i&&(this.__isDraggingOver=!0)}dragOverHandler(t){const{e:e}=t,i=this.targetCanDrop(e);!this.__isDraggingOver&&i?this.__isDraggingOver=!0:this.__isDraggingOver&&!i&&(this.__isDraggingOver=!1),this.__isDraggingOver&&(e.preventDefault(),t.canDrop=!0,t.dropTarget=this.target)}dragLeaveHandler(){(this.__isDraggingOver||this.isActive())&&(this.__isDraggingOver=!1)}dropHandler(t){var e;const{e:i}=t,s=i.defaultPrevented;this.__isDraggingOver=!1,i.preventDefault();let n=null===(e=i.dataTransfer)||void 0===e?void 0:e.getData("text/plain");if(n&&!s){const e=this.target,s=e.canvas;let r=e.getSelectionStartFromPointer(i);const{styles:o}=i.dataTransfer.types.includes("application/fabric")?JSON.parse(i.dataTransfer.getData("application/fabric")):{},a=n[Math.max(0,n.length-1)],h=0;if(this.__dragStartSelection){const t=this.__dragStartSelection.selectionStart,i=this.__dragStartSelection.selectionEnd;r>t&&r<=i?r=t:r>i&&(r-=i-t),e.removeChars(t,i),delete this.__dragStartSelection}e._reNewline.test(a)&&(e._reNewline.test(e._text[r])||r===e._text.length)&&(n=n.trimEnd()),t.didDrop=!0,t.dropTarget=e,e.insertChars(n,o,r),s.setActiveObject(e),e.enterEditing(i),e.selectionStart=Math.min(r+h,e._text.length),e.selectionEnd=Math.min(e.selectionStart+n.length,e._text.length),e.hiddenTextarea.value=e.text,e._updateTextarea(),e.hiddenTextarea.focus(),e.fire(D,{index:r+h,action:"drop"}),s.fire("text:changed",{target:e}),s.contextTopDirty=!0,s.requestRenderAll()}}dragEndHandler(t){let{e:e}=t;if(this.isActive()&&this.__dragStartFired&&this.__dragStartSelection){var i;const t=this.target,s=this.target.canvas,{selectionStart:n,selectionEnd:r}=this.__dragStartSelection,o=(null===(i=e.dataTransfer)||void 0===i?void 0:i.dropEffect)||_;o===_?(t.selectionStart=n,t.selectionEnd=r,t._updateTextarea(),t.hiddenTextarea.focus()):(t.clearContextTop(),"move"===o&&(t.removeChars(n,r),t.selectionStart=t.selectionEnd=n,t.hiddenTextarea&&(t.hiddenTextarea.value=t.text),t._updateTextarea(),t.fire(D,{index:n,action:"dragend"}),s.fire("text:changed",{target:t}),s.requestRenderAll()),t.exitEditing())}this.__dragImageDisposer&&this.__dragImageDisposer(),delete this.__dragImageDisposer,delete this.__dragStartSelection,this.__isDraggingOver=!1}dispose(){this._dispose&&this._dispose()}}class OverlayEditor{constructor(t){_defineProperty(this,"canvas",void 0),_defineProperty(this,"target",void 0),_defineProperty(this,"container",void 0),_defineProperty(this,"textarea",void 0),_defineProperty(this,"hostDiv",void 0),_defineProperty(this,"isDestroyed",!1),_defineProperty(this,"isComposing",!1),_defineProperty(this,"lastText",void 0),_defineProperty(this,"onCommit",void 0),_defineProperty(this,"onCancel",void 0),_defineProperty(this,"boundHandlers",{onInput:this.handleInput.bind(this),onKeyDown:this.handleKeyDown.bind(this),onBlur:this.handleBlur.bind(this),onCompositionStart:this.handleCompositionStart.bind(this),onCompositionEnd:this.handleCompositionEnd.bind(this),onAfterRender:this.handleAfterRender.bind(this),onMouseWheel:this.handleMouseWheel.bind(this),onFocus:this.handleFocus.bind(this),onMouseDown:this.handleMouseDown.bind(this)}),this.canvas=t.canvas,this.target=t.target,this.onCommit=t.onCommit,this.onCancel=t.onCancel,this.lastText=this.target.text||"",this.container=this.getCanvasContainer(),this.createOverlayDOM(),this.attachEventListeners(),this.refresh(),this.focusTextarea()}getCanvasContainer(){const t=undefined,e=this.canvas.upperCanvasEl.parentElement;if(!e)throw new Error("Canvas must be mounted in DOM to use overlay editing");return e.style.position="relative",e}createOverlayDOM(){this.hostDiv=document.createElement("div"),this.hostDiv.style.position="absolute",this.hostDiv.style.pointerEvents="none",this.hostDiv.style.zIndex="1000",this.hostDiv.style.transformOrigin="left top",this.textarea=document.createElement("textarea"),this.textarea.style.position="absolute",this.textarea.style.left="0",this.textarea.style.top="0",this.textarea.style.margin="0",this.textarea.style.resize="none",this.textarea.style.pointerEvents="auto";const t=/[\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(this.target.text||""),e=/[a-zA-Z]/.test(this.target.text||""),i="ltr"===this.target.direction;this.textarea.style.unicodeBidi=t&&e&&i||t&&i?"embed":"plaintext",this.textarea.style.caretColor="auto",this.textarea.style.border="none",this.textarea.style.padding="0",this.textarea.style.background="transparent",this.textarea.style.outline="none",this.textarea.style.overflow="hidden",this.textarea.style.whiteSpace="pre-wrap",this.textarea.style.wordBreak="normal",this.textarea.style.overflowWrap="break-word",this.textarea.style.userSelect="text",this.textarea.style.textTransform="none",this.textarea.style.opacity="1",this.textarea.value=this.target.text||"",this.hostDiv.appendChild(this.textarea),document.body.appendChild(this.hostDiv)}attachEventListeners(){this.textarea.addEventListener("input",this.boundHandlers.onInput),this.textarea.addEventListener("keydown",this.boundHandlers.onKeyDown),this.textarea.addEventListener("blur",this.boundHandlers.onBlur),this.textarea.addEventListener("compositionstart",this.boundHandlers.onCompositionStart),this.textarea.addEventListener("compositionend",this.boundHandlers.onCompositionEnd),this.textarea.addEventListener("focus",this.boundHandlers.onFocus),this.canvas.on("after:render",this.boundHandlers.onAfterRender),this.canvas.on("mouse:wheel",this.boundHandlers.onMouseWheel),this.canvas.on("mouse:down",this.boundHandlers.onMouseDown),this.setupViewportChangeDetection()}removeEventListeners(){this.textarea.removeEventListener("input",this.boundHandlers.onInput),this.textarea.removeEventListener("keydown",this.boundHandlers.onKeyDown),this.textarea.removeEventListener("blur",this.boundHandlers.onBlur),this.textarea.removeEventListener("compositionstart",this.boundHandlers.onCompositionStart),this.textarea.removeEventListener("compositionend",this.boundHandlers.onCompositionEnd),this.textarea.removeEventListener("focus",this.boundHandlers.onFocus),this.canvas.off("after:render",this.boundHandlers.onAfterRender),this.canvas.off("mouse:wheel",this.boundHandlers.onMouseWheel),this.canvas.off("mouse:down",this.boundHandlers.onMouseDown),this.restoreViewportChangeDetection()}updatePosition(){this.applyOverlayStyle()}updateObjectBounds(){if(this.isDestroyed)return;const t=this.target,e=this.canvas.getZoom();parseFloat(this.hostDiv.style.width);const i=parseFloat(this.hostDiv.style.height)/e,s=undefined,n=undefined;Math.abs(i-t.height)>.5&&(t.height,t.height=i,t.setCoords(),t.dirty=!0,this.canvas.requestRenderAll(),requestAnimationFrame(()=>{this.isDestroyed||this.applyOverlayStyle()}))}letterSpacingPx(t,e){return t/1e3*e}firstStrongDir(t){const e=undefined;return/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(t)?"rtl":"ltr"}applyOverlayStyle(){var t,e;const i=this.target,s=this.canvas;i.setCoords();const n=i.aCoords,r=undefined,o=s.upperCanvasEl.getBoundingClientRect(),a=window.scrollX||window.pageXOffset,h=window.scrollY||window.pageYOffset,l=s.getZoom(),c=s.viewportTransform,d=i.padding||0,u=d*(i.scaleX||1)*l,g=d*(i.scaleY||1)*l,f=transformPoint({x:n.tl.x,y:n.tl.y},c),p=o.left+a+f.x,m=o.top+h+f.y,y=i.getBoundingRect(),x=Math.round(y.width*l),v=Math.round(y.height*l);this.hostDiv.style.position="absolute",this.hostDiv.style.left=`${p}px`,this.hostDiv.style.top=`${m}px`,this.hostDiv.style.width=`${x}px`,this.hostDiv.style.height=`${v}px`,this.hostDiv.style.overflow="hidden",i.angle?(this.hostDiv.style.transform=`rotate(${i.angle}deg)`,this.hostDiv.style.transformOrigin="top left"):(this.hostDiv.style.transform="",this.hostDiv.style.transformOrigin="");const _=undefined,C=undefined,b=(null!==(t=i.fontSize)&&void 0!==t?t:16)*(i.scaleX||1)*l,S=i.lineHeight||1.16;this.textarea.style.boxSizing="border-box",this.textarea.style.width=`${x}px`,this.textarea.style.height="100%",this.textarea.style.padding=`${g}px ${u}px`;const w=(i.charSpacing||0)/1e3*b;!1!==i.dirty&&i.initDimensions&&i.initDimensions(),this.textarea.style.fontSize=`${b}px`,this.textarea.style.lineHeight=String(S),this.textarea.style.fontFamily=i.fontFamily||"Arial",this.textarea.style.fontWeight=String(i.fontWeight||"normal"),this.textarea.style.fontStyle=i.fontStyle||"normal";const T=i.textAlign||"left";let P=T;const M=this.firstStrongDir(this.textarea.value||"");if(T.includes("justify"))try{P="justify","justify"===T||"justify-left"===T?this.textarea.style.textAlignLast="rtl"===M?"right":"left":"justify-right"===T?this.textarea.style.textAlignLast="ltr"===M?"left":"right":"justify-center"===T&&(this.textarea.style.textAlignLast="center"),this.textarea.style.textJustify="inter-word",this.textarea.style.wordSpacing="normal",this.textarea.style.textAlign="justify",this.textarea.style.textAlignLast=this.textarea.style.textAlignLast,this.textarea.style.textJustifyTrim="none",this.textarea.style.textAutospace="none"}catch(t){P=T.replace("justify-","").replace("justify","left")}else this.textarea.style.textAlignLast="auto",this.textarea.style.textJustify="auto",this.textarea.style.wordSpacing="normal";this.textarea.style.textAlign=P,this.textarea.style.color=(null===(e=i.fill)||void 0===e?void 0:e.toString())||"#000",this.textarea.style.letterSpacing=`${w}px`;const O=i.direction;this.textarea.style.direction=M||O||"ltr",this.textarea.style.fontVariant="normal",this.textarea.style.fontStretch="normal",this.textarea.style.textRendering="auto",this.textarea.style.fontKerning="normal",this.textarea.style.fontFeatureSettings="normal",this.textarea.style.fontVariationSettings="normal",this.textarea.style.margin="0",this.textarea.style.border="none",this.textarea.style.outline="none",this.textarea.style.background="transparent",this.textarea.style.overflowWrap="break-word",this.textarea.style.whiteSpace="pre-wrap",this.textarea.style.hyphens="none",T.includes("justify"),this.textarea.style.webkitFontSmoothing="auto",this.textarea.style.mozOsxFontSmoothing="auto",this.textarea.style.fontSmooth="auto",this.textarea.style.textSizeAdjust="none";const k=String(i.fontWeight||"normal"),D=undefined;("bold"===k||"700"===k||parseInt(k)>=600)&&(this.textarea.style.webkitFontSmoothing="subpixel-antialiased",this.textarea.style.mozOsxFontSmoothing="unset")}debugBoundingBoxComparison(){const t=this.target,e=this.canvas,i=e.getZoom(),s=this.textarea.getBoundingClientRect(),n=this.hostDiv.getBoundingClientRect(),r=t.getBoundingRect(),o=e.upperCanvasEl.getBoundingClientRect(),a=e.viewportTransform,h=o.left+r.left*i+a[4],l=o.top+r.top*i+a[5],c=r.width*i,d=r.height*i;Math.round(100*(n.left-h)),Math.round(100*(n.top-l)),Math.round(100*(n.width-c)),Math.round(100*(n.height-d)),Math.round(100*(s.left-h)),Math.round(100*(s.top-l)),Math.round(100*(s.width-c)),Math.round(100*(s.height-d))}debugTextWrapping(){this.target;const t=undefined,e=this.textarea.value.split("\n");e.forEach((t,e)=>{});const i=window.getComputedStyle(this.textarea);this.target.getBoundingRect().width;const s=parseFloat(window.getComputedStyle(this.textarea).width);this.canvas.getZoom();const n=this.textarea.scrollHeight,r=parseFloat(i.lineHeight)||1.2*parseFloat(i.fontSize),o=Math.round(n/r);e.length}focusTextarea(){this.target.opacity=.01,this.target.selected=!0,this.target.isEditing=!1,this.target.set({hasControls:!0,hasBorders:!0,selectable:!0,lockMovementX:!1,lockMovementY:!1}),this.canvas.setActiveObject(this.target),this.canvas.requestRenderAll(),this.target.setCoords(),this.applyOverlayStyle(),this.target._fixCharacterMappingAfterJsonLoad&&this.target._fixCharacterMappingAfterJsonLoad(),this.textarea.focus(),this.textarea.setSelectionRange(this.textarea.value.length,this.textarea.value.length),this.canvas.setActiveObject(this.target),this.canvas.requestRenderAll()}refresh(){this.isDestroyed||this.updatePosition()}destroy(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(!this.isDestroyed){if(this.isDestroyed=!0,this.removeEventListeners(),this.target.__overlayEditor===this&&(this.target.__overlayEditor=void 0,void 0!==this.target.__overlayOriginalOpacity&&(this.target.opacity=this.target.__overlayOriginalOpacity,delete this.target.__overlayOriginalOpacity)),this.hostDiv.parentNode&&this.hostDiv.parentNode.removeChild(this.hostDiv),t&&!this.isComposing){const t=this.textarea.value,e=this.firstStrongDir(t),i=this.target.direction||"ltr",s=undefined;!("inherit"!==i)&&e&&e!==i&&(this.target.set("direction",e),this.canvas.requestRenderAll()),this.onCommit&&this.onCommit(t)}else!t&&this.onCancel&&this.onCancel();setTimeout(()=>{this.canvas.upperCanvasEl.style.cursor="",this.canvas.setCursor(this.canvas.defaultCursor)},0),this.canvas.requestRenderAll()}}handleInput(){this.isComposing||this.target.text===this.textarea.value||(this.target.text=this.textarea.value,this.autoResizeTextarea(),this.target.selected=!0,this.target.isEditing=!1,this.canvas.setActiveObject(this.target),this.canvas.requestRenderAll())}autoResizeTextarea(){const t=this.textarea.scrollTop,e=parseFloat(this.hostDiv.style.height||"0");this.textarea.style.height="1px";const i=undefined,s=2,n=this.textarea.scrollHeight+2,r=undefined;Math.abs(n-e)>1?(this.textarea.style.height=`${n}px`,this.hostDiv.style.height=`${n}px`,this.updateObjectBounds()):this.textarea.style.height=this.hostDiv.style.height,this.textarea.scrollTop=t}handleKeyDown(t){"Escape"===t.key?(t.preventDefault(),this.destroy(!1)):(t.ctrlKey||t.metaKey)&&"Enter"===t.key?(t.preventDefault(),this.destroy(!0)):"Enter"!==t.key&&"Backspace"!==t.key&&"Delete"!==t.key||(requestAnimationFrame(()=>{this.isDestroyed||this.autoResizeTextarea()}),setTimeout(()=>{this.isDestroyed||this.autoResizeTextarea()},10))}handleFocus(){}handleBlur(){this.isComposing||this.destroy(!0)}handleCompositionStart(){this.isComposing=!0}handleCompositionEnd(){this.isComposing=!1,this.handleInput()}handleAfterRender(){this.refresh()}handleMouseWheel(){this.refresh()}handleMouseDown(t){t.target!==this.target&&this.destroy(!0)}setupViewportChangeDetection(){this.canvas.__originalSetZoom=this.canvas.setZoom,this.canvas.__originalSetViewportTransform=this.canvas.setViewportTransform,this.canvas.__overlayEditor=this;const t=this.canvas.setZoom.bind(this.canvas);this.canvas.setZoom=e=>{const i=t(e);return this.canvas.__overlayEditor&&!this.isDestroyed&&this.refresh(),i};const e=this.canvas.setViewportTransform.bind(this.canvas);this.canvas.setViewportTransform=t=>{const i=e(t);return this.canvas.__overlayEditor&&!this.isDestroyed&&this.refresh(),i}}restoreViewportChangeDetection(){this.canvas.__originalSetZoom&&(this.canvas.setZoom=this.canvas.__originalSetZoom,delete this.canvas.__originalSetZoom),this.canvas.__originalSetViewportTransform&&(this.canvas.setViewportTransform=this.canvas.__originalSetViewportTransform,delete this.canvas.__originalSetViewportTransform),delete this.canvas.__overlayEditor}}function enterTextOverlayEdit(t,e,i){e.__overlayEditor&&e.__overlayEditor.destroy(!1),e.__overlayOriginalOpacity=e.opacity;const s=new OverlayEditor({canvas:t,target:e,onCommit:null==i?void 0:i.onCommit,onCancel:null==i?void 0:i.onCancel});return e.__overlayEditor=s,s}const fi=/[ \n\.,;!\?\-\u060C\u061B\u061F\u06D4\u0640\u05C3\u05F4\u2000-\u206F]/;class ITextBehavior extends FabricText{constructor(){super(...arguments),_defineProperty(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:i,delay:s,onComplete:n}=t;return animate({startValue:this._currentCursorOpacity,endValue:e,duration:i,delay:s,onComplete:n,abort:()=>!this.canvas||this.selectionStart!==this.selectionEnd,onChange:t=>{this._currentCursorOpacity=t,this.renderCursorOrSelection()}})}_tick(t){this._currentTickState=this._animateCursor({toValue:0,duration:this.cursorDuration/2,delay:Math.max(t||0,100),onComplete:this._onTickComplete})}_onTickComplete(){var t;null===(t=this._currentTickCompleteState)||void 0===t||t.abort(),this._currentTickCompleteState=this._animateCursor({toValue:1,duration:this.cursorDuration,onComplete:this._tick})}initDelayedCursor(t){this.abortCursorAnimation(),this._tick(t?0:this.cursorDelay)}abortCursorAnimation(){let t=!1;[this._currentTickState,this._currentTickCompleteState].forEach(e=>{e&&!e.isDone()&&(t=!0,e.abort())}),this._currentCursorOpacity=1,t&&this.clearContextTop()}restartCursorIfNeeded(){[this._currentTickState,this._currentTickCompleteState].some(t=>!t||t.isDone())&&this.initDelayedCursor()}selectAll(){return this.selectionStart=0,this.selectionEnd=this._text.length,this._fireSelectionChanged(),this._updateTextarea(),this}cmdAll(){this.selectAll(),this.renderCursorOrSelection()}getSelectedText(){return this._text.slice(this.selectionStart,this.selectionEnd).join("")}findWordBoundaryLeft(t){let e=0,i=t-1;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i--;for(;/S/.test(this._text[i])&&i>-1;)e++,i--;return t-e}findWordBoundaryRight(t){let e=0,i=t;if(this._reSpace.test(this._text[i]))for(;this._reSpace.test(this._text[i]);)e++,i++;for(;/S/.test(this._text[i])&&i<this._text.length;)e++,i++;return t+e}findLineBoundaryLeft(t){let e=0,i=t-1;for(;!/\n/.test(this._text[i])&&i>-1;)e++,i--;return t-e}findLineBoundaryRight(t){let e=0,i=t;for(;!/\n/.test(this._text[i])&&i<this._text.length;)e++,i++;return t+e}searchWordBoundary(t,e){return"undefined"!=typeof Intl&&Intl.Segmenter?this._searchWordBoundaryWithSegmenter(t,e):this._searchWordBoundaryWithRegex(t,e)}_searchWordBoundaryWithSegmenter(t,e){const i=this.text,s=undefined,n=new(0,Intl.Segmenter)(void 0,{granularity:"word"}),r=Array.from(n.segment(i));if(0===r.length)return-1===e?0:i.length;let o=0;for(let e=0;e<r.length;e++){const i=r[e];if(t>=i.index&&t<i.index+i.segment.length){o=e;break}t>=i.index+i.segment.length&&(o=e)}if(-1===e){let e=o;for(t===r[e].index&&e>0&&e--;e>0&&!r[e].isWordLike;)e--;return r[e].isWordLike?r[e].index:0}{let t=o;if(r[t].isWordLike)return r[t].index+r[t].segment.length;for(;t<r.length&&!r[t].isWordLike;)t++;return t<r.length&&r[t].isWordLike?r[t].index+r[t].segment.length:i.length}}_searchWordBoundaryWithRegex(t,e){const i=Array.from(this.text);let s=t>0&&this._reSpace.test(i[t])&&(-1===e||!C.test(i[t-1]))?t-1:t,n=i[s];for(;s>0&&s<i.length&&!fi.test(n);)s+=e,n=i[s];return-1===e&&fi.test(n)&&s++,s}selectWord(t){t=null!=t?t:this.selectionStart;const e=this.searchWordBoundary(t,-1),i=Math.max(e,this.searchWordBoundary(t,1));this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection()}selectLine(t){t=null!=t?t:this.selectionStart;const e=this.findLineBoundaryLeft(t),i=this.findLineBoundaryRight(t);this.selectionStart=e,this.selectionEnd=i,this._fireSelectionChanged(),this._updateTextarea()}enterEditing(t){!this.isEditing&&this.editable&&(this.enterEditingImpl(),this.fire("editing:entered",t?{e:t}:void 0),this._fireSelectionChanged(),this.canvas&&(this.canvas.fire("text:editing:entered",{target:this,e:t}),this.canvas.requestRenderAll()))}enterEditingImpl(){this.canvas&&(this.canvas.calcOffset(),this.canvas.textEditingManager.exitTextEditing()),this.isEditing=!0,this.useOverlayEditing?this.enterOverlayEditing():(this.initHiddenTextarea(),this.hiddenTextarea.focus(),this.hiddenTextarea.value=this.text,this._updateTextarea(),this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this._tick())}enterOverlayEditing(){this._saveEditingProps(),this._setEditingProps(),this._textBeforeEdit=this.text,this.canvas&&enterTextOverlayEdit(this.canvas,this,{onCommit:t=>{this.commitOverlayEdit(t)},onCancel:()=>{this.cancelOverlayEdit()}})}commitOverlayEdit(t){const e=this.left,i=this.top,s=this.get("width"),n=this.dynamicMinWidth,r=this._usingBrowserWrapping,o=this.lockDynamicMinWidth;this.lockDynamicMinWidth=!0;const a=this.__overlayEditor;if(a)try{const t=undefined;storeBrowserLines(this,extractLinesFromDOM(a.textareaElement).lines)}catch(t){}this.text=t,void 0!==n&&(this.dynamicMinWidth=Math.max(n||0,s||0)),void 0!==r&&(this._usingBrowserWrapping=r),this.dirty=!0,this.initDimensions(),this.set({left:e,top:i,width:s}),this.setCoords(),this.exitEditing(),this.lockDynamicMinWidth=o,this.fire("changed"),this.canvas&&this.canvas.requestRenderAll()}cancelOverlayEdit(){this.text=this._textBeforeEdit||this.text,this.exitEditing()}updateSelectionOnMouseMove(t){if(this.getActiveControl())return;const e=this.hiddenTextarea;getDocumentFromElement(e).activeElement!==e&&e.focus();const i=this.getSelectionStartFromPointer(t),s=this.selectionStart,n=this.selectionEnd;if(!(i===this.__selectionStartOnMouseDown&&s!==n||s!==i&&n!==i))return;const r=Math.min(i,this.__selectionStartOnMouseDown),o=Math.max(i,this.__selectionStartOnMouseDown);this.selectionStart=r,this.selectionEnd=o,this.selectionStart===s&&this.selectionEnd===n||(this._fireSelectionChanged(),this._updateTextarea(),this.renderCursorOrSelection())}_setEditingProps(){this.hoverCursor="text",this.canvas&&(this.canvas.defaultCursor=this.canvas.moveCursor="text"),this.borderColor=this.editingBorderColor,this.hasControls=this.selectable=!1,this.lockMovementX=this.lockMovementY=!0}fromStringToGraphemeSelection(t,e,i){const s=i.slice(0,t),n=this.graphemeSplit(s).length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=i.slice(t,e),o=undefined;return{selectionStart:n,selectionEnd:n+this.graphemeSplit(r).length}}fromGraphemeToStringSelection(t,e,i){const s=undefined,n=i.slice(0,t).join("").length;if(t===e)return{selectionStart:n,selectionEnd:n};const r=undefined,o=undefined;return{selectionStart:n,selectionEnd:n+i.slice(t,e).join("").length}}_updateTextarea(){if(this.cursorOffsetCache={},!this.hiddenTextarea)return;const t=this.text;if(this.hiddenTextarea.value!==t&&(this.hiddenTextarea.value=t),!this.inCompositionMode){const t=this.fromGraphemeToStringSelection(this.selectionStart,this.selectionEnd,this._text);this.hiddenTextarea.selectionStart=t.selectionStart,this.hiddenTextarea.selectionEnd=t.selectionEnd}this.updateTextareaPosition()}updateFromTextArea(){if(!this.hiddenTextarea)return;this.cursorOffsetCache={};const t=this.hiddenTextarea;this.text=t.value,this.set("dirty",!0),this.initDimensions(),this.setCoords();const e=this.fromStringToGraphemeSelection(t.selectionStart,t.selectionEnd,t.value);this.selectionEnd=this.selectionStart=e.selectionEnd,this.inCompositionMode||(this.selectionStart=e.selectionStart),this.updateTextareaPosition()}updateTextareaPosition(){if(this.selectionStart===this.selectionEnd){const t=this._calcTextareaPosition();this.hiddenTextarea.style.left=t.left,this.hiddenTextarea.style.top=t.top}}_calcTextareaPosition(){if(!this.canvas)return{left:"1px",top:"1px"};const t=this.inCompositionMode?this.compositionStart:this.selectionStart,e=this._getCursorBoundaries(t),i=this.get2DCursorLocation(t),s=i.lineIndex,n=i.charIndex,r=this.getValueOfPropertyAt(s,n,"fontSize")*this.lineHeight,o=e.leftOffset,a=this.getCanvasRetinaScaling(),h=this.canvas.upperCanvasEl,l=h.width/a,c=h.height/a,d=l-r,u=c-r,g=new Point(e.left+o,e.top+e.topOffset+r).transform(this.calcTransformMatrix()).transform(this.canvas.viewportTransform).multiply(new Point(h.clientWidth/l,h.clientHeight/c));return g.x<0&&(g.x=0),g.x>d&&(g.x=d),g.y<0&&(g.y=0),g.y>u&&(g.y=u),g.x+=this.canvas._offset.left,g.y+=this.canvas._offset.top,{left:`${g.x}px`,top:`${g.y}px`,fontSize:`${r}px`,charHeight:r}}_saveEditingProps(){this._savedProps={hasControls:this.hasControls,borderColor:this.borderColor,lockMovementX:this.lockMovementX,lockMovementY:this.lockMovementY,hoverCursor:null,selectable:this.selectable,defaultCursor:"default",moveCursor:"move"}}_restoreEditingProps(){if(this._savedProps){var t,e;if(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=null!==(t=this._savedProps.defaultCursor)&&void 0!==t?t:"default",this.canvas.moveCursor=null!==(e=this._savedProps.moveCursor)&&void 0!==e?e:"move";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(R),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:i,charIndex:s}=this.get2DCursorLocation(t,!0),{lineIndex:n,charIndex:r}=this.get2DCursorLocation(e,!0);if(i!==n){if(this.styles[i])for(let t=s;t<this._unwrappedTextLines[i].length;t++)delete this.styles[i][t];if(this.styles[n])for(let t=r;t<this._unwrappedTextLines[n].length;t++){const e=this.styles[n][t];e&&(this.styles[i]||(this.styles[i]={}),this.styles[i][s+t-r]=e)}for(let t=i+1;t<=n;t++)delete this.styles[t];this.shiftLineStyles(n,i-n)}else if(this.styles[i]){const t=this.styles[i],e=r-s;for(let e=s;e<r;e++)delete t[e];for(const s in this.styles[i]){const i=parseInt(s,10);i>=r&&(t[i-e]=t[s],delete t[s])}}}shiftLineStyles(t,e){const i=Object.assign({},this.styles);for(const s in this.styles){const n=parseInt(s,10);n>t&&(this.styles[n+e]=i[n],i[n-e]||delete this.styles[n])}}insertNewlineStyleObject(t,e,i,s){const n={},r=this._unwrappedTextLines[t].length,o=r===e;let a=!1;i||(i=1),this.shiftLineStyles(t,i);const h=this.styles[t]?this.styles[t][0===e?e:e-1]:void 0;for(const i in this.styles[t]){const s=parseInt(i,10);s>=e&&(a=!0,n[s-e]=this.styles[t][i],o&&0===e||delete this.styles[t][i])}let l=!1;for(a&&!o&&(this.styles[t+i]=n,l=!0),(l||r>e)&&i--;i>0;)s&&s[i-1]?this.styles[t+i]={0:{...s[i-1]}}:h?this.styles[t+i]={0:{...h}}:delete this.styles[t+i],i--;this._forceClearCache=!0}insertCharStyleObject(t,e,i,s){this.styles||(this.styles={});const n=this.styles[t],r=n?{...n}:{};i||(i=1);for(const t in r){const s=parseInt(t,10);s>=e&&(n[s+i]=r[s],r[s-i]||delete n[s])}if(this._forceClearCache=!0,s){for(;i--;)Object.keys(s[i]).length&&(this.styles[t]||(this.styles[t]={}),this.styles[t][e+i]={...s[i]});return}if(!n)return;const o=n[e?e-1:1];for(;o&&i--;)this.styles[t][e+i]={...o}}insertNewStyleBlock(t,e,i){const s=this.get2DCursorLocation(e,!0),n=[0];let r=0,o;for(let e=0;e<t.length;e++)"\n"===t[e]?(r++,n[r]=0):n[r]++;for(n[0]>0&&(this.insertCharStyleObject(s.lineIndex,s.charIndex,n[0],i),i=i&&i.slice(n[0]+1)),r&&this.insertNewlineStyleObject(s.lineIndex,s.charIndex+n[0],r),o=1;o<r;o++)n[o]>0?this.insertCharStyleObject(s.lineIndex+o,0,n[o],i):i&&this.styles[s.lineIndex+o]&&i[0]&&(this.styles[s.lineIndex+o][0]=i[0]),i=i&&i.slice(n[o]+1);n[o]>0&&this.insertCharStyleObject(s.lineIndex+o,0,n[o],i)}removeChars(t){let e=arguments.length>1&&void 0!==arguments[1]?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,i){let s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:i;s>i&&this.removeStyleFromTo(i,s);const n=this.graphemeSplit(t);this.insertNewStyleBlock(n,i,e),this._text=[...this._text.slice(0,i),...n,...this._text.slice(s)],this.text=this._text.join(""),this.set("dirty",!0),this.initDimensions(),this.setCoords(),this._removeExtraneousStyles()}setSelectionStartEndWithShift(t,e,i){i<=t?(e===t?this._selectionDirection=m:this._selectionDirection===v&&(this._selectionDirection=m,this.selectionEnd=t),this.selectionStart=i):i>t&&i<e?this._selectionDirection===v?this.selectionEnd=i:this.selectionStart=i:(e===t?this._selectionDirection=v:this._selectionDirection===m&&(this._selectionDirection=v,this.selectionStart=e),this.selectionEnd=i)}}class ITextKeyBehavior extends ITextBehavior{initHiddenTextarea(){const t=this.canvas&&getDocumentFromElement(this.canvas.getElement())||getFabricDocument(),e=t.createElement("textarea");Object.entries({autocapitalize:"off",autocorrect:"off",autocomplete:"off",spellcheck:"false","data-fabric":"textarea",wrap:"off"}).map(t=>{let[i,s]=t;return e.setAttribute(i,s)});const{top:i,left:s,fontSize:n}=this._calcTextareaPosition();e.style.cssText=`position: absolute; top: ${i}; left: ${s}; z-index: -999; opacity: 0; width: 1px; height: 1px; font-size: 1px; padding-top: ${n};`,(this.hiddenTextareaContainer||t.body).appendChild(e),Object.entries({blur:"blur",keydown:"onKeyDown",keyup:"onKeyUp",input:"onInput",copy:"copy",cut:"copy",paste:"paste",compositionstart:"onCompositionStart",compositionupdate:"onCompositionUpdate",compositionend:"onCompositionEnd"}).map(t=>{let[i,s]=t;return e.addEventListener(i,this[s].bind(this))}),this.hiddenTextarea=e}blur(){this.abortCursorAnimation()}onKeyDown(t){if(!this.isEditing)return;const e="rtl"===this.direction?this.keysMapRtl:this.keysMap;if(t.keyCode in e)this[e[t.keyCode]](t);else{if(!(t.keyCode in this.ctrlKeysMapDown)||!t.ctrlKey&&!t.metaKey)return;this[this.ctrlKeysMapDown[t.keyCode]](t)}t.stopImmediatePropagation(),t.preventDefault(),t.keyCode>=33&&t.keyCode<=40?(this.inCompositionMode=!1,this.clearContextTop(),this.renderCursorOrSelection()):this.canvas&&this.canvas.requestRenderAll()}onKeyUp(t){!this.isEditing||this._copyDone||this.inCompositionMode?this._copyDone=!1:t.keyCode in this.ctrlKeysMapUp&&(t.ctrlKey||t.metaKey)&&(this[this.ctrlKeysMapUp[t.keyCode]](t),t.stopImmediatePropagation(),t.preventDefault(),this.canvas&&this.canvas.requestRenderAll())}onInput(t){const i=this.fromPaste,{value:s,selectionStart:n,selectionEnd:r}=this.hiddenTextarea;if(this.fromPaste=!1,t&&t.stopPropagation(),!this.isEditing)return;if(this.text!==s&&!this.inCompositionMode)return this.cursorOffsetCache={},this._browserWrapCache=null,this._lastDimensionState=null,this._forceClearCache=!0,this.updateFromTextArea(),this.fire(D),void(this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.renderAll()));const updateAndFire=()=>{this.updateFromTextArea(),this.fire(D),this.canvas&&(this.canvas.fire("text:changed",{target:this}),this.canvas.requestRenderAll())};if(""===this.hiddenTextarea.value)return this.styles={},void updateAndFire();const o=this._splitTextIntoLines(s).graphemeText,a=this._text.length,h=o.length,l=this.selectionStart,c=this.selectionEnd,d=l!==c;let u,g,f=h-a,p,m;const y=this.fromStringToGraphemeSelection(n,r,s),x=l>y.selectionStart;d?(g=this._text.slice(l,c),f+=c-l):h<a&&(g=x?this._text.slice(c+f,c):this._text.slice(l,l-f));const v=o.slice(y.selectionEnd-f,y.selectionEnd);if(g&&g.length&&(v.length&&(u=this.getSelectionStyles(l,l+1,!1),u=v.map(()=>u[0])),d?(p=l,m=c):x?(p=c-g.length,m=c):(p=c,m=c+g.length),this.removeStyleFromTo(p,m)),v.length){const{copyPasteData:t}=getEnv();i&&v.join("")===t.copiedText&&!e.disableStyleCopyPaste&&(u=t.copiedTextStyle),this.insertNewStyleBlock(v,l,u)}updateAndFire()}onCompositionStart(){this.inCompositionMode=!0}onCompositionEnd(){this.inCompositionMode=!1}onCompositionUpdate(t){let{target:e}=t;const{selectionStart:i,selectionEnd:s}=e;this.compositionStart=i,this.compositionEnd=s,this.updateTextareaPosition()}copy(){if(this.selectionStart===this.selectionEnd)return;const{copyPasteData:t}=getEnv();t.copiedText=this.getSelectedText(),e.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 i=this._getLineLeftOffset(t),s;return e>0&&(s=this.__charBounds[t][e-1],i+=s.left+s.width),i}getDownCursorOffset(t,e){const i=this._getSelectionForOffset(t,e),s=this.get2DCursorLocation(i),n=s.lineIndex;if(n===this._textLines.length-1||t.metaKey||34===t.keyCode)return this._text.length-i;const r=s.charIndex,o=this._getWidthBeforeCursor(n,r),a=this._getIndexOnLine(n+1,o),h=undefined;return this._textLines[n].slice(r).length+a+1+this.missingNewlineOffset(n)}_getSelectionForOffset(t,e){return t.shiftKey&&this.selectionStart!==this.selectionEnd&&e?this.selectionEnd:this.selectionStart}getUpCursorOffset(t,e){const i=this._getSelectionForOffset(t,e),s=this.get2DCursorLocation(i),n=s.lineIndex;if(0===n||t.metaKey||33===t.keyCode)return-i;const r=s.charIndex,o=this._getWidthBeforeCursor(n,r),a=this._getIndexOnLine(n-1,o),h=this._textLines[n].slice(0,r),l=this.missingNewlineOffset(n-1);return-this._textLines[n-1].length+a-h.length+(1-l)}_getIndexOnLine(t,e){const i=this._textLines[t],s=undefined;let n=this._getLineLeftOffset(t),r=0,o,a;for(let s=0,h=i.length;s<h;s++)if(o=this.__charBounds[t][s].width,n+=o,n>e){a=!0;const t=n-o,i=n,h=Math.abs(t-e),l=undefined;r=Math.abs(i-e)<h?s:s-1;break}return a||(r=i.length-1),r}moveCursorDown(t){this.selectionStart>=this._text.length&&this.selectionEnd>=this._text.length||this._moveCursorUpOrDown("Down",t)}moveCursorUp(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorUpOrDown("Up",t)}_moveCursorUpOrDown(t,e){const i=this[`get${t}CursorOffset`](e,this._selectionDirection===v);if(e.shiftKey?this.moveCursorWithShift(i):this.moveCursorWithoutShift(i),0!==i){const t=this.text.length;this.selectionStart=capValue(0,this.selectionStart,t),this.selectionEnd=capValue(0,this.selectionEnd,t),this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea()}}moveCursorWithShift(t){const e=this._selectionDirection===m?this.selectionStart+t:this.selectionEnd+t;return this.setSelectionStartEndWithShift(this.selectionStart,this.selectionEnd,e),0!==t}moveCursorWithoutShift(t){return t<0?(this.selectionStart+=t,this.selectionEnd=this.selectionStart):(this.selectionEnd+=t,this.selectionStart=this.selectionEnd),0!==t}moveCursorLeft(t){0===this.selectionStart&&0===this.selectionEnd||this._moveCursorLeftOrRight("Left",t)}_move(t,e,i){let s;if(t.altKey)s=this[`findWordBoundary${i}`](this[e]);else{if(!t.metaKey&&35!==t.keyCode&&36!==t.keyCode)return this[e]+="Left"===i?-1:1,!0;s=this[`findLineBoundary${i}`](this[e])}return void 0!==s&&this[e]!==s&&(this[e]=s,!0)}_moveLeft(t,e){return this._move(t,e,"Left")}_moveRight(t,e){return this._move(t,e,"Right")}moveCursorLeftWithoutShift(t){let e=!0;return this._selectionDirection=m,this.selectionEnd===this.selectionStart&&0!==this.selectionStart&&(e=this._moveLeft(t,"selectionStart")),this.selectionEnd=this.selectionStart,e}moveCursorLeftWithShift(t){return this._selectionDirection===v&&this.selectionStart!==this.selectionEnd?this._moveLeft(t,"selectionEnd"):0!==this.selectionStart?(this._selectionDirection=m,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 i=`moveCursor${t}${e.shiftKey?"WithShift":"WithoutShift"}`;this._currentCursorOpacity=1,this[i](e)&&(this.abortCursorAnimation(),this.initDelayedCursor(),this._fireSelectionChanged(),this._updateTextarea())}moveCursorRightWithShift(t){return this._selectionDirection===m&&this.selectionStart!==this.selectionEnd?this._moveRight(t,"selectionStart"):this.selectionEnd!==this._text.length?(this._selectionDirection=v,this._moveRight(t,"selectionEnd")):void 0}moveCursorRightWithoutShift(t){let e=!0;return this._selectionDirection=v,this.selectionStart===this.selectionEnd?(e=this._moveRight(t,"selectionStart"),this.selectionEnd=this.selectionStart):this.selectionStart=this.selectionEnd,e}}const notALeftClick=t=>!!t.button;class ITextClickBehavior extends ITextKeyBehavior{constructor(){super(...arguments),_defineProperty(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 DraggableTextDelegate(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.useOverlayEditing&&this.editable?this.enterEditing(t.e):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:e,alreadySelected:i}=t;this.canvas&&this.editable&&!notALeftClick(e)&&!this.getActiveControl()&&(this.draggableTextDelegate.start(e)||(this.canvas.textEditingManager.register(this),i&&(this.inCompositionMode=!1,this.setCursorByClick(e)),this.isEditing&&(this.__selectionStartOnMouseDown=this.selectionStart,this.selectionStart===this.selectionEnd&&this.abortCursorAnimation(),this.renderCursorOrSelection()),this.selected||(this.selected=i||this.isEditing)))}mouseUpHandler(t){let{e:e,transform:i}=t;const s=this.draggableTextDelegate.end(e);if(this.canvas){this.canvas.textEditingManager.unregister(this);const t=this.canvas._activeObject;if(t&&t!==this)return}!this.editable||this.group&&!this.group.interactive||i&&i.actionPerformed||notALeftClick(e)||s||this.selected&&!this.getActiveControl()&&(this.enterEditing(e),this.selectionStart===this.selectionEnd?this.initDelayedCursor(!0):this.renderCursorOrSelection())}setCursorByClick(t){const e=this.getSelectionStartFromPointer(t),i=this.selectionStart,s=this.selectionEnd;t.shiftKey?this.setSelectionStartEndWithShift(i,s,e):(this.selectionStart=e,this.selectionEnd=e),this.isEditing&&(this._fireSelectionChanged(),this._updateTextarea())}getSelectionStartFromPointer(t){const e=this.canvas.getScenePoint(t).transform(invertTransform(this.calcTransformMatrix())).add(new Point(-this._getLeftOffset(),-this._getTopOffset()));"rtl"===this.direction&&(e.x*=-1);let i=0,s=0,n=0;for(let t=0;t<this._textLines.length&&i<=e.y;t++)i+=this.getHeightOfLine(t),n=t,t>0&&(s+=this._textLines[t-1].length+this.missingNewlineOffset(t-1));const r=this._getLineLeftOffset(n),o=this._textLines[n].length,a=this.__charBounds[n],h=s;for(let t=0;t<o;t++){var l,c;const i=r+a[t].left,n=r+(null!==(l=null===(c=a[t+1])||void 0===c?void 0:c.left)&&void 0!==l?l:a[t].left+a[t].kernedWidth),d=(i+n)/2;if(e.x<=d){s=h+t;break}if(e.x<=n){s=h+t+1;break}s=h+o}let d=s-h;this.flipX&&(d=o-d);const u=this._displayToOriginalIndex(n,d);let g=0;for(let t=0;t<n;t++){const e=undefined;g+=this._getOriginalLineLength(t)+this.missingNewlineOffset(t)}const f=g+u;return Math.min(f,this.text.length)}}function getCursorRect(t,e,i){if(0===e.lines.length)return{x:0,y:0,width:2,height:i.fontSize,baseline:.8*i.fontSize};const s=findPositionFromIndex(t,e),n=e.lines[s.lineIndex];if(!n){const t=undefined;return{x:e.lines[e.lines.length-1].width,y:(e.lines.length-1)*(i.fontSize*i.lineHeight),width:2,height:i.fontSize*i.lineHeight,baseline:.8*i.fontSize}}let r=0;if(s.graphemeIndex>0&&n.bounds.length>0){const t=Math.min(s.graphemeIndex-1,n.bounds.length-1),e=n.bounds[t];r=e.x+e.kernedWidth}const o=calculateLineY(s.lineIndex,e);return{x:r,y:o,width:2,height:n.height,baseline:o+n.baseline}}function findPositionFromIndex(t,e){let i=0;for(let s=0;s<e.lines.length;s++){const n=undefined,r=e.lines[s].graphemes.length;if(t>=i&&t<=i+r)return{lineIndex:s,graphemeIndex:t-i};if(i+=r,s<e.lines.length-1&&(i+=1,t===i-1))return{lineIndex:s,graphemeIndex:r}}const s=e.lines.length-1,n=e.lines[s];return{lineIndex:s,graphemeIndex:n?n.graphemes.length:0}}function calculateLineY(t,e,i){let s=0;for(let i=0;i<t&&i<e.lines.length;i++)s+=e.lines[i].height;return s}const pi="moveCursorUp",mi="moveCursorDown",yi="moveCursorLeft",xi="moveCursorRight",vi="exitEditing",_i=undefined,Ci=undefined,bi=undefined,Si=undefined,applyCanvasTransform=(t,e)=>{const i=e.getRetinaScaling();t.setTransform(i,0,0,i,0,0);const s=e.viewportTransform;t.transform(s[0],s[1],s[2],s[3],s[4],s[5])},wi=undefined,Ti={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:vi,27:vi,33:pi,34:mi,35:xi,36:yi,37:yi,38:pi,39:xi,40:mi},keysMapRtl:{9:vi,27:vi,33:pi,34:mi,35:yi,36:xi,37:xi,38:pi,39:yi,40:mi},ctrlKeysMapDown:{65:"cmdAll"},ctrlKeysMapUp:{67:"copy",88:"cut"},...{_selectionDirection:null,_reSpace:/\s|\r?\n/,inCompositionMode:!1}};class IText extends ITextClickBehavior{static getDefaults(){return{...super.getDefaults(),...IText.ownDefaults}}get type(){const t=super.type;return"itext"===t?"i-text":t}constructor(t,e){super(t,{...IText.ownDefaults,...e}),_defineProperty(this,"_visualPositionsCache",new Map),this.initBehavior()}_set(t,e){return this.isEditing&&this._savedProps&&t in this._savedProps?(this._savedProps[t]=e,this):("canvas"===t&&(this.canvas instanceof Canvas&&this.canvas.textEditingManager.remove(this),e instanceof Canvas&&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&&void 0!==arguments[0]?arguments[0]:this.selectionStart||0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.selectionEnd,i=arguments.length>2?arguments[2]:void 0;return super.getSelectionStyles(t,e,i)}setSelectionStyles(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.selectionStart||0,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.selectionEnd;return super.setSelectionStyles(t,e,i)}get2DCursorLocation(){let t=arguments.length>0&&void 0!==arguments[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._clearVisualPositionsCache(),this.renderCursorOrSelection()}toCanvasElement(t){const e=this.isEditing;this.isEditing=!1;const i=super.toCanvasElement(t);return this.isEditing=e,i}renderCursorOrSelection(){if(!this.isEditing||!this.canvas)return;const t=this.clearContextTop(!0);if(!t)return;this.cursorOffsetCache={};const e=this._getCursorBoundaries(),i=this.findAncestorsWithClipPath(),s=i.length>0;let n=t,r;if(s){r=createCanvasElementFor(t.canvas),n=r.getContext("2d"),applyCanvasTransform(n,this.canvas);const e=this.calcTransformMatrix();n.transform(e[0],e[1],e[2],e[3],e[4],e[5])}if(this.selectionStart!==this.selectionEnd||this.inCompositionMode?this.renderSelection(n,e):this.renderCursor(n,e),s)for(const e of i){const i=e.clipPath,s=createCanvasElementFor(t.canvas),r=s.getContext("2d");if(applyCanvasTransform(r,this.canvas),!i.absolutePositioned){const t=e.calcTransformMatrix();r.transform(t[0],t[1],t[2],t[3],t[4],t[5])}i.transform(r),i.drawObject(r,!0,{}),this.drawClipPathOnCache(n,i,s)}s&&(t.setTransform(1,0,0,1,0,0),t.drawImage(r,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&&void 0!==arguments[0]?arguments[0]:this.selectionStart,e=arguments.length>1?arguments[1]:void 0;return this._getCursorBoundariesOriginal(t,e)}_getCursorBoundariesOffsets(t,e){return e?this.__getCursorBoundariesOffsets(t):this.cursorOffsetCache&&"top"in this.cursorOffsetCache?this.cursorOffsetCache:this.cursorOffsetCache=this.__getCursorBoundariesOffsets(t)}_getCursorBoundariesAdvanced(t){if(!this.enableAdvancedLayout||!this._layoutTextAdvanced)return this._getCursorBoundariesOriginal(t);const e=undefined,i=getCursorRect(t,this._layoutTextAdvanced(),this._getAdvancedLayoutOptions());return{left:this._getLeftOffset(),top:this._getTopOffset(),leftOffset:i.x,topOffset:i.y}}getSelectionStartFromPointer(t){const e=undefined,i=this.canvas.getScenePoint(t).transform(invertTransform(this.calcTransformMatrix())),s=i.x+this.width/2,n=i.y+this.height/2;let r=0,o=0;for(let t=0;t<this._textLines.length;t++){const e=this.getHeightOfLine(t);if(n>=r&&n<r+e){o=t;break}r+=e,t===this._textLines.length-1&&(o=t)}let a=0;for(let t=0;t<o;t++){const e=this._getOriginalLineLength(t),i=this.missingNewlineOffset(t);console.log(`📍 Line ${t}: origLen=${e}, displayLen=${this._textLines[t].length}, tatweels=${this._getTatweelCountForLine(t)}, newlineOffset=${i}`),a+=e+i}console.log(`📍 Click on line ${o}, lineStartIndex=${a}`);const h=this._textLines[o],l=h.join(""),c=h.length,d=this._getOriginalLineLength(o);if(0===c)return a;const u=this._measureVisualPositions(o,l),g=this.getLineWidth(o);let f=0;"center"===this.textAlign||"justify-center"===this.textAlign?f=(this.width-g)/2:"right"===this.textAlign||"justify-right"===this.textAlign?f=this.width-g:"rtl"!==this.direction||"justify"!==this.textAlign&&"left"!==this.textAlign||(f=this.width-g);const p=s-f,m=[...u].sort((t,e)=>t.visualX-e.visualX);if(m.length>0&&p<m[0].visualX)return"rtl"===this.direction?a+d:a;if(m.length>0){const t=m[m.length-1];if(p>t.visualX+t.width)return"rtl"===this.direction?a:a+d}for(let t=0;t<m.length;t++){const e=m[t],i=e.visualX+e.width;if(p>=e.visualX&&p<=i){const t=this._displayToOriginalIndex(o,e.logicalIndex),i=this._isTatweelAtDisplayIndex(o,e.logicalIndex);console.log(`📍 Hit char: displayIdx=${e.logicalIndex}, origIdx=${t}, isTatweel=${i}, char="${this._textLines[o][e.logicalIndex]}"`);const s=undefined,n=p<=e.visualX+e.width/2;if(i){const e=a+t;return console.log(`📍 Tatweel click result: ${e}`),e}if(e.isRtl){const e=a+(n?t+1:t);return console.log(`📍 RTL char result: ${e} (clickedLeftHalf=${n})`),e}{const e=a+(n?t:t+1);return console.log(`📍 LTR char result: ${e} (clickedLeftHalf=${n})`),e}}}return a+d}_clearVisualPositionsCache(){this._visualPositionsCache.clear()}_measureVisualPositions(t,e){if(this._visualPositionsCache.has(t))return this._visualPositionsCache.get(t);const i=this._textLines[t],s=[],n=this.__charBounds[t];if(!n||0===n.length)return this._visualPositionsCache.set(t,s),s;if("rtl"!==this.direction){for(let t=0;t<i.length;t++){var r,o;s.push({logicalIndex:t,visualX:(null===(r=n[t])||void 0===r?void 0:r.left)||0,width:(null===(o=n[t])||void 0===o?void 0:o.kernedWidth)||0,isRtl:!1})}return this._visualPositionsCache.set(t,s),s}const a=analyzeBiDi(e,"rtl"),h=[];let l=0;for(let t=0;t<i.length;t++){const e=i[t];for(let i=0;i<e.length;i++)h[l+i]=t;l+=e.length}const c=[];for(const t of a){const e=[];let i=0;const s=new Set;for(let r=t.start;r<t.end;r++){const t=h[r];var d;if(void 0!==t&&!s.has(t))s.add(t),e.push(t),i+=(null===(d=n[t])||void 0===d?void 0:d.kernedWidth)||0}c.push({run:t,width:i,charIndices:e})}const u=undefined;let g=this.getLineWidth(t);for(const t of c){g-=t.width;const e=undefined;if("rtl"===t.run.direction){let e=g+t.width;for(const i of t.charIndices){var f;const t=(null===(f=n[i])||void 0===f?void 0:f.kernedWidth)||0;e-=t,s.push({logicalIndex:i,visualX:e,width:t,isRtl:!0})}}else{let e=g;for(const i of t.charIndices){var p;const t=(null===(p=n[i])||void 0===p?void 0:p.kernedWidth)||0;s.push({logicalIndex:i,visualX:e,width:t,isRtl:!1}),e+=t}}}return this._visualPositionsCache.set(t,s),s}_getCursorBoundariesOriginal(t,e){const i=this._getLeftOffset(),s=this._getTopOffset(),n=this._getCursorBoundariesOffsets(t,e);return{left:i,top:s,leftOffset:n.left,topOffset:n.top}}__getCursorBoundariesOffsets(t){let e=0,i=0,s=t;for(let t=0;t<this._textLines.length;t++){const e=this._getOriginalLineLength(t);if(s<=e){i=t;break}s-=e+this.missingNewlineOffset(t),i=t+1}i>=this._textLines.length&&(i=this._textLines.length-1,s=this._getOriginalLineLength(i));for(let t=0;t<i;t++)e+=this.getHeightOfLine(t);const n=this._originalToDisplayIndex(i,s),r=this._textLines[i].join(""),o=this._measureVisualPositions(i,r),a=this.getLineWidth(i);this._textLines[i].length;const h=this._getOriginalLineLength(i);let l=0;if(0===o.length)return{top:e,left:0};if(0===s)l="rtl"===this.direction?a:0;else if(s>=h)l="rtl"===this.direction?0:a;else{const t=o.find(t=>t.logicalIndex===n);if(t)l=t.isRtl?t.visualX+t.width:t.visualX;else{const t=n>0?n-1:0,e=o.find(e=>e.logicalIndex===t);if(e)l=e.isRtl?e.visualX:e.visualX+e.width;else{const t=this.__charBounds[i][n];l=(null==t?void 0:t.left)||0}}}let c=0,d;return"center"===this.textAlign||"justify-center"===this.textAlign?c=(this.width-a)/2:"right"===this.textAlign||"justify-right"===this.textAlign?c=this.width-a:"rtl"!==this.direction||"justify"!==this.textAlign&&"left"!==this.textAlign||(c=this.width-a),d="rtl"===this.direction?-this.width+c+l:c+l,{top:e,left:d}}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&&void 0!==arguments[0]?arguments[0]:this.selectionStart,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this._getCursorBoundaries(t);const i=this.get2DCursorLocation(t),s=i.lineIndex,n=i.charIndex>0?i.charIndex-1:0,r=this.getValueOfPropertyAt(s,n,"fontSize"),o=this.getObjectScaling().x*this.canvas.getZoom(),a=this.cursorWidth/o,h=this.getValueOfPropertyAt(s,n,"deltaY"),l=e.topOffset+(1-this._fontSizeFraction)*this.getHeightOfLine(s)/this.lineHeight-r*(1-this._fontSizeFraction);return{color:this.cursorColor||this.getValueOfPropertyAt(s,n,"fill"),opacity:this._currentCursorOpacity,left:e.left+e.leftOffset-a/2,top:l+e.top+h,width:a,height:r}}_renderCursor(t,e,i){const{color:s,opacity:n,left:r,top:o,width:a,height:h}=this.getCursorRenderingData(i,e);t.fillStyle=s,t.globalAlpha=n,t.fillRect(r,o,a,h)}renderSelection(t,e){const i={selectionStart:this.inCompositionMode?this.hiddenTextarea.selectionStart:this.selectionStart,selectionEnd:this.inCompositionMode?this.hiddenTextarea.selectionEnd:this.selectionEnd};this._renderSelection(t,i,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,i){const s=e.selectionStart,n=e.selectionEnd,r=this.textAlign.includes(rt);let o=0,a=0,h=s,l=n,c=0;for(let t=0;t<this._textLines.length;t++){const e=this._getOriginalLineLength(t);if(c+e>=s){o=t,h=s-c;break}c+=e+this.missingNewlineOffset(t)}c=0;for(let t=0;t<this._textLines.length;t++){const e=this._getOriginalLineLength(t);if(c+e>=n){a=t,l=n-c;break}c+=e+this.missingNewlineOffset(t),t===this._textLines.length-1&&(a=t,l=e)}for(let e=o;e<=a;e++){let s=this.getHeightOfLine(e),n=0;const c=this._textLines[e].join(""),d=this._measureVisualPositions(e,c);this._textLines[e].length;const u=undefined;let g=0,f=this._getOriginalLineLength(e);e===o&&(g=h),e===a&&(f=l);const p=this._originalToDisplayIndex(e,g),m=this._originalToDisplayIndex(e,f);let y=1/0,x=-1/0;for(const t of d)t.logicalIndex>=p&&t.logicalIndex<m&&(y=Math.min(y,t.visualX),x=Math.max(x,t.visualX+t.width));if(y===1/0||x===-1/0){if(!(e>=o&&e<a))continue;y=0,x=r&&!this.isEndOfWrapping(e)?this.width:this.getLineWidth(e)||5}n=s,(this.lineHeight<1||e===a&&this.lineHeight>1)&&(s/=this.lineHeight);const v=this.getLineWidth(e);let _=0;"center"===this.textAlign||"justify-center"===this.textAlign?_=(this.width-v)/2:"right"===this.textAlign||"justify-right"===this.textAlign?_=this.width-v:"rtl"!==this.direction||"justify"!==this.textAlign&&"left"!==this.textAlign||(_=this.width-v);const C=-this.width/2+_+y,b=x-y;let S=s,w=0;this.inCompositionMode?(t.fillStyle=this.compositionColor||"black",S=1,w=s):t.fillStyle=this.selectionColor,t.fillRect(C,i.top+i.topOffset+w,b,S),i.topOffset+=n}}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,I)}_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()}}_defineProperty(IText,"ownDefaults",Ti),_defineProperty(IText,"type","IText"),X.setClass(IText),X.setClass(IText,"i-text");const Pi={minWidth:20,dynamicMinWidth:2,lockScalingFlip:!0,noScaleCache:!1,_wordJoiners:/[ \t\r]/,splitByGrapheme:!1};class Textbox extends IText{static getDefaults(){return{...super.getDefaults(),...Textbox.ownDefaults}}constructor(t,e){super(t,{...Textbox.ownDefaults,...e}),this.initializeEventListeners()}static createControls(){return{controls:createTextboxDefaultControls()}}initDimensions(){this.initialized||(this.initialized=!0);const t=`${this.text}|${this.width}|${this.fontSize}|${this.fontFamily}|${this.textAlign}|${this.kashida}`;if(this._lastDimensionState===t&&this._textLines&&this._textLines.length>0)return;if(this._lastDimensionState=t,this.enableAdvancedLayout)return this.initDimensionsAdvanced();this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.dynamicMinWidth=0;const e=this._splitText();if(this._styleMap=this._generateStyleMap(e),this._usingBrowserWrapping&&e&&e.lines){this._textLines=e.lines.map(t=>t.split(""));const t=e.justifySpaceMeasurements;t&&(this._styleMap.justifySpaceMeasurements=t);const i=e.actualBrowserHeight;i&&(this._actualBrowserHeight=i)}if(!this._usingBrowserWrapping&&this.dynamicMinWidth>this.width&&this._set("width",this.dynamicMinWidth),this._usingBrowserWrapping&&this.width<50&&(this.width=300),this.height=this.calcTextHeight(),this.textAlign.includes(rt)){for(let t=0;t<this._textLines.length;t++)this.getLineWidth(t);this._usingBrowserWrapping?this._applyBrowserJustifySpaces():this.__charBounds&&this.__charBounds.length>0&&this.enlargeSpaces()}}_scheduleJustifyAfterFontLoad(){if("undefined"==typeof document||!("fonts"in document))return;if(this._fontJustifyScheduled)return;this._fontJustifyScheduled=!0;const t=`${this.fontSize}px ${this.fontFamily}`;document.fonts.load(t).then(()=>{var t;this._fontJustifyScheduled=!1,this.initDimensions(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()}).catch(()=>{this._fontJustifyScheduled=!1})}initDimensionsAdvanced(){if(!this.initialized)return;this.isEditing&&this.initDelayedCursor(),this._clearCache(),this.lockDynamicMinWidth||(this.dynamicMinWidth=0);const t=undefined,e="none"!==this.kashida&&this.textAlign.includes(rt)?"rtl"===this.direction?"right":"left":this._mapTextAlignToAlign(this.textAlign),i=layoutText({text:this.text,width:this.width,height:this.ellipsis?this.height:void 0,wrap:this.wrap||"word",align:e,ellipsis:this.ellipsis||!1,fontSize:this.fontSize,lineHeight:this.lineHeight,letterSpacing:this.letterSpacing||0,charSpacing:this.charSpacing,direction:"inherit"===this.direction?"ltr":this.direction,fontFamily:this.fontFamily,fontStyle:this.fontStyle,fontWeight:this.fontWeight,verticalAlign:this.verticalAlign||"top"});if(this.lockDynamicMinWidth)this.height=i.totalHeight,this._convertLayoutToLegacyFormat(i);else{if(i.lines.length>0){const t=Math.max(...i.lines.map(t=>t.width));this.dynamicMinWidth=Math.max(this.minWidth,t)}if(this.dynamicMinWidth>this.width){this._set("width",this.dynamicMinWidth);const t=layoutText({...this._getAdvancedLayoutOptions(),width:this.width});this.height=t.totalHeight,this._convertLayoutToLegacyFormat(t)}else this.height=i.totalHeight,this._convertLayoutToLegacyFormat(i)}this._styleMap=this._generateStyleMapFromLayout(i),this.textAlign.includes(rt)&&"none"!==this.kashida&&this._applyKashidaToLayout(),this.dirty=!0}_applyKashidaToLayout(){if(!this._textLines||!this.__charBounds)return;this._visualPositionsCache&&this._clearVisualPositionsCache();const t=undefined,e={none:0,short:.25,medium:.5,long:.75,stylistic:1}[this.kashida]||0;if(0===e)return;const i=undefined,s=document.createElement("canvas").getContext("2d");if(!s)return;s.font=this._getFontDeclaration();const n=s.measureText(ai).width;if(n<=0)return;this.__kashidaInfo=[];const r=this._textLines.length;for(let t=0;t<r;t++){this.__kashidaInfo[t]=[];const i=this._textLines[t];if(!this.__charBounds||!this.__charBounds[t])continue;const s=undefined;if(t===r-1)continue;const a=this.__charBounds[t],h=a[a.length-1],l=h?h.left+h.kernedWidth:0,c=this.width-l;if(c<=2)continue;const d=findKashidaPoints(i);if(0===d.length)continue;const u=c*e,g=Math.floor(u/n);if(0===g)continue;const f=Math.min(d.length,g),p=d.slice(0,f),m=Math.floor(g/f),y=g%f,x=[...p].sort((t,e)=>e.charIndex-t.charIndex),v=[...i];for(let e=0;e<x.length;e++){const i=x[e],s=undefined,r=m+(p.indexOf(i)<y?1:0);if(r>0){const e=Array(r).fill(ai);v.splice(i.charIndex+1,0,...e),this.__kashidaInfo[t].push({charIndex:i.charIndex,width:r*n,tatweelCount:r})}}this._textLines[t]=v,this.textLines&&(this.textLines[t]=v.join("")),this.__charBounds[t]=[],this.__lineWidths[t]=void 0,this._measureLine(t);let _=this.__charBounds[t];if(_&&_.length>0){let e=_[_.length-1],i=e?e.left+e.kernedWidth:0,s=this.width-i;if(s>.5){let t=0;for(let e=0;e<v.length;e++)/\s/.test(v[e])&&t++;if(t>0){const n=s/t;let r=0;for(let t=0;t<_.length;t++){const e=_[t];e&&(e.left+=r,/\s/.test(v[t])&&(e.width+=n,e.kernedWidth+=n,r+=n))}_[v.length]&&(_[v.length].left+=r),e=_[_.length-1],i=e?e.left+e.kernedWidth:0,s=this.width-i}}if(s>.5&&this.__kashidaInfo[t].length>0){const e=undefined,i=s/this.__kashidaInfo[t].length;let n=0,r=0;for(let e=0;e<_.length;e++){const s=_[e];if(s&&(s.left+=r,v[e]===ai)){var o;const a=i/((null===(o=this.__kashidaInfo[t][n])||void 0===o?void 0:o.tatweelCount)||1);s.width+=a,s.kernedWidth+=a,r+=a;const h=undefined;this.__kashidaInfo[t][n]&&e>0&&(e+1>=v.length||v[e+1]!==ai)&&n++}}_[v.length]&&(_[v.length].left+=r)}}this.__lineWidths[t]=this.width}for(let t=0;t<this._textLines.length;t++)if(void 0===this.__lineWidths[t]&&this.__charBounds[t]){const e=this.__charBounds[t],i=e[e.length-1];i&&(this.__lineWidths[t]=i.left+i.kernedWidth)}this._text=this._textLines.flat(),this._justifyApplied=!0}_generateStyleMapFromLayout(t){const e={};let i=0,s=0;return t.lines.forEach((n,r)=>{n.text.includes("\n")&&r>0&&i++,e[r]={line:i,offset:0},s+=n.graphemes.length,r<t.lines.length-1&&(s+=1)}),e}_generateStyleMap(t){let e=0,i=0,s=0;const n={};for(let r=0;r<t.graphemeLines.length;r++)"\n"===t.graphemeText[s]&&r>0?(i=0,s++,e++):!this.splitByGrapheme&&this._reSpaceAndTab.test(t.graphemeText[s])&&r>0&&(i++,s++),n[r]={line:e,offset:i},s+=t.graphemeLines[r].length,i+=t.graphemeLines[r].length;return n}styleHas(t,e){if(this._styleMap&&!this.isWrapping){const t=this._styleMap[e];t&&(e=t.line)}return super.styleHas(t,e)}isEmptyStyles(t){if(!this.styles)return!0;let e=0,i=t+1,s,n=!1;const r=this._styleMap[t],o=this._styleMap[t+1];r&&(t=r.line,e=r.offset),o&&(i=o.line,n=i===t,s=o.offset);const a=void 0===t?this.styles:{line:this.styles[t]};for(const t in a)for(const i in a[t]){const r=parseInt(i,10);if(r>=e&&(!n||r<s))for(const e in a[t][i])return!1}return!0}_getStyleDeclaration(t,e){if(this._styleMap&&!this.isWrapping){const i=this._styleMap[t];if(!i)return{};t=i.line,e=i.offset+e}return super._getStyleDeclaration(t,e)}_setStyleDeclaration(t,e,i){const s=this._styleMap[t];super._setStyleDeclaration(s.line,s.offset+e,i)}_deleteStyleDeclaration(t,e){const i=this._styleMap[t];super._deleteStyleDeclaration(i.line,i.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 i=this.getGraphemeDataForRender(t),s=[];for(let t=0;t<i.wordsData.length;t++)s.push(...this._wrapLine(t,e,i));return this.isWrapping=!1,s}getGraphemeDataForRender(t){const e=this.splitByGrapheme,i=e?"":" ";let s=0;const n=undefined;return{wordsData:t.map((t,n)=>{let r=0;const o=e?this.graphemeSplit(t):this.wordSplit(t);return 0===o.length?[{word:[],width:0}]:o.map(t=>{const o=e?[t]:this.graphemeSplit(t),a=this._measureWord(o,n,r);return s=Math.max(a,s),r+=o.length+i.length,{word:o,width:a}})}),largestWordWidth:s}}_measureWord(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,s=0,n;const r=!0;for(let o=0,a=t.length;o<a;o++){const a=undefined;s+=this._getGraphemeBox(t[o],e,o+i,n,r).kernedWidth,n=t[o]}return s}wordSplit(t){return t.split(this._wordJoiners)}_wrapLine(t,e,i){let{largestWordWidth:s,wordsData:n}=i,r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0;const o=this._getWidthOfCharSpacing(),a=this.splitByGrapheme,h=[],l=a?"":" ";let c=0,d=[],u=0,g=0,f=!0;e-=r;const p=Math.max(e,s,this.dynamicMinWidth),m=n[t];let y;for(u=0,y=0;y<m.length;y++){const{word:e,width:i}=m[y];u+=e.length;const s=c+g+i-o;s>p&&!f?(h.push(d),d=[],c=i,f=!0):c=s+o,f||a||d.push(l),d=d.concat(e),g=a?0:this._measureWord([l],t,u),u++,f=!1}return y&&h.push(d),!this._usingBrowserWrapping&&s+r>this.dynamicMinWidth&&(this.dynamicMinWidth=s-o+r),h}isEndOfWrapping(t){return!this._styleMap[t+1]||this._styleMap[t+1].line!==this._styleMap[t].line}missingNewlineOffset(t,e){return this.splitByGrapheme&&!e?this.isEndOfWrapping(t)?1:0:1}_splitTextIntoLines(t){const e=undefined;if(this.fontFamily&&fontLacksEnglishGlyphsCached(this.fontFamily)){const e=undefined,i=`${t.length+t.slice(0,50)}|${this.width}|${this.fontSize}|${this.fontFamily}|${this.textAlign}`;if(this._browserWrapCache&&this._browserWrapCache.key===i){const t=this._browserWrapCache.result;if(!this.textAlign.includes("justify")||t.justifySpaceMeasurements)return t}const s=this._splitTextIntoLinesWithBrowser(t);return this._browserWrapCache={key:i,result:s},this._usingBrowserWrapping=!0,s}this._usingBrowserWrapping=!1;const i=super._splitTextIntoLines(t),s=this._wrapText(i.lines,this.width),n=new Array(s.length);for(let t=0;t<s.length;t++)n[t]=s[t].join("");return i.lines=n,i.graphemeLines=s,i}_splitTextIntoLinesWithBrowser(t){if("undefined"==typeof document)return this._splitTextIntoLinesDefault(t);const e=document.createElement("div");e.style.position="absolute",e.style.left="-9999px",e.style.visibility="hidden",e.style.fontSize=`${this.fontSize}px`,e.style.fontFamily=`"${this.fontFamily}"`,e.style.fontWeight=String(this.fontWeight||"normal"),e.style.fontStyle=String(this.fontStyle||"normal"),e.style.lineHeight=String(this.lineHeight||1.16),e.style.width=`${this.width}px`,e.style.direction=this.direction||"ltr",e.style.whiteSpace="pre-wrap",e.style.wordBreak="normal",e.style.overflowWrap="break-word",this.textAlign.includes("justify")?(e.style.textAlign="justify",e.style.textAlignLast="auto"):e.style.textAlign=this.textAlign,e.textContent=t,document.body.appendChild(e);const i=document.createRange(),s=[],n=[];try{const r=e.firstChild;if(r&&r.nodeType===Node.TEXT_NODE){let e=0;const o=t.length;let a=0;for(let h=0;h<=o;h++){i.setStart(r,e),i.setEnd(r,h);const l=i.getBoundingClientRect();if(h>e&&(l.bottom>a+5||h===o)){const i=h===o?h:h-1,r=t.substring(e,i).trim();if(r){s.push(r);const t=r.split("");n.push(t)}e=i,a=l.bottom}}}}catch(i){return document.body.removeChild(e),this._splitTextIntoLinesDefault(t)}const r=e.scrollHeight,o=e.getBoundingClientRect();let a=null;this.textAlign.includes("justify")&&(a=this._extractJustifySpaceMeasurements(e,s)),document.body.removeChild(e);let h=Math.max(r,o.height);const l=undefined;if(fontLacksEnglishGlyphsCached(this.fontFamily)){const t=undefined;h+=.25*this.fontSize}return{_unwrappedLines:[t.split("")],lines:s,graphemeText:t.split(""),graphemeLines:n,justifySpaceMeasurements:a,actualBrowserHeight:h}}_extractJustifySpaceMeasurements(t,e){const i=this._browserMeasureCtx||(this._browserMeasureCtx=document.createElement("canvas").getContext("2d"));if(!i)return[];i.font=`${this.fontStyle||"normal"} ${this.fontWeight||"normal"} ${this.fontSize}px "${this.fontFamily}"`;const s=i.measureText(" ").width||6,n=[];return e.forEach((t,r)=>{const o=[],a=(t.match(/\s/g)||[]).length,h=r===e.length-1;if(a>0&&!h){const e=i.measureText(t).width,n=this.width-e,r=undefined,h=s+(n>0?n/a:0),l=Math.max(s,h);for(let t=0;t<a;t++)o.push(l)}else if(a>0)for(let t=0;t<a;t++)o.push(s);n.push(o)}),n}_applyBrowserJustifySpaces(){if(!this._textLines||!this.__charBounds)return;const t=undefined,e={none:0,short:.25,medium:.5,long:.75,stylistic:1}[this.kashida]||0;this.__kashidaInfo=[];const i=this._textLines.length;this._textLines.forEach((t,s)=>{if(this.__kashidaInfo[s]=[],!this.__charBounds||!this.__charBounds[s])return;const n=undefined;if(s===i-1)return;const r=undefined,o=this.__charBounds[s].reduce((t,e)=>t+((null==e?void 0:e.kernedWidth)||0),0),a=this.width-o;if(a<=0)return;const h=[];for(let e=0;e<t.length;e++)/\s/.test(t[e])&&h.push(e);const l=h.length,c=e>0?findKashidaPoints(t):[],d=c.length>0;let u=0;d&&e>0&&(u=a*e);const g=d?u/c.length:0;if(d&&g>0){const e=[...c].sort((t,e)=>e.charIndex-t.charIndex),i=undefined,n=document.createElement("canvas").getContext("2d");if(n){n.font=this._getFontDeclaration();const i=n.measureText(ai).width;if(i>0){const n=[...t];for(const t of e){const e=Math.max(1,Math.round(g/i));for(let i=0;i<e;i++)n.splice(t.charIndex+1,0,ai);this.__kashidaInfo[s].push({charIndex:t.charIndex,width:g,tatweelCount:e})}this._textLines[s]=n,this.textLines&&void 0!==this.textLines[s]&&(this.textLines[s]=n.join("")),this.__charBounds[s]=[],this.__lineWidths[s]=void 0,this._measureLine(s)}}}else for(const t of c)this.__kashidaInfo[s].push({charIndex:t.charIndex,width:g,tatweelCount:0});const f=this.__charBounds[s],p=f.reduce((t,e)=>t+((null==e?void 0:e.kernedWidth)||0),0),m=this.width-p;if(m>0&&l>0){const t=m/l;let e=0;for(let i=0;i<this._textLines[s].length;i++){const n=f[i];n&&(n.left+=e,/\s/.test(this._textLines[s][i])&&(n.width+=t,n.kernedWidth+=t,e+=t))}}const y=undefined,x=this.__charBounds[s].reduce((t,e)=>Math.max(t,((null==e?void 0:e.left)||0)+((null==e?void 0:e.width)||0)),0);this.__lineWidths[s]=x}),this.dirty=!0,this._justifyApplied=!0}_splitTextIntoLinesDefault(t){const e=super._splitTextIntoLines(t),i=this._wrapText(e.lines,this.width),s=new Array(i.length);for(let t=0;t<i.length;t++)s[t]=i[t].join("");return e.lines=s,e.graphemeLines=i,e}getMinWidth(){return Math.max(this.minWidth,this.dynamicMinWidth)}_removeExtraneousStyles(){const t=new Map;for(const e in this._styleMap){const i=parseInt(e,10);if(this._textLines[i]){const i=this._styleMap[e].line;t.set(`${i}`,!0)}}for(const e in this.styles)t.has(e)||delete this.styles[e]}initializeEventListeners(){var t;let e=null;this.on("resizing",t=>{if(t.transform){const{originX:i}=t.transform;e="right"===i?"left":"left"===i?"right":null}else if(t.originX){const{originX:i}=t;e="right"===i?"left":"left"===i?"right":null}}),this.on("modified",()=>{const t=e;setTimeout(()=>this.safetySnapWidth(t),10),e=null}),null===(t=this.canvas)||void 0===t||t.on("object:modified",t=>{if(t.target===this){const t=e;setTimeout(()=>this.safetySnapWidth(t),10),e=null}})}safetySnapWidth(t){if(!this._textLines||"textbox"!==this.type.toLowerCase()||0===this._textLines.length)return;if(null==t)return;const e=this._textLines.length;if(0===e)return;let i=0;for(let t=0;t<e;t++){const e=this._textLines[t].join(""),s=this.getLineWidth(t),n=undefined;if(/[\u0590-\u05FF\u0600-\u06FF\u0750-\u077F\uFB50-\uFDFF\uFE70-\uFEFF]/.test(e)){const t=.15*(this.fontSize||16);i=Math.max(i,s+t)}else i=Math.max(i,s)}const s=2;if(i>this.width-2){var n;const t=i+1,e=this.left,s=this.top,r=t-this.width,o=this.lockDynamicMinWidth;this.lockDynamicMinWidth=!0,this.set("width",t),this.initDimensions(),this.lockDynamicMinWidth=o,this.set({left:e-r,top:s}),this.setCoords(),this.__overlayEditor&&setTimeout(()=>{this.__overlayEditor.refresh()},0),null===(n=this.canvas)||void 0===n||n.requestRenderAll()}}_fixCharacterMappingAfterJsonLoad(){this._usingBrowserWrapping&&(this._browserWrapCache=null,this._lastDimensionState=null,this.initDimensions(),this._forceClearCache=!0,this.setCoords(),this.canvas&&this.canvas.requestRenderAll())}forceTextReinitialization(){this.initialized=!0,this._clearCache(),this.dirty=!0,this.dynamicMinWidth=0,this.isEditing=!1,this.initDimensions(),this.textAlign.includes("justify")&&this.__charBounds&&setTimeout(()=>{var t;let e=!1;this.__charBounds.forEach((t,i)=>{if(t&&this._textLines&&this._textLines[i]){const s=t.filter((t,e)=>/\s/.test(this._textLines[i][e]));if(s.length>1){const t=s[0].width;e=s.some(e=>Math.abs(e.width-t)>.1)}}}),!e&&this.__charBounds.length>0&&this.enlargeSpaces&&this.enlargeSpaces(),this._usingBrowserWrapping&&this._actualBrowserHeight?this.height=this._actualBrowserHeight:this.height=this.calcTextHeight(),null===(t=this.canvas)||void 0===t||t.requestRenderAll()},10)}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return super.toObject(["minWidth","splitByGrapheme",...t])}}_defineProperty(Textbox,"type","Textbox"),_defineProperty(Textbox,"textLayoutProperties",[...IText.textLayoutProperties,"width"]),_defineProperty(Textbox,"ownDefaults",Pi),X.setClass(Textbox);const Mi=20;function getOriginalDimensions(t){const e=t.getElement();return e?{width:e.naturalWidth||e.width||t.width||100,height:e.naturalHeight||e.height||t.height||100}:{width:t.width||100,height:t.height||100}}const resizeFromRightHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleX||1,a=n.cropX||0,h=getLocalPoint(e,e.originX,e.originY,i,s),l=Math.max(Mi,Math.abs(h.x)),c=undefined;if(l<=(r.width-a)*o)n.width=l/o;else{n.width=r.width-a;const t=l/n.width;n.scaleX=t,n.scaleY=t;const e=(n.height||r.height)*o;n.height=e/t}return n.setCoords(),!0},resizeFromLeftHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleX||1,a=n.cropX||0,h=n.width||r.width,l=getLocalPoint(e,e.originX,e.originY,i,s),c=Math.max(Mi,Math.abs(l.x)),d=a+h,u=undefined;if(c<=d*o){const t=c/o,e=d-t;e>=0?(n.cropX=e,n.width=t):(n.cropX=0,n.width=d)}else{n.cropX=0,n.width=d;const t=c/n.width;n.scaleX=t,n.scaleY=t;const e=(n.height||r.height)*o;n.height=e/t}return n.setCoords(),!0},cropFromRightHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"left","center",i,s),o=getOriginalDimensions(n),a=n.cropX||0,h=n.scaleX||1,l=(o.width-a)*h,c=Math.max(Mi,r.x);if(c<=l)n.width=c/h;else{n.width=o.width-a;const t=c/n.width;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},resizeFromBottomHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleY||1,a=n.cropY||0,h=getLocalPoint(e,e.originX,e.originY,i,s),l=Math.max(Mi,Math.abs(h.y)),c=undefined;if(l<=(r.height-a)*o)n.height=l/o;else{n.height=r.height-a;const t=l/n.height;n.scaleX=t,n.scaleY=t;const e=(n.width||r.width)*o;n.width=e/t}return n.setCoords(),!0},resizeFromTopHandler=(t,e,i,s)=>{const n=e.target,r=getOriginalDimensions(n),o=n.scaleY||1,a=n.cropY||0,h=n.height||r.height,l=getLocalPoint(e,e.originX,e.originY,i,s),c=Math.max(Mi,Math.abs(l.y)),d=a+h,u=undefined;if(c<=d*o){const t=c/o,e=d-t;e>=0?(n.cropY=e,n.height=t):(n.cropY=0,n.height=d)}else{n.cropY=0,n.height=d;const t=c/n.height;n.scaleX=t,n.scaleY=t;const e=(n.width||r.width)*o;n.width=e/t}return n.setCoords(),!0},Oi=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromRightHandler)),ki=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromLeftHandler)),Di=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromBottomHandler)),Ei=wrapWithFireEvent(M,wrapWithFixedAnchor(resizeFromTopHandler)),cropFromLeftHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"right","center",i,s);getOriginalDimensions(n);const o=n.cropX||0,a=n.width||100,h=n.scaleX||1,l=Math.max(Mi,Math.abs(r.x)),c=o+a,d=undefined;if(l<=c*h){const t=l/h,e=c-t;e>=0?(n.cropX=e,n.width=t):(n.cropX=0,n.width=c)}else{n.cropX=0,n.width=c;const t=l/n.width;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},cropFromBottomHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"center","top",i,s),o=getOriginalDimensions(n),a=n.cropY||0,h=n.scaleY||1,l=(o.height-a)*h,c=Math.max(Mi,r.y);if(c<=l)n.height=c/h;else{n.height=o.height-a;const t=c/n.height;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},cropFromTopHandler=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,"center","bottom",i,s);getOriginalDimensions(n);const o=n.cropY||0,a=n.height||100,h=n.scaleY||1,l=Math.max(Mi,Math.abs(r.y)),c=o+a,d=undefined;if(l<=c*h){const t=l/h,e=c-t;e>=0?(n.cropY=e,n.height=t):(n.cropY=0,n.height=c)}else{n.cropY=0,n.height=c;const t=l/n.height;n.scaleX=t,n.scaleY=t}return n.setCoords(),!0},createCornerCropHandler=(t,e)=>{const i="left"===t?cropFromLeftHandler:cropFromRightHandler,s="top"===e?cropFromTopHandler:cropFromBottomHandler;return(t,e,n,r)=>{const o=i(t,e,n,r),a=s(t,e,n,r);return o||a}},Ai=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromRightHandler)),Fi=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromLeftHandler)),Li=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromBottomHandler)),ji=wrapWithFireEvent(M,wrapWithFixedAnchor(cropFromTopHandler)),Ii=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("left","top"))),Bi=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("right","top"))),Ri=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("left","bottom"))),Wi=wrapWithFireEvent(M,wrapWithFixedAnchor(createCornerCropHandler("right","bottom"))),createImageCropControls=()=>({ml:new Control({x:-.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:ki,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mr:new Control({x:.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Oi,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mb:new Control({x:0,y:.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Di,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6}),mt:new Control({x:0,y:-.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Ei,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6}),tl:new Control({x:-.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),tr:new Control({x:.5,y:-.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),bl:new Control({x:-.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),br:new Control({x:.5,y:.5,cursorStyleHandler:scaleCursorStyleHandler,actionHandler:Ht}),mtr:new Control({x:0,y:-.5,actionHandler:Rt,cursorStyleHandler:rotationStyleHandler,offsetY:-40,withConnection:!0,actionName:T})}),createImageCropModeControls=()=>({ml:new Control({x:-.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Fi,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mr:new Control({x:.5,y:0,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Ai,actionName:M,render:renderHorizontalPillControl,sizeX:6,sizeY:20}),mb:new Control({x:0,y:.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:Li,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6}),mt:new Control({x:0,y:-.5,cursorStyleHandler:scaleSkewCursorStyleHandler,actionHandler:ji,actionName:M,render:renderVerticalPillControl,sizeX:20,sizeY:6})});class Canvas2dFilterBackend{constructor(){_defineProperty(this,"resources",{})}applyFilters(t,e,i,s,n){const r=n.getContext("2d",{willReadFrequently:!0,desynchronized:!0});if(!r)return;r.drawImage(e,0,0,i,s);const o=undefined,a=undefined,h={sourceWidth:i,sourceHeight:s,imageData:r.getImageData(0,0,i,s),originalEl:e,originalImageData:r.getImageData(0,0,i,s),canvasEl:n,ctx:r,filterBackend:this};t.forEach(t=>{t.applyTo(h)});const{imageData:l}=h;return l.width===i&&l.height===s||(n.width=l.width,n.height=l.height),r.putImageData(l,0,0),h}}class WebGLFilterBackend{constructor(){let{tileSize:t=e.textureSize}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_defineProperty(this,"aPosition",new Float32Array([0,0,0,1,1,0,1,1])),_defineProperty(this,"resources",{}),this.tileSize=t,this.setupGLContext(t,t),this.captureGPUInfo()}setupGLContext(t,e){this.dispose(),this.createWebGLCanvas(t,e)}createWebGLCanvas(t,e){const i=createCanvasElementFor({width:t,height:e}),s={alpha:!0,premultipliedAlpha:!1,depth:!1,stencil:!1,antialias:!1},n=i.getContext("webgl",s);n&&(n.clearColor(0,0,0,0),this.canvas=i,this.gl=n)}applyFilters(t,e,i,s,n,r){const o=this.gl,a=n.getContext("2d");if(!o||!a)return;let h;r&&(h=this.getCachedTexture(r,e));const l={originalWidth:e.width||e.naturalWidth||0,originalHeight:e.height||e.naturalHeight||0,sourceWidth:i,sourceHeight:s,destinationWidth:i,destinationHeight:s,context:o,sourceTexture:this.createTexture(o,i,s,h?void 0:e),targetTexture:this.createTexture(o,i,s),originalTexture:h||this.createTexture(o,i,s,h?void 0:e),passes:t.length,webgl:!0,aPosition:this.aPosition,programCache:this.programCache,pass:0,filterBackend:this,targetCanvas:n},c=o.createFramebuffer();return o.bindFramebuffer(o.FRAMEBUFFER,c),t.forEach(t=>{t&&t.applyTo(l)}),resizeCanvasIfNeeded(l),this.copyGLTo2D(o,l),o.bindTexture(o.TEXTURE_2D,null),o.deleteTexture(l.sourceTexture),o.deleteTexture(l.targetTexture),o.deleteFramebuffer(c),a.setTransform(1,0,0,1,0,0),l}dispose(){this.canvas&&(this.canvas=null,this.gl=null),this.clearWebGLCaches()}clearWebGLCaches(){this.programCache={},this.textureCache={}}createTexture(t,e,i,s,n){const{NEAREST:r,TEXTURE_2D:o,RGBA:a,UNSIGNED_BYTE:h,CLAMP_TO_EDGE:l,TEXTURE_MAG_FILTER:c,TEXTURE_MIN_FILTER:d,TEXTURE_WRAP_S:u,TEXTURE_WRAP_T:g}=t,f=t.createTexture();return t.bindTexture(o,f),t.texParameteri(o,c,n||r),t.texParameteri(o,d,n||r),t.texParameteri(o,u,l),t.texParameteri(o,g,l),s?t.texImage2D(o,0,a,a,h,s):t.texImage2D(o,0,a,e,i,0,a,h,null),f}getCachedTexture(t,e,i){const{textureCache:s}=this;if(s[t])return s[t];{const n=this.createTexture(this.gl,e.width,e.height,e,i);return n&&(s[t]=n),n}}evictCachesForKey(t){this.textureCache[t]&&(this.gl.deleteTexture(this.textureCache[t]),delete this.textureCache[t])}copyGLTo2D(t,e){const i=t.canvas,s=e.targetCanvas,n=s.getContext("2d");if(!n)return;n.translate(0,s.height),n.scale(1,-1);const r=i.height-s.height;n.drawImage(i,0,r,s.width,s.height,0,0,s.width,s.height)}copyGLTo2DPutImageData(t,e){const i=undefined,s=e.targetCanvas.getContext("2d"),n=e.destinationWidth,r=e.destinationHeight,o=n*r*4;if(!s)return;const a=new Uint8Array(this.imageBuffer,0,o),h=new Uint8ClampedArray(this.imageBuffer,0,o);t.readPixels(0,0,n,r,t.RGBA,t.UNSIGNED_BYTE,a);const l=new ImageData(h,n,r);s.putImageData(l,0,0)}captureGPUInfo(){if(this.gpuInfo)return this.gpuInfo;const t=this.gl,e={renderer:"",vendor:""};if(!t)return e;const i=t.getExtension("WEBGL_debug_renderer_info");if(i){const s=t.getParameter(i.UNMASKED_RENDERER_WEBGL),n=t.getParameter(i.UNMASKED_VENDOR_WEBGL);s&&(e.renderer=s.toLowerCase()),n&&(e.vendor=n.toLowerCase())}return this.gpuInfo=e,e}}function resizeCanvasIfNeeded(t){const e=t.targetCanvas,i=e.width,s=e.height,n=t.destinationWidth,r=t.destinationHeight;i===n&&s===r||(e.width=n,e.height=r)}let Hi;function initFilterBackend(){const{WebGLProbe:t}=getEnv();return t.queryWebGL(createCanvasElement()),e.enableGLFiltering&&t.isSupported(e.textureSize)?new WebGLFilterBackend({tileSize:e.textureSize}):new Canvas2dFilterBackend}function getFilterBackend(){let t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return!Hi&&t&&(Hi=initFilterBackend()),Hi}function setFilterBackend(t){Hi=t}const Xi={strokeWidth:0,srcFromAttribute:!1,minimumScaleTrigger:.5,cropX:0,cropY:0,imageSmoothing:!0,cropMode:!1},$i=["cropX","cropY"];class FabricImage extends FabricObject{static getDefaults(){return{...super.getDefaults(),...FabricImage.ownDefaults}}static createControls(){return{controls:createImageCropControls()}}enterCropMode(){var t;this.cropMode||(this.cropMode=!0,this._normalControls={...this.controls},this.controls=createImageCropModeControls(),this.dirty=!0,this._cropModeDragActive=!1,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}exitCropMode(){var t;this.cropMode&&(this.cropMode=!1,this._normalControls?(this.controls=this._normalControls,this._normalControls=void 0):this.controls=createImageCropControls(),this.dirty=!0,this.setCoords(),null===(t=this.canvas)||void 0===t||t.requestRenderAll())}toggleCropMode(){this.cropMode?this.exitCropMode():this.enterCropMode()}set(t,e){if(this.cropMode&&this.isMoving&&"string"==typeof t){if("left"===t&&"number"==typeof e)return this._setCropModePosition("left",e);if("top"===t&&"number"==typeof e)return this._setCropModePosition("top",e)}return super.set(t,e)}_setCropModePosition(t,e){const i=this._element;if(!i)return super.set(t,e);this._cropModeDragActive||(this._cropModeDragActive=!0,this._cropModeOriginalLeft=this.left,this._cropModeOriginalTop=this.top,this._cropModeOriginalCropX=this.cropX,this._cropModeOriginalCropY=this.cropY);const s="left"===t?this.scaleX||1:this.scaleY||1,n="left"===t?this._cropModeOriginalLeft:this._cropModeOriginalTop,r="left"===t?this._cropModeOriginalCropX:this._cropModeOriginalCropY,o="left"===t?"cropX":"cropY",a="left"===t?"width":"height",h="left"===t?i.naturalWidth||i.width:i.naturalHeight||i.height;if(void 0===n||void 0===r)return super.set(t,e);const l=undefined,c=(e-n)/Math.abs(s),d=this[a]||h;let u=r+c;const g=Math.max(0,h-d);return u=Math.max(0,Math.min(g,u)),super.set(o,u),super.set(t,n),this.dirty=!0,this}_onMouseUp(){this.cropMode&&(this._cropModeDragActive=!1)}constructor(t,e){super(),_defineProperty(this,"_lastScaleX",1),_defineProperty(this,"_lastScaleY",1),_defineProperty(this,"_filterScalingX",1),_defineProperty(this,"_filterScalingY",1),_defineProperty(this,"_normalControls",void 0),_defineProperty(this,"_cropModeOriginalLeft",void 0),_defineProperty(this,"_cropModeOriginalTop",void 0),_defineProperty(this,"_cropModeOriginalCropX",void 0),_defineProperty(this,"_cropModeOriginalCropY",void 0),_defineProperty(this,"_cropModeDragActive",void 0),this.filters=[],Object.assign(this,FabricImage.ownDefaults),this.setOptions(e),this.cacheKey=`texture${uid()}`,this.setElement("string"==typeof t?(this.canvas&&getDocumentFromElement(this.canvas.getElement())||getFabricDocument()).getElementById(t):t,e)}getElement(){return this._element}setElement(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this.removeTexture(this.cacheKey),this.removeTexture(`${this.cacheKey}_filtered`),this._element=t,this._originalElement=t,this._setWidthHeight(e),0!==this.filters.length&&this.applyFilters(),this.resizeFilter&&this.applyResizeFilters()}removeTexture(t){const e=getFilterBackend(!1);e instanceof WebGLFilterBackend&&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&&getEnv().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||0===this.strokeWidth)return;const e=this.width/2,i=this.height/2;t.beginPath(),t.moveTo(-e,-i),t.lineTo(e,-i),t.lineTo(e,i),t.lineTo(-e,i),t.lineTo(-e,-i),t.closePath()}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];const e=[];return this.filters.forEach(t=>{t&&e.push(t.toObject())}),{...super.toObject([...$i,...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,i=-this.width/2,s=-this.height/2;let n=[],r=[],o="",a="";if(!e)return[];if(this.hasCrop()){const t=uid();n.push('<clipPath id="imageCrop_'+t+'">\n','\t<rect x="'+i+'" y="'+s+'" width="'+this.width+'" height="'+this.height+'" />\n',"</clipPath>\n"),o=' clip-path="url(#imageCrop_'+t+')" '}if(this.imageSmoothing||(a=' image-rendering="optimizeSpeed"'),t.push("\t<image ","COMMON_PARTS",`xlink:href="${this.getSvgSrc(!0)}" x="${i-this.cropX}" y="${s-this.cropY}" width="${e.width||e.naturalWidth}" height="${e.height||e.naturalHeight}"${a}${o}></image>\n`),this.stroke||this.strokeDashArray){const t=this.fill;this.fill=null,r=[`\t<rect x="${i}" y="${s}" width="${this.width}" height="${this.height}" style="${this.getSvgStyles()}" />\n`],this.fill=t}return n=this.paintFirst!==I?n.concat(r,t):n.concat(t,r),n}getSrc(t){const e=t?this._element:this._originalElement;return e?e.toDataURL?e.toDataURL():this.srcFromAttribute?e.getAttribute("src")||"":e.src:this.src||""}getSvgSrc(t){return this.getSrc(t)}setSrc(t){let{crossOrigin:e,signal:i}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return loadImage(t,{crossOrigin:e,signal:i}).then(t=>{void 0!==e&&this.set({crossOrigin:e}),this.setElement(t)})}toString(){return`#<Image: { src: "${this.getSrc()}" }>`}applyResizeFilters(){const t=this.resizeFilter,e=this.minimumScaleTrigger,i=this.getTotalObjectScaling(),s=i.x,n=i.y,r=this._filteredEl||this._originalElement;if(this.group&&this.set("dirty",!0),!t||s>e&&n>e)return this._element=r,this._filterScalingX=1,this._filterScalingY=1,this._lastScaleX=s,void(this._lastScaleY=n);const o=createCanvasElementFor(r),{width:a,height:h}=r;this._element=o,this._lastScaleX=t.scaleX=s,this._lastScaleY=t.scaleY=n,getFilterBackend().applyFilters([t],r,a,h,this._element),this._filterScalingX=o.width/this._originalElement.width,this._filterScalingY=o.height/this._originalElement.height}applyFilters(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.filters||[];if(t=t.filter(t=>t&&!t.isNeutralState()),this.set("dirty",!0),this.removeTexture(`${this.cacheKey}_filtered`),0===t.length)return this._element=this._originalElement,this._filteredEl=void 0,this._filterScalingX=1,void(this._filterScalingY=1);const e=this._originalElement,i=e.naturalWidth||e.width,s=e.naturalHeight||e.height;if(this._element===this._originalElement){const t=createCanvasElementFor({width:i,height:s});this._element=t,this._filteredEl=t}else this._filteredEl&&(this._element=this._filteredEl,this._filteredEl.getContext("2d").clearRect(0,0,i,s),this._lastScaleX=1,this._lastScaleY=1);getFilterBackend().applyFilters(t,this._originalElement,i,s,this._element,this.cacheKey),this._originalElement.width===this._element.width&&this._originalElement.height===this._element.height||(this._filterScalingX=this._element.width/this._originalElement.width,this._filterScalingY=this._element.height/this._originalElement.height)}_render(t){t.imageSmoothingEnabled=this.imageSmoothing,!0!==this.isMoving&&this.resizeFilter&&this._needsResize()&&this.applyResizeFilters(),this._stroke(t),this._renderPaintInOrder(t)}drawCacheOnCanvas(t){t.imageSmoothingEnabled=this.imageSmoothing,super.drawCacheOnCanvas(t)}shouldCache(){return!this.cropMode&&this.needsItsOwnCache()}_renderFill(t){const e=this._element;if(!e)return;const i=this._filterScalingX,s=this._filterScalingY,n=this.width,r=this.height,o=Math.max(this.cropX,0),a=Math.max(this.cropY,0),h=e.naturalWidth||e.width,l=e.naturalHeight||e.height,c=o*i,d=a*s,u=Math.min(n*i,h-c),g=Math.min(r*s,l-d),f=-n/2,p=-r/2,m=Math.min(n,h/i-o),y=Math.min(r,l/s-a);this.cropMode?this._renderCropMode(t,e,h,l,i,s):e&&t.drawImage(e,c,d,u,g,f,p,m,y)}_renderCropMode(t,e,i,s,n,r){const o=this.width,a=this.height,h=Math.max(this.cropX,0),l=Math.max(this.cropY,0),c=i/n,d=s/r,u=-o/2-h,g=-a/2-l;t.save(),t.globalAlpha=.3,t.drawImage(e,0,0,i,s,u,g,c,d),t.restore(),t.save(),t.fillStyle="rgba(0, 0, 0, 0.5)",h>0&&t.fillRect(u,g,h,d);const f=-o/2+o,p=c-h-o;p>0&&t.fillRect(f,g,p,d),l>0&&t.fillRect(-o/2,g,o,l);const m=-a/2+a,y=d-l-a;y>0&&t.fillRect(-o/2,m,o,y),t.restore();const x=h*n,v=l*r,_=Math.min(o*n,i-x),C=Math.min(a*r,s-v),b=-o/2,S=-a/2,w=Math.min(o,i/n-h),T=Math.min(a,s/r-l);t.drawImage(e,x,v,_,C,b,S,w,T),t.save(),t.strokeStyle="#fff",t.lineWidth=2,t.strokeRect(-o/2,-a/2,o,a),t.restore()}_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&&void 0!==arguments[0]?arguments[0]:{};const i=this.getOriginalSize();this.width=t||i.width,this.height=e||i.height}parsePreserveAspectRatioAttribute(){const t=parsePreserveAspectRatioAttribute(this.preserveAspectRatio||""),e=this.width,i=this.height,s={width:e,height:i};let n=this._element.width,r=this._element.height,o=1,a=1,h=0,l=0,c=0,d=0,u;return!t||t.alignX===_&&t.alignY===_?(o=e/n,a=i/r):("meet"===t.meetOrSlice&&(o=a=findScaleToFit(this._element,s),u=(e-n*o)/2,"Min"===t.alignX&&(h=-u),"Max"===t.alignX&&(h=u),u=(i-r*a)/2,"Min"===t.alignY&&(l=-u),"Max"===t.alignY&&(l=u)),"slice"===t.meetOrSlice&&(o=a=findScaleToCover(this._element,s),u=n-e/o,"Mid"===t.alignX&&(c=u/2),"Max"===t.alignX&&(c=u),u=r-i/a,"Mid"===t.alignY&&(d=u/2),"Max"===t.alignY&&(d=u),n=e/o,r=i/a)),{width:n,height:r,scaleX:o,scaleY:a,offsetLeft:h,offsetTop:l,cropX:c,cropY:d}}static fromObject(t,e){let{filters:i,resizeFilter:s,src:n,crossOrigin:r,type:o,...a}=t;return Promise.all([loadImage(n,{...e,crossOrigin:r}),i&&enlivenObjects(i,e),s?enlivenObjects([s],e):[],enlivenObjectEnlivables(a,e)]).then(t=>{let[e,i=[],[s],r={}]=t;return new this(e,{...a,src:n,filters:i,resizeFilter:s,...r})})}static fromURL(t){let{crossOrigin:e=null,signal:i}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},s=arguments.length>2?arguments[2]:void 0;return loadImage(t,{crossOrigin:e,signal:i}).then(t=>new this(t,s))}static async fromElement(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2?arguments[2]:void 0;const s=parseAttributes(t,this.ATTRIBUTE_NAMES,i);return this.fromURL(s["xlink:href"]||s.href,e,s).catch(t=>(log("log","Unable to parse Image",t),null))}}_defineProperty(FabricImage,"type","Image"),_defineProperty(FabricImage,"cacheProperties",[...Ot,...$i]),_defineProperty(FabricImage,"ownDefaults",Xi),_defineProperty(FabricImage,"ATTRIBUTE_NAMES",[...se,"x","y","width","height","preserveAspectRatio","xlink:href","href","crossOrigin","image-rendering"]),X.setClass(FabricImage),X.setSVGClass(FabricImage);class FrameLayout extends LayoutStrategy{shouldPerformLayout(t){let{type:e}=t;return e===Ce}calcBoundingBox(t,e){var i,s,n,r;const{type:o,target:a}=e,h=null!==(i=null!==(s=a.frameWidth)&&void 0!==s?s:a.width)&&void 0!==i?i:200,l=null!==(n=null!==(r=a.frameHeight)&&void 0!==r?r:a.height)&&void 0!==n?n:200,c=new Point(h,l);if(o===Ce){const t=undefined;return{center:new Point(0,0),size:c,relativeCorrection:new Point(0,0)}}const d=undefined;return{center:a.getRelativeCenterPoint(),size:c}}getInitialSize(t,e){var i,s,n,r;const{target:o}=t,a=null!==(i=null!==(s=o.frameWidth)&&void 0!==s?s:o.width)&&void 0!==i?i:200,h=null!==(n=null!==(r=o.frameHeight)&&void 0!==r?r:o.height)&&void 0!==n?n:200;return new Point(a,h)}}_defineProperty(FrameLayout,"type","frame-layout"),X.setClass(FrameLayout);const zi={frameWidth:200,frameHeight:200,frameShape:"rect",frameBorderRadius:0,isEditMode:!1,placeholderText:"Drop image here",placeholderColor:"#d0d0d0",frameMeta:{contentScale:1,contentOffsetX:0,contentOffsetY:0}};class Frame extends Group{static getDefaults(){return{...super.getDefaults(),...Frame.ownDefaults}}constructor(){var t,e,i;let s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=new LayoutManager(new FrameLayout);super(s,{...n,layoutManager:r}),_defineProperty(this,"_contentImage",null),_defineProperty(this,"_placeholder",null),_defineProperty(this,"_editModeObjectCaching",void 0),_defineProperty(this,"_editModeOriginalControls",void 0),_defineProperty(this,"_boundConstrainMove",void 0),_defineProperty(this,"_boundConstrainScale",void 0),_defineProperty(this,"_editModeClipPath",void 0),_defineProperty(this,"_contentExpandMode",!1),Object.assign(this,Frame.ownDefaults),this.setOptions(n);const o=zi.frameMeta||{};this.frameMeta={contentScale:null!==(t=o.contentScale)&&void 0!==t?t:1,contentOffsetX:null!==(e=o.contentOffsetX)&&void 0!==e?e:0,contentOffsetY:null!==(i=o.contentOffsetY)&&void 0!==i?i:0,...n.frameMeta},this.set({width:this.frameWidth,height:this.frameHeight}),this._updateClipPath(),0===s.length&&this._createPlaceholder(),this._setupResizeControls()}_setupResizeControls(){const changeFrameWidth=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,e.originX,e.originY,i,s),o=n.frameWidth,a=Math.max(20,Math.abs(r.x));return!(Math.abs(o-a)<1)&&(n.frameWidth=a,n.width=a,n._updateClipPath(),n._adjustContentAfterResize(),!0)},changeFrameHeight=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,e.originX,e.originY,i,s),o=n.frameHeight,a=Math.max(20,Math.abs(r.y));return!(Math.abs(o-a)<1)&&(n.frameHeight=a,n.height=a,n._updateClipPath(),n._adjustContentAfterResize(),!0)},changeFrameSize=(t,e,i,s)=>{const n=e.target,r=getLocalPoint(e,e.originX,e.originY,i,s),o=n.frameWidth,a=n.frameHeight,h=Math.max(20,Math.abs(r.x)),l=Math.max(20,Math.abs(r.y));return!(Math.abs(o-h)<1&&Math.abs(a-l)<1)&&(n.frameWidth=h,n.frameHeight=l,n.width=h,n.height=l,n._updateClipPath(),n._adjustContentAfterResize(),!0)},t=wrapWithFireEvent(M,wrapWithFixedAnchor(changeFrameSize)),e=wrapWithFireEvent(M,wrapWithFixedAnchor(changeFrameWidth)),i=wrapWithFireEvent(M,wrapWithFixedAnchor(changeFrameHeight));if(!this.controls)return void console.warn("Frame: controls not initialized yet");const s=undefined;["tl","tr","bl","br"].forEach(e=>{const i=this.controls[e];i&&(this.controls[e]=new Control({x:i.x,y:i.y,cursorStyleHandler:i.cursorStyleHandler,actionHandler:t,actionName:"resizing"}))});const n=undefined;["ml","mr"].forEach(t=>{const i=this.controls[t];i&&(this.controls[t]=new Control({x:i.x,y:i.y,cursorStyleHandler:i.cursorStyleHandler,actionHandler:e,actionName:"resizing",render:i.render,sizeX:i.sizeX,sizeY:i.sizeY}))});const r=undefined;["mt","mb"].forEach(t=>{const e=this.controls[t];e&&(this.controls[t]=new Control({x:e.x,y:e.y,cursorStyleHandler:e.cursorStyleHandler,actionHandler:i,actionName:"resizing",render:e.render,sizeX:e.sizeX,sizeY:e.sizeY}))})}_adjustContentAfterResize(){if(this._placeholder&&this._placeholder.set({width:this.frameWidth,height:this.frameHeight}),this._contentImage){var t,e,i,s,n,r,o;const a=this._contentImage,h=null!==(t=null!==(e=this.frameMeta.originalWidth)&&void 0!==e?e:a.width)&&void 0!==t?t:100,l=null!==(i=null!==(s=this.frameMeta.originalHeight)&&void 0!==s?s:a.height)&&void 0!==i?i:100;let c=null!==(n=a.scaleX)&&void 0!==n?n:1,d=null!==(r=a.left)&&void 0!==r?r:0,u=null!==(o=a.top)&&void 0!==o?o:0;const g=this._calculateCoverScale(h,l);if(c<g){const t=g/c;d*=t,u*=t,c=g,a.set({scaleX:c,scaleY:c}),this.frameMeta={...this.frameMeta,contentScale:c}}const f=h*c/2,p=l*c/2,m=this.frameWidth/2,y=this.frameHeight/2,x=Math.max(0,f-m),v=Math.max(0,p-y),_=Math.abs(d)>x,C=Math.abs(u)>v;_&&(d=Math.max(-x,Math.min(x,d))),C&&(u=Math.max(-v,Math.min(v,u))),(_||C)&&(a.set({left:d,top:u}),this.frameMeta={...this.frameMeta,contentOffsetX:d,contentOffsetY:u}),a.setCoords()}this.setCoords()}_updateClipPath(){let t;switch(this.frameShape){case"circle":{const e=Math.min(this.frameWidth,this.frameHeight)/2;t=new Circle({radius:e,originX:"center",originY:"center",left:0,top:0});break}case"rounded-rect":t=new Rect({width:this.frameWidth,height:this.frameHeight,rx:this.frameBorderRadius,ry:this.frameBorderRadius,originX:"center",originY:"center",left:0,top:0});break;case"custom":if(this.frameCustomPath){t=new Path(this.frameCustomPath,{originX:"center",originY:"center",left:0,top:0});const e=t.getBoundingRect(),i=this.frameWidth/e.width,s=this.frameHeight/e.height;t.set({scaleX:i,scaleY:s})}else t=new Rect({width:this.frameWidth,height:this.frameHeight,originX:"center",originY:"center",left:0,top:0});break;case"rect":default:t=new Rect({width:this.frameWidth,height:this.frameHeight,originX:"center",originY:"center",left:0,top:0});break}this.clipPath=t,this.set("dirty",!0)}_createPlaceholder(){this._placeholder&&(super.remove(this._placeholder),this._placeholder=null);const t=new Rect({width:this.frameWidth,height:this.frameHeight,fill:this.placeholderColor,originX:"center",originY:"center",left:0,top:0,selectable:!1,evented:!1});this._placeholder=t,super.add(t),this._restoreFixedDimensions()}_removePlaceholder(){this._placeholder&&(super.remove(this._placeholder),this._placeholder=null)}_restoreFixedDimensions(){this.set({width:this.frameWidth,height:this.frameHeight})}async setImage(t){var e,i;let s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const{crossOrigin:n="anonymous",signal:r}=s,o=await FabricImage.fromURL(t,{crossOrigin:n,signal:r}),a=null!==(e=o.width)&&void 0!==e?e:100,h=null!==(i=o.height)&&void 0!==i?i:100,l=this._calculateCoverScale(a,h);o.set({scaleX:l,scaleY:l,originX:"center",originY:"center",left:0,top:0,selectable:!1,evented:!1}),this._clearContent(),this._contentImage=o,super.add(o),this._contentImage.set({left:0,top:0}),this.frameMeta={...this.frameMeta,contentScale:l,contentOffsetX:0,contentOffsetY:0,imageSrc:t,originalWidth:a,originalHeight:h},this._restoreFixedDimensions(),this.setCoords(),this._contentImage.setCoords(),this.set("dirty",!0)}setImageObject(t){var e,i;const s=null!==(e=t.width)&&void 0!==e?e:100,n=null!==(i=t.height)&&void 0!==i?i:100,r=this._calculateCoverScale(s,n);t.set({scaleX:r,scaleY:r,originX:"center",originY:"center",left:0,top:0,selectable:!1,evented:!1}),this._clearContent(),this._contentImage=t,super.add(t),this.frameMeta={...this.frameMeta,contentScale:r,contentOffsetX:0,contentOffsetY:0,imageSrc:t.getSrc(),originalWidth:s,originalHeight:n},this._restoreFixedDimensions(),this.set("dirty",!0)}_calculateCoverScale(t,e){const i=this.frameWidth/t,s=this.frameHeight/e;return Math.max(i,s)}_clearContent(){this._removePlaceholder(),this._contentImage&&(super.remove(this._contentImage),this._contentImage=null);const t=undefined;this.getObjects().forEach(t=>super.remove(t))}clearContent(){this._clearContent(),this._createPlaceholder(),this.frameMeta={contentScale:1,contentOffsetX:0,contentOffsetY:0},this.set("dirty",!0)}hasContent(){return null!==this._contentImage}getContentImage(){return this._contentImage}enterEditMode(){var t,e,i,s;if(!this._contentImage||this.isEditMode)return;this.isEditMode=!0,this._editModeObjectCaching=this.objectCaching,this.objectCaching=!1,this.dirty=!0,this._cacheCanvas&&(this._cacheCanvas=null,this._cacheContext=null),this.subTargetCheck=!0,this.interactive=!0;const n=null!==(t=null!==(e=this.frameMeta.originalWidth)&&void 0!==e?e:this._contentImage.width)&&void 0!==t?t:100,r=null!==(i=null!==(s=this.frameMeta.originalHeight)&&void 0!==s?s:this._contentImage.height)&&void 0!==i?i:100,o=this._calculateCoverScale(n,r);this._contentImage.set({selectable:!0,evented:!0,hasControls:!0,hasBorders:!0,minScaleLimit:o,lockScalingFlip:!0,lockUniScaling:!1,objectCaching:!1}),this._contentImage.dirty=!0,this._editModeOriginalControls=this._contentImage.controls,this._contentImage.controls={tl:this._contentImage.controls.tl,tr:this._contentImage.controls.tr,bl:this._contentImage.controls.bl,br:this._contentImage.controls.br},this.clipPath&&(this._editModeClipPath=this.clipPath,this.clipPath=void 0),this._setupEditModeConstraints(),this.set("dirty",!0),this.canvas&&requestAnimationFrame(()=>{this._contentImage&&this.canvas&&(this.canvas.setActiveObject(this._contentImage),this.canvas.requestRenderAll())}),this.fire("frame:editmode:enter",{target:this})}_setupEditModeConstraints(){if(!this._contentImage||!this.canvas)return;const t=this,e=this._contentImage;this._boundConstrainMove=i=>{var s,n,r,o,a,h,l,c;if(i.target!==e||!t.isEditMode)return;const d=null!==(s=null!==(n=t.frameMeta.originalWidth)&&void 0!==n?n:e.width)&&void 0!==s?s:100,u=null!==(r=null!==(o=t.frameMeta.originalHeight)&&void 0!==o?o:e.height)&&void 0!==r?r:100,g=undefined,f=undefined,p=d*(null!==(a=e.scaleX)&&void 0!==a?a:1)/2,m=u*(null!==(h=e.scaleY)&&void 0!==h?h:1)/2,y=t.frameWidth/2,x=t.frameHeight/2,v=Math.max(0,p-y),_=Math.max(0,m-x);let C=null!==(l=e.left)&&void 0!==l?l:0,b=null!==(c=e.top)&&void 0!==c?c:0;C=Math.max(-v,Math.min(v,C)),b=Math.max(-_,Math.min(_,b)),e.set({left:C,top:b})},this._boundConstrainScale=i=>{var s,n,r,o,a,h,l;if(i.target!==e||!t.isEditMode)return;const c=null!==(s=null!==(n=t.frameMeta.originalWidth)&&void 0!==n?n:e.width)&&void 0!==s?s:100,d=null!==(r=null!==(o=t.frameMeta.originalHeight)&&void 0!==o?o:e.height)&&void 0!==r?r:100,u=t.frameWidth/c,g=t.frameHeight/d;let f=null!==(a=e.scaleX)&&void 0!==a?a:1,p=null!==(h=e.scaleY)&&void 0!==h?h:1;f=Math.max(u,f),p=Math.max(g,p),e.set({scaleX:f,scaleY:p}),null===(l=t._boundConstrainMove)||void 0===l||l.call(t,i)},this.canvas.on("object:moving",this._boundConstrainMove),this.canvas.on("object:scaling",this._boundConstrainScale)}_removeEditModeConstraints(){this.canvas&&(this._boundConstrainMove&&(this.canvas.off("object:moving",this._boundConstrainMove),this._boundConstrainMove=void 0),this._boundConstrainScale&&(this.canvas.off("object:scaling",this._boundConstrainScale),this._boundConstrainScale=void 0))}shouldCache(){return this.isEditMode?(this.ownCaching=!1,!1):super.shouldCache()}drawObject(t,e,i){this._renderBackground(t);for(let e=0;e<this._objects.length;e++){const i=this._objects[e];i.group===this&&i.render(t)}this.isEditMode||this._drawClipPath(t,this.clipPath,i)}render(t){super.render(t),this.isEditMode&&this._editModeClipPath&&this._renderEditModeOverlay(t,!1)}_renderEditModeOverlay(t){let e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];t.save();const i=this.calcTransformMatrix();if(t.transform(i[0],i[1],i[2],i[3],i[4],i[5]),!e){t.beginPath();const e=2e3;if(t.rect(-e,-e,2*e,2*e),"circle"===this.frameShape){const e=Math.min(this.frameWidth,this.frameHeight)/2;t.moveTo(e,0),t.arc(0,0,e,0,2*Math.PI,!0)}else if("rounded-rect"===this.frameShape){const e=this.frameWidth/2,i=this.frameHeight/2,s=Math.min(this.frameBorderRadius,e,i);t.moveTo(e,i-s),t.arcTo(e,-i,e-s,-i,s),t.arcTo(-e,-i,-e,-i+s,s),t.arcTo(-e,i,-e+s,i,s),t.arcTo(e,i,e,i-s,s),t.closePath()}else{const e=this.frameWidth/2,i=this.frameHeight/2;t.moveTo(e,-i),t.lineTo(-e,-i),t.lineTo(-e,i),t.lineTo(e,i),t.closePath()}t.fillStyle="rgba(0, 0, 0, 0.5)",t.fill("evenodd")}if(t.beginPath(),"circle"===this.frameShape){const e=Math.min(this.frameWidth,this.frameHeight)/2;t.arc(0,0,e,0,2*Math.PI)}else if("rounded-rect"===this.frameShape){const e=this.frameWidth/2,i=this.frameHeight/2,s=Math.min(this.frameBorderRadius,e,i);t.moveTo(e-s,-i),t.arcTo(e,-i,e,-i+s,s),t.arcTo(e,i,e-s,i,s),t.arcTo(-e,i,-e,i-s,s),t.arcTo(-e,-i,-e+s,-i,s),t.closePath()}else{const e=this.frameWidth/2,i=this.frameHeight/2;t.rect(-e,-i,this.frameWidth,this.frameHeight)}t.strokeStyle="rgba(255, 255, 255, 0.8)",t.lineWidth=2,t.stroke(),t.setLineDash([5,5]),t.strokeStyle="rgba(0, 150, 255, 0.8)",t.lineWidth=1,t.stroke(),t.restore()}exitEditMode(){var t,e,i,s,n,r,o,a;if(!this._contentImage||!this.isEditMode)return;this._contentExpandMode&&this.exitContentExpandMode(),this.isEditMode=!1,this._removeEditModeConstraints(),this.subTargetCheck=!1,this.interactive=!1;const h=null!==(t=this._contentImage.left)&&void 0!==t?t:0,l=null!==(e=this._contentImage.top)&&void 0!==e?e:0,c=null!==(i=this._contentImage.scaleX)&&void 0!==i?i:1,d=null!==(s=this._contentImage.scaleY)&&void 0!==s?s:1,u=undefined,g=undefined,f=(null!==(n=null!==(r=this.frameMeta.originalWidth)&&void 0!==r?r:this._contentImage.width)&&void 0!==n?n:100)*c/2,p=(null!==(o=null!==(a=this.frameMeta.originalHeight)&&void 0!==a?a:this._contentImage.height)&&void 0!==o?o:100)*d/2,m=this.frameWidth/2,y=this.frameHeight/2,x=Math.max(0,f-m),v=Math.max(0,p-y),_=Math.max(-x,Math.min(x,h)),C=Math.max(-v,Math.min(v,l));this._contentImage.set({left:_,top:C}),this.frameMeta={...this.frameMeta,contentOffsetX:_,contentOffsetY:C,contentScaleX:c,contentScaleY:d},this._editModeOriginalControls&&(this._contentImage.controls=this._editModeOriginalControls,this._editModeOriginalControls=void 0),this._contentImage.set({selectable:!1,evented:!1,hasControls:!1,hasBorders:!1,lockUniScaling:!1,centeredScaling:!1,objectCaching:!0}),this._editModeClipPath&&(this.clipPath=this._editModeClipPath,this._editModeClipPath=void 0),void 0!==this._editModeObjectCaching&&(this.objectCaching=this._editModeObjectCaching,this._editModeObjectCaching=void 0),this.set("dirty",!0),this.canvas&&(this.canvas.setActiveObject(this),this.canvas.renderAll()),this.fire("frame:editmode:exit",{target:this})}toggleEditMode(){this.isEditMode?this.exitEditMode():this.enterEditMode()}enterContentExpandMode(){this._contentImage&&this.isEditMode?this._contentExpandMode||(this._contentExpandMode=!0,this._removeEditModeConstraints(),this._contentImage.enterExpandMode(),this.canvas&&this.canvas.requestRenderAll()):console.warn("Frame: Must be in edit mode with content to enter expand mode")}exitContentExpandMode(){this._contentImage&&this._contentExpandMode&&(this._contentExpandMode=!1,this._contentImage.exitExpandMode(),this.isEditMode&&this._setupEditModeConstraints(),this.canvas&&this.canvas.requestRenderAll())}toggleContentExpandMode(){this._contentExpandMode?this.exitContentExpandMode():this.enterContentExpandMode()}isContentExpandMode(){return this._contentExpandMode}getContentExpansion(){return this._contentImage?this._contentImage.getExpansion():null}setContentExpansion(t){this._contentImage&&this._contentImage.setExpansion(t)}resetContentExpansion(){this._contentImage&&this._contentImage.resetExpansion()}hasContentExpansion(){return!!this._contentImage&&this._contentImage.hasExpansion()}resizeFrame(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const{maintainAspect:s=!1}=i;if(s){const i=this.frameWidth/this.frameHeight,s=undefined;t/e>i?e=t/i:t=e*i}this.frameWidth=t,this.frameHeight=e,super.set({width:this.frameWidth,height:this.frameHeight}),this._updateClipPath(),this._adjustContentAfterResize(),this.set("dirty",!0),this.setCoords()}setFrameShape(t,e){this.frameShape=t,e&&(this.frameCustomPath=e),this._updateClipPath(),this.set("dirty",!0)}setBorderRadius(t){this.frameBorderRadius=t,"rounded-rect"===this.frameShape&&(this._updateClipPath(),this.set("dirty",!0))}add(){const t=super.add(...arguments);return this._restoreFixedDimensions(),t}remove(){const t=super.remove(...arguments);return this._restoreFixedDimensions(),t}insertAt(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),s=1;s<e;s++)i[s-1]=arguments[s];const n=super.insertAt(t,...i);return this._restoreFixedDimensions(),n}toObject(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return{...super.toObject(t),frameWidth:this.frameWidth,frameHeight:this.frameHeight,frameShape:this.frameShape,frameBorderRadius:this.frameBorderRadius,frameCustomPath:this.frameCustomPath,frameMeta:{...this.frameMeta},isEditMode:!1,placeholderText:this.placeholderText,placeholderColor:this.placeholderColor}}static fromObject(t,e){const{objects:i=[],layoutManager:s,frameWidth:n,frameHeight:r,frameShape:o,frameBorderRadius:a,frameCustomPath:h,frameMeta:l,placeholderText:c,placeholderColor:d,...u}=t;return Promise.all([enlivenObjects(i,e),enlivenObjectEnlivables(u,e)]).then(t=>{var e,i,s;let[g,f]=t;const p=new Frame([],{...u,...f,frameWidth:n,frameHeight:r,frameShape:o,frameBorderRadius:a,frameCustomPath:h,frameMeta:l?{contentScale:null!==(e=l.contentScale)&&void 0!==e?e:1,contentOffsetX:null!==(i=l.contentOffsetX)&&void 0!==i?i:0,contentOffsetY:null!==(s=l.contentOffsetY)&&void 0!==s?s:0,...l}:void 0,placeholderText:c,placeholderColor:d});return null!=l&&l.imageSrc&&p.setImage(l.imageSrc).then(()=>{var t,e,i,s;p._contentImage&&p._contentImage.set({left:null!==(t=l.contentOffsetX)&&void 0!==t?t:0,top:null!==(e=l.contentOffsetY)&&void 0!==e?e:0,scaleX:null!==(i=l.contentScale)&&void 0!==i?i:1,scaleY:null!==(s=l.contentScale)&&void 0!==s?s:1});p.set("dirty",!0)}).catch(t=>{console.warn("Failed to restore frame image:",t)}),p})}static createWithAspect(t){var e,i,s;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:200,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o,a;switch(t){case"16:9":o=n,a=n*(9/16);break;case"9:16":o=n*(9/16),a=n;break;case"4:5":o=.8*n,a=n;break;case"4:3":o=n,a=n*(3/4);break;case"3:4":o=n*(3/4),a=n;break;case"1:1":default:o=n,a=n;break}const h=zi.frameMeta||{};return new Frame([],{...r,frameWidth:o,frameHeight:a,frameMeta:{contentScale:null!==(e=h.contentScale)&&void 0!==e?e:1,contentOffsetX:null!==(i=h.contentOffsetX)&&void 0!==i?i:0,contentOffsetY:null!==(s=h.contentOffsetY)&&void 0!==s?s:0,aspect:t,...r.frameMeta}})}}_defineProperty(Frame,"type","Frame"),_defineProperty(Frame,"ownDefaults",zi),X.setClass(Frame),X.setClass(Frame,"frame");class ClipPathLayout extends LayoutStrategy{shouldPerformLayout(t){return!!t.target.clipPath&&super.shouldPerformLayout(t)}shouldLayoutClipPath(){return!1}calcLayoutResult(t,e){const{target:i}=t,{clipPath:s,group:n}=i;if(!s||!this.shouldPerformLayout(t))return;const{width:r,height:o}=makeBoundingBoxFromPoints(getObjectBounds(i,s)),a=new Point(r,o);if(s.absolutePositioned){const t=undefined;return{center:sendPointToPlane(s.getRelativeCenterPoint(),void 0,n?n.calcTransformMatrix():void 0),size:a}}{const n=s.getRelativeCenterPoint().transform(i.calcOwnMatrix(),!0);if(this.shouldPerformLayout(t)){const{center:i=new Point,correction:s=new Point}=this.calcBoundingBox(e,t)||{};return{center:i.add(n),correction:s.subtract(n),size:a}}return{center:i.getRelativeCenterPoint().add(n),size:a}}}}_defineProperty(ClipPathLayout,"type","clip-path"),X.setClass(ClipPathLayout);class FixedLayout extends LayoutStrategy{getInitialSize(t,e){let{target:i}=t,{size:s}=e;return new Point(i.width||s.x,i.height||s.y)}}_defineProperty(FixedLayout,"type","fixed"),X.setClass(FixedLayout);class ActiveSelectionLayoutManager extends LayoutManager{subscribeTargets(t){const e=t.target,i=undefined;t.targets.reduce((t,e)=>(e.parent&&t.add(e.parent),t),new Set).forEach(t=>{t.layoutManager.subscribeTargets({target:t,targets:[e]})})}unsubscribeTargets(t){const e=t.target,i=e.getObjects(),s=undefined;t.targets.reduce((t,e)=>(e.parent&&t.add(e.parent),t),new Set).forEach(t=>{!i.some(e=>e.parent===t)&&t.layoutManager.unsubscribeTargets({target:t,targets:[e]})})}}const Yi={multiSelectionStacking:"canvas-stacking"};class ActiveSelection extends Group{static getDefaults(){return{...super.getDefaults(),...ActiveSelection.ownDefaults}}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),Object.assign(this,ActiveSelection.ownDefaults),this.setOptions(e);const{left:i,top:s,layoutManager:n}=e;this.groupInit(t,{left:i,top:s,layoutManager:null!=n?n:new ActiveSelectionLayoutManager})}_shouldSetNestedCoords(){return!0}__objectSelectionMonitor(){}multiSelectAdd(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];"selection-order"===this.multiSelectionStacking?this.add(...e):e.forEach(t=>{const e=this._objects.findIndex(e=>e.isInFrontOf(t)),i=-1===e?this.size():e;this.insertAt(i,t)})}canEnterGroup(t){return this.getObjects().some(e=>e.isDescendantOf(t)||t.isDescendantOf(e))?(log("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 i=new Set;e.forEach(t=>{const{parent:e}=t;e&&i.add(e)}),t===Se?i.forEach(t=>{t._onAfterObjectsChange(be,e)}):i.forEach(t=>{t._set("dirty",!0)})}onDeselect(){return this.removeAll(),!1}toString(){return`#<ActiveSelection: (${this.complexity()})>`}shouldCache(){return!1}isOnACache(){return!1}_renderControls(t,e,i){t.save(),t.globalAlpha=this.isMoving?this.borderOpacityWhenMoving:1;const s={hasControls:!1,...i,forActiveSelection:!0};for(let e=0;e<this._objects.length;e++)this._objects[e]._renderControls(t,s);super._renderControls(t,e),t.restore()}}function applyViewboxTransform(t){if(!Ct.test(t.nodeName))return{};const e=t.getAttribute("viewBox");let i=1,s=1,n=0,r=0,o,a;const h=t.getAttribute("width"),l=t.getAttribute("height"),c=t.getAttribute("x")||0,d=t.getAttribute("y")||0,u=undefined,g=!(e&&St.test(e)),f=!h||!l||"100%"===h||"100%"===l;let p="",m=0,y=0;if(g&&(c||d)&&t.parentNode&&"#document"!==t.parentNode.nodeName&&(p=" translate("+parseUnit(c||"0")+" "+parseUnit(d||"0")+") ",o=(t.getAttribute("transform")||"")+p,t.setAttribute("transform",o),t.removeAttribute("x"),t.removeAttribute("y")),g&&f)return{width:0,height:0};const x={width:0,height:0};if(g)return x.width=parseUnit(h),x.height=parseUnit(l),x;const v=e.match(St);n=-parseFloat(v[1]),r=-parseFloat(v[2]);const C=parseFloat(v[3]),b=parseFloat(v[4]);x.minX=n,x.minY=r,x.viewBoxWidth=C,x.viewBoxHeight=b,f?(x.width=C,x.height=b):(x.width=parseUnit(h),x.height=parseUnit(l),i=x.width/C,s=x.height/b);const S=parsePreserveAspectRatioAttribute(t.getAttribute("preserveAspectRatio")||"");if(S.alignX!==_&&("meet"===S.meetOrSlice&&(s=i=i>s?s:i),"slice"===S.meetOrSlice&&(s=i=i>s?i:s),m=x.width-C*i,y=x.height-b*i,"Mid"===S.alignX&&(m/=2),"Mid"===S.alignY&&(y/=2),"Min"===S.alignX&&(m=0),"Min"===S.alignY&&(y=0)),1===i&&1===s&&0===n&&0===r&&0===c&&0===d)return x;if((c||d)&&"#document"!==t.parentNode.nodeName&&(p=" translate("+parseUnit(c||"0")+" "+parseUnit(d||"0")+") "),o=p+" matrix("+i+" 0 0 "+s+" "+(n*i+m)+" "+(r*s+y)+") ","svg"===t.nodeName){for(a=t.ownerDocument.createElementNS(dt,"g");t.firstChild;)a.appendChild(t.firstChild);t.appendChild(a)}else a=t,a.removeAttribute("x"),a.removeAttribute("y"),o=a.getAttribute("transform")+o;return a.setAttribute("transform",o),x}_defineProperty(ActiveSelection,"type","ActiveSelection"),_defineProperty(ActiveSelection,"ownDefaults",Yi),X.setClass(ActiveSelection),X.setClass(ActiveSelection,"activeSelection");const getTagName=t=>t.tagName.replace("svg:",""),Vi=getSvgRegex(pt);function hasInvalidAncestor(t){let e=t;for(;e&&(e=e.parentElement);)if(e&&e.nodeName&&Vi.test(getTagName(e))&&!e.getAttribute("instantiated_by_use"))return!0;return!1}function getMultipleNodes(t,e){let i,s=[],n,r,o;for(r=0,o=e.length;r<o;r++)i=e[r],n=t.getElementsByTagNameNS("http://www.w3.org/2000/svg",i),s=s.concat(Array.from(n));return s}function parseUseDirectives(t){const e=getMultipleNodes(t,["use","svg:use"]),i=["x","y","xlink:href","href","transform"];for(const s of e){const e=s.attributes,n={};for(const t of e)t.value&&(n[t.name]=t.value);const r=(n["xlink:href"]||n.href||"").slice(1);if(""===r)return;const o=t.getElementById(r);if(null===o)return;let a=o.cloneNode(!0);const h=a.attributes,l={};for(const t of h)t.value&&(l[t.name]=t.value);const{x:c=0,y:d=0,transform:u=""}=n,g=`${u} ${l.transform||""} translate(${c}, ${d})`;if(applyViewboxTransform(a),/^svg$/i.test(a.nodeName)){const t=a.ownerDocument.createElementNS(dt,"g");Object.entries(l).forEach(e=>{let[i,s]=e;return t.setAttributeNS(dt,i,s)}),t.append(...a.childNodes),a=t}for(const t of e){if(!t)continue;const{name:e,value:s}=t;if(!i.includes(e))if("style"===e){const t={};parseStyleString(s,t),Object.entries(l).forEach(e=>{let[i,s]=e;t[i]=s}),parseStyleString(l.style||"",t);const i=Object.entries(t).map(t=>t.join(":")).join(";");a.setAttribute(e,i)}else!l[e]&&a.setAttribute(e,s)}a.setAttribute("transform",g),a.setAttribute("instantiated_by_use","1"),a.removeAttribute("id"),s.parentNode.replaceChild(a,s)}}const Gi=["gradientTransform","x1","x2","y1","y2","gradientUnits","cx","cy","r","fx","fy"],Ni="xlink:href";function recursivelyParseGradientsXlink(t,e){var i;const s=(null===(i=e.getAttribute(Ni))||void 0===i?void 0:i.slice(1))||"",n=t.getElementById(s);if(n&&n.getAttribute(Ni)&&recursivelyParseGradientsXlink(t,n),n&&(Gi.forEach(t=>{const i=n.getAttribute(t);!e.hasAttribute(t)&&i&&e.setAttribute(t,i)}),!e.children.length)){const t=n.cloneNode(!0);for(;t.firstChild;)e.appendChild(t.firstChild)}e.removeAttribute(Ni)}const Ui=["linearGradient","radialGradient","svg:linearGradient","svg:radialGradient"];function getGradientDefs(t){const e=getMultipleNodes(t,Ui),i={};let s=e.length;for(;s--;){const n=e[s];n.getAttribute("xlink:href")&&recursivelyParseGradientsXlink(t,n);const r=n.getAttribute("id");r&&(i[r]=n)}return i}function getCSSRules(t){const e=t.getElementsByTagName("style"),i={};for(let t=0;t<e.length;t++){const s=(e[t].textContent||"").replace(/\/\*[\s\S]*?\*\//g,"");""!==s.trim()&&s.split("}").filter((t,e,i)=>i.length>1&&t.trim()).forEach(t=>{if((t.match(/{/g)||[]).length>1&&t.trim().startsWith("@"))return;const e=t.split("{"),s={},n=undefined,r=e[1].trim().split(";").filter(function(t){return t.trim()});for(let t=0;t<r.length;t++){const e=r[t].split(":"),i=e[0].trim(),n=e[1].trim();s[i]=n}(t=e[0].trim()).split(",").forEach(t=>{""!==(t=t.replace(/^svg/i,"").trim())&&(i[t]={...i[t]||{},...s})})})}return i}const findTag=t=>X.getSVGClass(getTagName(t).toLowerCase());class ElementsParser{constructor(t,e,i,s,n){this.elements=t,this.options=e,this.reviver=i,this.regexUrl=/^url\(['"]?#([^'"]+)['"]?\)/g,this.doc=s,this.clipPaths=n,this.gradientDefs=getGradientDefs(s),this.cssRules=getCSSRules(s)}parse(){return Promise.all(this.elements.map(t=>this.createObject(t)))}async createObject(t){const e=findTag(t);if(e){const i=await e.fromElement(t,this.options,this.cssRules);return this.resolveGradient(i,t,I),this.resolveGradient(i,t,B),i instanceof FabricImage&&i._originalElement?removeTransformMatrixForSvgParsing(i,i.parsePreserveAspectRatioAttribute()):removeTransformMatrixForSvgParsing(i),await this.resolveClipPath(i,t),this.reviver&&this.reviver(t,i),i}return null}extractPropertyDefinition(t,e,i){const s=t[e],n=this.regexUrl;if(!n.test(s))return;n.lastIndex=0;const r=n.exec(s)[1];return n.lastIndex=0,i[r]}resolveGradient(t,e,i){const s=this.extractPropertyDefinition(t,i,this.gradientDefs);if(s){const n=e.getAttribute(i+"-opacity"),r=Gradient.fromElement(s,t,{...this.options,opacity:n});t.set(i,r)}}async resolveClipPath(t,e,i){const s=this.extractPropertyDefinition(t,"clipPath",this.clipPaths);if(s){const n=invertTransform(t.calcTransformMatrix()),r=s[0].parentElement;let o=e;for(;!i&&o.parentElement&&o.getAttribute("clip-path")!==t.clipPath;)o=o.parentElement;o.parentElement.appendChild(r);const a=parseTransformAttribute(`${o.getAttribute("transform")||""} ${r.getAttribute("originalTransform")||""}`);r.setAttribute("transform",`matrix(${a.join(",")})`);const h=await Promise.all(s.map(t=>findTag(t).fromElement(t,this.options,this.cssRules).then(t=>(removeTransformMatrixForSvgParsing(t),t.fillRule=t.clipRule,delete t.clipRule,t)))),l=1===h.length?h[0]:new Group(h),c=multiplyTransformMatrices(n,l.calcTransformMatrix());l.clipPath&&await this.resolveClipPath(l,o,r.getAttribute("clip-path")?o:void 0);const{scaleX:d,scaleY:u,angle:g,skewX:f,translateX:m,translateY:y}=qrDecompose(c);l.set({flipX:!1,flipY:!1}),l.set({scaleX:d,scaleY:u,angle:g,skewX:f,skewY:0}),l.setPositionByOrigin(new Point(m,y),p,p),t.clipPath=l}else delete t.clipPath}}const isValidSvgTag=t=>_t.test(getTagName(t)),createEmptyResponse=()=>({objects:[],elements:[],options:{},allElements:[]});async function parseSVGDocument(t,e){let{crossOrigin:i,signal:s}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(s&&s.aborted)return log("log",new SignalAbortedError("parseSVGDocument")),{objects:[],elements:[],options:{},allElements:[]};const n=t.documentElement;parseUseDirectives(t);const r=Array.from(n.getElementsByTagName("*")),o={...applyViewboxTransform(n),crossOrigin:i,signal:s},a=r.filter(t=>(applyViewboxTransform(t),isValidSvgTag(t)&&!hasInvalidAncestor(t)));if(!a||a&&!a.length)return{objects:[],elements:[],options:{},allElements:[],options:o,allElements:r};const h={};r.filter(t=>"clipPath"===getTagName(t)).forEach(t=>{t.setAttribute("originalTransform",t.getAttribute("transform")||"");const e=t.getAttribute("id");h[e]=Array.from(t.getElementsByTagName("*")).filter(t=>isValidSvgTag(t))});const l=new ElementsParser(a,o,e,t,h),c=undefined;return{objects:await l.parse(),elements:a,options:o,allElements:r}}function loadSVGFromString(t,e,i){const s=undefined,n=undefined;return parseSVGDocument((new(getFabricWindow().DOMParser)).parseFromString(t.trim(),"text/xml"),e,i)}function loadSVGFromURL(t,e){let i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return fetch(t.replace(/^\n\s*/,"").trim(),{signal:i.signal}).then(t=>{if(!t.ok)throw new FabricError(`HTTP error! status: ${t.status}`);return t.text()}).then(t=>loadSVGFromString(t,e,i)).catch(()=>({objects:[],elements:[],options:{},allElements:[]}))}const qi=O,createPolyPositionHandler=t=>function(e,i,s){const{points:n,pathOffset:r}=s;return new Point(n[t]).subtract(r).transform(multiplyTransformMatrices(s.getViewportTransform(),s.calcTransformMatrix()))},polyActionHandler=(t,e,i,s)=>{const{target:n,pointIndex:r}=e,o=n,a=sendPointToPlane(new Point(i,s),void 0,o.calcOwnMatrix());return o.points[r]=a.add(o.pathOffset),o.setDimensions(),o.set("dirty",!0),!0},factoryPolyActionHandler=(t,e)=>function(i,s,n,r){const o=s.target,a=new Point(o.points[(t>0?t:o.points.length)-1]),h=a.subtract(o.pathOffset).transform(o.calcOwnMatrix()),l=e(i,{...s,pointIndex:t},n,r),c=undefined,d=a.subtract(o.pathOffset).transform(o.calcOwnMatrix()).subtract(h);return o.left-=d.x,o.top-=d.y,l},createPolyActionHandler=t=>wrapWithFireEvent(qi,factoryPolyActionHandler(t,polyActionHandler));function createPolyControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i={};for(let s=0;s<("number"==typeof t?t:t.points.length);s++)i[`p${s}`]=new Control({actionName:qi,positionHandler:createPolyPositionHandler(s),actionHandler:createPolyActionHandler(s),...e});return i}const Ki="modifyPath",calcPathPointPosition=(t,e,i)=>{const{path:s,pathOffset:n}=t,r=s[e];return new Point(r[i]-n.x,r[i+1]-n.y).transform(multiplyTransformMatrices(t.getViewportTransform(),t.calcTransformMatrix()))},movePathPoint=(t,e,i,s,n)=>{const{path:r,pathOffset:o}=t,a=r[(s>0?s:r.length)-1],h=new Point(a[n],a[n+1]),l=h.subtract(o).transform(t.calcOwnMatrix()),c=sendPointToPlane(new Point(e,i),void 0,t.calcOwnMatrix());r[s][n]=c.x+o.x,r[s][n+1]=c.y+o.y,t.setDimensions();const d=undefined,u=h.subtract(t.pathOffset).transform(t.calcOwnMatrix()).subtract(l);return t.left-=u.x,t.top-=u.y,t.set("dirty",!0),!0};function pathPositionHandler(t,e,i){const{commandIndex:s,pointIndex:n}=this;return calcPathPointPosition(i,s,n)}function pathActionHandler(t,e,i,s){const{target:n}=e,{commandIndex:r,pointIndex:o}=this,a=movePathPoint(n,i,s,r,o);return fireEvent(this.actionName,{...commonEventInfo(t,e,i,s),commandIndex:r,pointIndex:o}),a}const indexFromPrevCommand=t=>"C"===t?5:"Q"===t?3:1;class PathPointControl extends Control{constructor(t){super(t)}render(t,e,i,s,n){const r={...s,cornerColor:this.controlFill,cornerStrokeColor:this.controlStroke,transparentCorners:!this.controlFill};super.render(t,e,i,r,n)}}class PathControlPointControl extends PathPointControl{constructor(t){super(t)}render(t,e,i,s,n){const{path:r}=n,{commandIndex:o,pointIndex:a,connectToCommandIndex:h,connectToPointIndex:l}=this;t.save(),t.strokeStyle=this.controlStroke,this.connectionDashArray&&t.setLineDash(this.connectionDashArray);const[c]=r[o],d=calcPathPointPosition(n,h,l);if("Q"===c){const s=calcPathPointPosition(n,o,a+2);t.moveTo(s.x,s.y),t.lineTo(e,i)}else t.moveTo(e,i);t.lineTo(d.x,d.y),t.stroke(),t.restore(),super.render(t,e,i,s,n)}}const createControl=(t,e,i,s,n,r)=>new(i?PathControlPointControl:PathPointControl)({commandIndex:t,pointIndex:e,actionName:Ki,positionHandler:pathPositionHandler,actionHandler:pathActionHandler,connectToCommandIndex:n,connectToPointIndex:r,...s,...i?s.controlPointStyle:s.pointStyle});function createPathControls(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const i={};let s="M";return t.path.forEach((t,n)=>{const r=t[0];switch("Z"!==r&&(i[`c_${n}_${r}`]=createControl(n,t.length-2,!1,e)),r){case"C":i[`c_${n}_C_CP_1`]=createControl(n,1,!0,e,n-1,indexFromPrevCommand(s)),i[`c_${n}_C_CP_2`]=createControl(n,3,!0,e,n,5);break;case"Q":i[`c_${n}_Q_CP_1`]=createControl(n,1,!0,e,n,3);break}s=r}),i}var Ji=Object.freeze({__proto__:null,EXPAND_HANDLE_FILL:Vt,EXPAND_HANDLE_STROKE:Gt,EXPAND_PREVIEW_DASH:qt,EXPAND_PREVIEW_FILL:Nt,EXPAND_PREVIEW_STROKE:Ut,ExpandControl:ExpandControl,changeWidth:Ft,createDefaultExpansion:createDefaultExpansion,createExpandControls:createExpandControls,createImageCropControls:createImageCropControls,createImageCropModeControls:createImageCropModeControls,createObjectDefaultControls:createObjectDefaultControls,createPathControls:createPathControls,createPolyActionHandler:createPolyActionHandler,createPolyControls:createPolyControls,createPolyPositionHandler:createPolyPositionHandler,createResizeControls:createResizeControls,createTextboxDefaultControls:createTextboxDefaultControls,cropFromBottom:Li,cropFromBottomLeft:Ri,cropFromBottomRight:Wi,cropFromLeft:Fi,cropFromRight:Ai,cropFromTop:ji,cropFromTopLeft:Ii,cropFromTopRight:Bi,dragHandler:dragHandler,expandBottomHandler:expandBottomHandler,expandLeftHandler:expandLeftHandler,expandRightHandler:expandRightHandler,expandTopHandler:expandTopHandler,factoryPolyActionHandler:factoryPolyActionHandler,getExpansion:getExpansion,getLocalPoint:getLocalPoint,polyActionHandler:polyActionHandler,renderCircleControl:renderCircleControl,renderSquareControl:renderSquareControl,rotationStyleHandler:rotationStyleHandler,rotationWithSnapping:Rt,scaleCursorStyleHandler:scaleCursorStyleHandler,scaleOrSkewActionName:scaleOrSkewActionName,scaleSkewCursorStyleHandler:scaleSkewCursorStyleHandler,scalingEqually:Ht,scalingX:Xt,scalingXOrSkewingY:scalingXOrSkewingY,scalingY:$t,scalingYOrSkewingX:scalingYOrSkewingX,setExpansion:setExpansion,skewCursorStyleHandler:skewCursorStyleHandler,skewHandlerX:skewHandlerX,skewHandlerY:skewHandlerY,wrapWithFireEvent:wrapWithFireEvent,wrapWithFixedAnchor:wrapWithFixedAnchor});const isWebGLPipelineState=t=>void 0!==t.webgl,isPutImageFaster=(t,e)=>{const i=createCanvasElementFor({width:t,height:e}),s=undefined,n=createCanvasElement().getContext("webgl"),r=undefined,o={imageBuffer:new ArrayBuffer(t*e*4)},a={destinationWidth:t,destinationHeight:e,targetCanvas:i};let h;h=getFabricWindow().performance.now(),WebGLFilterBackend.prototype.copyGLTo2D.call(o,n,a);const l=getFabricWindow().performance.now()-h;h=getFabricWindow().performance.now(),WebGLFilterBackend.prototype.copyGLTo2DPutImageData.call(o,n,a);const c=undefined;return l>getFabricWindow().performance.now()-h},Zi="precision highp float",Qi=`\n ${Zi};\n varying vec2 vTexCoord;\n uniform sampler2D uTexture;\n void main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n }`,ts="\n attribute vec2 aPosition;\n varying vec2 vTexCoord;\n void main() {\n vTexCoord = aPosition;\n gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n }",es=new RegExp(Zi,"g");class BaseFilter{get type(){return this.constructor.type}constructor(){let{type:t,...e}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,this.constructor.defaults,e)}getFragmentSource(){return Qi}getVertexSource(){return ts}createProgram(t){let e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.getFragmentSource(),i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:this.getVertexSource();const{WebGLProbe:{GLPrecision:s="highp"}}=getEnv();"highp"!==s&&(e=e.replace(es,Zi.replace("highp",s)));const n=t.createShader(t.VERTEX_SHADER),r=t.createShader(t.FRAGMENT_SHADER),o=t.createProgram();if(!n||!r||!o)throw new FabricError("Vertex, fragment shader or program creation error");if(t.shaderSource(n,i),t.compileShader(n),!t.getShaderParameter(n,t.COMPILE_STATUS))throw new FabricError(`Vertex shader compile error for ${this.type}: ${t.getShaderInfoLog(n)}`);if(t.shaderSource(r,e),t.compileShader(r),!t.getShaderParameter(r,t.COMPILE_STATUS))throw new FabricError(`Fragment shader compile error for ${this.type}: ${t.getShaderInfoLog(r)}`);if(t.attachShader(o,n),t.attachShader(o,r),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS))throw new FabricError(`Shader link error for "${this.type}" ${t.getProgramInfoLog(o)}`);const a=this.getUniformLocations(t,o)||{};return a.uStepW=t.getUniformLocation(o,"uStepW"),a.uStepH=t.getUniformLocation(o,"uStepH"),{program:o,attributeLocations:this.getAttributeLocations(t,o),uniformLocations:a}}getAttributeLocations(t,e){return{aPosition:t.getAttribLocation(e,"aPosition")}}getUniformLocations(t,e){const i=this.constructor.uniformLocations,s={};for(let n=0;n<i.length;n++)s[i[n]]=t.getUniformLocation(e,i[n]);return s}sendAttributeData(t,e,i){const s=e.aPosition,n=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,n),t.enableVertexAttribArray(s),t.vertexAttribPointer(s,2,t.FLOAT,!1,0,0),t.bufferData(t.ARRAY_BUFFER,i,t.STATIC_DRAW)}_setupFrameBuffer(t){const e=t.context;if(t.passes>1){const i=t.destinationWidth,s=t.destinationHeight;t.sourceWidth===i&&t.sourceHeight===s||(e.deleteTexture(t.targetTexture),t.targetTexture=t.filterBackend.createTexture(e,i,s)),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t.targetTexture,0)}else e.bindFramebuffer(e.FRAMEBUFFER,null),e.finish()}_swapTextures(t){t.passes--,t.pass++;const e=t.targetTexture;t.targetTexture=t.sourceTexture,t.sourceTexture=e}isNeutralState(t){return!1}applyTo(t){isWebGLPipelineState(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,i=this.retrieveShader(t);0===t.pass&&t.originalTexture?e.bindTexture(e.TEXTURE_2D,t.originalTexture):e.bindTexture(e.TEXTURE_2D,t.sourceTexture),e.useProgram(i.program),this.sendAttributeData(e,i.attributeLocations,t.aPosition),e.uniform1f(i.uniformLocations.uStepW,1/t.sourceWidth),e.uniform1f(i.uniformLocations.uStepH,1/t.sourceHeight),this.sendUniformData(e,i.uniformLocations),e.viewport(0,0,t.destinationWidth,t.destinationHeight),e.drawArrays(e.TRIANGLE_STRIP,0,4)}bindAdditionalTexture(t,e,i){t.activeTexture(i),t.bindTexture(t.TEXTURE_2D,e),t.activeTexture(t.TEXTURE0)}unbindAdditionalTexture(t,e){t.activeTexture(e),t.bindTexture(t.TEXTURE_2D,null),t.activeTexture(t.TEXTURE0)}sendUniformData(t,e){}createHelpLayer(t){if(!t.helpLayer){const{sourceWidth:e,sourceHeight:i}=t,s=createCanvasElementFor({width:e,height:i});t.helpLayer=s}}toObject(){const t=Object.keys(this.constructor.defaults||{});return{type:this.type,...t.reduce((t,e)=>(t[e]=this[e],t),{})}}toJSON(){return this.toObject()}static async fromObject(t,e){let{type:i,...s}=t;return new this(s)}}_defineProperty(BaseFilter,"type","BaseFilter"),_defineProperty(BaseFilter,"uniformLocations",[]);const is={multiply:"gl_FragColor.rgb *= uColor.rgb;\n",screen:"gl_FragColor.rgb = 1.0 - (1.0 - gl_FragColor.rgb) * (1.0 - uColor.rgb);\n",add:"gl_FragColor.rgb += uColor.rgb;\n",difference:"gl_FragColor.rgb = abs(gl_FragColor.rgb - uColor.rgb);\n",subtract:"gl_FragColor.rgb -= uColor.rgb;\n",lighten:"gl_FragColor.rgb = max(gl_FragColor.rgb, uColor.rgb);\n",darken:"gl_FragColor.rgb = min(gl_FragColor.rgb, uColor.rgb);\n",exclusion:"gl_FragColor.rgb += uColor.rgb - 2.0 * (uColor.rgb * gl_FragColor.rgb);\n",overlay:"\n if (uColor.r < 0.5) {\n gl_FragColor.r *= 2.0 * uColor.r;\n } else {\n gl_FragColor.r = 1.0 - 2.0 * (1.0 - gl_FragColor.r) * (1.0 - uColor.r);\n }\n if (uColor.g < 0.5) {\n gl_FragColor.g *= 2.0 * uColor.g;\n } else {\n gl_FragColor.g = 1.0 - 2.0 * (1.0 - gl_FragColor.g) * (1.0 - uColor.g);\n }\n if (uColor.b < 0.5) {\n gl_FragColor.b *= 2.0 * uColor.b;\n } else {\n gl_FragColor.b = 1.0 - 2.0 * (1.0 - gl_FragColor.b) * (1.0 - uColor.b);\n }\n ",tint:"\n gl_FragColor.rgb *= (1.0 - uColor.a);\n gl_FragColor.rgb += uColor.rgb;\n "},ss={color:"#F95C63",mode:"multiply",alpha:1};class BlendColor extends BaseFilter{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n gl_FragColor = color;\n if (color.a > 0.0) {\n ${is[this.mode]}\n }\n }\n `}applyTo2d(t){let{imageData:{data:e}}=t;const i=new Color(this.color).getSource(),s=this.alpha,n=i[0]*s,r=i[1]*s,o=i[2]*s,a=1-s;for(let t=0;t<e.length;t+=4){const i=e[t],s=e[t+1],h=e[t+2];let l,c,d;switch(this.mode){case"multiply":l=i*n/255,c=s*r/255,d=h*o/255;break;case"screen":l=255-(255-i)*(255-n)/255,c=255-(255-s)*(255-r)/255,d=255-(255-h)*(255-o)/255;break;case"add":l=i+n,c=s+r,d=h+o;break;case"difference":l=Math.abs(i-n),c=Math.abs(s-r),d=Math.abs(h-o);break;case"subtract":l=i-n,c=s-r,d=h-o;break;case"darken":l=Math.min(i,n),c=Math.min(s,r),d=Math.min(h,o);break;case"lighten":l=Math.max(i,n),c=Math.max(s,r),d=Math.max(h,o);break;case"overlay":l=n<128?2*i*n/255:255-2*(255-i)*(255-n)/255,c=r<128?2*s*r/255:255-2*(255-s)*(255-r)/255,d=o<128?2*h*o/255:255-2*(255-h)*(255-o)/255;break;case"exclusion":l=n+i-2*n*i/255,c=r+s-2*r*s/255,d=o+h-2*o*h/255;break;case"tint":l=n+i*a,c=r+s*a,d=o+h*a}e[t]=l,e[t+1]=c,e[t+2]=d}}sendUniformData(t,e){const i=new Color(this.color).getSource();i[0]=this.alpha*i[0]/255,i[1]=this.alpha*i[1]/255,i[2]=this.alpha*i[2]/255,i[3]=this.alpha,t.uniform4fv(e.uColor,i)}}_defineProperty(BlendColor,"defaults",ss),_defineProperty(BlendColor,"type","BlendColor"),_defineProperty(BlendColor,"uniformLocations",["uColor"]),X.setClass(BlendColor);const ns={multiply:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform sampler2D uImage;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec4 color2 = texture2D(uImage, vTexCoord2);\n color.rgba *= color2.rgba;\n gl_FragColor = color;\n }\n ",mask:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform sampler2D uImage;\n uniform vec4 uColor;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec4 color2 = texture2D(uImage, vTexCoord2);\n color.a = color2.a;\n gl_FragColor = color;\n }\n "},rs="\n attribute vec2 aPosition;\n varying vec2 vTexCoord;\n varying vec2 vTexCoord2;\n uniform mat3 uTransformMatrix;\n void main() {\n vTexCoord = aPosition;\n vTexCoord2 = (uTransformMatrix * vec3(aPosition, 1.0)).xy;\n gl_Position = vec4(aPosition * 2.0 - 1.0, 0.0, 1.0);\n }\n ",os={mode:"multiply",alpha:1};class BlendImage extends BaseFilter{getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return ns[this.mode]}getVertexSource(){return rs}applyToWebGL(t){const e=t.context,i=this.createTexture(t.filterBackend,this.image);this.bindAdditionalTexture(e,i,e.TEXTURE1),super.applyToWebGL(t),this.unbindAdditionalTexture(e,e.TEXTURE1)}createTexture(t,e){return t.getCachedTexture(e.cacheKey,e.getElement())}calculateMatrix(){const t=this.image,{width:e,height:i}=t.getElement();return[1/t.scaleX,0,0,0,1/t.scaleY,0,-t.left/e,-t.top/i,1]}applyTo2d(t){let{imageData:{data:e,width:i,height:s},filterBackend:{resources:n}}=t;const r=this.image;n.blendImage||(n.blendImage=createCanvasElement());const o=n.blendImage,a=o.getContext("2d");o.width!==i||o.height!==s?(o.width=i,o.height=s):a.clearRect(0,0,i,s),a.setTransform(r.scaleX,0,0,r.scaleY,r.left,r.top),a.drawImage(r.getElement(),0,0,i,s);const h=a.getImageData(0,0,i,s).data;for(let t=0;t<e.length;t+=4){const i=e[t],s=e[t+1],n=e[t+2],r=e[t+3],o=h[t],a=h[t+1],l=h[t+2],c=h[t+3];switch(this.mode){case"multiply":e[t]=i*o/255,e[t+1]=s*a/255,e[t+2]=n*l/255,e[t+3]=r*c/255;break;case"mask":e[t+3]=c;break}}}sendUniformData(t,e){const i=this.calculateMatrix();t.uniform1i(e.uImage,1),t.uniformMatrix3fv(e.uTransformMatrix,!1,i)}toObject(){return{...super.toObject(),image:this.image&&this.image.toObject()}}static async fromObject(t,e){let{type:i,image:s,...n}=t;return FabricImage.fromObject(s,e).then(t=>new this({...n,image:t}))}}_defineProperty(BlendImage,"type","BlendImage"),_defineProperty(BlendImage,"defaults",os),_defineProperty(BlendImage,"uniformLocations",["uTransformMatrix","uImage"]),X.setClass(BlendImage);const as="\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n const float nSamples = 15.0;\n vec3 v3offset = vec3(12.9898, 78.233, 151.7182);\n float random(vec3 scale) {\n /* use the fragment position for a different seed per-pixel */\n return fract(sin(dot(gl_FragCoord.xyz, scale)) * 43758.5453);\n }\n void main() {\n vec4 color = vec4(0.0);\n float totalC = 0.0;\n float totalA = 0.0;\n float offset = random(v3offset);\n for (float t = -nSamples; t <= nSamples; t++) {\n float percent = (t + offset - 0.5) / nSamples;\n vec4 sample = texture2D(uTexture, vTexCoord + uDelta * percent);\n float weight = 1.0 - abs(percent);\n float alpha = weight * sample.a;\n color.rgb += sample.rgb * alpha;\n color.a += alpha;\n totalA += weight;\n totalC += alpha;\n }\n gl_FragColor.rgb = color.rgb / totalC;\n gl_FragColor.a = color.a / totalA;\n }\n ",hs={blur:0};class Blur extends BaseFilter{getFragmentSource(){return as}applyTo(t){isWebGLPipelineState(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:i,height:s}}=t;this.aspectRatio=i/s,this.horizontal=!0;let n=this.getBlurValue()*i;const r=new Uint8ClampedArray(e),o=15,a=4*i;for(let t=0;t<e.length;t+=4){let i=0,s=0,h=0,l=0,c=0;const d=t-t%a,u=d+a;for(let r=-14;r<o;r++){const a=r/o,g=4*Math.floor(n*a),f=1-Math.abs(a);let p=t+g;p<d?p=d:p>u&&(p=u);const m=e[p+3]*f;i+=e[p]*m,s+=e[p+1]*m,h+=e[p+2]*m,l+=m,c+=f}r[t]=i/l,r[t+1]=s/l,r[t+2]=h/l,r[t+3]=l/c}this.horizontal=!1,n=this.getBlurValue()*s;for(let t=0;t<r.length;t+=4){let i=0,s=0,h=0,l=0,c=0;const d=t%a,u=r.length-a+d;for(let e=-14;e<o;e++){const g=e/o,f=Math.floor(n*g)*a,p=1-Math.abs(g);let m=t+f;m<d?m=d:m>u&&(m=u);const y=r[m+3]*p;i+=r[m]*y,s+=r[m+1]*y,h+=r[m+2]*y,l+=y,c+=p}e[t]=i/l,e[t+1]=s/l,e[t+2]=h/l,e[t+3]=l/c}}sendUniformData(t,e){const i=this.chooseRightDelta();t.uniform2fv(e.uDelta,i)}isNeutralState(){return 0===this.blur}getBlurValue(){let t=1;const{horizontal:e,aspectRatio:i}=this;return e?i>1&&(t=1/i):i<1&&(t=i),t*this.blur*.12}chooseRightDelta(){const t=this.getBlurValue();return this.horizontal?[t,0]:[0,t]}}_defineProperty(Blur,"type","Blur"),_defineProperty(Blur,"defaults",hs),_defineProperty(Blur,"uniformLocations",["uDelta"]),X.setClass(Blur);const ls="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uBrightness;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color.rgb += uBrightness;\n gl_FragColor = color;\n }\n",cs={brightness:0};class Brightness extends BaseFilter{getFragmentSource(){return ls}applyTo2d(t){let{imageData:{data:e}}=t;const i=Math.round(255*this.brightness);for(let t=0;t<e.length;t+=4)e[t]+=i,e[t+1]+=i,e[t+2]+=i}isNeutralState(){return 0===this.brightness}sendUniformData(t,e){t.uniform1f(e.uBrightness,this.brightness)}}_defineProperty(Brightness,"type","Brightness"),_defineProperty(Brightness,"defaults",cs),_defineProperty(Brightness,"uniformLocations",["uBrightness"]),X.setClass(Brightness);const ds="\n precision highp float;\n uniform sampler2D uTexture;\n varying vec2 vTexCoord;\n uniform mat4 uColorMatrix;\n uniform vec4 uConstants;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color *= uColorMatrix;\n color += uConstants;\n gl_FragColor = color;\n }",us={matrix:[1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],colorsOnly:!0};class ColorMatrix extends BaseFilter{getFragmentSource(){return ds}applyTo2d(t){const e=undefined,i=t.imageData.data,s=this.matrix,n=this.colorsOnly;for(let t=0;t<i.length;t+=4){const e=i[t],r=i[t+1],o=i[t+2];if(i[t]=e*s[0]+r*s[1]+o*s[2]+255*s[4],i[t+1]=e*s[5]+r*s[6]+o*s[7]+255*s[9],i[t+2]=e*s[10]+r*s[11]+o*s[12]+255*s[14],!n){const n=i[t+3];i[t]+=n*s[3],i[t+1]+=n*s[8],i[t+2]+=n*s[13],i[t+3]=e*s[15]+r*s[16]+o*s[17]+n*s[18]+255*s[19]}}}sendUniformData(t,e){const i=this.matrix,s=[i[0],i[1],i[2],i[3],i[5],i[6],i[7],i[8],i[10],i[11],i[12],i[13],i[15],i[16],i[17],i[18]],n=[i[4],i[9],i[14],i[19]];t.uniformMatrix4fv(e.uColorMatrix,!1,s),t.uniform4fv(e.uConstants,n)}toObject(){return{...super.toObject(),matrix:[...this.matrix]}}}function createColorMatrixFilter(t,e){var i;const s=(_defineProperty(i=class newClass extends ColorMatrix{toObject(){return{type:this.type,colorsOnly:this.colorsOnly}}},"type",t),_defineProperty(i,"defaults",{colorsOnly:!1,matrix:e}),i);return X.setClass(s,t),s}_defineProperty(ColorMatrix,"type","ColorMatrix"),_defineProperty(ColorMatrix,"defaults",us),_defineProperty(ColorMatrix,"uniformLocations",["uColorMatrix","uConstants"]),X.setClass(ColorMatrix);const gs=createColorMatrixFilter("Brownie",[.5997,.34553,-.27082,0,.186,-.0377,.86095,.15059,0,-.1449,.24113,-.07441,.44972,0,-.02965,0,0,0,1,0]),fs=createColorMatrixFilter("Vintage",[.62793,.32021,-.03965,0,.03784,.02578,.64411,.03259,0,.02926,.0466,-.08512,.52416,0,.02023,0,0,0,1,0]),ps=createColorMatrixFilter("Kodachrome",[1.12855,-.39673,-.03992,0,.24991,-.16404,1.08352,-.05498,0,.09698,-.16786,-.56034,1.60148,0,.13972,0,0,0,1,0]),ms=createColorMatrixFilter("Technicolor",[1.91252,-.85453,-.09155,0,.04624,-.30878,1.76589,-.10601,0,-.27589,-.2311,-.75018,1.84759,0,.12137,0,0,0,1,0]),ys=createColorMatrixFilter("Polaroid",[1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0]),xs=createColorMatrixFilter("Sepia",[.393,.769,.189,0,0,.349,.686,.168,0,0,.272,.534,.131,0,0,0,0,0,1,0]),vs=createColorMatrixFilter("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 Composed extends BaseFilter{constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(t),this.subFilters=t.subFilters||[]}applyTo(t){isWebGLPipelineState(t)&&(t.passes+=this.subFilters.length-1),this.subFilters.forEach(e=>{e.applyTo(t)})}toObject(){return{type:this.type,subFilters:this.subFilters.map(t=>t.toObject())}}isNeutralState(){return!this.subFilters.some(t=>!t.isNeutralState())}static fromObject(t,e){return Promise.all((t.subFilters||[]).map(t=>X.getClass(t.type).fromObject(t,e))).then(t=>new this({subFilters:t}))}}_defineProperty(Composed,"type","Composed"),X.setClass(Composed);const _s="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uContrast;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float contrastF = 1.015 * (uContrast + 1.0) / (1.0 * (1.015 - uContrast));\n color.rgb = contrastF * (color.rgb - 0.5) + 0.5;\n gl_FragColor = color;\n }",Cs={contrast:0};class Contrast extends BaseFilter{getFragmentSource(){return _s}isNeutralState(){return 0===this.contrast}applyTo2d(t){let{imageData:{data:e}}=t;const i=Math.floor(255*this.contrast),s=259*(i+255)/(255*(259-i));for(let t=0;t<e.length;t+=4)e[t]=s*(e[t]-128)+128,e[t+1]=s*(e[t+1]-128)+128,e[t+2]=s*(e[t+2]-128)+128}sendUniformData(t,e){t.uniform1f(e.uContrast,this.contrast)}}_defineProperty(Contrast,"type","Contrast"),_defineProperty(Contrast,"defaults",Cs),_defineProperty(Contrast,"uniformLocations",["uContrast"]),X.setClass(Contrast);const bs={Convolute_3_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[9];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 3.0; h+=1.0) {\n for (float w = 0.0; w < 3.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 1), uStepH * (h - 1));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 3.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_3_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[9];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 3.0; h+=1.0) {\n for (float w = 0.0; w < 3.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 1.0), uStepH * (h - 1.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 3.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_5_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[25];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 5.0; h+=1.0) {\n for (float w = 0.0; w < 5.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 5.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_5_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[25];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 5.0; h+=1.0) {\n for (float w = 0.0; w < 5.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 2.0), uStepH * (h - 2.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 5.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_7_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[49];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 7.0; h+=1.0) {\n for (float w = 0.0; w < 7.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 7.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_7_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[49];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 7.0; h+=1.0) {\n for (float w = 0.0; w < 7.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 3.0), uStepH * (h - 3.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 7.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n ",Convolute_9_1:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[81];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 0);\n for (float h = 0.0; h < 9.0; h+=1.0) {\n for (float w = 0.0; w < 9.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n color += texture2D(uTexture, vTexCoord + matrixPos) * uMatrix[int(h * 9.0 + w)];\n }\n }\n gl_FragColor = color;\n }\n ",Convolute_9_0:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uMatrix[81];\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = vec4(0, 0, 0, 1);\n for (float h = 0.0; h < 9.0; h+=1.0) {\n for (float w = 0.0; w < 9.0; w+=1.0) {\n vec2 matrixPos = vec2(uStepW * (w - 4.0), uStepH * (h - 4.0));\n color.rgb += texture2D(uTexture, vTexCoord + matrixPos).rgb * uMatrix[int(h * 9.0 + w)];\n }\n }\n float alpha = texture2D(uTexture, vTexCoord).a;\n gl_FragColor = color;\n gl_FragColor.a = alpha;\n }\n "},Ss={opaque:!1,matrix:[0,0,0,0,1,0,0,0,0]};class Convolute extends BaseFilter{getCacheKey(){return`${this.type}_${Math.sqrt(this.matrix.length)}_${this.opaque?1:0}`}getFragmentSource(){return bs[this.getCacheKey()]}applyTo2d(t){const e=t.imageData,i=e.data,s=this.matrix,n=Math.round(Math.sqrt(s.length)),r=Math.floor(n/2),o=e.width,a=e.height,h=t.ctx.createImageData(o,a),l=h.data,c=this.opaque?1:0;let d,u,g,f,p,m,y,x,v,_,C,b,S;for(C=0;C<a;C++)for(_=0;_<o;_++){for(p=4*(C*o+_),d=0,u=0,g=0,f=0,S=0;S<n;S++)for(b=0;b<n;b++)y=C+S-r,m=_+b-r,y<0||y>=a||m<0||m>=o||(x=4*(y*o+m),v=s[S*n+b],d+=i[x]*v,u+=i[x+1]*v,g+=i[x+2]*v,c||(f+=i[x+3]*v));l[p]=d,l[p+1]=u,l[p+2]=g,l[p+3]=c?i[p+3]:f}t.imageData=h}sendUniformData(t,e){t.uniform1fv(e.uMatrix,this.matrix)}toObject(){return{...super.toObject(),opaque:this.opaque,matrix:[...this.matrix]}}}_defineProperty(Convolute,"type","Convolute"),_defineProperty(Convolute,"defaults",Ss),_defineProperty(Convolute,"uniformLocations",["uMatrix","uOpaque","uHalfSize","uSize"]),X.setClass(Convolute);const ws="\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec3 uGamma;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n vec3 correction = (1.0 / uGamma);\n color.r = pow(color.r, correction.r);\n color.g = pow(color.g, correction.g);\n color.b = pow(color.b, correction.b);\n gl_FragColor = color;\n gl_FragColor.rgb *= color.a;\n }\n",Ts="Gamma",Ps={gamma:[1,1,1]};class Gamma extends BaseFilter{getFragmentSource(){return ws}constructor(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(t),this.gamma=t.gamma||this.constructor.defaults.gamma.concat()}applyTo2d(t){let{imageData:{data:e}}=t;const i=this.gamma,s=1/i[0],n=1/i[1],r=1/i[2];this.rgbValues||(this.rgbValues={r:new Uint8Array(256),g:new Uint8Array(256),b:new Uint8Array(256)});const o=this.rgbValues;for(let t=0;t<256;t++)o.r[t]=255*Math.pow(t/255,s),o.g[t]=255*Math.pow(t/255,n),o.b[t]=255*Math.pow(t/255,r);for(let t=0;t<e.length;t+=4)e[t]=o.r[e[t]],e[t+1]=o.g[e[t+1]],e[t+2]=o.b[e[t+2]]}sendUniformData(t,e){t.uniform3fv(e.uGamma,this.gamma)}isNeutralState(){const{gamma:t}=this;return 1===t[0]&&1===t[1]&&1===t[2]}toObject(){return{type:Ts,gamma:this.gamma.concat()}}}_defineProperty(Gamma,"type",Ts),_defineProperty(Gamma,"defaults",Ps),_defineProperty(Gamma,"uniformLocations",["uGamma"]),X.setClass(Gamma);const Ms={average:"\n precision highp float;\n uniform sampler2D uTexture;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float average = (color.r + color.b + color.g) / 3.0;\n gl_FragColor = vec4(average, average, average, color.a);\n }\n ",lightness:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uMode;\n varying vec2 vTexCoord;\n void main() {\n vec4 col = texture2D(uTexture, vTexCoord);\n float average = (max(max(col.r, col.g),col.b) + min(min(col.r, col.g),col.b)) / 2.0;\n gl_FragColor = vec4(average, average, average, col.a);\n }\n ",luminosity:"\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uMode;\n varying vec2 vTexCoord;\n void main() {\n vec4 col = texture2D(uTexture, vTexCoord);\n float average = 0.21 * col.r + 0.72 * col.g + 0.07 * col.b;\n gl_FragColor = vec4(average, average, average, col.a);\n }\n "},Os={mode:"average"};class Grayscale extends BaseFilter{applyTo2d(t){let{imageData:{data:e}}=t;for(let t=0,i;t<e.length;t+=4){const s=e[t],n=e[t+1],r=e[t+2];switch(this.mode){case"average":i=(s+n+r)/3;break;case"lightness":i=(Math.min(s,n,r)+Math.max(s,n,r))/2;break;case"luminosity":i=.21*s+.72*n+.07*r;break}e[t+2]=e[t+1]=e[t]=i}}getCacheKey(){return`${this.type}_${this.mode}`}getFragmentSource(){return Ms[this.mode]}sendUniformData(t,e){const i=1;t.uniform1i(e.uMode,1)}isNeutralState(){return!1}}_defineProperty(Grayscale,"type","Grayscale"),_defineProperty(Grayscale,"defaults",Os),_defineProperty(Grayscale,"uniformLocations",["uMode"]),X.setClass(Grayscale);const ks={...us,rotation:0};class HueRotation extends ColorMatrix{calculateMatrix(){const t=this.rotation*Math.PI,e=cos(t),i=sin(t),s=1/3,n=Math.sqrt(s)*i,r=1-e;this.matrix=[e+r/3,s*r-n,s*r+n,0,0,s*r+n,e+s*r,s*r-n,0,0,s*r-n,s*r+n,e+s*r,0,0,0,0,0,1,0]}isNeutralState(){return 0===this.rotation}applyTo(t){this.calculateMatrix(),super.applyTo(t)}toObject(){return{type:this.type,rotation:this.rotation}}}_defineProperty(HueRotation,"type","HueRotation"),_defineProperty(HueRotation,"defaults",ks),X.setClass(HueRotation);const Ds="\n precision highp float;\n uniform sampler2D uTexture;\n uniform int uInvert;\n uniform int uAlpha;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n if (uInvert == 1) {\n if (uAlpha == 1) {\n gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,1.0 -color.a);\n } else {\n gl_FragColor = vec4(1.0 - color.r,1.0 -color.g,1.0 -color.b,color.a);\n }\n } else {\n gl_FragColor = color;\n }\n }\n",Es={alpha:!1,invert:!0};class Invert extends BaseFilter{applyTo2d(t){let{imageData:{data:e}}=t;for(let t=0;t<e.length;t+=4)e[t]=255-e[t],e[t+1]=255-e[t+1],e[t+2]=255-e[t+2],this.alpha&&(e[t+3]=255-e[t+3])}getFragmentSource(){return Ds}isNeutralState(){return!this.invert}sendUniformData(t,e){t.uniform1i(e.uInvert,Number(this.invert)),t.uniform1i(e.uAlpha,Number(this.alpha))}}_defineProperty(Invert,"type","Invert"),_defineProperty(Invert,"defaults",Es),_defineProperty(Invert,"uniformLocations",["uInvert","uAlpha"]),X.setClass(Invert);const As="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uStepH;\n uniform float uNoise;\n uniform float uSeed;\n varying vec2 vTexCoord;\n float rand(vec2 co, float seed, float vScale) {\n return fract(sin(dot(co.xy * vScale ,vec2(12.9898 , 78.233))) * 43758.5453 * (seed + 0.01) / 2.0);\n }\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n color.rgb += (0.5 - rand(vTexCoord, uSeed, 0.1 / uStepH)) * uNoise;\n gl_FragColor = color;\n }\n",Fs={noise:0};class Noise extends BaseFilter{getFragmentSource(){return As}applyTo2d(t){let{imageData:{data:e}}=t;const i=this.noise;for(let t=0;t<e.length;t+=4){const s=(.5-Math.random())*i;e[t]+=s,e[t+1]+=s,e[t+2]+=s}}sendUniformData(t,e){t.uniform1f(e.uNoise,this.noise/255),t.uniform1f(e.uSeed,Math.random())}isNeutralState(){return 0===this.noise}}_defineProperty(Noise,"type","Noise"),_defineProperty(Noise,"defaults",Fs),_defineProperty(Noise,"uniformLocations",["uNoise","uSeed"]),X.setClass(Noise);const Ls="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uBlocksize;\n uniform float uStepW;\n uniform float uStepH;\n varying vec2 vTexCoord;\n void main() {\n float blockW = uBlocksize * uStepW;\n float blockH = uBlocksize * uStepH;\n int posX = int(vTexCoord.x / blockW);\n int posY = int(vTexCoord.y / blockH);\n float fposX = float(posX);\n float fposY = float(posY);\n vec2 squareCoords = vec2(fposX * blockW, fposY * blockH);\n vec4 color = texture2D(uTexture, squareCoords);\n gl_FragColor = color;\n }\n",js={blocksize:4};class Pixelate extends BaseFilter{applyTo2d(t){let{imageData:{data:e,width:i,height:s}}=t;for(let t=0;t<s;t+=this.blocksize)for(let n=0;n<i;n+=this.blocksize){const r=4*t*i+4*n,o=e[r],a=e[r+1],h=e[r+2],l=e[r+3];for(let r=t;r<Math.min(t+this.blocksize,s);r++)for(let t=n;t<Math.min(n+this.blocksize,i);t++){const s=4*r*i+4*t;e[s]=o,e[s+1]=a,e[s+2]=h,e[s+3]=l}}}isNeutralState(){return 1===this.blocksize}getFragmentSource(){return Ls}sendUniformData(t,e){t.uniform1f(e.uBlocksize,this.blocksize)}}_defineProperty(Pixelate,"type","Pixelate"),_defineProperty(Pixelate,"defaults",js),_defineProperty(Pixelate,"uniformLocations",["uBlocksize"]),X.setClass(Pixelate);const Is="\nprecision highp float;\nuniform sampler2D uTexture;\nuniform vec4 uLow;\nuniform vec4 uHigh;\nvarying vec2 vTexCoord;\nvoid main() {\n gl_FragColor = texture2D(uTexture, vTexCoord);\n if(all(greaterThan(gl_FragColor.rgb,uLow.rgb)) && all(greaterThan(uHigh.rgb,gl_FragColor.rgb))) {\n gl_FragColor.a = 0.0;\n }\n}\n",Bs={color:"#FFFFFF",distance:.02,useAlpha:!1};class RemoveColor extends BaseFilter{getFragmentSource(){return Is}applyTo2d(t){let{imageData:{data:e}}=t;const i=255*this.distance,s=new Color(this.color).getSource(),n=[s[0]-i,s[1]-i,s[2]-i],r=[s[0]+i,s[1]+i,s[2]+i];for(let t=0;t<e.length;t+=4){const i=e[t],s=e[t+1],o=e[t+2];i>n[0]&&s>n[1]&&o>n[2]&&i<r[0]&&s<r[1]&&o<r[2]&&(e[t+3]=0)}}sendUniformData(t,e){const i=new Color(this.color).getSource(),s=this.distance,n=[0+i[0]/255-s,0+i[1]/255-s,0+i[2]/255-s,1],r=[i[0]/255+s,i[1]/255+s,i[2]/255+s,1];t.uniform4fv(e.uLow,n),t.uniform4fv(e.uHigh,r)}}_defineProperty(RemoveColor,"type","RemoveColor"),_defineProperty(RemoveColor,"defaults",Bs),_defineProperty(RemoveColor,"uniformLocations",["uLow","uHigh"]),X.setClass(RemoveColor);const Rs={resizeType:"hermite",scaleX:1,scaleY:1,lanczosLobes:3};class Resize extends BaseFilter{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,i=this.getFilterWindow(),s=new Array(i);for(let n=1;n<=i;n++)s[n-1]=t(n*e);return s}generateShader(t){const e=new Array(t);for(let i=1;i<=t;i++)e[i-1]=`${i}.0 * uDelta`;return`\n precision highp float;\n uniform sampler2D uTexture;\n uniform vec2 uDelta;\n varying vec2 vTexCoord;\n uniform float uTaps[${t}];\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float sum = 1.0;\n ${e.map((t,e)=>`\n color += texture2D(uTexture, vTexCoord + ${t}) * uTaps[${e}] + texture2D(uTexture, vTexCoord - ${t}) * uTaps[${e}];\n sum += 2.0 * uTaps[${e}];\n `).join("\n")}\n gl_FragColor = color / sum;\n }\n `}applyToForWebgl(t){t.passes++,this.width=t.sourceWidth,this.horizontal=!0,this.dW=Math.round(this.width*this.scaleX),this.dH=t.sourceHeight,this.tempScale=this.dW/this.width,this.taps=this.getTaps(),t.destinationWidth=this.dW,super.applyTo(t),t.sourceWidth=t.destinationWidth,this.height=t.sourceHeight,this.horizontal=!1,this.dH=Math.round(this.height*this.scaleY),this.tempScale=this.dH/this.height,this.taps=this.getTaps(),t.destinationHeight=this.dH,super.applyTo(t),t.sourceHeight=t.destinationHeight}applyTo(t){isWebGLPipelineState(t)?this.applyToForWebgl(t):this.applyTo2d(t)}isNeutralState(){return 1===this.scaleX&&1===this.scaleY}lanczosCreate(t){return e=>{if(e>=t||e<=-t)return 0;if(e<1.1920929e-7&&e>-1.1920929e-7)return 1;const i=(e*=Math.PI)/t;return Math.sin(e)/e*Math.sin(i)/i}}applyTo2d(t){const e=t.imageData,i=this.scaleX,s=this.scaleY;this.rcpScaleX=1/i,this.rcpScaleY=1/s;const n=e.width,r=e.height,o=Math.round(n*i),a=Math.round(r*s);let h;h="sliceHack"===this.resizeType?this.sliceByTwo(t,n,r,o,a):"hermite"===this.resizeType?this.hermiteFastResize(t,n,r,o,a):"bilinear"===this.resizeType?this.bilinearFiltering(t,n,r,o,a):"lanczos"===this.resizeType?this.lanczosResize(t,n,r,o,a):new ImageData(o,a),t.imageData=h}sliceByTwo(t,e,i,s,n){const r=t.imageData,o=.5;let a=!1,h=!1,l=e*o,c=i*o;const d=t.filterBackend.resources;let u=0,g=0;const f=e;let p=0;d.sliceByTwo||(d.sliceByTwo=createCanvasElement());const m=d.sliceByTwo;(m.width<1.5*e||m.height<i)&&(m.width=1.5*e,m.height=i);const y=m.getContext("2d");for(y.clearRect(0,0,1.5*e,i),y.putImageData(r,0,0),s=Math.floor(s),n=Math.floor(n);!a||!h;)e=l,i=c,s<Math.floor(l*o)?l=Math.floor(l*o):(l=s,a=!0),n<Math.floor(c*o)?c=Math.floor(c*o):(c=n,h=!0),y.drawImage(m,u,g,e,i,f,p,l,c),u=f,g=p,p+=c;return y.getImageData(u,g,s,n)}lanczosResize(t,e,i,s,n){function process(t){let x,v,_,C,b,S,w,T,P,M,O;for(m.x=(t+.5)*l,y.x=Math.floor(m.x),x=0;x<n;x++){for(m.y=(x+.5)*c,y.y=Math.floor(m.y),b=0,S=0,w=0,T=0,P=0,v=y.x-g;v<=y.x+g;v++)if(!(v<0||v>=e)){M=Math.floor(1e3*Math.abs(v-m.x)),p[M]||(p[M]={});for(let t=y.y-f;t<=y.y+f;t++)t<0||t>=i||(O=Math.floor(1e3*Math.abs(t-m.y)),p[M][O]||(p[M][O]=h(Math.sqrt(Math.pow(M*d,2)+Math.pow(O*u,2))/1e3)),_=p[M][O],_>0&&(C=4*(t*e+v),b+=_,S+=_*r[C],w+=_*r[C+1],T+=_*r[C+2],P+=_*r[C+3]))}C=4*(x*s+t),a[C]=S/b,a[C+1]=w/b,a[C+2]=T/b,a[C+3]=P/b}return++t<s?process(t):o}const r=t.imageData.data,o=t.ctx.createImageData(s,n),a=o.data,h=this.lanczosCreate(this.lanczosLobes),l=this.rcpScaleX,c=this.rcpScaleY,d=2/this.rcpScaleX,u=2/this.rcpScaleY,g=Math.ceil(l*this.lanczosLobes/2),f=Math.ceil(c*this.lanczosLobes/2),p={},m={x:0,y:0},y={x:0,y:0};return process(0)}bilinearFiltering(t,e,i,s,n){let r,o,a,h,l,c,d,u,g,f,p,m,y=0,x;const v=this.rcpScaleX,_=this.rcpScaleY,C=4*(e-1),b=undefined,S=t.imageData.data,w=t.ctx.createImageData(s,n),T=w.data;for(d=0;d<n;d++)for(u=0;u<s;u++)for(l=Math.floor(v*u),c=Math.floor(_*d),g=v*u-l,f=_*d-c,x=4*(c*e+l),p=0;p<4;p++)r=S[x+p],o=S[x+4+p],a=S[x+C+p],h=S[x+C+4+p],m=r*(1-g)*(1-f)+o*g*(1-f)+a*f*(1-g)+h*g*f,T[y++]=m;return w}hermiteFastResize(t,e,i,s,n){const r=this.rcpScaleX,o=this.rcpScaleY,a=Math.ceil(r/2),h=Math.ceil(o/2),l=undefined,c=t.imageData.data,d=t.ctx.createImageData(s,n),u=d.data;for(let t=0;t<n;t++)for(let i=0;i<s;i++){const n=4*(i+t*s);let l=0,d=0,g=0,f=0,p=0,m=0,y=0;const x=(t+.5)*o;for(let s=Math.floor(t*o);s<(t+1)*o;s++){const t=Math.abs(x-(s+.5))/h,n=(i+.5)*r,o=t*t;for(let t=Math.floor(i*r);t<(i+1)*r;t++){let i=Math.abs(n-(t+.5))/a;const r=Math.sqrt(o+i*i);r>1&&r<-1||(l=2*r*r*r-3*r*r+1,l>0&&(i=4*(t+s*e),y+=l*c[i+3],g+=l,c[i+3]<255&&(l=l*c[i+3]/250),f+=l*c[i],p+=l*c[i+1],m+=l*c[i+2],d+=l))}}u[n]=f/d,u[n+1]=p/d,u[n+2]=m/d,u[n+3]=y/g}return d}}_defineProperty(Resize,"type","Resize"),_defineProperty(Resize,"defaults",Rs),_defineProperty(Resize,"uniformLocations",["uDelta","uTaps"]),X.setClass(Resize);const Ws="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uSaturation;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float rgMax = max(color.r, color.g);\n float rgbMax = max(rgMax, color.b);\n color.r += rgbMax != color.r ? (rgbMax - color.r) * uSaturation : 0.00;\n color.g += rgbMax != color.g ? (rgbMax - color.g) * uSaturation : 0.00;\n color.b += rgbMax != color.b ? (rgbMax - color.b) * uSaturation : 0.00;\n gl_FragColor = color;\n }\n",Hs={saturation:0};class Saturation extends BaseFilter{getFragmentSource(){return Ws}applyTo2d(t){let{imageData:{data:e}}=t;const i=-this.saturation;for(let t=0;t<e.length;t+=4){const s=e[t],n=e[t+1],r=e[t+2],o=Math.max(s,n,r);e[t]+=o!==s?(o-s)*i:0,e[t+1]+=o!==n?(o-n)*i:0,e[t+2]+=o!==r?(o-r)*i:0}}sendUniformData(t,e){t.uniform1f(e.uSaturation,-this.saturation)}isNeutralState(){return 0===this.saturation}}_defineProperty(Saturation,"type","Saturation"),_defineProperty(Saturation,"defaults",Hs),_defineProperty(Saturation,"uniformLocations",["uSaturation"]),X.setClass(Saturation);const Xs="\n precision highp float;\n uniform sampler2D uTexture;\n uniform float uVibrance;\n varying vec2 vTexCoord;\n void main() {\n vec4 color = texture2D(uTexture, vTexCoord);\n float max = max(color.r, max(color.g, color.b));\n float avg = (color.r + color.g + color.b) / 3.0;\n float amt = (abs(max - avg) * 2.0) * uVibrance;\n color.r += max != color.r ? (max - color.r) * amt : 0.00;\n color.g += max != color.g ? (max - color.g) * amt : 0.00;\n color.b += max != color.b ? (max - color.b) * amt : 0.00;\n gl_FragColor = color;\n }\n",$s={vibrance:0};class Vibrance extends BaseFilter{getFragmentSource(){return Xs}applyTo2d(t){let{imageData:{data:e}}=t;const i=-this.vibrance;for(let t=0;t<e.length;t+=4){const s=e[t],n=e[t+1],r=e[t+2],o=Math.max(s,n,r),a=(s+n+r)/3,h=2*Math.abs(o-a)/255*i;e[t]+=o!==s?(o-s)*h:0,e[t+1]+=o!==n?(o-n)*h:0,e[t+2]+=o!==r?(o-r)*h:0}}sendUniformData(t,e){t.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return 0===this.vibrance}}_defineProperty(Vibrance,"type","Vibrance"),_defineProperty(Vibrance,"defaults",$s),_defineProperty(Vibrance,"uniformLocations",["uVibrance"]),X.setClass(Vibrance);var zs=Object.freeze({__proto__:null,BaseFilter:BaseFilter,BlackWhite:vs,BlendColor:BlendColor,BlendImage:BlendImage,Blur:Blur,Brightness:Brightness,Brownie:gs,ColorMatrix:ColorMatrix,Composed:Composed,Contrast:Contrast,Convolute:Convolute,Gamma:Gamma,Grayscale:Grayscale,HueRotation:HueRotation,Invert:Invert,Kodachrome:ps,Noise:Noise,Pixelate:Pixelate,Polaroid:ys,RemoveColor:RemoveColor,Resize:Resize,Saturation:Saturation,Sepia:xs,Technicolor:ms,Vibrance:Vibrance,Vintage:fs});t.ActiveSelection=ActiveSelection,t.BaseBrush=BaseBrush,t.BaseFabricObject=At,t.Canvas=Canvas,t.Canvas2dFilterBackend=Canvas2dFilterBackend,t.CanvasDOMManager=CanvasDOMManager,t.Circle=Circle,t.CircleBrush=CircleBrush,t.ClipPathLayout=ClipPathLayout,t.Color=Color,t.Control=Control,t.Ellipse=Ellipse,t.FabricImage=FabricImage,t.FabricObject=FabricObject,t.FabricText=FabricText,t.FitContentLayout=FitContentLayout,t.FixedLayout=FixedLayout,t.Frame=Frame,t.FrameLayout=FrameLayout,t.Gradient=Gradient,t.Group=Group,t.IText=IText,t.Image=FabricImage,t.InteractiveFabricObject=InteractiveFabricObject,t.Intersection=Intersection,t.LayoutManager=LayoutManager,t.LayoutStrategy=LayoutStrategy,t.Line=Line,t.Object=FabricObject,t.Observable=Observable,t.Path=Path,t.Pattern=Pattern,t.PatternBrush=PatternBrush,t.PencilBrush=PencilBrush,t.Point=Point,t.Polygon=Polygon,t.Polyline=Polyline,t.Rect=Rect,t.Shadow=Shadow,t.SprayBrush=SprayBrush,t.StaticCanvas=StaticCanvas,t.StaticCanvasDOMManager=StaticCanvasDOMManager,t.Text=FabricText,t.Textbox=Textbox,t.Triangle=Triangle,t.WebGLFilterBackend=WebGLFilterBackend,t.cache=n,t.classRegistry=X,t.config=e,t.controlsUtils=Ji,t.createCollectionMixin=createCollectionMixin,t.filters=zs,t.getEnv=getEnv,t.getFabricDocument=getFabricDocument,t.getFabricWindow=getFabricWindow,t.getFilterBackend=getFilterBackend,t.iMatrix=d,t.initFilterBackend=initFilterBackend,t.isPutImageFaster=isPutImageFaster,t.isWebGLPipelineState=isWebGLPipelineState,t.loadSVGFromString=loadSVGFromString,t.loadSVGFromURL=loadSVGFromURL,t.parseSVGDocument=parseSVGDocument,t.runningAnimations=$,t.setEnv=setEnv,t.setFilterBackend=setFilterBackend,t.util=Re,t.version=o});
2
2
  //# sourceMappingURL=index.min.js.map