@bensitu/image-editor 1.2.2 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  (()=>{/**
2
2
  * @file image-editor.js
3
3
  * @module image-editor
4
- * @version 1.2.2
4
+ * @version 1.3.1
5
5
  * @author Ben Situ
6
6
  * @license MIT
7
7
  * @description Lightweight canvas-based image editor with masking/transform/export support.
8
- */var v=null;function A(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:null}function B(){let _=A();return _&&_.fabric?_.fabric:null}function x(_){return v=_||B(),v}function w(){return v||x(),v}var k=class{constructor(t={}){let s={getText:a=>a.maskName,textOptions:{fontSize:12,fill:"#fff",backgroundColor:"rgba(0,0,0,0.7)",padding:2,fontFamily:"monospace",fontWeight:"bold",selectable:!1,evented:!1,originX:"left",originY:"top"}},e={minWidth:100,minHeight:100,padding:10,hideMasksDuringCrop:!0,preserveMasksAfterCrop:!1,allowRotationOfCropRect:!1},i=t.label||{},n=t.crop||{};this.options={canvasWidth:800,canvasHeight:600,backgroundColor:"transparent",animationDuration:300,minScale:.1,maxScale:5,scaleStep:.05,rotationStep:90,expandCanvasToImage:!0,fitImageToCanvas:!1,coverImageToCanvas:!1,downsampleOnLoad:!0,downsampleMaxWidth:4e3,downsampleMaxHeight:3e3,downsampleQuality:.92,exportMultiplier:1,exportImageAreaByDefault:!0,defaultMaskWidth:50,defaultMaskHeight:80,maskRotatable:!1,maskLabelOnSelect:!0,maskLabelOffset:3,maskName:"mask",groupSelection:!1,showPlaceholder:!0,initialImageBase64:null,defaultDownloadFileName:"edited_image.jpg",onError:null,onWarning:null,...t,label:{...s,...i,textOptions:{...s.textOptions,...i.textOptions||{}}},crop:{...e,...n}},this._fabricLoaded=!!w(),this._fabricLoaded||this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted."),this.canvas=null,this.canvasElement=null,this.containerElement=null,this.placeholderElement=null,this.originalImage=null,this.baseImageScale=1,this.currentScale=1,this.currentRotation=0,this.maskCounter=0,this.isAnimating=!1,this.elements={},this.isImageLoadedToCanvas=!1,this.maxHistorySize=50,this._handlersByElementKey={},this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null,this._lastSnapshot=null,this._cropMode=!1,this._cropRect=null,this._cropHandlers=[],this._cropPrevEvented=null,this._prevSelectionSetting=void 0,this._containerOriginalOverflow=void 0,this.onImageLoaded=typeof t.onImageLoaded=="function"?t.onImageLoaded:null,this.animQueue=new S,this.historyManager=new I(this.maxHistorySize)}get canvasEl(){return this.canvasElement}set canvasEl(t){this.canvasElement=t}get containerEl(){return this.containerElement}set containerEl(t){this.containerElement=t}get placeholderEl(){return this.placeholderElement}set placeholderEl(t){this.placeholderElement=t}init(t={}){if(!this._fabricLoaded)return;let s={canvas:"fabricCanvas",canvasContainer:null,imgPlaceholder:"imgPlaceholder",scaleRate:"scaleRate",rotationLeftInput:"rotationLeftInput",rotationRightInput:"rotationRightInput",rotateLeftBtn:"rotateLeftBtn",rotateRightBtn:"rotateRightBtn",addMaskBtn:"addMaskBtn",removeMaskBtn:"removeMaskBtn",removeAllMasksBtn:"removeAllMasksBtn",mergeBtn:"mergeBtn",downloadBtn:"downloadBtn",maskList:"maskList",zoomInBtn:"zoomInBtn",zoomOutBtn:"zoomOutBtn",resetBtn:"resetBtn",undoBtn:"undoBtn",redoBtn:"redoBtn",imageInput:"imageInput",cropBtn:"cropBtn",applyCropBtn:"applyCropBtn",cancelCropBtn:"cancelCropBtn"};this.elements={...s,...t},this._initCanvas(),this._bindEvents(),this._updateInputs(),this._updateMaskList(),this._updateUI(),this.options.initialImageBase64?this.loadImage(this.options.initialImageBase64):this._updatePlaceholderStatus()}_reportError(t,s=null){let e=this.options&&this.options.onError;if(typeof e=="function")try{e(s,t)}catch{}}_reportWarning(t,s=null){let e=this.options&&this.options.onWarning;if(typeof e=="function")try{e(s,t)}catch{}}_initCanvas(){let t=document.getElementById(this.elements.canvas);if(!t)throw new Error("Canvas is not found: "+this.elements.canvas);if(this.canvasElement=t,this.elements.canvasContainer){let i=document.getElementById(this.elements.canvasContainer);this.containerElement=i||t.parentElement}else this.containerElement=t.parentElement;this.placeholderElement=document.getElementById(this.elements.imgPlaceholder)||null;let s=this.options.canvasWidth,e=this.options.canvasHeight;if(this.containerElement){let i=Math.floor(this.containerElement.clientWidth),n=Math.floor(this.containerElement.clientHeight);i>0&&n>0&&(s=i,e=n)}this.canvas=new v.Canvas(t,{width:s,height:e,backgroundColor:this.options.backgroundColor,selection:this.options.groupSelection,preserveObjectStacking:!0}),this.canvas.on("selection:created",i=>this._handleSelectionChanged(i.selected)),this.canvas.on("selection:updated",i=>this._handleSelectionChanged(i.selected)),this.canvas.on("selection:cleared",()=>this._handleSelectionChanged([])),this.canvas.on("object:moving",i=>{i.target&&i.target.maskId&&this._syncMaskLabel(i.target)}),this.canvas.on("object:scaling",i=>{i.target&&i.target.maskId&&this._syncMaskLabel(i.target)}),this.canvas.on("object:rotating",i=>{i.target&&i.target.maskId&&this._syncMaskLabel(i.target)}),this.canvas.on("object:modified",i=>this._handleObjectModified(i.target)),this.canvasElement.style.display="block"}_handleObjectModified(t){let s=this._getModifiedMasks(t);s.length&&(s.forEach(e=>{typeof e.setCoords=="function"&&e.setCoords(),this._syncMaskLabel(e),this._expandCanvasToFitObject(e)}),this.saveState())}_getModifiedMasks(t){if(!t)return[];if(t.maskId)return[t];let s=typeof t.getObjects=="function"?t.getObjects():[];return Array.isArray(s)?s.filter(e=>e&&e.maskId):[]}_syncContainerOverflow(){if(!(!this.containerElement||!this.containerElement.style))if(this._containerOriginalOverflow===void 0&&(this._containerOriginalOverflow=this.containerElement.style.overflow||""),this.options.coverImageToCanvas){let t=!this.isImageLoadedToCanvas;this.containerElement.style.overflow="scroll",t&&(this.containerElement.scrollLeft=0,this.containerElement.scrollTop=0)}else this.options.fitImageToCanvas?(this.containerElement.style.overflow="auto",this.containerElement.scrollLeft=0,this.containerElement.scrollTop=0):this.containerElement.style.overflow=this._containerOriginalOverflow}_bindEvents(){this._bindIfExists("uploadArea","click",()=>{let t=document.getElementById(this.elements.uploadArea);this._isElementDisabled(t)||document.getElementById(this.elements.imageInput)?.click()}),this._bindIfExists("imageInput","change",t=>{let s=t.target.files&&t.target.files[0];s&&this._loadImageFile(s)}),this._bindIfExists("zoomInBtn","click",()=>this.scaleImage(this.currentScale+this.options.scaleStep)),this._bindIfExists("zoomOutBtn","click",()=>this.scaleImage(this.currentScale-this.options.scaleStep)),this._bindIfExists("resetBtn","click",()=>{this.resetImageTransform()}),this._bindIfExists("addMaskBtn","click",()=>this.createMask()),this._bindIfExists("removeMaskBtn","click",()=>this.removeSelectedMask()),this._bindIfExists("removeAllMasksBtn","click",()=>this.removeAllMasks()),this._bindIfExists("mergeBtn","click",()=>this.mergeMasks()),this._bindIfExists("downloadBtn","click",()=>this.downloadImage()),this._bindIfExists("undoBtn","click",()=>this.undo()),this._bindIfExists("redoBtn","click",()=>this.redo()),this._bindIfExists("rotateLeftBtn","click",()=>{let t=document.getElementById(this.elements.rotationLeftInput),s=this.options.rotationStep;if(t){let e=parseFloat(t.value);isNaN(e)||(s=e)}this.rotateImage(this.currentRotation-s)}),this._bindIfExists("rotateRightBtn","click",()=>{let t=document.getElementById(this.elements.rotationRightInput),s=this.options.rotationStep;if(t){let e=parseFloat(t.value);isNaN(e)||(s=e)}this.rotateImage(this.currentRotation+s)}),this._bindIfExists("cropBtn","click",()=>this.enterCropMode()),this._bindIfExists("applyCropBtn","click",()=>{this.applyCrop().catch(t=>this._reportError("applyCrop failed",t))}),this._bindIfExists("cancelCropBtn","click",()=>this.cancelCrop())}_bindIfExists(t,s,e){let i=document.getElementById(this.elements[t]);i&&(i.addEventListener(s,e),this._handlersByElementKey=this._handlersByElementKey||{},this._handlersByElementKey[t]||(this._handlersByElementKey[t]=[]),this._handlersByElementKey[t].push({eventName:s,handler:e}))}_loadImageFile(t){if(!t||!t.type.startsWith("image/"))return;let s=new FileReader;s.onload=e=>this.loadImage(e.target.result),s.onerror=e=>{this._reportError("Image file could not be read",e)},s.readAsDataURL(t)}async loadImage(t){if(!this._fabricLoaded||!this.canvas||!t||typeof t!="string"||!t.startsWith("data:image/"))return;this._setPlaceholderVisible(!1),this._syncContainerOverflow();let s=await this._createImageElement(t),e=t;if(this.options.downsampleOnLoad&&(s.naturalWidth>this.options.downsampleMaxWidth||s.naturalHeight>this.options.downsampleMaxHeight)){let n=Math.min(this.options.downsampleMaxWidth/s.naturalWidth,this.options.downsampleMaxHeight/s.naturalHeight),a=Math.round(s.naturalWidth*n),o=Math.round(s.naturalHeight*n);e=this._resampleImageToDataURL(s,a,o,this.options.downsampleQuality)}return new Promise((i,n)=>{v.Image.fromURL(e,a=>{try{if(!a)throw new Error("Image could not be loaded");this.canvas.discardActiveObject(),this._hideAllMaskLabels(),this.canvas.clear(),this.canvas.setBackgroundColor(this.options.backgroundColor,this.canvas.renderAll.bind(this.canvas)),a.set({originX:"left",originY:"top",selectable:!1,evented:!1});let o=a.width,r=a.height,h=this._getContainerViewportSize(),c=h.width,l=h.height;if(this.options.fitImageToCanvas){let u=Math.max(1,Math.min(this.options.canvasWidth,c)-1),d=Math.max(1,Math.min(this.options.canvasHeight,l)-1);this._setCanvasSizeInt(u,d);let p=Math.min(u/o,d/r,1);a.set({left:0,top:0}),a.scale(p),this.baseImageScale=a.scaleX||1}else if(this.options.coverImageToCanvas){let u=this._calculateCoverCanvasLayout(o,r);this._setCanvasSizeInt(u.canvasWidth,u.canvasHeight),a.set({left:0,top:0}),a.scale(u.scale),this.baseImageScale=a.scaleX||1}else if(this.options.expandCanvasToImage){let u=Math.max(c,Math.floor(o)),d=Math.max(l,Math.floor(r));this._setCanvasSizeInt(u,d),a.set({left:0,top:0}),a.scale(1),this.baseImageScale=1}else{let u=Math.max(this.options.canvasWidth,c),d=Math.max(this.options.canvasHeight,l);this._setCanvasSizeInt(u,d);let p=Math.min(u/o,d/r,1);a.set({left:0,top:0}),a.scale(p),this.baseImageScale=a.scaleX||1}this.originalImage=a,this.canvas.add(a),this.canvas.sendToBack(a),this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null,this.maskCounter=0,this.currentScale=1,this.currentRotation=0,this._updateInputs(),this._updateMaskList(),this.isImageLoadedToCanvas=!0,this._updateUI(),this.canvas.renderAll();try{this._lastSnapshot=this._serializeCanvasState()}catch(u){this._reportWarning("loadImage: failed to capture initial canvas snapshot",u)}typeof this.onImageLoaded=="function"&&this.onImageLoaded(),i()}catch(o){n(o)}},{crossOrigin:"anonymous"})})}isImageLoaded(){let t=w();return!!(this.originalImage&&t&&this.originalImage instanceof t.Image&&this.originalImage.width>0&&this.originalImage.height>0)}_createImageElement(t){return new Promise((s,e)=>{let i=new Image;i.onload=()=>{i.onload=null,i.onerror=null,s(i)},i.onerror=n=>{i.onload=null,i.onerror=null,e(n)},i.src=t})}_resampleImageToDataURL(t,s,e,i=.92){let n=document.createElement("canvas");return n.width=s,n.height=e,n.getContext("2d").drawImage(t,0,0,t.naturalWidth,t.naturalHeight,0,0,s,e),n.toDataURL("image/jpeg",i)}_setCanvasSizeInt(t,s){let e=Math.max(1,Math.round(Number(t)||1)),i=Math.max(1,Math.round(Number(s)||1));this.canvas.setWidth(e),this.canvas.setHeight(i),typeof this.canvas.calcOffset=="function"&&this.canvas.calcOffset(),this.canvasElement&&(this.canvasElement.style.width=e+"px",this.canvasElement.style.height=i+"px",this.canvasElement.style.maxWidth="none")}_ceilCanvasDimension(t){let s=Number(t)||0,e=Math.round(s);return Math.abs(s-e)<.01?e:Math.ceil(s)}_getContainerViewportSize(){if(!this.containerElement)return{width:Math.max(1,Math.floor(this.options.canvasWidth||1)),height:Math.max(1,Math.floor(this.options.canvasHeight||1))};if(this._hasFixedContainerScrollbars())return{width:Math.max(1,Math.floor(this.containerElement.clientWidth||this.options.canvasWidth||1)),height:Math.max(1,Math.floor(this.containerElement.clientHeight||this.options.canvasHeight||1))};let t=this.containerElement.style.overflow;this.containerElement.style.overflow="hidden";let s=Math.max(1,Math.floor(this.containerElement.clientWidth||this.options.canvasWidth||1)),e=Math.max(1,Math.floor(this.containerElement.clientHeight||this.options.canvasHeight||1));return this.containerElement.style.overflow=t,{width:s,height:e}}_hasFixedContainerScrollbars(){if(!this.containerElement)return!1;let t=this.containerElement.style.overflow,s=this.containerElement.style.overflowX,e=this.containerElement.style.overflowY,i="",n="",a="";if(typeof window<"u"&&typeof window.getComputedStyle=="function"){let o=window.getComputedStyle(this.containerElement);i=o.overflow,n=o.overflowX,a=o.overflowY}return[t,s,e,i,n,a].some(o=>o==="scroll")}_getScrollbarSize(){if(typeof document>"u"||!document.createElement||!document.body)return{width:0,height:0};let t=document.createElement("div");t.style.position="absolute",t.style.visibility="hidden",t.style.overflow="scroll",t.style.width="100px",t.style.height="100px",t.style.top="-9999px",document.body.appendChild(t);let s=Math.max(0,t.offsetWidth-t.clientWidth),e=Math.max(0,t.offsetHeight-t.clientHeight);return document.body.removeChild(t),{width:s,height:e}}_getScrollSafetyMargin(){return 2}_getScrollableCanvasSize(t,s,e=this._getContainerViewportSize()){if(this._hasFixedContainerScrollbars()){let h=this._getScrollSafetyMargin(),c=Math.max(1,e.width-h),l=Math.max(1,e.height-h);return{width:t>e.width+.5?this._ceilCanvasDimension(t):c,height:s>e.height+.5?this._ceilCanvasDimension(s):l,viewportWidth:e.width,viewportHeight:e.height,hasHorizontal:!0,hasVertical:!0}}let i=this._getScrollbarSize(),n=!1,a=!1,o=e.width,r=e.height;for(let h=0;h<4;h+=1){o=Math.max(1,e.width-(n?i.width:0)),r=Math.max(1,e.height-(a?i.height:0));let c=s>r+.5,l=t>o+.5;if(c===n&&l===a)break;n=c,a=l}return o=Math.max(1,e.width-(n?i.width:0)),r=Math.max(1,e.height-(a?i.height:0)),{width:a?this._ceilCanvasDimension(t):o,height:n?this._ceilCanvasDimension(s):r,viewportWidth:o,viewportHeight:r,hasHorizontal:a,hasVertical:n}}_calculateCoverCanvasLayout(t,s){let e=this._getContainerViewportSize();if(this._hasFixedContainerScrollbars()){let d=this._getScrollSafetyMargin(),p=Math.max(1,e.width-d),m=Math.max(1,e.height-d),g=Math.min(1,Math.max(p/t,m/s)),f=t*g,C=s*g,y=this._getScrollableCanvasSize(f,C,e);return{scale:g,canvasWidth:y.width,canvasHeight:y.height}}let i=this._getScrollbarSize(),n=!1,a=!1,o=1,r=t,h=s,c=e.width,l=e.height;for(let d=0;d<4;d+=1){c=Math.max(1,e.width-(n?i.width:0)),l=Math.max(1,e.height-(a?i.height:0)),o=Math.min(1,Math.max(c/t,l/s)),r=t*o,h=s*o;let p=h>l+.5,m=r>c+.5;if(p===n&&m===a)break;n=p,a=m}let u=this._getScrollableCanvasSize(r,h,e);return{scale:o,canvasWidth:u.width,canvasHeight:u.height}}_getStateProperties(){return["maskId","maskName","maskLabel","isCropRect","originalAlpha","originalStroke","originalStrokeWidth","selectable","evented","hasControls","lockRotation","borderColor","cornerColor","cornerSize","transparentCorners","strokeUniform","strokeDashArray"]}_getMaskNormalStyle(t){let s=Number(t&&t.originalStrokeWidth),e=Number(t&&t.originalAlpha),i={stroke:t&&t.originalStroke||"#ccc",strokeWidth:Number.isFinite(s)?s:1};return Number.isFinite(e)&&(i.opacity=e),i}_withNormalizedMaskStyles(t){if(!this.canvas)return t();let s=this.canvas.getObjects().filter(i=>i.maskId),e=s.map(i=>({object:i,stroke:i.stroke,strokeWidth:i.strokeWidth,opacity:i.opacity}));try{return s.forEach(i=>{i.set(this._getMaskNormalStyle(i))}),t()}finally{e.forEach(i=>{try{i.object.set({stroke:i.stroke,strokeWidth:i.strokeWidth,opacity:i.opacity})}catch(n){}})}}_restoreMaskControls(t){if(!t)return;let s=Number(t.cornerSize);t.set({selectable:t.selectable!==!1,evented:t.evented!==!1,hasControls:t.hasControls!==!1,lockRotation:typeof t.lockRotation=="boolean"?t.lockRotation:!this.options.maskRotatable,borderColor:t.borderColor||"red",cornerColor:t.cornerColor||"black",cornerSize:Number.isFinite(s)?s:8,transparentCorners:t.transparentCorners===!0,strokeUniform:t.strokeUniform!==!1}),typeof t.setCoords=="function"&&t.setCoords()}_serializeCanvasState(){return this.canvas?this._withNormalizedMaskStyles(()=>{let t=this.canvas.toJSON(this._getStateProperties());return Array.isArray(t.objects)&&(t.objects=t.objects.filter(s=>!s.isCropRect&&!s.maskLabel)),JSON.stringify(t)}):null}_normalizeQuality(t){let s=Number(t);return Number.isFinite(s)?Math.max(0,Math.min(1,s)):this.options.downsampleQuality??.92}_normalizeImageFormat(t){return{jpeg:"jpeg",jpg:"jpeg","image/jpeg":"jpeg",png:"png","image/png":"png",webp:"webp","image/webp":"webp"}[String(t||"jpeg").toLowerCase()]||"jpeg"}_getClampedCanvasRegion(t,s={}){let e=Math.max(1,Math.round(this.canvas.getWidth())),i=Math.max(1,Math.round(this.canvas.getHeight())),n=Number(t.left)||0,a=Number(t.top)||0,o=Math.max(0,Number(t.width)||0),r=Math.max(0,Number(t.height)||0),c=s.includePartialPixels!==!1?Math.ceil:Math.floor,l=Math.min(e-1,Math.max(0,Math.floor(n))),u=Math.min(i-1,Math.max(0,Math.floor(a))),d=Math.min(e,Math.max(l+1,c(n+o))),p=Math.min(i,Math.max(u+1,c(a+r)));return{sx:l,sy:u,sw:Math.max(1,d-l),sh:Math.max(1,p-u)}}async _cropDataUrl(t,s,e,i,n,a,o="jpeg",r=.92){return new Promise((h,c)=>{let l=new Image;l.onload=()=>{try{let u=Math.max(1,Number(a)||1),d=Math.round(s*u),p=Math.round(e*u),m=Math.max(1,Math.round(i*u)),g=Math.max(1,Math.round(n*u)),f=document.createElement("canvas");f.width=m,f.height=g,f.getContext("2d").drawImage(l,d,p,m,g,0,0,m,g),h(f.toDataURL(`image/${o}`,r))}catch(u){c(u)}},l.onerror=c,l.src=t})}async _exportCanvasRegionToDataURL({sx:t,sy:s,sw:e,sh:i,multiplier:n=1,quality:a=.92,format:o="jpeg"}){let r=Math.max(1,Number(n)||1),h=this.canvas.toDataURL({format:o,quality:a,multiplier:r});return this._cropDataUrl(h,t,s,e,i,r,o,a)}_getObjectTopLeftPoint(t){if(!t)return{x:0,y:0};t.setCoords();let s=typeof t.getCoords=="function"?t.getCoords():null;if(s&&s.length)return s[0];let e=t.getBoundingRect(!0,!0);return{x:e.left,y:e.top}}_setObjectOriginKeepingPosition(t,s,e,i){!t||!i||!t.setPositionByOrigin||(t.set({originX:s,originY:e}),t.setPositionByOrigin(i,s,e),t.setCoords())}_alignObjectBoundingBoxToCanvasTopLeft(t){if(!t)return;t.setCoords();let s=t.getBoundingRect(!0,!0),e=s.left,i=s.top;t.set({left:(t.left||0)-e,top:(t.top||0)-i}),t.setCoords(),this.canvas.renderAll()}_updateCanvasSizeToImageBounds(){if(!this.originalImage)return;this.originalImage.setCoords();let t=this.originalImage.getBoundingRect(!0,!0),s=this._getScrollableCanvasSize(t.width,t.height);this._setCanvasSizeInt(s.width,s.height)}_expandCanvasToFitObject(t,s=10){if(!(!this.canvas||!t||!this.options.expandCanvasToImage))try{t.setCoords();let e=t.getBoundingRect(!0,!0),i=Math.ceil(e.left+e.width+s),n=Math.ceil(e.top+e.height+s),a=this.containerElement?Math.floor(this.containerElement.clientWidth||0):0,o=this.containerElement?Math.floor(this.containerElement.clientHeight||0):0,r=Math.max(this.canvas.getWidth(),a,i),h=Math.max(this.canvas.getHeight(),o,n);this._setCanvasSizeInt(r,h)}catch(e){this._reportWarning("expandCanvasToFitObject: failed to expand canvas",e)}}scaleImage(t,s={}){return this.animQueue.add(()=>this._scaleImageImpl(t,s))}_scaleImageImpl(t,s={}){if(!this.originalImage||this.isAnimating)return Promise.resolve();let e=s.saveHistory!==!1;t=Math.max(this.options.minScale,Math.min(this.options.maxScale,t)),this.currentScale=t,this.isAnimating=!0,this._updateUI();let i=this.baseImageScale*t,n=this._getObjectTopLeftPoint(this.originalImage);this._setObjectOriginKeepingPosition(this.originalImage,"left","top",n);let a=new Promise(r=>{this.originalImage.animate("scaleX",i,{duration:this.options.animationDuration,onChange:this.canvas.renderAll.bind(this.canvas),onComplete:r})}),o=new Promise(r=>{this.originalImage.animate("scaleY",i,{duration:this.options.animationDuration,onChange:this.canvas.renderAll.bind(this.canvas),onComplete:r})});return Promise.all([a,o]).then(()=>{this.originalImage.set({scaleX:i,scaleY:i}),this.originalImage.setCoords(),(this.options.expandCanvasToImage||this.options.coverImageToCanvas)&&this._updateCanvasSizeToImageBounds(),this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage),this.canvas.getObjects().forEach(r=>{r.maskId&&this._syncMaskLabel(r)}),this.isAnimating=!1,this._updateInputs(),this._updateUI(),e&&this.saveState()}).catch(()=>{this.isAnimating=!1,this._updateUI()})}rotateImage(t,s={}){return this.animQueue.add(()=>this._rotateImageImpl(t,s))}_rotateImageImpl(t,s={}){if(!this.originalImage||this.isAnimating||isNaN(t))return Promise.resolve();let e=s.saveHistory!==!1;this.currentRotation=t,this.isAnimating=!0,this._updateUI();let i=this.originalImage.getCenterPoint();return this._setObjectOriginKeepingPosition(this.originalImage,"center","center",i),new Promise(a=>{this.originalImage.animate("angle",t,{duration:this.options.animationDuration,onChange:this.canvas.renderAll.bind(this.canvas),onComplete:a})}).then(()=>{this.originalImage.set("angle",t),this.originalImage.setCoords(),(this.options.expandCanvasToImage||this.options.coverImageToCanvas)&&this._updateCanvasSizeToImageBounds(),this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);let a=this._getObjectTopLeftPoint(this.originalImage);this._setObjectOriginKeepingPosition(this.originalImage,"left","top",a),this.canvas.getObjects().forEach(o=>{o.maskId&&this._syncMaskLabel(o)}),this.isAnimating=!1,this._updateInputs(),this._updateUI(),e&&this.saveState()}).catch(()=>{this.isAnimating=!1,this._updateUI()})}resetImageTransform(){return this.originalImage?this.animQueue.add(async()=>{let t=this._serializeCanvasState();await this._scaleImageImpl(1,{saveHistory:!1}),await this._rotateImageImpl(0,{saveHistory:!1});let s=this._serializeCanvasState();this._pushStateTransition(t,s)}).catch(t=>{this._reportError("resetImageTransform() failed",t)}):Promise.resolve()}reset(){return this.resetImageTransform()}loadFromState(t){return!t||!this.canvas?Promise.resolve():new Promise(s=>{try{let e=typeof t=="string"?JSON.parse(t):t;this.canvas.loadFromJSON(e,()=>{try{this._hideAllMaskLabels();let i=this.canvas.getObjects();if(this.originalImage=i.find(a=>a.type==="image"&&!a.maskId)||null,this.originalImage){this.originalImage.set({originX:"left",originY:"top",selectable:!1,evented:!1,hasControls:!1,hoverCursor:"default"}),this.canvas.sendToBack(this.originalImage),this.currentRotation=Number(this.originalImage.angle)||0;let a=Number(this.baseImageScale)||1,o=Number(this.originalImage.scaleX)||a;this.currentScale=o/a}else this.currentScale=1,this.currentRotation=0;let n=i.filter(a=>a.maskId);n.forEach(a=>{this._restoreMaskControls(a),this._rebindMaskEvents(a),a.set(this._getMaskNormalStyle(a))}),this.maskCounter=n.reduce((a,o)=>Math.max(a,o.maskId),0),this._lastMask=n.length?n[n.length-1]:null,this._lastMask||(this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null),this.isImageLoadedToCanvas=!!this.originalImage,this.canvas.renderAll(),this._updateInputs(),this._updateMaskList(),this._updatePlaceholderStatus(),this._lastSnapshot=this._serializeCanvasState(),this._updateUI()}catch(i){this._reportError("loadFromState() failed",i)}finally{s()}})}catch(e){this._reportError("loadFromState() failed",e),s()}})}saveState(){if(!this.canvas)return;let t=this.canvas.getActiveObject();this._hideAllMaskLabels();try{let s=this._serializeCanvasState(),e=this._lastSnapshot||s;if(s===e)return;let i=!1,n=new b(()=>{if(i)return this.loadFromState(s);i=!0},()=>this.loadFromState(e));this.historyManager.execute(n),this._lastSnapshot=s}catch(s){this._reportWarning("saveState: failed to save canvas snapshot",s)}finally{t&&t.maskId&&this.canvas.getObjects().includes(t)&&this._handleSelectionChanged([t]),this._updateUI()}}_pushStateTransition(t,s){if(!t||!s||t===s)return;this.historyManager||(this.historyManager=new I(this.maxHistorySize||50));let e=new b(()=>this.loadFromState(s),()=>this.loadFromState(t));this.historyManager.push(e),this._lastSnapshot=s,this._updateUI()}undo(){return this.historyManager.undo().then(()=>{this._updateUI()}).catch(t=>{this._reportError("undo failed",t)})}redo(){return this.historyManager.redo().then(()=>{this._updateUI()}).catch(t=>{this._reportError("redo failed",t)})}_rebindMaskEvents(t){if(!t)return;if(t.__imageEditorMaskHandlers)try{t.off("mouseover",t.__imageEditorMaskHandlers.mouseover),t.off("mouseout",t.__imageEditorMaskHandlers.mouseout)}catch(o){}let s={};Number.isFinite(Number(t.originalAlpha))||(s.originalAlpha=Number.isFinite(Number(t.opacity))?Number(t.opacity):.5),t.originalStroke||(s.originalStroke=t.stroke||"#ccc"),Number.isFinite(Number(t.originalStrokeWidth))||(s.originalStrokeWidth=Number.isFinite(Number(t.strokeWidth))?Number(t.strokeWidth):1),Object.keys(s).length&&t.set(s);let e={stroke:t.originalStroke||"#ccc",strokeWidth:t.originalStrokeWidth,opacity:t.originalAlpha},i={stroke:"#ff5500",strokeWidth:2,opacity:Math.min(t.originalAlpha+.2,1)},n=()=>{t.set(i),t.canvas&&t.canvas.requestRenderAll()},a=()=>{t.set(e),t.canvas&&t.canvas.requestRenderAll()};t.on("mouseover",n),t.on("mouseout",a),t.__imageEditorMaskHandlers={mouseover:n,mouseout:a}}createMask(t={}){if(!this.canvas)return null;let s=t.shape||"rect",e={shape:s,width:this.options.defaultMaskWidth,height:this.options.defaultMaskHeight,color:"rgba(0,0,0,0.5)",alpha:.5,gap:5,left:void 0,top:void 0,angle:0,selectable:!0,...t},i=10,n=i,a=i,o=(d,p)=>{if(typeof d=="function")return d(this.canvas,this.options);if(typeof d=="string"&&d.endsWith("%")){let m=parseFloat(d)/100;return Math.floor((this.canvas?this.canvas.getWidth():0)*m)}return d??p};if(e.left===void 0&&this._lastMask){let d=this._lastMask,p=d.left;d.getScaledWidth?p+=d.getScaledWidth():d.width&&(p+=d.width*(d.scaleX??1)),n=Math.round(p+e.gap),a=d.top??i}else n=o(e.left,i),a=o(e.top,i);e.width=o(e.width,this.options.defaultMaskWidth),e.height=o(e.height,this.options.defaultMaskHeight);let r;if(typeof e.fabricGenerator=="function")r=e.fabricGenerator(e,this.canvas,this.options);else switch(s){case"circle":r=new v.Circle({left:n,top:a,radius:o(e.radius,Math.min(e.width,e.height)/2),fill:e.color,opacity:e.alpha,angle:e.angle,...e.styles});break;case"ellipse":r=new v.Ellipse({left:n,top:a,rx:o(e.rx,e.width/2),ry:o(e.ry,e.height/2),fill:e.color,opacity:e.alpha,angle:e.angle,...e.styles});break;case"polygon":{let d=e.points||[];Array.isArray(d)&&d.length&&typeof d[0]=="object"&&(d=d.map(p=>({x:Number(p.x),y:Number(p.y)}))),r=new v.Polygon(d,{left:n,top:a,fill:e.color,opacity:e.alpha,angle:e.angle,...e.styles});break}case"rect":default:r=new v.Rect({left:n,top:a,width:o(e.width,this.options.defaultMaskWidth),height:o(e.height,this.options.defaultMaskHeight),fill:e.color,opacity:e.alpha,angle:e.angle,rx:e.rx,ry:e.ry,...e.styles})}let h=e.styles||{},c=d=>Object.prototype.hasOwnProperty.call(h,d),l={selectable:e.selectable!==!1,hasControls:"hasControls"in e?e.hasControls:!0,lockRotation:!this.options.maskRotatable,borderColor:"borderColor"in e?e.borderColor:"red",cornerColor:"cornerColor"in e?e.cornerColor:"black",cornerSize:"cornerSize"in e?e.cornerSize:8,transparentCorners:"transparentCorners"in e?e.transparentCorners:!1,stroke:c("stroke")?h.stroke:"#ccc",strokeWidth:c("strokeWidth")?h.strokeWidth:1,strokeUniform:"strokeUniform"in e?e.strokeUniform:c("strokeUniform")?h.strokeUniform:!0};c("strokeDashArray")&&(l.strokeDashArray=h.strokeDashArray),r.set(l),r.setCoords(),r.set({originalAlpha:e.alpha,originalStroke:r.stroke||"#ccc",originalStrokeWidth:Number.isFinite(Number(r.strokeWidth))?Number(r.strokeWidth):1}),this._rebindMaskEvents(r),this._expandCanvasToFitObject(r),this._lastMaskInitialLeft=n,this._lastMaskInitialTop=a,this._lastMaskInitialWidth=o(e.width,this.options.defaultMaskWidth);let u=++this.maskCounter;return r.set({maskId:u,maskName:`${this.options.maskName}${u}`}),this._lastMask=r,this.canvas.add(r),this.canvas.bringToFront(r),e.selectable&&this.canvas.setActiveObject(r),this._handleSelectionChanged([r]),this._updateMaskList(),this._updateUI(),this.canvas.renderAll(),this.saveState(),typeof e.onCreate=="function"&&e.onCreate(r,this.canvas),r}addMask(t={}){return this.createMask(t)}removeSelectedMask(){let t=this.canvas.getActiveObject(),s=this._getModifiedMasks(t);if(!s.length)return;this.canvas.discardActiveObject(),s.forEach(i=>{this._removeLabelForMask(i),this.canvas.remove(i)});let e=this.canvas.getObjects().filter(i=>i.maskId);this._lastMask=e.length?e[e.length-1]:null,this._lastMask||(this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null),this._updateMaskList(),this._updateUI(),this.canvas.renderAll(),this.saveState()}removeAllMasks(t={}){let s=t.saveHistory!==!1,e=this.canvas.getObjects().filter(i=>i.maskId);e.forEach(i=>this._removeLabelForMask(i)),e.forEach(i=>this.canvas.remove(i)),this.canvas.discardActiveObject(),this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null,this._updateMaskList(),this._updateUI(),this.canvas.renderAll(),s&&this.saveState()}_removeLabelForMask(t){if(!(!t||!this.canvas)&&t.__label){try{this.canvas.getObjects().includes(t.__label)&&this.canvas.remove(t.__label)}catch(s){}try{delete t.__label}catch(s){}}}_createLabelForMask(t){if(!t||!this.options.maskLabelOnSelect)return;this._removeLabelForMask(t);let s=null;if(this.options.label&&typeof this.options.label.create=="function"&&(s=this.options.label.create(t,v)),!s){let e=t.maskName,i={left:0,top:0,fontSize:12,fill:"#fff",backgroundColor:"rgba(0,0,0,0.7)",selectable:!1,evented:!1,padding:2,originX:"left",originY:"top"};if(this.options.label){if(typeof this.options.label.getText=="function"){let n=this.canvas?this.canvas.getObjects().filter(o=>o.maskId):[],a=Math.max(0,n.indexOf(t));e=this.options.label.getText(t,a)}this.options.label.textOptions&&Object.assign(i,this.options.label.textOptions)}s=new v.Text(e,i)}s.maskLabel=!0,t.__label=s,this.canvas.add(s),this.canvas.bringToFront(s),this._syncMaskLabel(t)}_hideAllMaskLabels(){if(!this.canvas)return;let t=this.canvas.getObjects();t.filter(e=>e.maskLabel).forEach(e=>{try{t.includes(e)&&this.canvas.remove(e)}catch(i){}}),t.forEach(e=>{if(e.maskId&&e.__label)try{delete e.__label}catch(i){}})}_syncMaskLabel(t){if(!t||!this.options.maskLabelOnSelect||!t.__label)return;let s=t.getCoords?t.getCoords():null;if(!s||s.length<4)return;let e=s[0],i=t.getCenterPoint(),n=i.x-e.x,a=i.y-e.y,o=Math.sqrt(n*n+a*a)||1,r=n/o,h=a/o,c=Math.max(0,this.options.maskLabelOffset??3),l=e.x+r*c,u=e.y+h*c;t.__label.set({left:Math.round(l),top:Math.round(u),angle:t.angle||0,originX:"left",originY:"top",visible:!0}),t.__label.setCoords(),typeof this.canvas.requestRenderAll=="function"?this.canvas.requestRenderAll():this.canvas.renderAll()}_showLabelForMask(t){t&&this.options.maskLabelOnSelect&&(t.__label||this._createLabelForMask(t),t.__label.set({visible:!0}),this._syncMaskLabel(t))}_handleSelectionChanged(t){let s=(t||[]).find(i=>i.maskId);this.canvas.getObjects().filter(i=>i.maskId).forEach(i=>{if(i!==s){if(i.__label){try{this.canvas.remove(i.__label)}catch(a){}delete i.__label}let n=Number(i.originalStrokeWidth);i.set({stroke:i.originalStroke||"#ccc",strokeWidth:Number.isFinite(n)?n:1})}else i.set({stroke:"#ff0000",strokeWidth:1})}),s&&this._showLabelForMask(s),this._updateMaskListSelection(s),this.canvas.renderAll(),this._updateUI()}_updateMaskList(){let t=document.getElementById(this.elements.maskList);if(!t)return;t.innerHTML="",this.canvas.getObjects().filter(e=>e.maskId).forEach(e=>{let i=document.createElement("li");i.className="list-group-item mask-item",i.textContent=e.maskName,i.onclick=()=>{this.canvas.setActiveObject(e),this._handleSelectionChanged([e])},t.appendChild(i)})}_updateMaskListSelection(t){let s=document.getElementById(this.elements.maskList);if(!s)return;s.querySelectorAll(".mask-item").forEach(i=>{let n=!!t&&i.textContent===t.maskName;i.classList.toggle("active",n)})}async mergeMasks(){if(!(!this.originalImage||!this.canvas.getObjects().filter(s=>s.maskId).length)){this.canvas.discardActiveObject(),this.canvas.renderAll();try{let s=this._serializeCanvasState(),e=await this.exportImageBase64({exportImageArea:!0,multiplier:this.options.exportMultiplier});this.removeAllMasks({saveHistory:!1}),await this.loadImage(e);let i=this._serializeCanvasState();this._pushStateTransition(s,i)}catch(s){this._reportError("merge error",s)}}}async merge(){return this.mergeMasks()}downloadImage(t=this.options.defaultDownloadFileName){if(!this.originalImage)return;let s=this.options.exportImageAreaByDefault;this.exportImageBase64({exportImageArea:s,multiplier:this.options.exportMultiplier}).then(e=>{let i=document.createElement("a");i.download=t,i.href=e,document.body.appendChild(i),i.click(),document.body.removeChild(i)}).catch(e=>this._reportError("download error",e))}async exportImageBase64(t={}){if(!this.originalImage)throw new Error("No image loaded");let s=typeof t.exportImageArea=="boolean"?t.exportImageArea:this.options.exportImageAreaByDefault,e=t.multiplier||this.options.exportMultiplier||1,i=this._normalizeQuality(t.quality??this.options.downsampleQuality),n=this._normalizeImageFormat(t.fileType||t.format);if(!s){let h=this.canvas.getObjects().filter(l=>l.maskId||l.maskLabel),c=h.map(l=>({object:l,visible:l.visible}));try{h.forEach(g=>{g.set({visible:!1})}),this.canvas.discardActiveObject(),this.canvas.renderAll(),this.originalImage.setCoords();let l=this.originalImage.getBoundingRect(!0,!0),{sx:u,sy:d,sw:p,sh:m}=this._getClampedCanvasRegion(l,{includePartialPixels:!1});return await this._exportCanvasRegionToDataURL({sx:u,sy:d,sw:p,sh:m,multiplier:e,quality:i,format:n})}finally{c.forEach(l=>{try{l.object.set({visible:l.visible})}catch(u){}}),this.canvas.renderAll()}}let a=this.canvas.getObjects().filter(h=>h.maskId),o=a.map(h=>({object:h,opacity:h.opacity,fill:h.fill,strokeWidth:h.strokeWidth,stroke:h.stroke,selectable:h.selectable,lockRotation:h.lockRotation})),r;try{a.forEach(p=>this._removeLabelForMask(p)),this.canvas.discardActiveObject(),this.canvas.renderAll(),a.forEach(p=>{p.set({opacity:1,fill:"#000000",strokeWidth:0,stroke:null,selectable:!1}),p.setCoords()}),this.canvas.renderAll(),this.originalImage.setCoords();let h=this.originalImage.getBoundingRect(!0,!0),{sx:c,sy:l,sw:u,sh:d}=this._getClampedCanvasRegion(h,{includePartialPixels:!1});r=await this._exportCanvasRegionToDataURL({sx:c,sy:l,sw:u,sh:d,multiplier:e,quality:i,format:n})}finally{o.forEach(h=>{try{h.object.set({opacity:h.opacity,fill:h.fill,strokeWidth:h.strokeWidth,stroke:h.stroke,selectable:h.selectable,lockRotation:h.lockRotation}),h.object.setCoords()}catch(c){}}),this.canvas.renderAll()}return r}async getImageBase64(t={}){return this.exportImageBase64(t)}async exportImageFile(t={}){if(!this.originalImage)throw new Error("No image loaded");let{mergeMask:s=!0,fileType:e="jpeg",quality:i=this.options.downsampleQuality??.92,multiplier:n=this.options.exportMultiplier??1,fileName:a=this.options.defaultDownloadFileName??"exported_image.jpg"}=t,o=this._normalizeImageFormat(e),r;s?r=await this.exportImageBase64({exportImageArea:!0,multiplier:n,quality:i,fileType:o}):r=await this.exportImageBase64({exportImageArea:!1,multiplier:n,quality:i,fileType:o});let h=r;h.startsWith(`data:image/${o}`)||(h=await new Promise((p,m)=>{let g=new window.Image;g.crossOrigin="Anonymous",g.onload=()=>{try{let f=document.createElement("canvas");f.width=g.width,f.height=g.height,f.getContext("2d").drawImage(g,0,0);let y=f.toDataURL(`image/${o}`,i);p(y)}catch(f){m(f)}},g.onerror=m,g.src=r}));let c=atob(h.split(",")[1]),l=`image/${o}`,u=c.length,d=new Uint8Array(u);for(;u--;)d[u]=c.charCodeAt(u);return new File([d],a,{type:l})}_clearMaskPlacementMemory(){this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null}async _restoreStateAfterCropFailure(t,s,e){if(this._reportError(s,e),this._cropRect&&this.canvas&&this._removeCropRect(),this._cropRect=null,this._cropMode=!1,this.canvas&&this._prevSelectionSetting!==void 0&&(this.canvas.selection=!!this._prevSelectionSetting),this._prevSelectionSetting=void 0,t)try{await this.loadFromState(t)}catch(i){this._reportError("applyCrop: rollback failed",i)}this._updateUI(),this.canvas&&this.canvas.renderAll()}_restoreCropObjectState(){Array.isArray(this._cropPrevEvented)&&this._cropPrevEvented.forEach(t=>{try{t.object.set({evented:t.evented,selectable:t.selectable,visible:t.visible})}catch(s){}}),this._cropPrevEvented=null}_removeCropRect(){if(this._cropRect){try{this._cropHandlers&&this._cropHandlers.length&&this._cropHandlers.forEach(t=>{t.handlers.forEach(s=>{t.target.off(s.eventName,s.handler)})})}catch(t){}try{this.canvas.remove(this._cropRect)}catch(t){}this._cropRect=null,this._cropHandlers=[]}}enterCropMode(){if(!this.canvas||!this.originalImage||this._cropMode||!this.isImageLoaded())return;this._cropMode=!0,this._prevSelectionSetting=this.canvas.selection,this.canvas.selection=!1,this.canvas.discardActiveObject(),this.originalImage.setCoords();let t=this.originalImage.getBoundingRect(!0,!0),s=this.options.crop&&this.options.crop.padding?this.options.crop.padding:10,e=Math.max(0,Math.floor(t.left+s)),i=Math.max(0,Math.floor(t.top+s)),n=Math.min(this.options.crop.minWidth||50,Math.floor(t.width-s*2)),a=Math.min(this.options.crop.minHeight||50,Math.floor(t.height-s*2)),o=new v.Rect({left:e,top:i,width:n,height:a,fill:"rgba(0,0,0,0.12)",stroke:"#00aaff",strokeDashArray:[6,4],strokeWidth:1,strokeUniform:!0,selectable:!0,hasRotatingPoint:!!(this.options.crop&&this.options.crop.allowRotationOfCropRect),lockRotation:!(this.options.crop&&this.options.crop.allowRotationOfCropRect),cornerSize:8,objectCaching:!1,originX:"left",originY:"top"});this.canvas.add(o),o.isCropRect=!0,this.canvas.bringToFront(o),this.canvas.setActiveObject(o),this._cropRect=o,this._cropPrevEvented=[];let r=!!(this.options.crop&&this.options.crop.hideMasksDuringCrop);this.canvas.getObjects().forEach(c=>{if(c!==o){this._cropPrevEvented.push({object:c,evented:c.evented,selectable:c.selectable,visible:c.visible});try{let l={evented:!1,selectable:!1};r&&(c.maskId||c.maskLabel)&&(l.visible=!1),c.set(l)}catch(l){}}});let h=()=>{try{o.setCoords(),this.canvas.requestRenderAll()}catch(c){}};o.on("modified",h),o.on("moving",h),o.on("scaling",h),this._cropHandlers.push({target:o,handlers:[{eventName:"modified",handler:h},{eventName:"moving",handler:h},{eventName:"scaling",handler:h}]}),this._updateUI(),this.canvas.renderAll()}cancelCrop(){!this.canvas||!this._cropMode||(this._removeCropRect(),this._restoreCropObjectState(),this._cropMode=!1,this.canvas.selection=!!this._prevSelectionSetting,this._prevSelectionSetting=void 0,this.canvas.discardActiveObject(),this._updateUI(),this.canvas.renderAll())}async applyCrop(){if(!this.canvas||!this._cropMode||!this._cropRect)return;this._cropRect.setCoords();let t=this._cropRect.getBoundingRect(!0,!0),{sx:s,sy:e,sw:i,sh:n}=this._getClampedCanvasRegion(t),a=!!(this.options.crop&&this.options.crop.preserveMasksAfterCrop);this._restoreCropObjectState();let o=null;try{o=this._serializeCanvasState()}catch(l){this._reportWarning("applyCrop: could not serialize before state",l),o=null}let r=[];try{let l=this.canvas.getObjects().filter(u=>u.maskId);l&&l.length&&(l.forEach(u=>{try{u.setCoords();let d=u.getBoundingRect(!0,!0),p=d.left<s+i&&d.left+d.width>s&&d.top<e+n&&d.top+d.height>e;this._removeLabelForMask(u),this.canvas.remove(u),a&&p&&(u.set({left:(u.left||0)-s,top:(u.top||0)-e,visible:!0}),u.setCoords(),r.push(u))}catch(d){this._reportWarning("applyCrop: failed to remove mask",d)}}),this._clearMaskPlacementMemory(),this.canvas.discardActiveObject(),this.canvas.renderAll())}catch(l){this._reportWarning("applyCrop: error while removing masks",l)}this._removeCropRect(),this._cropMode=!1,this.canvas.selection=!!this._prevSelectionSetting,this._prevSelectionSetting=void 0;let h;try{h=await this._exportCanvasRegionToDataURL({sx:s,sy:e,sw:i,sh:n,multiplier:1,quality:this._normalizeQuality(this.options.downsampleQuality),format:"jpeg"})}catch(l){await this._restoreStateAfterCropFailure(o,"applyCrop: failed to create cropped image",l);return}try{await this.loadImage(h),r.length&&(r.forEach(l=>{this._rebindMaskEvents(l),this.canvas.add(l),this.canvas.bringToFront(l)}),this._lastMask=r[r.length-1],this.maskCounter=r.reduce((l,u)=>Math.max(l,u.maskId||0),this.maskCounter),this._updateMaskList(),this.canvas.renderAll())}catch(l){await this._restoreStateAfterCropFailure(o,"applyCrop: loadImage(croppedBase64) failed",l);return}let c=null;try{c=this._serializeCanvasState()}catch(l){this._reportWarning("applyCrop: failed to serialize after state",l),c=null}try{this._pushStateTransition(o,c)}catch(l){this._reportWarning("applyCrop: failed to push history command",l)}this._updateUI(),this.canvas.renderAll()}_updateInputs(){let t=document.getElementById(this.elements.scaleRate);t&&(t.value=Math.round(this.currentScale*100))}_updateUI(){let t=!!this.originalImage,e=(t?this.canvas.getObjects().filter(c=>c.maskId):[]).length>0,i=this.canvas.getActiveObject(),n=i&&i.maskId,a=this.currentScale===1&&this.currentRotation===0,o=this.historyManager?.canUndo(),r=this.historyManager?.canRedo();if(!!this._cropMode){for(let c of Object.keys(this.elements||{}))document.getElementById(this.elements[c])&&(c==="applyCropBtn"||c==="cancelCropBtn"?this._setDisabled(c,!1):this._setDisabled(c,!0));return}this._setDisabled("zoomInBtn",!t||this.isAnimating||this.currentScale>=this.options.maxScale),this._setDisabled("zoomOutBtn",!t||this.isAnimating||this.currentScale<=this.options.minScale),this._setDisabled("rotateLeftBtn",!t||this.isAnimating),this._setDisabled("rotateRightBtn",!t||this.isAnimating),this._setDisabled("addMaskBtn",!t||this.isAnimating),this._setDisabled("removeMaskBtn",!n||this.isAnimating),this._setDisabled("removeAllMasksBtn",!e||this.isAnimating),this._setDisabled("mergeBtn",!t||!e||this.isAnimating),this._setDisabled("downloadBtn",!t||this.isAnimating),this._setDisabled("resetBtn",!t||a||this.isAnimating),this._setDisabled("undoBtn",!t||this.isAnimating||!o),this._setDisabled("redoBtn",!t||this.isAnimating||!r),this._setDisabled("cropBtn",!t||this.isAnimating),this._setDisabled("applyCropBtn",!0),this._setDisabled("cancelCropBtn",!0),this._setDisabled("imageInput",this.isAnimating),this._setDisabled("uploadArea",this.isAnimating)}_setDisabled(t,s){let e=document.getElementById(this.elements[t]);if(e){if("disabled"in e){e.disabled=!!s;return}s?(e.setAttribute("aria-disabled","true"),e.style.pointerEvents="none"):(e.removeAttribute("aria-disabled"),e.style.pointerEvents="")}}_isElementDisabled(t){return t?"disabled"in t?!!t.disabled:t.getAttribute("aria-disabled")==="true":!1}_updatePlaceholderStatus(){this.options.showPlaceholder&&this._setPlaceholderVisible(!this.originalImage)}_setPlaceholderVisible(t){this.placeholderElement&&(t?(this.placeholderElement.classList.remove("d-none"),this.placeholderElement.classList.add("d-flex"),this.containerElement.classList.add("d-none")):(this.placeholderElement.classList.remove("d-flex"),this.placeholderElement.classList.add("d-none"),this.containerElement.classList.remove("d-none")))}dispose(){try{for(let t in this._handlersByElementKey||{}){let s=this._handlersByElementKey[t]||[],e=document.getElementById(this.elements[t]);e&&s.forEach(i=>{try{e.removeEventListener(i.eventName,i.handler)}catch(n){}})}}catch(t){}if(this._cropRect){try{this.canvas.remove(this._cropRect)}catch(t){}this._cropRect=null}if(this.containerElement&&this._containerOriginalOverflow!==void 0)try{this.containerElement.style.overflow=this._containerOriginalOverflow}catch(t){}if(this.canvas){try{this.canvas.dispose()}catch(t){}this.canvas=null,this.canvasElement=null,this.isImageLoadedToCanvas=!1}this._handlersByElementKey={}}},S=class{constructor(){this.queue=[],this.running=!1}async add(t){return new Promise((s,e)=>{this.queue.push({fn:t,resolve:s,reject:e}),this.running||this.processQueue()})}async processQueue(){if(this.queue.length===0){this.running=!1;return}this.running=!0;let{fn:t,resolve:s,reject:e}=this.queue.shift();try{let i=await t();s(i)}catch(i){e(i)}this.processQueue()}},b=class{constructor(t,s){this.execute=t,this.undo=s}},I=class{constructor(t=50){this.history=[],this.currentIndex=-1,this.maxSize=t,this.pending=Promise.resolve()}enqueue(t){let s=this.pending.then(t,t);return this.pending=s.catch(()=>{}),s}execute(t){t.execute(),this.push(t)}push(t){this.currentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.currentIndex+1)),this.history.push(t),this.history.length>this.maxSize?this.history.shift():this.currentIndex++}canUndo(){return this.currentIndex>=0}canRedo(){return this.currentIndex<this.history.length-1}undo(){return this.enqueue(async()=>{if(this.currentIndex>=0){let t=this.currentIndex;await this.history[t].undo(),this.currentIndex=t-1}})}redo(){return this.enqueue(async()=>{if(this.currentIndex<this.history.length-1){let t=this.currentIndex+1;await this.history[t].execute(),this.currentIndex=t}})}};var E=k;var M=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:null;x(M&&M.fabric);M&&(M.ImageEditor=E);})();
8
+ */var v=null;function L(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:null}function W(){let _=L();return _&&_.fabric?_.fabric:null}function B(_){return v=_||W(),v}function O(){return v||B(),v}var w=class{constructor(t={}){let i={getText:r=>r.maskName,textOptions:{fontSize:12,fill:"#fff",backgroundColor:"rgba(0,0,0,0.7)",padding:2,fontFamily:"monospace",fontWeight:"bold",selectable:!1,evented:!1,originX:"left",originY:"top"}},e={minWidth:100,minHeight:100,padding:10,hideMasksDuringCrop:!0,preserveMasksAfterCrop:!1,allowRotationOfCropRect:!1},s=t.label||{},n=t.crop||{};this.options={canvasWidth:800,canvasHeight:600,backgroundColor:"transparent",animationDuration:300,minScale:.1,maxScale:5,scaleStep:.05,rotationStep:90,expandCanvasToImage:!0,fitImageToCanvas:!1,coverImageToCanvas:!1,downsampleOnLoad:!0,downsampleMaxWidth:4e3,downsampleMaxHeight:3e3,downsampleQuality:.92,imageLoadTimeoutMs:3e4,exportMultiplier:1,exportImageAreaByDefault:!0,defaultMaskWidth:50,defaultMaskHeight:80,maskRotatable:!1,maskLabelOnSelect:!0,maskLabelOffset:3,maskName:"mask",groupSelection:!1,showPlaceholder:!0,initialImageBase64:null,defaultDownloadFileName:"edited_image.jpg",onError:null,onWarning:null,...t,label:{...i,...s,textOptions:{...i.textOptions,...s.textOptions||{}}},crop:{...e,...n}},this._fabricLoaded=!!O(),this._fabricLoaded||this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted."),this.canvas=null,this.canvasElement=null,this.containerElement=null,this.placeholderElement=null,this.originalImage=null,this.baseImageScale=1,this.currentScale=1,this.currentRotation=0,this.maskCounter=0,this.isAnimating=!1,this.elements={},this.isImageLoadedToCanvas=!1,this.maxHistorySize=50,this._handlersByElementKey={},this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null,this._lastSnapshot=null,this._cropMode=!1,this._cropRect=null,this._cropHandlers=[],this._cropPrevEvented=null,this._prevSelectionSetting=void 0,this._containerOriginalOverflow=void 0,this._scrollbarSizeCache=null,this.onImageLoaded=typeof t.onImageLoaded=="function"?t.onImageLoaded:null,this.animationQueue=new E,this.historyManager=new C(this.maxHistorySize)}get canvasEl(){return this.canvasElement}set canvasEl(t){this.canvasElement=t}get containerEl(){return this.containerElement}set containerEl(t){this.containerElement=t}get placeholderEl(){return this.placeholderElement}set placeholderEl(t){this.placeholderElement=t}init(t={}){if(!this._fabricLoaded)return;let i={canvas:"fabricCanvas",canvasContainer:null,imgPlaceholder:"imgPlaceholder",scaleRate:"scaleRate",rotationLeftInput:"rotationLeftInput",rotationRightInput:"rotationRightInput",rotateLeftBtn:"rotateLeftBtn",rotateRightBtn:"rotateRightBtn",addMaskBtn:"addMaskBtn",removeMaskBtn:"removeMaskBtn",removeAllMasksBtn:"removeAllMasksBtn",mergeBtn:"mergeBtn",downloadBtn:"downloadBtn",maskList:"maskList",zoomInBtn:"zoomInBtn",zoomOutBtn:"zoomOutBtn",resetBtn:"resetBtn",undoBtn:"undoBtn",redoBtn:"redoBtn",imageInput:"imageInput",cropBtn:"cropBtn",applyCropBtn:"applyCropBtn",cancelCropBtn:"cancelCropBtn"};this.elements={...i,...t},this._initCanvas(),this._bindEvents(),this._updateInputs(),this._updateMaskList(),this._updateUI(),this.options.initialImageBase64?this.loadImage(this.options.initialImageBase64):this._updatePlaceholderStatus()}_reportError(t,i=null){let e=this.options&&this.options.onError;if(typeof e=="function")try{e(i,t)}catch{}}_reportWarning(t,i=null){let e=this.options&&this.options.onWarning;if(typeof e=="function")try{e(i,t)}catch{}}_initCanvas(){let t=document.getElementById(this.elements.canvas);if(!t)throw new Error("Canvas is not found: "+this.elements.canvas);if(this.canvasElement=t,this.elements.canvasContainer){let s=document.getElementById(this.elements.canvasContainer);this.containerElement=s||t.parentElement}else this.containerElement=t.parentElement;this.placeholderElement=document.getElementById(this.elements.imgPlaceholder)||null;let i=this.options.canvasWidth,e=this.options.canvasHeight;if(this.containerElement){let s=Math.floor(this.containerElement.clientWidth),n=Math.floor(this.containerElement.clientHeight);s>0&&n>0&&(i=s,e=n)}this.canvas=new v.Canvas(t,{width:i,height:e,backgroundColor:this.options.backgroundColor,selection:this.options.groupSelection,preserveObjectStacking:!0}),this.canvas.on("selection:created",s=>this._handleSelectionChanged(s.selected)),this.canvas.on("selection:updated",s=>this._handleSelectionChanged(s.selected)),this.canvas.on("selection:cleared",()=>this._handleSelectionChanged([])),this.canvas.on("object:moving",s=>{s.target&&s.target.maskId&&this._syncMaskLabel(s.target)}),this.canvas.on("object:scaling",s=>{s.target&&s.target.maskId&&this._syncMaskLabel(s.target)}),this.canvas.on("object:rotating",s=>{s.target&&s.target.maskId&&this._syncMaskLabel(s.target)}),this.canvas.on("object:modified",s=>this._handleObjectModified(s.target)),this.canvasElement.style.display="block"}_handleObjectModified(t){let i=this._getModifiedMasks(t);i.length&&(i.forEach(e=>{typeof e.setCoords=="function"&&e.setCoords(),this._syncMaskLabel(e)}),this._expandCanvasToFitObjects(i),this.saveState())}_getModifiedMasks(t){if(!t)return[];if(t.maskId)return[t];let i=typeof t.getObjects=="function"?t.getObjects():[];return Array.isArray(i)?i.filter(e=>e&&e.maskId):[]}_syncContainerOverflow(t={}){if(!this.containerElement||!this.containerElement.style)return;this._containerOriginalOverflow===void 0&&(this._containerOriginalOverflow=this.containerElement.style.overflow||"");let i=t.preserveScroll===!0;this.options.coverImageToCanvas?(this.containerElement.style.overflow="scroll",i||(this.containerElement.scrollLeft=0,this.containerElement.scrollTop=0)):this.options.fitImageToCanvas?(this.containerElement.style.overflow="auto",i||(this.containerElement.scrollLeft=0,this.containerElement.scrollTop=0)):this.containerElement.style.overflow=this._containerOriginalOverflow}_bindEvents(){this._bindIfExists("uploadArea","click",()=>{let t=document.getElementById(this.elements.uploadArea);this._isElementDisabled(t)||document.getElementById(this.elements.imageInput)?.click()}),this._bindIfExists("imageInput","change",t=>{let i=t.target.files&&t.target.files[0];i&&this._loadImageFile(i)}),this._bindIfExists("zoomInBtn","click",()=>this.scaleImage(this.currentScale+this.options.scaleStep)),this._bindIfExists("zoomOutBtn","click",()=>this.scaleImage(this.currentScale-this.options.scaleStep)),this._bindIfExists("resetBtn","click",()=>{this.resetImageTransform()}),this._bindIfExists("addMaskBtn","click",()=>this.createMask()),this._bindIfExists("removeMaskBtn","click",()=>this.removeSelectedMask()),this._bindIfExists("removeAllMasksBtn","click",()=>this.removeAllMasks()),this._bindIfExists("mergeBtn","click",()=>this.mergeMasks()),this._bindIfExists("downloadBtn","click",()=>this.downloadImage()),this._bindIfExists("undoBtn","click",()=>this.undo()),this._bindIfExists("redoBtn","click",()=>this.redo()),this._bindIfExists("rotateLeftBtn","click",()=>{let t=document.getElementById(this.elements.rotationLeftInput),i=this.options.rotationStep;if(t){let e=parseFloat(t.value);isNaN(e)||(i=e)}this.rotateImage(this.currentRotation-i)}),this._bindIfExists("rotateRightBtn","click",()=>{let t=document.getElementById(this.elements.rotationRightInput),i=this.options.rotationStep;if(t){let e=parseFloat(t.value);isNaN(e)||(i=e)}this.rotateImage(this.currentRotation+i)}),this._bindIfExists("cropBtn","click",()=>this.enterCropMode()),this._bindIfExists("applyCropBtn","click",()=>{this.applyCrop().catch(t=>this._reportError("applyCrop failed",t))}),this._bindIfExists("cancelCropBtn","click",()=>this.cancelCrop())}_bindIfExists(t,i,e){let s=document.getElementById(this.elements[t]);s&&(s.addEventListener(i,e),this._handlersByElementKey=this._handlersByElementKey||{},this._handlersByElementKey[t]||(this._handlersByElementKey[t]=[]),this._handlersByElementKey[t].push({eventName:i,handler:e}))}_loadImageFile(t){if(!t||!t.type.startsWith("image/"))return;let i=new FileReader;i.onload=e=>this.loadImage(e.target.result),i.onerror=e=>{this._reportError("Image file could not be read",e)},i.readAsDataURL(t)}_warnOnImageLayoutOptionConflict(){let t=[["fitImageToCanvas",this.options.fitImageToCanvas],["coverImageToCanvas",this.options.coverImageToCanvas],["expandCanvasToImage",this.options.expandCanvasToImage]].filter(([,i])=>!!i).map(([i])=>i);t.length<=1||this._reportWarning(`Only one image layout mode should be enabled. Active modes: ${t.join(", ")}.`)}async loadImage(t,i={}){if(!this._fabricLoaded||!this.canvas||!t||typeof t!="string"||!t.startsWith("data:image/"))return;this._warnOnImageLayoutOptionConflict(),this._setPlaceholderVisible(!1),this._syncContainerOverflow({preserveScroll:i.preserveScroll===!0});let e=await this._createImageElement(t),s=t;if(this.options.downsampleOnLoad&&(e.naturalWidth>this.options.downsampleMaxWidth||e.naturalHeight>this.options.downsampleMaxHeight)){let r=Math.min(this.options.downsampleMaxWidth/e.naturalWidth,this.options.downsampleMaxHeight/e.naturalHeight),l=Math.round(e.naturalWidth*r),o=Math.round(e.naturalHeight*r);s=this._resampleImageToDataURL(e,l,o,this.options.downsampleQuality)}return new Promise((n,r)=>{v.Image.fromURL(s,l=>{try{if(!l)throw new Error("Image could not be loaded");this.canvas.discardActiveObject(),this._hideAllMaskLabels(),this.canvas.clear(),this.canvas.setBackgroundColor(this.options.backgroundColor,this.canvas.renderAll.bind(this.canvas)),l.set({originX:"left",originY:"top",selectable:!1,evented:!1});let o=l.width,a=l.height,h=this._getContainerViewportSize(),c=h.width,p=h.height;if(this.options.fitImageToCanvas){let d=Math.max(1,c-1),u=Math.max(1,p-1);this._setCanvasSizeInt(d,u);let m=Math.min(d/o,u/a,1);l.set({left:0,top:0}),l.scale(m),this.baseImageScale=l.scaleX||1}else if(this.options.coverImageToCanvas){let d=this._calculateCoverCanvasLayout(o,a);this._setCanvasSizeInt(d.canvasWidth,d.canvasHeight),l.set({left:0,top:0}),l.scale(d.scale),this.baseImageScale=l.scaleX||1}else if(this.options.expandCanvasToImage){let d=Math.max(c,Math.floor(o)),u=Math.max(p,Math.floor(a));this._setCanvasSizeInt(d,u),l.set({left:0,top:0}),l.scale(1),this.baseImageScale=1}else{let d=Math.max(this.options.canvasWidth,c),u=Math.max(this.options.canvasHeight,p);this._setCanvasSizeInt(d,u);let m=Math.min(d/o,u/a,1);l.set({left:0,top:0}),l.scale(m),this.baseImageScale=l.scaleX||1}this.originalImage=l,this.canvas.add(l),this.canvas.sendToBack(l),this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null,this.maskCounter=0,this.currentScale=1,this.currentRotation=0,this._updateInputs(),this._updateMaskList(),this.isImageLoadedToCanvas=!0,this._updateUI(),this.canvas.renderAll();try{this._lastSnapshot=this._serializeCanvasState()}catch(d){this._reportWarning("loadImage: failed to capture initial canvas snapshot",d)}typeof this.onImageLoaded=="function"&&this.onImageLoaded(),n()}catch(o){r(o)}},{crossOrigin:"anonymous"})})}isImageLoaded(){let t=O();return!!(this.originalImage&&t&&this.originalImage instanceof t.Image&&this.originalImage.width>0&&this.originalImage.height>0)}_createImageElement(t,i=this.options.imageLoadTimeoutMs){return new Promise((e,s)=>{let n=new Image,r=!1,l=Number.isFinite(Number(i))&&Number(i)>0?Number(i):3e4,o,a=h=>{r||(r=!0,clearTimeout(o),n.onload=null,n.onerror=null,h())};o=setTimeout(()=>{a(()=>s(new Error("Image load timed out")));try{n.src=""}catch(h){}},l),n.onload=()=>a(()=>e(n)),n.onerror=h=>a(()=>s(h)),n.src=t})}_resampleImageToDataURL(t,i,e,s=.92){let n=document.createElement("canvas");n.width=i,n.height=e;let r=n.getContext("2d");if(!r)throw new Error("2D canvas context is unavailable");return r.drawImage(t,0,0,t.naturalWidth,t.naturalHeight,0,0,i,e),n.toDataURL("image/jpeg",s)}_setCanvasSizeInt(t,i){let e=Math.max(1,Math.round(Number(t)||1)),s=Math.max(1,Math.round(Number(i)||1));this.canvas.setWidth(e),this.canvas.setHeight(s),typeof this.canvas.calcOffset=="function"&&this.canvas.calcOffset(),this.canvasElement&&(this.canvasElement.style.width=e+"px",this.canvasElement.style.height=s+"px",this.canvasElement.style.maxWidth="none")}_ceilCanvasDimension(t){let i=Number(t)||0,e=Math.round(i);return Math.abs(i-e)<.01?e:Math.ceil(i)}_getContainerViewportSize(){if(!this.containerElement)return{width:Math.max(1,Math.floor(this.options.canvasWidth||1)),height:Math.max(1,Math.floor(this.options.canvasHeight||1))};let t=Math.max(1,Math.floor(this.containerElement.clientWidth||this.options.canvasWidth||1)),i=Math.max(1,Math.floor(this.containerElement.clientHeight||this.options.canvasHeight||1));if(this._hasFixedContainerScrollbars())return{width:t,height:i};let e=this._getContainerOverflowValues(),s=e.x.some(o=>o==="auto"||o==="scroll"),n=e.y.some(o=>o==="auto"||o==="scroll"),r=s&&this.containerElement.scrollWidth>this.containerElement.clientWidth,l=n&&this.containerElement.scrollHeight>this.containerElement.clientHeight;if(r||l){let o=this._getScrollbarSize();l&&(t+=o.width),r&&(i+=o.height)}return{width:t,height:i}}_getContainerOverflowValues(){if(!this.containerElement)return{x:[],y:[]};let t=this.containerElement.style.overflow,i=this.containerElement.style.overflowX,e=this.containerElement.style.overflowY,s="",n="",r="";if(typeof window<"u"&&typeof window.getComputedStyle=="function"){let l=window.getComputedStyle(this.containerElement);s=l.overflow,n=l.overflowX,r=l.overflowY}return{x:[t,i,s,n],y:[t,e,s,r]}}_hasFixedContainerScrollbars(){if(!this.containerElement)return!1;let t=this._getContainerOverflowValues();return[...t.x,...t.y].some(i=>i==="scroll")}_getScrollbarSize(){if(this._scrollbarSizeCache)return{...this._scrollbarSizeCache};if(typeof document>"u"||!document.createElement||!document.body)return{width:0,height:0};let t=document.createElement("div");t.style.position="absolute",t.style.visibility="hidden",t.style.overflow="scroll",t.style.width="100px",t.style.height="100px",t.style.top="-9999px",document.body.appendChild(t);let i=Math.max(0,t.offsetWidth-t.clientWidth),e=Math.max(0,t.offsetHeight-t.clientHeight);return document.body.removeChild(t),this._scrollbarSizeCache={width:i,height:e},{...this._scrollbarSizeCache}}_getScrollSafetyMargin(){return 2}_getScrollableCanvasSize(t,i,e=this._getContainerViewportSize()){if(this._hasFixedContainerScrollbars()){let a=this._getScrollSafetyMargin(),h=Math.max(1,e.width-a),c=Math.max(1,e.height-a);return{width:t>e.width+.5?this._ceilCanvasDimension(t):h,height:i>e.height+.5?this._ceilCanvasDimension(i):c,viewportWidth:e.width,viewportHeight:e.height,hasHorizontal:!0,hasVertical:!0}}let s=this._getScrollbarSize(),n=!1,r=!1,l,o;for(let a=0;a<4;a+=1){l=Math.max(1,e.width-(n?s.width:0)),o=Math.max(1,e.height-(r?s.height:0));let h=i>o+.5,c=t>l+.5;if(h===n&&c===r)break;n=h,r=c}return l=Math.max(1,e.width-(n?s.width:0)),o=Math.max(1,e.height-(r?s.height:0)),{width:r?this._ceilCanvasDimension(t):l,height:n?this._ceilCanvasDimension(i):o,viewportWidth:l,viewportHeight:o,hasHorizontal:r,hasVertical:n}}_calculateCoverCanvasLayout(t,i){let e=this._getContainerViewportSize();if(this._hasFixedContainerScrollbars()){let d=this._getScrollSafetyMargin(),u=Math.max(1,e.width-d),m=Math.max(1,e.height-d),g=Math.min(1,Math.max(u/t,m/i)),f=t*g,y=i*g,b=this._getScrollableCanvasSize(f,y,e);return{scale:g,canvasWidth:b.width,canvasHeight:b.height}}let s=this._getScrollbarSize(),n=!1,r=!1,l=1,o=t,a=i,h,c;for(let d=0;d<4;d+=1){h=Math.max(1,e.width-(n?s.width:0)),c=Math.max(1,e.height-(r?s.height:0)),l=Math.min(1,Math.max(h/t,c/i)),o=t*l,a=i*l;let u=a>c+.5,m=o>h+.5;if(u===n&&m===r)break;n=u,r=m}let p=this._getScrollableCanvasSize(o,a,e);return{scale:l,canvasWidth:p.width,canvasHeight:p.height}}_getStateProperties(){return["maskId","maskName","maskLabel","isCropRect","originalAlpha","originalStroke","originalStrokeWidth","selectable","evented","hasControls","lockRotation","borderColor","cornerColor","cornerSize","transparentCorners","strokeUniform","strokeDashArray"]}_getMaskNormalStyle(t){let i=Number(t&&t.originalStrokeWidth),e=Number(t&&t.originalAlpha),s={stroke:t&&t.originalStroke||"#ccc",strokeWidth:Number.isFinite(i)?i:1};return Number.isFinite(e)&&(s.opacity=e),s}_withNormalizedMaskStyles(t){if(!this.canvas)return t();let i=this.canvas.getObjects().filter(s=>s.maskId),e=[];try{return i.forEach(s=>{let n=this._getMaskNormalStyle(s),r={};Object.keys(n).forEach(a=>{s[a]!==n[a]&&(r[a]=n[a])});let l=Object.keys(r);if(!l.length)return;let o={object:s};l.forEach(a=>{o[a]=s[a]}),e.push(o),s.set(r)}),t()}finally{e.forEach(s=>{try{let n={};Object.keys(s).forEach(r=>{r!=="object"&&(n[r]=s[r])}),s.object.set(n)}catch(n){}})}}_restoreMaskControls(t){if(!t)return;let i=Number(t.cornerSize);t.set({selectable:t.selectable!==!1,evented:t.evented!==!1,hasControls:t.hasControls!==!1,lockRotation:typeof t.lockRotation=="boolean"?t.lockRotation:!this.options.maskRotatable,borderColor:t.borderColor||"red",cornerColor:t.cornerColor||"black",cornerSize:Number.isFinite(i)?i:8,transparentCorners:t.transparentCorners===!0,strokeUniform:t.strokeUniform!==!1}),typeof t.setCoords=="function"&&t.setCoords()}_serializeEditorMetadata(){let t=Number(this.baseImageScale),i=Number(this.currentScale),e=Number(this.currentRotation),s=Number(this.maskCounter);return{version:1,baseImageScale:Number.isFinite(t)&&t>0?t:1,currentScale:Number.isFinite(i)&&i>0?i:1,currentRotation:Number.isFinite(e)?e:0,maskCounter:Number.isFinite(s)&&s>0?Math.floor(s):0}}_serializeCanvasState(){return this.canvas?this._withNormalizedMaskStyles(()=>{let t=this.canvas.toJSON(this._getStateProperties());return Array.isArray(t.objects)&&(t.objects=t.objects.filter(i=>!i.isCropRect&&!i.maskLabel)),t.imageEditorMetadata=this._serializeEditorMetadata(),JSON.stringify(t)}):null}_normalizeQuality(t){let i=Number(t);return Number.isFinite(i)?Math.max(0,Math.min(1,i)):this.options.downsampleQuality??.92}_normalizeImageFormat(t){return{jpeg:"jpeg",jpg:"jpeg","image/jpeg":"jpeg",png:"png","image/png":"png",webp:"webp","image/webp":"webp"}[String(t||"jpeg").toLowerCase()]||"jpeg"}_getClampedCanvasRegion(t,i={}){let e=Math.max(1,Math.round(this.canvas.getWidth())),s=Math.max(1,Math.round(this.canvas.getHeight())),n=Number(t.left)||0,r=Number(t.top)||0,l=Math.max(0,Number(t.width)||0),o=Math.max(0,Number(t.height)||0),h=i.includePartialPixels!==!1?Math.ceil:Math.floor,c=Math.min(e-1,Math.max(0,Math.floor(n))),p=Math.min(s-1,Math.max(0,Math.floor(r))),d=Math.min(e,Math.max(c+1,h(n+l))),u=Math.min(s,Math.max(p+1,h(r+o)));return{sourceX:c,sourceY:p,sourceWidth:Math.max(1,d-c),sourceHeight:Math.max(1,u-p)}}async _cropDataUrl(t,i,e,s,n,r,l="jpeg",o=.92){return new Promise((a,h)=>{let c=new Image,p=!1,d=Number(this.options.imageLoadTimeoutMs),u=Number.isFinite(d)&&d>0?d:3e4,m,g=f=>{p||(p=!0,clearTimeout(m),c.onload=null,c.onerror=null,f())};m=setTimeout(()=>{g(()=>h(new Error("Image crop load timed out")));try{c.src=""}catch(f){}},u),c.onload=()=>{try{let f=Math.max(1,Number(r)||1),y=Math.round(i*f),b=Math.round(e*f),k=Math.max(1,Math.round(s*f)),x=Math.max(1,Math.round(n*f)),M=document.createElement("canvas");M.width=k,M.height=x;let A=M.getContext("2d");if(!A)throw new Error("2D canvas context is unavailable");A.drawImage(c,y,b,k,x,0,0,k,x),g(()=>a(M.toDataURL(`image/${l}`,o)))}catch(f){g(()=>h(f))}},c.onerror=f=>g(()=>h(f)),c.src=t})}async _exportCanvasRegionToDataURL({sourceX:t,sourceY:i,sourceWidth:e,sourceHeight:s,multiplier:n=1,quality:r=.92,format:l="jpeg"}){let o=Math.max(1,Number(n)||1),a=this.canvas.toDataURL({format:l,quality:r,multiplier:o});return this._cropDataUrl(a,t,i,e,s,o,l,r)}_getObjectTopLeftPoint(t){if(!t)return{x:0,y:0};t.setCoords();let i=typeof t.getCoords=="function"?t.getCoords():null;if(i&&i.length)return i[0];let e=t.getBoundingRect(!0,!0);return{x:e.left,y:e.top}}_setObjectOriginKeepingPosition(t,i,e,s){!t||!s||!t.setPositionByOrigin||(t.set({originX:i,originY:e}),t.setPositionByOrigin(s,i,e),t.setCoords())}_alignObjectBoundingBoxToCanvasTopLeft(t){if(!t)return;t.setCoords();let i=t.getBoundingRect(!0,!0),e=i.left,s=i.top;t.set({left:(t.left||0)-e,top:(t.top||0)-s}),t.setCoords(),this.canvas.renderAll()}_updateCanvasSizeToImageBounds(){if(!this.originalImage)return;this.originalImage.setCoords();let t=this.originalImage.getBoundingRect(!0,!0),i=this._getScrollableCanvasSize(t.width,t.height);this._setCanvasSizeInt(i.width,i.height)}_shouldResizeCanvasToContentBounds(){return!!(this.options.expandCanvasToImage||this.options.coverImageToCanvas||this.options.fitImageToCanvas)}_expandCanvasToFitObjects(t,i=10){if(!(!this.canvas||!Array.isArray(t)||!t.length||!this._shouldResizeCanvasToContentBounds()))try{let e=this.canvas.getWidth(),s=this.canvas.getHeight();t.forEach(a=>{if(!a)return;typeof a.setCoords=="function"&&a.setCoords();let h=a.getBoundingRect(!0,!0);e=Math.max(e,Math.ceil(h.left+h.width+i)),s=Math.max(s,Math.ceil(h.top+h.height+i))});let n=this.containerElement?Math.floor(this.containerElement.clientWidth||0):0,r=this.containerElement?Math.floor(this.containerElement.clientHeight||0):0,l=Math.max(this.canvas.getWidth(),n,e),o=Math.max(this.canvas.getHeight(),r,s);(l!==this.canvas.getWidth()||o!==this.canvas.getHeight())&&this._setCanvasSizeInt(l,o)}catch(e){this._reportWarning("expandCanvasToFitObjects: failed to expand canvas",e)}}_expandCanvasToFitObject(t,i=10){this._expandCanvasToFitObjects([t],i)}scaleImage(t,i={}){return this.animationQueue.add(()=>this._scaleImageImpl(t,i))}_scaleImageImpl(t,i={}){if(!this.originalImage||this.isAnimating)return Promise.resolve();let e=i.saveHistory!==!1;t=Math.max(this.options.minScale,Math.min(this.options.maxScale,t)),this.currentScale=t,this.isAnimating=!0,this._updateUI();let s=this.baseImageScale*t,n=this._getObjectTopLeftPoint(this.originalImage);this._setObjectOriginKeepingPosition(this.originalImage,"left","top",n);let r=new Promise(o=>{this.originalImage.animate("scaleX",s,{duration:this.options.animationDuration,onChange:this.canvas.renderAll.bind(this.canvas),onComplete:o})}),l=new Promise(o=>{this.originalImage.animate("scaleY",s,{duration:this.options.animationDuration,onChange:this.canvas.renderAll.bind(this.canvas),onComplete:o})});return Promise.all([r,l]).then(()=>{this.originalImage.set({scaleX:s,scaleY:s}),this.originalImage.setCoords(),this._shouldResizeCanvasToContentBounds()&&this._updateCanvasSizeToImageBounds(),this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage),this.canvas.getObjects().forEach(o=>{o.maskId&&this._syncMaskLabel(o)}),this.isAnimating=!1,this._updateInputs(),this._updateUI(),e&&this.saveState()}).catch(()=>{this.isAnimating=!1,this._updateUI()})}rotateImage(t,i={}){return this.animationQueue.add(()=>this._rotateImageImpl(t,i))}_rotateImageImpl(t,i={}){if(!this.originalImage||this.isAnimating||isNaN(t))return Promise.resolve();let e=i.saveHistory!==!1;this.currentRotation=t,this.isAnimating=!0,this._updateUI();let s=this.originalImage.getCenterPoint();return this._setObjectOriginKeepingPosition(this.originalImage,"center","center",s),new Promise(r=>{this.originalImage.animate("angle",t,{duration:this.options.animationDuration,onChange:this.canvas.renderAll.bind(this.canvas),onComplete:r})}).then(()=>{this.originalImage.set("angle",t),this.originalImage.setCoords(),this._shouldResizeCanvasToContentBounds()&&this._updateCanvasSizeToImageBounds(),this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);let r=this._getObjectTopLeftPoint(this.originalImage);this._setObjectOriginKeepingPosition(this.originalImage,"left","top",r),this.canvas.getObjects().forEach(l=>{l.maskId&&this._syncMaskLabel(l)}),this.isAnimating=!1,this._updateInputs(),this._updateUI(),e&&this.saveState()}).catch(()=>{this.isAnimating=!1,this._updateUI()})}resetImageTransform(){return this.originalImage?this.animationQueue.add(async()=>{let t=this._lastSnapshot||this._serializeCanvasState();await this._scaleImageImpl(1,{saveHistory:!1}),await this._rotateImageImpl(0,{saveHistory:!1});let i=this._serializeCanvasState();this._pushStateTransition(t,i)}).catch(t=>{this._reportError("resetImageTransform() failed",t)}):Promise.resolve()}reset(){return this.resetImageTransform()}loadFromState(t){return!t||!this.canvas?Promise.resolve():new Promise(i=>{try{let e=typeof t=="string"?JSON.parse(t):t,s=e&&e.imageEditorMetadata?e.imageEditorMetadata:null;this.canvas.loadFromJSON(e,()=>{try{this._hideAllMaskLabels();let n=this.canvas.getObjects();if(this.originalImage=n.find(a=>a.type==="image"&&!a.maskId)||null,this.originalImage){this.originalImage.set({originX:"left",originY:"top",selectable:!1,evented:!1,hasControls:!1,hoverCursor:"default"}),this.canvas.sendToBack(this.originalImage);let a=Number(s&&s.baseImageScale),h=Number(s&&s.currentScale),c=Number(s&&s.currentRotation);if(Number.isFinite(a)&&a>0&&(this.baseImageScale=a),Number.isFinite(h)&&h>0)this.currentScale=h;else{let p=Number(this.baseImageScale)||1,d=Number(this.originalImage.scaleX)||p;this.currentScale=d/p}this.currentRotation=Number.isFinite(c)?c:Number(this.originalImage.angle)||0}else this.baseImageScale=1,this.currentScale=1,this.currentRotation=0;let r=n.filter(a=>a.maskId);r.forEach(a=>{this._restoreMaskControls(a),this._rebindMaskEvents(a),a.set(this._getMaskNormalStyle(a))});let l=Number(s&&s.maskCounter),o=r.reduce((a,h)=>Math.max(a,h.maskId),0);this.maskCounter=Number.isFinite(l)&&l>=o?Math.floor(l):o,this._lastMask=r.length?r[r.length-1]:null,this._lastMask||(this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null),this.isImageLoadedToCanvas=!!this.originalImage,this.canvas.renderAll(),this._updateInputs(),this._updateMaskList(),this._updatePlaceholderStatus(),this._lastSnapshot=this._serializeCanvasState(),this._updateUI()}catch(n){this._reportError("loadFromState() failed",n)}finally{i()}})}catch(e){this._reportError("loadFromState() failed",e),i()}})}saveState(){if(!this.canvas)return;let t=this.canvas.getActiveObject();try{let i=this._serializeCanvasState(),e=this._lastSnapshot||i;if(i===e)return;let s=!1,n=new I(()=>{if(s)return this.loadFromState(i);s=!0},()=>this.loadFromState(e));this.historyManager.execute(n),this._lastSnapshot=i}catch(i){this._reportWarning("saveState: failed to save canvas snapshot",i)}finally{t&&t.maskId&&!t.__label&&this.canvas.getObjects().includes(t)&&this._handleSelectionChanged([t]),this._updateUI()}}_pushStateTransition(t,i){if(!t||!i||t===i)return;this.historyManager||(this.historyManager=new C(this.maxHistorySize||50));let e=new I(()=>this.loadFromState(i),()=>this.loadFromState(t));this.historyManager.push(e),this._lastSnapshot=i,this._updateUI()}undo(){return this.historyManager.undo().then(()=>{this._updateUI()}).catch(t=>{this._reportError("undo failed",t)})}redo(){return this.historyManager.redo().then(()=>{this._updateUI()}).catch(t=>{this._reportError("redo failed",t)})}_rebindMaskEvents(t){if(!t)return;if(t.__imageEditorMaskHandlers)try{t.off("mouseover",t.__imageEditorMaskHandlers.mouseover),t.off("mouseout",t.__imageEditorMaskHandlers.mouseout)}catch(l){}let i={};Number.isFinite(Number(t.originalAlpha))||(i.originalAlpha=Number.isFinite(Number(t.opacity))?Number(t.opacity):.5),t.originalStroke||(i.originalStroke=t.stroke||"#ccc"),Number.isFinite(Number(t.originalStrokeWidth))||(i.originalStrokeWidth=Number.isFinite(Number(t.strokeWidth))?Number(t.strokeWidth):1),Object.keys(i).length&&t.set(i);let e={stroke:t.originalStroke||"#ccc",strokeWidth:t.originalStrokeWidth,opacity:t.originalAlpha},s={stroke:"#ff5500",strokeWidth:2,opacity:Math.min(t.originalAlpha+.2,1)},n=()=>{t.set(s),t.canvas&&t.canvas.requestRenderAll()},r=()=>{t.set(e),t.canvas&&t.canvas.requestRenderAll()};t.on("mouseover",n),t.on("mouseout",r),t.__imageEditorMaskHandlers={mouseover:n,mouseout:r}}createMask(t={}){if(!this.canvas)return null;let i=t.shape||"rect",e={shape:i,width:this.options.defaultMaskWidth,height:this.options.defaultMaskHeight,color:"rgba(0,0,0,0.5)",alpha:.5,gap:5,left:void 0,top:void 0,angle:0,selectable:!0,...t},s=10,n,r,l=u=>{let m=this.canvas?this.canvas.getWidth():0,g=this.canvas?this.canvas.getHeight():0;return u==="height"?g:u==="min"?Math.min(m,g):m},o=(u,m,g="width")=>{if(typeof u=="function")return u(this.canvas,this.options);if(typeof u=="string"&&u.endsWith("%")){let f=Number.parseFloat(u)/100;return Number.isFinite(f)?Math.floor(l(g)*f):m}return u??m};if(e.left===void 0&&this._lastMask){let u=this._lastMask,m=u.left;u.getScaledWidth?m+=u.getScaledWidth():u.width&&(m+=u.width*(u.scaleX??1)),n=Math.round(m+e.gap),r=u.top??s}else n=o(e.left,s,"width"),r=o(e.top,s,"height");e.width=o(e.width,this.options.defaultMaskWidth,"width"),e.height=o(e.height,this.options.defaultMaskHeight,"height"),e.left=n,e.top=r;let a;if(typeof e.fabricGenerator=="function")a=e.fabricGenerator(e,this.canvas,this.options);else switch(i){case"circle":a=new v.Circle({left:n,top:r,radius:o(e.radius,Math.min(e.width,e.height)/2,"min"),fill:e.color,opacity:e.alpha,angle:e.angle,...e.styles});break;case"ellipse":a=new v.Ellipse({left:n,top:r,rx:o(e.rx,e.width/2,"width"),ry:o(e.ry,e.height/2,"height"),fill:e.color,opacity:e.alpha,angle:e.angle,...e.styles});break;case"polygon":{let u=e.points||[];Array.isArray(u)&&u.length&&(u=u.map(m=>Array.isArray(m)?{x:Number(m[0]),y:Number(m[1])}:{x:Number(m.x),y:Number(m.y)})),a=new v.Polygon(u,{left:n,top:r,fill:e.color,opacity:e.alpha,angle:e.angle,...e.styles});break}default:a=new v.Rect({left:n,top:r,width:o(e.width,this.options.defaultMaskWidth,"width"),height:o(e.height,this.options.defaultMaskHeight,"height"),fill:e.color,opacity:e.alpha,angle:e.angle,rx:e.rx,ry:e.ry,...e.styles})}let h=e.styles||{},c=u=>Object.prototype.hasOwnProperty.call(h,u),p={selectable:e.selectable!==!1,hasControls:"hasControls"in e?e.hasControls:!0,lockRotation:!this.options.maskRotatable,borderColor:"borderColor"in e?e.borderColor:"red",cornerColor:"cornerColor"in e?e.cornerColor:"black",cornerSize:"cornerSize"in e?e.cornerSize:8,transparentCorners:"transparentCorners"in e?e.transparentCorners:!1,stroke:c("stroke")?h.stroke:"#ccc",strokeWidth:c("strokeWidth")?h.strokeWidth:1,opacity:c("opacity")?h.opacity:e.alpha,strokeUniform:"strokeUniform"in e?e.strokeUniform:c("strokeUniform")?h.strokeUniform:!0};c("strokeDashArray")&&(p.strokeDashArray=h.strokeDashArray),a.set(p),a.setCoords(),a.set({originalAlpha:Number.isFinite(Number(a.opacity))?Number(a.opacity):e.alpha,originalStroke:a.stroke||"#ccc",originalStrokeWidth:Number.isFinite(Number(a.strokeWidth))?Number(a.strokeWidth):1}),this._rebindMaskEvents(a),this._expandCanvasToFitObject(a),this._lastMaskInitialLeft=n,this._lastMaskInitialTop=r,this._lastMaskInitialWidth=o(e.width,this.options.defaultMaskWidth,"width");let d=++this.maskCounter;return a.set({maskId:d,maskName:`${this.options.maskName}${d}`}),this._lastMask=a,this.canvas.add(a),this.canvas.bringToFront(a),e.selectable&&this.canvas.setActiveObject(a),this._handleSelectionChanged([a]),this._updateMaskList(),this._updateUI(),this.canvas.renderAll(),this.saveState(),typeof e.onCreate=="function"&&e.onCreate(a,this.canvas),a}addMask(t={}){return this.createMask(t)}removeSelectedMask(){let t=this.canvas.getActiveObject(),i=this._getModifiedMasks(t);if(!i.length)return;this.canvas.discardActiveObject(),i.forEach(s=>{this._removeLabelForMask(s),this.canvas.remove(s)});let e=this.canvas.getObjects().filter(s=>s.maskId);this._lastMask=e.length?e[e.length-1]:null,this._lastMask||(this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null),this._updateMaskList(),this._updateUI(),this.canvas.renderAll(),this.saveState()}removeAllMasks(t={}){let i=t.saveHistory!==!1,e=this.canvas.getObjects().filter(s=>s.maskId);e.forEach(s=>this._removeLabelForMask(s)),e.forEach(s=>this.canvas.remove(s)),this.canvas.discardActiveObject(),this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null,this._updateMaskList(),this._updateUI(),this.canvas.renderAll(),i&&this.saveState()}_removeLabelForMask(t){if(!(!t||!this.canvas)&&t.__label){try{this.canvas.getObjects().includes(t.__label)&&this.canvas.remove(t.__label)}catch(i){}try{delete t.__label}catch(i){}}}_getMaskCreationIndex(t){let i=Number(t&&t.maskId);if(Number.isFinite(i)&&i>0)return Math.floor(i)-1;let e=this.canvas?this.canvas.getObjects().filter(s=>s.maskId):[];return Math.max(0,e.indexOf(t))}_createLabelForMask(t){if(!t||!this.options.maskLabelOnSelect)return;this._removeLabelForMask(t);let i=null;if(this.options.label&&typeof this.options.label.create=="function"&&(i=this.options.label.create(t,v)),!i){let e=t.maskName,s={left:0,top:0,fontSize:12,fill:"#fff",backgroundColor:"rgba(0,0,0,0.7)",selectable:!1,evented:!1,padding:2,originX:"left",originY:"top"};this.options.label&&(typeof this.options.label.getText=="function"&&(e=this.options.label.getText(t,this._getMaskCreationIndex(t))),this.options.label.textOptions&&Object.assign(s,this.options.label.textOptions)),i=new v.Text(e,s)}i.maskLabel=!0,t.__label=i,this.canvas.add(i),this.canvas.bringToFront(i),this._syncMaskLabel(t)}_hideAllMaskLabels(){if(!this.canvas)return;let t=this.canvas.getObjects();t.filter(e=>e.maskLabel).forEach(e=>{try{t.includes(e)&&this.canvas.remove(e)}catch(s){}}),t.forEach(e=>{if(e.maskId&&e.__label)try{delete e.__label}catch(s){}})}_syncMaskLabel(t){if(!t||!this.options.maskLabelOnSelect||!t.__label)return;let i=t.getCoords?t.getCoords():null;if(!i||i.length<4)return;let e=i[0],s=t.getCenterPoint(),n=s.x-e.x,r=s.y-e.y,l=Math.sqrt(n*n+r*r)||1,o=n/l,a=r/l,h=Math.max(0,this.options.maskLabelOffset??3),c=e.x+o*h,p=e.y+a*h;t.__label.set({left:Math.round(c),top:Math.round(p),angle:t.angle||0,originX:"left",originY:"top",visible:!0}),t.__label.setCoords(),typeof this.canvas.requestRenderAll=="function"?this.canvas.requestRenderAll():this.canvas.renderAll()}_showLabelForMask(t){t&&this.options.maskLabelOnSelect&&(t.__label||this._createLabelForMask(t),t.__label.set({visible:!0}),this._syncMaskLabel(t))}_handleSelectionChanged(t){let i=(t||[]).find(s=>s.maskId);this.canvas.getObjects().filter(s=>s.maskId).forEach(s=>{if(s!==i){if(s.__label){try{this.canvas.remove(s.__label)}catch(r){}delete s.__label}let n=Number(s.originalStrokeWidth);s.set({stroke:s.originalStroke||"#ccc",strokeWidth:Number.isFinite(n)?n:1})}else s.set({stroke:"#ff0000",strokeWidth:1})}),i&&this._showLabelForMask(i),this._updateMaskListSelection(i),this.canvas.renderAll(),this._updateUI()}_updateMaskList(){let t=document.getElementById(this.elements.maskList);if(!t)return;t.innerHTML="",this.canvas.getObjects().filter(e=>e.maskId).forEach(e=>{let s=document.createElement("li");s.className="list-group-item mask-item",s.textContent=e.maskName,s.onclick=()=>{this.canvas.setActiveObject(e),this._handleSelectionChanged([e])},t.appendChild(s)})}_updateMaskListSelection(t){let i=document.getElementById(this.elements.maskList);if(!i)return;i.querySelectorAll(".mask-item").forEach(s=>{let n=!!t&&s.textContent===t.maskName;s.classList.toggle("active",n)})}async mergeMasks(){if(!(!this.originalImage||!this.canvas.getObjects().filter(i=>i.maskId).length)){this.canvas.discardActiveObject(),this.canvas.renderAll();try{let i=this._serializeCanvasState(),e=await this.exportImageBase64({exportImageArea:!0,multiplier:this.options.exportMultiplier});this.removeAllMasks({saveHistory:!1}),await this.loadImage(e,{preserveScroll:!0});let s=this._serializeCanvasState();this._pushStateTransition(i,s)}catch(i){this._reportError("merge error",i)}}}async merge(){return this.mergeMasks()}downloadImage(t=this.options.defaultDownloadFileName){if(!this.originalImage)return;let i=this.options.exportImageAreaByDefault;this.exportImageBase64({exportImageArea:i,multiplier:this.options.exportMultiplier}).then(e=>{let s=document.createElement("a");s.download=t,s.href=e,document.body.appendChild(s),s.click(),document.body.removeChild(s)}).catch(e=>this._reportError("download error",e))}async exportImageBase64(t={}){if(!this.originalImage)throw new Error("No image loaded");let i=typeof t.exportImageArea=="boolean"?t.exportImageArea:this.options.exportImageAreaByDefault,e=t.multiplier||this.options.exportMultiplier||1,s=this._normalizeQuality(t.quality??this.options.downsampleQuality),n=this._normalizeImageFormat(t.fileType||t.format);if(!i){let a=this.canvas.getObjects().filter(c=>c.maskId||c.maskLabel),h=a.map(c=>({object:c,visible:c.visible}));try{a.forEach(d=>{d.set({visible:!1})}),this.canvas.discardActiveObject(),this.canvas.renderAll(),this.originalImage.setCoords();let c=this.originalImage.getBoundingRect(!0,!0),p=this._getClampedCanvasRegion(c,{includePartialPixels:!1});return await this._exportCanvasRegionToDataURL({...p,multiplier:e,quality:s,format:n})}finally{h.forEach(c=>{try{c.object.set({visible:c.visible})}catch(p){}}),this.canvas.renderAll()}}let r=this.canvas.getObjects().filter(a=>a.maskId),l=r.map(a=>({object:a,opacity:a.opacity,fill:a.fill,strokeWidth:a.strokeWidth,stroke:a.stroke,selectable:a.selectable,lockRotation:a.lockRotation})),o;try{r.forEach(c=>this._removeLabelForMask(c)),this.canvas.discardActiveObject(),this.canvas.renderAll(),r.forEach(c=>{c.set({opacity:1,fill:"#000000",strokeWidth:0,stroke:null,selectable:!1}),c.setCoords()}),this.canvas.renderAll(),this.originalImage.setCoords();let a=this.originalImage.getBoundingRect(!0,!0),h=this._getClampedCanvasRegion(a,{includePartialPixels:!1});o=await this._exportCanvasRegionToDataURL({...h,multiplier:e,quality:s,format:n})}finally{l.forEach(a=>{try{a.object.set({opacity:a.opacity,fill:a.fill,strokeWidth:a.strokeWidth,stroke:a.stroke,selectable:a.selectable,lockRotation:a.lockRotation}),a.object.setCoords()}catch(h){}}),this.canvas.renderAll()}return o}async getImageBase64(t={}){return this.exportImageBase64(t)}async exportImageFile(t={}){if(!this.originalImage)throw new Error("No image loaded");let{mergeMask:i=!0,fileType:e="jpeg",quality:s=this.options.downsampleQuality??.92,multiplier:n=this.options.exportMultiplier??1,fileName:r=this.options.defaultDownloadFileName??"exported_image.jpg"}=t,l=this._normalizeImageFormat(e),o;i?o=await this.exportImageBase64({exportImageArea:!0,multiplier:n,quality:s,fileType:l}):o=await this.exportImageBase64({exportImageArea:!1,multiplier:n,quality:s,fileType:l});let a=o;a.startsWith(`data:image/${l}`)||(a=await new Promise((u,m)=>{let g=new window.Image;g.crossOrigin="Anonymous",g.onload=()=>{try{let f=document.createElement("canvas");f.width=g.width,f.height=g.height,f.getContext("2d").drawImage(g,0,0);let b=f.toDataURL(`image/${l}`,s);u(b)}catch(f){m(f)}},g.onerror=m,g.src=o}));let h=atob(a.split(",")[1]),c=`image/${l}`,p=h.length,d=new Uint8Array(p);for(;p--;)d[p]=h.charCodeAt(p);return new File([d],r,{type:c})}_clearMaskPlacementMemory(){this._lastMask=null,this._lastMaskInitialLeft=null,this._lastMaskInitialTop=null,this._lastMaskInitialWidth=null}async _restoreStateAfterCropFailure(t,i,e){if(this._reportError(i,e),this._cropRect&&this.canvas&&this._removeCropRect(),this._cropRect=null,this._cropMode=!1,this.canvas&&this._prevSelectionSetting!==void 0&&(this.canvas.selection=!!this._prevSelectionSetting),this._prevSelectionSetting=void 0,t)try{await this.loadFromState(t)}catch(s){this._reportError("applyCrop: rollback failed",s)}this._updateUI(),this.canvas&&this.canvas.renderAll()}_restoreCropObjectState(){Array.isArray(this._cropPrevEvented)&&this._cropPrevEvented.forEach(t=>{try{t.object.set({evented:t.evented,selectable:t.selectable,visible:t.visible})}catch(i){}}),this._cropPrevEvented=null}_removeCropRect(){if(this._cropRect){try{this._cropHandlers&&this._cropHandlers.length&&this._cropHandlers.forEach(t=>{t.handlers.forEach(i=>{t.target.off(i.eventName,i.handler)})})}catch(t){}try{this.canvas.remove(this._cropRect)}catch(t){}this._cropRect=null,this._cropHandlers=[]}}enterCropMode(){if(!this.canvas||!this.originalImage||this._cropMode||!this.isImageLoaded())return;this._cropMode=!0,this._prevSelectionSetting=this.canvas.selection,this.canvas.selection=!1,this.canvas.discardActiveObject(),this.originalImage.setCoords();let t=this.originalImage.getBoundingRect(!0,!0),i=this.options.crop&&this.options.crop.padding?this.options.crop.padding:10,e=Math.max(0,Math.floor(t.left+i)),s=Math.max(0,Math.floor(t.top+i)),n=Math.max(1,Math.floor(t.width-i*2)),r=Math.max(1,Math.floor(t.height-i*2)),l=Math.max(1,Number(this.options.crop.minWidth)||50),o=Math.max(1,Number(this.options.crop.minHeight)||50),a=Math.min(l,n),h=Math.min(o,r),c=a,p=h,d=new v.Rect({left:e,top:s,width:c,height:p,fill:"rgba(0,0,0,0.12)",stroke:"#00aaff",strokeDashArray:[6,4],strokeWidth:1,strokeUniform:!0,selectable:!0,hasRotatingPoint:!!(this.options.crop&&this.options.crop.allowRotationOfCropRect),lockRotation:!(this.options.crop&&this.options.crop.allowRotationOfCropRect),cornerSize:8,objectCaching:!1,originX:"left",originY:"top",lockScalingFlip:!0});this.canvas.add(d),d.isCropRect=!0,this.canvas.bringToFront(d),this.canvas.setActiveObject(d),this._cropRect=d,this._cropPrevEvented=[];let u=!!(this.options.crop&&this.options.crop.hideMasksDuringCrop);this.canvas.getObjects().forEach(g=>{if(g!==d){this._cropPrevEvented.push({object:g,evented:g.evented,selectable:g.selectable,visible:g.visible});try{let f={evented:!1,selectable:!1};u&&(g.maskId||g.maskLabel)&&(f.visible=!1),g.set(f)}catch(f){}}});let m=()=>{try{let g=Math.max(1,Number(d.width)||1),f=Math.max(1,Number(d.height)||1),y=Math.min(n/g,Math.max(a/g,Number(d.scaleX)||1)),b=Math.min(r/f,Math.max(h/f,Number(d.scaleY)||1));d.set({scaleX:y,scaleY:b}),d.setCoords(),this.canvas.requestRenderAll()}catch(g){}};d.on("modified",m),d.on("moving",m),d.on("scaling",m),this._cropHandlers.push({target:d,handlers:[{eventName:"modified",handler:m},{eventName:"moving",handler:m},{eventName:"scaling",handler:m}]}),this._updateUI(),this.canvas.renderAll()}cancelCrop(){!this.canvas||!this._cropMode||(this._removeCropRect(),this._restoreCropObjectState(),this._cropMode=!1,this.canvas.selection=!!this._prevSelectionSetting,this._prevSelectionSetting=void 0,this.canvas.discardActiveObject(),this._updateUI(),this.canvas.renderAll())}async applyCrop(){if(!this.canvas||!this._cropMode||!this._cropRect)return;this._cropRect.setCoords();let t=this._cropRect.getBoundingRect(!0,!0),i=this._getClampedCanvasRegion(t,{includePartialPixels:!1}),e=!!(this.options.crop&&this.options.crop.preserveMasksAfterCrop);this._restoreCropObjectState();let s;try{s=this._serializeCanvasState()}catch(o){this._reportWarning("applyCrop: could not serialize before state",o),s=null}let n=[];try{let o=this.canvas.getObjects().filter(a=>a.maskId);o&&o.length&&(o.forEach(a=>{try{a.setCoords();let h=a.getBoundingRect(!0,!0),c=h.left<i.sourceX+i.sourceWidth&&h.left+h.width>i.sourceX&&h.top<i.sourceY+i.sourceHeight&&h.top+h.height>i.sourceY;this._removeLabelForMask(a),this.canvas.remove(a),e&&c&&(a.set({left:(a.left||0)-i.sourceX,top:(a.top||0)-i.sourceY,visible:!0}),a.setCoords(),n.push(a))}catch(h){this._reportWarning("applyCrop: failed to remove mask",h)}}),this._clearMaskPlacementMemory(),this.canvas.discardActiveObject(),this.canvas.renderAll())}catch(o){this._reportWarning("applyCrop: error while removing masks",o)}this._removeCropRect(),this._cropMode=!1,this.canvas.selection=!!this._prevSelectionSetting,this._prevSelectionSetting=void 0;let r;try{r=await this._exportCanvasRegionToDataURL({...i,multiplier:1,quality:this._normalizeQuality(this.options.downsampleQuality),format:"jpeg"})}catch(o){await this._restoreStateAfterCropFailure(s,"applyCrop: failed to create cropped image",o);return}try{await this.loadImage(r),n.length&&(n.forEach(o=>{this._rebindMaskEvents(o),this.canvas.add(o),this.canvas.bringToFront(o)}),this._lastMask=n[n.length-1],this.maskCounter=n.reduce((o,a)=>Math.max(o,a.maskId||0),this.maskCounter),this._updateMaskList(),this.canvas.renderAll())}catch(o){await this._restoreStateAfterCropFailure(s,"applyCrop: loadImage(croppedBase64) failed",o);return}let l;try{l=this._serializeCanvasState()}catch(o){this._reportWarning("applyCrop: failed to serialize after state",o),l=null}try{this._pushStateTransition(s,l)}catch(o){this._reportWarning("applyCrop: failed to push history command",o)}this._updateUI(),this.canvas.renderAll()}_updateInputs(){let t=document.getElementById(this.elements.scaleRate);t&&(t.value=Math.round(this.currentScale*100))}_updateUI(){let t=!!this.originalImage,e=(t?this.canvas.getObjects().filter(h=>h.maskId):[]).length>0,s=this.canvas.getActiveObject(),n=s&&s.maskId,r=this.currentScale===1&&this.currentRotation===0,l=this.historyManager?.canUndo(),o=this.historyManager?.canRedo();if(!!this._cropMode){for(let h of Object.keys(this.elements||{}))document.getElementById(this.elements[h])&&(h==="applyCropBtn"||h==="cancelCropBtn"?this._setDisabled(h,!1):this._setDisabled(h,!0));return}this._setDisabled("zoomInBtn",!t||this.isAnimating||this.currentScale>=this.options.maxScale),this._setDisabled("zoomOutBtn",!t||this.isAnimating||this.currentScale<=this.options.minScale),this._setDisabled("rotateLeftBtn",!t||this.isAnimating),this._setDisabled("rotateRightBtn",!t||this.isAnimating),this._setDisabled("addMaskBtn",!t||this.isAnimating),this._setDisabled("removeMaskBtn",!n||this.isAnimating),this._setDisabled("removeAllMasksBtn",!e||this.isAnimating),this._setDisabled("mergeBtn",!t||!e||this.isAnimating),this._setDisabled("downloadBtn",!t||this.isAnimating),this._setDisabled("resetBtn",!t||r||this.isAnimating),this._setDisabled("undoBtn",!t||this.isAnimating||!l),this._setDisabled("redoBtn",!t||this.isAnimating||!o),this._setDisabled("cropBtn",!t||this.isAnimating),this._setDisabled("applyCropBtn",!0),this._setDisabled("cancelCropBtn",!0),this._setDisabled("imageInput",this.isAnimating),this._setDisabled("uploadArea",this.isAnimating)}_setDisabled(t,i){let e=document.getElementById(this.elements[t]);if(e){if("disabled"in e){e.disabled=!!i;return}i?(e.setAttribute("aria-disabled","true"),e.style.pointerEvents="none"):(e.removeAttribute("aria-disabled"),e.style.pointerEvents="")}}_isElementDisabled(t){return t?"disabled"in t?!!t.disabled:t.getAttribute("aria-disabled")==="true":!1}_updatePlaceholderStatus(){this.options.showPlaceholder&&this._setPlaceholderVisible(!this.originalImage)}_setPlaceholderVisible(t){!this.placeholderElement||!this.containerElement||(this._setElementVisible(this.placeholderElement,t),this._setElementVisible(this.containerElement,!t))}_setElementVisible(t,i){t&&(t.hidden=!i,t.setAttribute("aria-hidden",i?"false":"true"),i&&t.classList&&t.classList.remove("d-none"))}dispose(){try{for(let t in this._handlersByElementKey||{}){let i=this._handlersByElementKey[t]||[],e=document.getElementById(this.elements[t]);e&&i.forEach(s=>{try{e.removeEventListener(s.eventName,s.handler)}catch(n){}})}}catch(t){}if(this._cropRect){try{this.canvas.remove(this._cropRect)}catch(t){}this._cropRect=null}if(this.containerElement&&this._containerOriginalOverflow!==void 0)try{this.containerElement.style.overflow=this._containerOriginalOverflow}catch(t){}if(this.canvas){try{this.canvas.dispose()}catch(t){}this.canvas=null,this.canvasElement=null,this.isImageLoadedToCanvas=!1}this._handlersByElementKey={}}},E=class{constructor(){this.animationTasks=[],this.isRunning=!1}async add(t){return new Promise((i,e)=>{this.animationTasks.push({animationFn:t,resolve:i,reject:e}),this.isRunning||this._drainQueue()})}async _drainQueue(){if(this.animationTasks.length===0){this.isRunning=!1;return}this.isRunning=!0;let{animationFn:t,resolve:i,reject:e}=this.animationTasks.shift();try{let s=await t();i(s)}catch(s){e(s)}await this._drainQueue()}},I=class{constructor(t,i){this.execute=t,this.undo=i}},C=class{constructor(t=50){this.history=[],this.currentIndex=-1,this.maxSize=t,this.pending=Promise.resolve()}enqueue(t){let i=this.pending.then(t,t),e,s=()=>{this.pending===e&&(this.pending=Promise.resolve())};return e=i.then(s,s),this.pending=e,i}execute(t){t.execute(),this.push(t)}push(t){this.currentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.currentIndex+1)),this.history.push(t),this.history.length>this.maxSize?this.history.shift():this.currentIndex++}canUndo(){return this.currentIndex>=0}canRedo(){return this.currentIndex<this.history.length-1}undo(){return this.enqueue(async()=>{if(this.currentIndex>=0){let t=this.currentIndex;await this.history[t].undo(),this.currentIndex=t-1}})}redo(){return this.enqueue(async()=>{if(this.currentIndex<this.history.length-1){let t=this.currentIndex+1;await this.history[t].execute(),this.currentIndex=t}})}};var R=w;var S=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:null;B(S&&S.fabric);S&&(S.ImageEditor=R);})();
9
9
  //# sourceMappingURL=image-editor.min.js.map