@bensitu/image-editor 2.0.0 → 2.2.0

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.
Files changed (147) hide show
  1. package/README.md +346 -90
  2. package/dist/cjs/index.cjs +4883 -1191
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/esm/animation/animation-queue.js +16 -9
  5. package/dist/esm/animation/animation-queue.js.map +1 -1
  6. package/dist/esm/annotation/annotation-lock.js +7 -0
  7. package/dist/esm/annotation/annotation-lock.js.map +1 -0
  8. package/dist/esm/annotation/annotation-manager.js +217 -0
  9. package/dist/esm/annotation/annotation-manager.js.map +1 -0
  10. package/dist/esm/annotation/annotation-style.js +50 -0
  11. package/dist/esm/annotation/annotation-style.js.map +1 -0
  12. package/dist/esm/annotation/draw-controller.js +114 -0
  13. package/dist/esm/annotation/draw-controller.js.map +1 -0
  14. package/dist/esm/annotation/text-controller.js +234 -0
  15. package/dist/esm/annotation/text-controller.js.map +1 -0
  16. package/dist/esm/core/default-options.js +447 -11
  17. package/dist/esm/core/default-options.js.map +1 -1
  18. package/dist/esm/core/editor-object-kind.js +37 -0
  19. package/dist/esm/core/editor-object-kind.js.map +1 -0
  20. package/dist/esm/core/errors.js +19 -0
  21. package/dist/esm/core/errors.js.map +1 -1
  22. package/dist/esm/core/layer-order.js +100 -0
  23. package/dist/esm/core/layer-order.js.map +1 -0
  24. package/dist/esm/core/operation-guard.js +28 -0
  25. package/dist/esm/core/operation-guard.js.map +1 -1
  26. package/dist/esm/core/public-types.js +34 -1
  27. package/dist/esm/core/public-types.js.map +1 -1
  28. package/dist/esm/core/state-serializer.js +108 -27
  29. package/dist/esm/core/state-serializer.js.map +1 -1
  30. package/dist/esm/crop/crop-controller.js +6 -2
  31. package/dist/esm/crop/crop-controller.js.map +1 -1
  32. package/dist/esm/export/export-format.js.map +1 -1
  33. package/dist/esm/export/export-service.js +140 -141
  34. package/dist/esm/export/export-service.js.map +1 -1
  35. package/dist/esm/export/overlay-merge-service.js +75 -0
  36. package/dist/esm/export/overlay-merge-service.js.map +1 -0
  37. package/dist/esm/fabric/fabric-animation.js +56 -4
  38. package/dist/esm/fabric/fabric-animation.js.map +1 -1
  39. package/dist/esm/history/history-manager.js +2 -2
  40. package/dist/esm/history/history-manager.js.map +1 -1
  41. package/dist/esm/image/image-loader.js +27 -65
  42. package/dist/esm/image/image-loader.js.map +1 -1
  43. package/dist/esm/image/image-resampler.js +7 -2
  44. package/dist/esm/image/image-resampler.js.map +1 -1
  45. package/dist/esm/image/layout-manager.js +2 -20
  46. package/dist/esm/image/layout-manager.js.map +1 -1
  47. package/dist/esm/image/transform-controller.js.map +1 -1
  48. package/dist/esm/image-editor.js +1474 -135
  49. package/dist/esm/image-editor.js.map +1 -1
  50. package/dist/esm/index.js +1 -1
  51. package/dist/esm/index.js.map +1 -1
  52. package/dist/esm/mask/mask-factory.js +92 -43
  53. package/dist/esm/mask/mask-factory.js.map +1 -1
  54. package/dist/esm/mask/mask-label-manager.js +2 -0
  55. package/dist/esm/mask/mask-label-manager.js.map +1 -1
  56. package/dist/esm/mask/mask-list.js +9 -3
  57. package/dist/esm/mask/mask-list.js.map +1 -1
  58. package/dist/esm/mask/mask-style.js.map +1 -1
  59. package/dist/esm/mosaic/mosaic-controller.js +666 -0
  60. package/dist/esm/mosaic/mosaic-controller.js.map +1 -0
  61. package/dist/esm/mosaic/mosaic-geometry.js +81 -0
  62. package/dist/esm/mosaic/mosaic-geometry.js.map +1 -0
  63. package/dist/esm/mosaic/mosaic-pixelate.js +71 -0
  64. package/dist/esm/mosaic/mosaic-pixelate.js.map +1 -0
  65. package/dist/esm/ui/dom-bindings.js +10 -3
  66. package/dist/esm/ui/dom-bindings.js.map +1 -1
  67. package/dist/esm/utils/image-element-loader.js +55 -0
  68. package/dist/esm/utils/image-element-loader.js.map +1 -0
  69. package/dist/esm/utils/number.js.map +1 -1
  70. package/dist/esm/utils/pointer.js +28 -0
  71. package/dist/esm/utils/pointer.js.map +1 -0
  72. package/dist/types/animation/animation-queue.d.ts.map +1 -1
  73. package/dist/types/annotation/annotation-lock.d.ts +12 -0
  74. package/dist/types/annotation/annotation-lock.d.ts.map +1 -0
  75. package/dist/types/annotation/annotation-manager.d.ts +33 -0
  76. package/dist/types/annotation/annotation-manager.d.ts.map +1 -0
  77. package/dist/types/annotation/annotation-style.d.ts +13 -0
  78. package/dist/types/annotation/annotation-style.d.ts.map +1 -0
  79. package/dist/types/annotation/draw-controller.d.ts +43 -0
  80. package/dist/types/annotation/draw-controller.d.ts.map +1 -0
  81. package/dist/types/annotation/text-controller.d.ts +47 -0
  82. package/dist/types/annotation/text-controller.d.ts.map +1 -0
  83. package/dist/types/core/default-options.d.ts +46 -6
  84. package/dist/types/core/default-options.d.ts.map +1 -1
  85. package/dist/types/core/editor-object-kind.d.ts +29 -0
  86. package/dist/types/core/editor-object-kind.d.ts.map +1 -0
  87. package/dist/types/core/errors.d.ts +12 -2
  88. package/dist/types/core/errors.d.ts.map +1 -1
  89. package/dist/types/core/layer-order.d.ts +21 -0
  90. package/dist/types/core/layer-order.d.ts.map +1 -0
  91. package/dist/types/core/operation-guard.d.ts +2 -0
  92. package/dist/types/core/operation-guard.d.ts.map +1 -1
  93. package/dist/types/core/public-types.d.ts +341 -33
  94. package/dist/types/core/public-types.d.ts.map +1 -1
  95. package/dist/types/core/state-serializer.d.ts +32 -5
  96. package/dist/types/core/state-serializer.d.ts.map +1 -1
  97. package/dist/types/crop/crop-controller.d.ts +6 -7
  98. package/dist/types/crop/crop-controller.d.ts.map +1 -1
  99. package/dist/types/export/export-format.d.ts +5 -33
  100. package/dist/types/export/export-format.d.ts.map +1 -1
  101. package/dist/types/export/export-service.d.ts +24 -15
  102. package/dist/types/export/export-service.d.ts.map +1 -1
  103. package/dist/types/export/overlay-merge-service.d.ts +38 -0
  104. package/dist/types/export/overlay-merge-service.d.ts.map +1 -0
  105. package/dist/types/fabric/fabric-animation.d.ts.map +1 -1
  106. package/dist/types/history/history-manager.d.ts +11 -14
  107. package/dist/types/history/history-manager.d.ts.map +1 -1
  108. package/dist/types/image/image-loader.d.ts +24 -21
  109. package/dist/types/image/image-loader.d.ts.map +1 -1
  110. package/dist/types/image/image-resampler.d.ts +2 -2
  111. package/dist/types/image/image-resampler.d.ts.map +1 -1
  112. package/dist/types/image/layout-manager.d.ts +5 -49
  113. package/dist/types/image/layout-manager.d.ts.map +1 -1
  114. package/dist/types/image/transform-controller.d.ts +6 -9
  115. package/dist/types/image/transform-controller.d.ts.map +1 -1
  116. package/dist/types/image-editor.d.ts +93 -14
  117. package/dist/types/image-editor.d.ts.map +1 -1
  118. package/dist/types/index.d.cts +3 -3
  119. package/dist/types/index.d.cts.map +1 -1
  120. package/dist/types/index.d.ts +3 -3
  121. package/dist/types/index.d.ts.map +1 -1
  122. package/dist/types/mask/mask-factory.d.ts +24 -21
  123. package/dist/types/mask/mask-factory.d.ts.map +1 -1
  124. package/dist/types/mask/mask-label-manager.d.ts +10 -9
  125. package/dist/types/mask/mask-label-manager.d.ts.map +1 -1
  126. package/dist/types/mask/mask-list.d.ts +11 -12
  127. package/dist/types/mask/mask-list.d.ts.map +1 -1
  128. package/dist/types/mask/mask-style.d.ts +19 -20
  129. package/dist/types/mask/mask-style.d.ts.map +1 -1
  130. package/dist/types/mosaic/mosaic-controller.d.ts +82 -0
  131. package/dist/types/mosaic/mosaic-controller.d.ts.map +1 -0
  132. package/dist/types/mosaic/mosaic-geometry.d.ts +29 -0
  133. package/dist/types/mosaic/mosaic-geometry.d.ts.map +1 -0
  134. package/dist/types/mosaic/mosaic-pixelate.d.ts +23 -0
  135. package/dist/types/mosaic/mosaic-pixelate.d.ts.map +1 -0
  136. package/dist/types/ui/dom-bindings.d.ts +3 -1
  137. package/dist/types/ui/dom-bindings.d.ts.map +1 -1
  138. package/dist/types/ui/visibility-state.d.ts +2 -2
  139. package/dist/types/utils/image-element-loader.d.ts +19 -0
  140. package/dist/types/utils/image-element-loader.d.ts.map +1 -0
  141. package/dist/types/utils/number.d.ts +1 -2
  142. package/dist/types/utils/number.d.ts.map +1 -1
  143. package/dist/types/utils/pointer.d.ts +16 -0
  144. package/dist/types/utils/pointer.d.ts.map +1 -0
  145. package/dist/umd/image-editor.umd.js +1 -1
  146. package/dist/umd/image-editor.umd.js.map +1 -1
  147. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ImageEditor={})}(this,function(e){"use strict";class t{constructor(){Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"running",{enumerable:!0,configurable:!0,writable:!0,value:!1})}add(e){return new Promise((t,i)=>{this.queue.push({run:e,resolve:t,reject:i}),this.running||this.drainQueue()})}clear(e){const t=this.queue;if(this.queue=[],void 0!==e)for(const i of t)i.reject(e);else for(const e of t)e.resolve()}isRunning(){return this.running}isBusy(){return this.running||this.queue.length>0}waitForIdle(){return this.running||0!==this.queue.length?this.add(()=>Promise.resolve()).then(()=>{},()=>{}):Promise.resolve()}async drainQueue(){if(0===this.queue.length)return void(this.running=!1);this.running=!0;const e=this.queue.shift();try{await e.run(),e.resolve()}catch(t){e.reject(t)}this.drainQueue()}}function i(e,t,i){const a=e.onWarning;if("function"==typeof a)try{a(t,i)}catch(e){console.warn("[ImageEditor] onWarning callback threw",e)}}function a(e,t,i){const a=e.onError;if("function"==typeof a)try{a(t,i)}catch(e){console.error("[ImageEditor] onError callback threw",e)}}const n={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,preserveSourceFormat:!0,downsampleMimeType:null,imageLoadTimeoutMs:3e4,maxHistorySize:50,exportMultiplier:1,maxExportPixels:5e7,exportAreaByDefault:"image",mergeMaskByDefault:!0,defaultMaskWidth:50,defaultMaskHeight:80,maskRotatable:!1,maskLabelOnSelect:!0,maskLabelOffset:3,maskName:"mask",groupSelection:!1,showPlaceholder:!0,initialImageBase64:null,defaultDownloadFileName:"edited_image.jpg",onImageLoadStart:null,onImageLoaded:null,onImageCleared:null,onImageChanged:null,onBusyChange:null,onEditorDisposed:null,onMasksChanged:null,onSelectionChange:null,onError:null,onWarning:null},o={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"},r={getText:e=>e.maskName},s=100,l=100,c=10,u=!0,h=!1,d=!1,m="source",g=new Set(["canvasWidth","canvasHeight","backgroundColor","animationDuration","minScale","maxScale","scaleStep","rotationStep","expandCanvasToImage","fitImageToCanvas","coverImageToCanvas","downsampleOnLoad","downsampleMaxWidth","downsampleMaxHeight","downsampleQuality","preserveSourceFormat","downsampleMimeType","imageLoadTimeoutMs","maxHistorySize","exportMultiplier","maxExportPixels","exportAreaByDefault","mergeMaskByDefault","defaultMaskWidth","defaultMaskHeight","maskRotatable","maskLabelOnSelect","maskLabelOffset","maskName","groupSelection","showPlaceholder","initialImageBase64","defaultDownloadFileName","onImageLoadStart","onImageLoaded","onImageCleared","onImageChanged","onBusyChange","onEditorDisposed","onMasksChanged","onSelectionChange","onError","onWarning","label","crop"]);function p(e){return"function"==typeof e?e:null}function f(e,t){const i=Number(e);return!Number.isFinite(i)||i<=0?t:Math.max(1,Math.floor(i))}function b(e,t){const i=Number(e);return!Number.isFinite(i)||i<=0?t:i}function v(e,t){const i=Number(e);return!Number.isFinite(i)||i<0?t:i}function y(e,t){const i=Number(e);return Number.isFinite(i)?i:t}function I(e){if(null==e)return n.downsampleQuality;const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):n.downsampleQuality}function C(e){const t=Number(e);return!Number.isFinite(t)||t<=0?n.maxExportPixels:Math.max(1,Math.floor(t))}function k(e){return"canvas"===e||"image"===e?e:n.exportAreaByDefault}function M(e){if(null==e)return;const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):void 0}function w(e){var t,i,a,w;const x=null!=e?e:{},S={...n};for(const e of Object.keys(x)){if(!g.has(e))continue;if("label"===e||"crop"===e)continue;if("onImageLoadStart"===e||"onImageLoaded"===e||"onImageCleared"===e||"onImageChanged"===e||"onBusyChange"===e||"onEditorDisposed"===e||"onMasksChanged"===e||"onSelectionChange"===e||"onError"===e||"onWarning"===e)continue;const t=x[e];void 0!==t&&("downsampleQuality"!==e?"maxExportPixels"!==e?"exportAreaByDefault"!==e?"canvasWidth"!==e?"canvasHeight"!==e?"animationDuration"!==e?"minScale"!==e?"maxScale"!==e?"scaleStep"!==e?"rotationStep"!==e?"downsampleMaxWidth"!==e?"downsampleMaxHeight"!==e?"imageLoadTimeoutMs"!==e?"exportMultiplier"!==e?"defaultMaskWidth"!==e?"defaultMaskHeight"!==e?"maskLabelOffset"!==e?S[e]=t:S.maskLabelOffset=v(t,n.maskLabelOffset):S.defaultMaskHeight=b(t,n.defaultMaskHeight):S.defaultMaskWidth=b(t,n.defaultMaskWidth):S.exportMultiplier=b(t,n.exportMultiplier):S.imageLoadTimeoutMs=f(t,n.imageLoadTimeoutMs):S.downsampleMaxHeight=f(t,n.downsampleMaxHeight):S.downsampleMaxWidth=f(t,n.downsampleMaxWidth):S.rotationStep=y(t,n.rotationStep):S.scaleStep=b(t,n.scaleStep):S.maxScale=b(t,n.maxScale):S.minScale=b(t,n.minScale):S.animationDuration=v(t,n.animationDuration):S.canvasHeight=f(t,n.canvasHeight):S.canvasWidth=f(t,n.canvasWidth):S.exportAreaByDefault=k(t):S.maxExportPixels=C(t):S.downsampleQuality=I(t))}if(S.onImageLoadStart=p(x.onImageLoadStart),S.onImageLoaded=p(x.onImageLoaded),S.onImageCleared=p(x.onImageCleared),S.onImageChanged=p(x.onImageChanged),S.onBusyChange=p(x.onBusyChange),S.onEditorDisposed=p(x.onEditorDisposed),S.onMasksChanged=p(x.onMasksChanged),S.onSelectionChange=p(x.onSelectionChange),S.onError=p(x.onError),S.onWarning=p(x.onWarning),S.maxHistorySize=function(e){const t=Number(e);return Number.isFinite(t)?Math.max(1,Math.floor(t)):n.maxHistorySize}(S.maxHistorySize),S.maxExportPixels=C(S.maxExportPixels),S.minScale>S.maxScale){const e=S.minScale;S.minScale=S.maxScale,S.maxScale=e}const O=x.label&&"object"==typeof x.label?x.label:{},E={...o,...O.textOptions&&"object"==typeof O.textOptions?O.textOptions:{}},L={getText:"function"==typeof O.getText?O.getText:r.getText,textOptions:E};"function"==typeof O.create&&(L.create=O.create),Object.freeze(L.textOptions),Object.freeze(L);const B=x.crop&&"object"==typeof x.crop?x.crop:{},j={minWidth:b(B.minWidth,s),minHeight:b(B.minHeight,l),padding:v(B.padding,c),hideMasksDuringCrop:null!==(t=B.hideMasksDuringCrop)&&void 0!==t?t:u,preserveMasksAfterCrop:null!==(i=B.preserveMasksAfterCrop)&&void 0!==i?i:h,allowRotationOfCropRect:null!==(a=B.allowRotationOfCropRect)&&void 0!==a?a:d,exportFileType:null!==(w=B.exportFileType)&&void 0!==w?w:m,exportQuality:M(B.exportQuality)};return Object.freeze(j),{...S,label:L,crop:j}}class x{constructor(){Object.defineProperty(this,"isAnimationActive",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isDisposedFlag",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isLoadingActive",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"currentOperationName",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentOperationToken",{enumerable:!0,configurable:!0,writable:!0,value:null})}isAnimating(){return this.isAnimationActive}isDisposed(){return this.isDisposedFlag}isLoading(){return this.isLoadingActive}activeOperationName(){return this.currentOperationName}isBusy(){return this.isAnimationActive||this.isLoadingActive||null!==this.currentOperationToken}beginAnimation(){this.isAnimationActive=!0}endAnimation(){this.isAnimationActive=!1}markDisposed(){this.isDisposedFlag=!0,this.isAnimationActive=!1,this.isLoadingActive=!1,this.currentOperationName=null,this.currentOperationToken=null}beginLoading(){this.isLoadingActive=!0}endLoading(){this.isLoadingActive=!1}beginBusyOperation(e){const t=Symbol(e);return this.currentOperationName=e,this.currentOperationToken=t,t}endBusyOperation(e){e&&e===this.currentOperationToken&&(this.currentOperationName=null,this.currentOperationToken=null)}isOwnOperation(e){return!!e&&e===this.currentOperationToken}async runAnimation(e){this.beginAnimation();try{return await e()}finally{this.endAnimation()}}assertNotAnimating(e){if(this.isAnimationActive)throw new Error(`[ImageEditor] Cannot run "${e}" while an animation is in progress.`)}assertIdleForOperation(e,t){var i;if(this.isDisposedFlag)throw new Error(`[ImageEditor] Cannot run "${e}" after dispose.`);const a=this.isOwnOperation(t);if(this.isAnimationActive)throw new Error(`[ImageEditor] Cannot run "${e}" while an animation is in progress.`);if(this.isLoadingActive&&!a)throw new Error(`[ImageEditor] Cannot run "${e}" while an image is loading.`);if(this.currentOperationToken&&!a)throw new Error(`[ImageEditor] Cannot run "${e}" while ${null!==(i=this.currentOperationName)&&void 0!==i?i:"another operation"} is running.`)}assertCanQueueAnimation(e,t){var i;if(this.isDisposedFlag)throw new Error(`[ImageEditor] Cannot run "${e}" after dispose.`);const a=this.isOwnOperation(t);if(this.isLoadingActive&&!a)throw new Error(`[ImageEditor] Cannot run "${e}" while an image is loading.`);if(this.currentOperationToken&&!a)throw new Error(`[ImageEditor] Cannot run "${e}" while ${null!==(i=this.currentOperationName)&&void 0!==i?i:"another operation"} is running.`)}}function S(e){return"maskId"in e&&"number"==typeof e.maskId}const O=["maskId","maskUid","maskName","isCropRect","maskLabel","originalAlpha","originalStroke","originalStrokeWidth","hasControls","selectable","strokeUniform","lockRotation","transparentCorners","borderColor","cornerColor","cornerSize"];function E(e){var t,i,a;const{canvas:n,currentScale:o,currentRotation:r,baseImageScale:s}=e,l=null===(i=(t=n).getActiveObject)||void 0===i?void 0:i.call(t),c=l&&S(l)?l.maskId:"number"==typeof e.activeMaskId?e.activeMaskId:null;(function(e){if(!e)return!1;if("activeselection"===("string"==typeof e.type?e.type.toLowerCase():""))return!0;const t=e.isType;return"function"==typeof t&&(t.call(e,"ActiveSelection")||t.call(e,"activeSelection")||t.call(e,"activeselection"))})(l)&&n.discardActiveObject();const u=n.toJSON(O);return function(e,t){if(Array.isArray(t))for(let i=0;i<t.length;i+=1){const a=e[i],n=t[i];a&&n&&("number"==typeof a.maskId&&(n.maskId=a.maskId),"string"==typeof a.maskUid&&(n.maskUid=a.maskUid),"string"==typeof a.maskName&&(n.maskName=a.maskName),"number"==typeof a.originalAlpha&&(n.originalAlpha=a.originalAlpha),"originalStroke"in a&&(n.originalStroke=a.originalStroke),"number"==typeof a.originalStrokeWidth&&(n.originalStrokeWidth=a.originalStrokeWidth),"boolean"==typeof a.hasControls&&(n.hasControls=a.hasControls),"boolean"==typeof a.selectable&&(n.selectable=a.selectable),"boolean"==typeof a.strokeUniform&&(n.strokeUniform=a.strokeUniform),"boolean"==typeof a.lockRotation&&(n.lockRotation=a.lockRotation),"boolean"==typeof a.transparentCorners&&(n.transparentCorners=a.transparentCorners),"string"==typeof a.borderColor&&(n.borderColor=a.borderColor),"string"==typeof a.cornerColor&&(n.cornerColor=a.cornerColor),"number"==typeof a.cornerSize&&(n.cornerSize=a.cornerSize),!0===a.isCropRect&&(n.isCropRect=!0),!0===a.maskLabel&&(n.maskLabel=!0))}}(n.getObjects(),u.objects),Array.isArray(u.objects)&&(u.objects=u.objects.filter(e=>!0!==e.isCropRect&&!0!==e.maskLabel)),u._editorState={currentScale:o,currentRotation:r,baseImageScale:s,currentImageMimeType:null!==(a=e.currentImageMimeType)&&void 0!==a?a:null},null!==c&&(u._editorState.activeMaskId=c),JSON.stringify(u)}async function L(e){var t,i;const{canvas:a,jsonString:n,setCanvasSize:o}=e,r="string"==typeof n?n:JSON.stringify(n),s=JSON.parse(r);"number"==typeof s.width&&s.width>0&&"number"==typeof s.height&&s.height>0&&o(s.width,s.height),await a.loadFromJSON(s);const l=a.getObjects();!function(e,t){var i,a,n,o,r;const s=new Set;for(const l of t){if("number"!=typeof l.maskId)continue;const t=String(null!==(i=l.type)&&void 0!==i?i:""),c=Number(null!==(a=l.left)&&void 0!==a?a:0),u=Number(null!==(n=l.top)&&void 0!==n?n:0),h="string"==typeof l.maskUid?l.maskUid:null;let d=-1;if(h&&(d=e.findIndex((e,t)=>!s.has(t)&&e.maskUid===h)),d<0&&(d=e.findIndex((e,i)=>{var a,n;return!s.has(i)&&((!t||e.type===t)&&(Math.abs((null!==(a=e.left)&&void 0!==a?a:0)-c)<.5&&Math.abs((null!==(n=e.top)&&void 0!==n?n:0)-u)<.5))})),d<0)continue;s.add(d);const m=e[d];m.maskId=l.maskId,"string"==typeof l.maskUid&&(m.maskUid=l.maskUid),m.maskName=String(null!==(o=l.maskName)&&void 0!==o?o:""),m.originalAlpha="number"==typeof l.originalAlpha?l.originalAlpha:null!==(r=m.opacity)&&void 0!==r?r:.5,"originalStroke"in l&&(m.originalStroke=l.originalStroke),"number"==typeof l.originalStrokeWidth&&(m.originalStrokeWidth=l.originalStrokeWidth),"boolean"==typeof l.hasControls&&(m.hasControls=l.hasControls),"boolean"==typeof l.selectable&&(m.selectable=l.selectable),"boolean"==typeof l.strokeUniform&&(m.strokeUniform=l.strokeUniform),"boolean"==typeof l.lockRotation&&(m.lockRotation=l.lockRotation),"boolean"==typeof l.transparentCorners&&(m.transparentCorners=l.transparentCorners),"string"==typeof l.borderColor&&(m.borderColor=l.borderColor),"string"==typeof l.cornerColor&&(m.cornerColor=l.cornerColor),"number"==typeof l.cornerSize&&(m.cornerSize=l.cornerSize)}t.forEach((t,i)=>{if(!0!==t.maskLabel)return;const a=e[i];a&&(a.maskLabel=!0)})}(l,null!==(t=s.objects)&&void 0!==t?t:[]);const c=s._editorState&&"object"==typeof s._editorState?{currentScale:"number"==typeof s._editorState.currentScale?s._editorState.currentScale:1,currentRotation:"number"==typeof s._editorState.currentRotation?s._editorState.currentRotation:0,baseImageScale:"number"==typeof s._editorState.baseImageScale?s._editorState.baseImageScale:1}:null;if(c&&s._editorState&&"number"==typeof s._editorState.activeMaskId&&(c.activeMaskId=s._editorState.activeMaskId),c&&s._editorState&&"currentImageMimeType"in s._editorState){const e=s._editorState.currentImageMimeType;c.currentImageMimeType="image/jpeg"===e||"image/png"===e||"image/webp"===e?e:null}return{editorState:c,maxMaskId:l.filter(S).reduce((e,t)=>Math.max(e,t.maskId),0),originalImage:null!==(i=l.find(B))&&void 0!==i?i:null,objects:l,jsonString:r}}function B(e){if(S(e))return!1;if("image"===("string"==typeof e.type?e.type.toLowerCase():""))return!0;const t=e.isType;return"function"==typeof t&&t.call(e,"image")}class j{constructor(e,t){Object.defineProperty(this,"execute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"undo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.execute=e,this.undo=t}}class A{constructor(e=50){Object.defineProperty(this,"history",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"currentIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"isProcessing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}execute(e){e.execute(),this.pushAndTrim(e)}push(e){this.pushAndTrim(e)}canUndo(){return this.currentIndex>=0}canRedo(){return this.currentIndex<this.history.length-1}async undo(){if(!this.isProcessing&&this.canUndo()){this.isProcessing=!0;try{const e=this.history[this.currentIndex];if(!e)return;await e.undo(),this.currentIndex--}finally{this.isProcessing=!1}}}async redo(){if(!this.isProcessing&&this.canRedo()){this.isProcessing=!0;try{const e=this.history[this.currentIndex+1];if(!e)return;await e.execute(),this.currentIndex++}finally{this.isProcessing=!1}}}pushAndTrim(e){this.currentIndex<this.history.length-1&&(this.history=this.history.slice(0,this.currentIndex+1)),this.history.push(e),this.history.length>this.maxSize?this.history.shift():this.currentIndex++}}function N(e){if(null===e||"object"!=typeof e)return!1;return"function"==typeof e.Canvas}function T(e,t){Object.setPrototypeOf(e,t.prototype)}class F extends Error{constructor(e="Failed to decode image data URL.",t=null){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ImageDecodeError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=t,T(this,F)}}class R extends Error{constructor(e,t){super(`Image load timed out after ${t}ms during ${e}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ImageLoadTimeoutError"}),Object.defineProperty(this,"label",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"elapsedMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.label=e,this.elapsedMs=t,T(this,R)}}class P extends Error{constructor(e="Failed to obtain a 2D context for downsampling.",t=null){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"DownsampleError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=t,T(this,P)}}class D extends Error{constructor(e="Failed to merge masks into the image.",t=null){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"MergeMasksError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=t,T(this,D)}}class W extends Error{constructor(e="Failed to apply crop to the image.",t=null){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CropApplyError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=t,T(this,W)}}class H extends Error{constructor(e="exportImageFile"){super(`Cannot ${e}: no image is loaded on the canvas.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ExportNotReadyError"}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.operation=e,T(this,H)}}class U extends Error{constructor(e="Failed to export image.",t=null){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ExportError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=t,T(this,U)}}const z="#ccc";function Q(e){var t;const i=Number(e.originalStrokeWidth);e.set({stroke:null!==(t=e.originalStroke)&&void 0!==t?t:z,strokeWidth:Number.isFinite(i)?i:1})}function $(e){const t=e,i=()=>{var e;t.set(function(e){const t=Number(e.originalAlpha),i=Number.isFinite(t)?t:.5;return{stroke:"#ff5500",strokeWidth:2,opacity:Math.min(i+.2,1)}}(t)),null===(e=t.canvas)||void 0===e||e.requestRenderAll()},a=()=>{var e;t.set(function(e){var t;const i=Number(e.originalStrokeWidth),a=Number(e.originalAlpha);return{stroke:null!==(t=e.originalStroke)&&void 0!==t?t:z,strokeWidth:Number.isFinite(i)?i:1,opacity:Number.isFinite(a)?a:.5}}(t)),null===(e=t.canvas)||void 0===e||e.requestRenderAll()};t.on("mouseover",i),t.on("mouseout",a),t.imageEditorMaskHandlers={mouseover:i,mouseout:a}}function q(e){var t;const i=e;if(i.imageEditorMaskHandlers){try{i.off("mouseover",i.imageEditorMaskHandlers.mouseover),i.off("mouseout",i.imageEditorMaskHandlers.mouseout)}catch{}delete i.imageEditorMaskHandlers}const a={};if(!Number.isFinite(Number(i.originalAlpha))){const e=Number(i.opacity);a.originalAlpha=Number.isFinite(e)?e:.5}if(null==i.originalStroke&&(a.originalStroke=null!==(t=i.stroke)&&void 0!==t?t:z),!Number.isFinite(Number(i.originalStrokeWidth))){const e=Number(i.strokeWidth);a.originalStrokeWidth=Number.isFinite(e)?e:1}Object.keys(a).length>0&&i.set(a),$(i)}function G(e){const t=e;if(t.imageEditorMaskHandlers){try{t.off("mouseover",t.imageEditorMaskHandlers.mouseover),t.off("mouseout",t.imageEditorMaskHandlers.mouseout)}catch{}delete t.imageEditorMaskHandlers}}function Y(e){var t,i,a,n,o,r,s;return{object:e,opacity:null!==(t=e.opacity)&&void 0!==t?t:1,fill:null!==(i=e.fill)&&void 0!==i?i:null,strokeWidth:null!==(a=e.strokeWidth)&&void 0!==a?a:0,stroke:null!==(n=e.stroke)&&void 0!==n?n:null,selectable:null===(o=e.selectable)||void 0===o||o,evented:null===(r=e.evented)||void 0===r||r,lockRotation:null!==(s=e.lockRotation)&&void 0!==s&&s}}function X(e){try{e.object.set({opacity:e.opacity,fill:e.fill,strokeWidth:e.strokeWidth,stroke:e.stroke,selectable:e.selectable,evented:e.evented,lockRotation:e.lockRotation}),"function"==typeof e.object.setCoords&&e.object.setCoords()}catch{}}function _(e){try{e.set({opacity:0,evented:!1,selectable:!1})}catch{}}function V(e,t,i){const a=Number(e.left),n=Number(e.top),o=Number(e.width),r=Number(e.height);if(!Number.isFinite(a)||!Number.isFinite(n)||!Number.isFinite(o)||!Number.isFinite(r)||o<=0||r<=0)return!1;const s=a+o,l=n+r;if(!Number.isFinite(s)||!Number.isFinite(l))return!1;const c=Number(t),u=Number(i);if(!Number.isFinite(c)||!Number.isFinite(u)||c<=0||u<=0)return!0;const h=Math.min(s,c)-Math.max(a,0),d=Math.min(l,u)-Math.max(n,0);return h>0&&d>0}function J(e,t,i,a={}){const n=Number.isFinite(e.left)?e.left:0,o=Number.isFinite(e.top)?e.top:0,r=Math.max(0,Number.isFinite(e.width)?e.width:0),s=Math.max(0,Number.isFinite(e.height)?e.height:0),l=!1!==a.includePartialPixels?Math.ceil:Math.floor,c=Number.isFinite(t),u=Number.isFinite(i),h=c?Math.max(1,Math.round(Number(t))):Number.POSITIVE_INFINITY,d=u?Math.max(1,Math.round(Number(i))):Number.POSITIVE_INFINITY,m=Math.min(h-1,Math.max(0,Math.floor(n))),g=Math.min(d-1,Math.max(0,Math.floor(o))),p=Math.min(h,Math.max(m+1,l(n+r))),f=Math.min(d,Math.max(g+1,l(o+s)));return{left:m,top:g,width:Math.max(1,p-m),height:Math.max(1,f-g)}}function K(e){const t=Number(e);return!!Number.isFinite(t)&&Math.abs(t-Math.round(t))>.01}function Z(e,t=0){if(!e)return null;const i=Math.abs((Number(t)||0)%90);if(!(i<.01||Math.abs(i-90)<.01))return null;const a=Number(e.left)||0,n=Number(e.top)||0;return{left:K(a),top:K(n),right:K(a+(Number(e.width)||0)),bottom:K(n+(Number(e.height)||0))}}function ee(e){e.setCoords();const t=e.getBoundingRect();return{left:t.left,top:t.top,width:t.width,height:t.height}}const te=Object.freeze({jpeg:"jpeg",jpg:"jpeg","image/jpeg":"jpeg",png:"png","image/png":"png",webp:"webp","image/webp":"webp"}),ie=Object.freeze({jpeg:"image/jpeg",png:"image/png",webp:"image/webp"});function ae(e){var t;if(!e)return null;const i=String(e).toLowerCase();return Object.prototype.hasOwnProperty.call(te,i)&&null!==(t=te[i])&&void 0!==t?t:null}function ne(e){return ie[e]}function oe(e,t){const i=Number(e);return Number.isFinite(i)?Math.max(0,Math.min(1,i)):t}function re(e,t){var i;const a=null!=e?e:{},n=a.fileType,o=a.format,r=function(e){var t;return null!==(t=ae(e))&&void 0!==t?t:"jpeg"}(n||o),s=ne(r);if("png"===r)return{format:r,mimeType:s,quality:void 0};return{format:r,mimeType:s,quality:oe(null!==(i=a.quality)&&void 0!==i?i:t,t)}}const se=[6,4],le=.92;function ce(e,t){const i=Number(e);return Number.isFinite(i)?i:t}function ue(e,t){const i=Number(e);if(Number.isFinite(i))return oe(i,le);const a=Number(t);return Number.isFinite(a)?oe(a,le):le}function he(e,t){for(const e of t.handlers)for(const t of e.handlers)try{e.target.off(t.eventName,t.callback)}catch{}if(t.handlers=[],t.cropRect){try{e.canvas.remove(t.cropRect)}catch{}t.cropRect=null}}function de(e){for(const t of e.prevEvented)try{t.object.set({evented:t.evented,selectable:t.selectable})}catch{}e.prevEvented=[]}function me(e,t){he(e,t),de(t),function(e){for(const t of e.maskBackups)X(t);e.maskBackups=[]}(t);try{e.canvas.selection=!!t.prevSelection}catch{}}function ge(e,t){const i=ee(e);return i.left<t.left+t.width&&i.left+i.width>t.left&&i.top<t.top+t.height&&i.top+i.height>t.top}function pe(e){const t=e.getCropSession();if(t){e.canvas.discardActiveObject(),me(e,t),e.setCropSession(null);try{e.canvas.renderAll()}catch{}}}async function fe(e){var t,i;const a=e.getCropSession();if(!a||!a.cropRect)return;const{canvas:n}=e;n.discardActiveObject();const o=a.beforeJson,r=a.cropRect,s=!!e.options.crop.preserveMasksAfterCrop;try{r.setCoords();const l=Number(r.angle)||0;if(!e.options.crop.allowRotationOfCropRect&&Math.abs(l%360)>.01)throw new W("applyCrop failed: rotated crop rectangles are disabled.");const c=function(e){const t=Number(e.angle)||0,i=Math.abs(t%360);return i>.01&&Math.abs(i-360)>.01?ee(e):{left:Number(e.left)||0,top:Number(e.top)||0,width:Math.max(0,(Number(e.width)||0)*Math.abs(Number(e.scaleX)||1)),height:Math.max(0,(Number(e.height)||0)*Math.abs(Number(e.scaleY)||1))}}(r);if(!V(c,n.getWidth(),n.getHeight()))throw new W("applyCrop failed: crop region is empty or outside the canvas.");const u=J(c,n.getWidth(),n.getHeight(),{includePartialPixels:!1}),h=s?function(e,t,i=[]){var a;const n=[],o=new Map(i.map(e=>[e.object,e])),r=e.getObjects().filter(S);for(const i of r)try{if(i.setCoords(),ge(i,t)){const e=null!==(a=o.get(i))&&void 0!==a?a:Y(i);n.push({mask:i,left:ce(i.left,0),top:ce(i.top,0),angle:ce(i.angle,0),scaleX:ce(i.scaleX,1),scaleY:ce(i.scaleY,1),styleBackup:e})}e.remove(i)}catch{}return n}(n,u,a.maskBackups):[];de(a),he(e,a),n.selection=!!a.prevSelection;const d=function(e){var t,i;const a=e.cropExportFileType,n=null==a||"source"===a?null!==(t=function(e){return"image/jpeg"===e?"jpeg":"image/png"===e?"png":"image/webp"===e?"webp":null}(e.currentImageMimeType))&&void 0!==t?t:"png":null!==(i=ae(String(a)))&&void 0!==i?i:"png",o=ne(n);return"png"===n?{format:n,mimeType:o}:{format:n,mimeType:o,quality:ue(e.cropExportQuality,e.downsampleQuality)}}({cropExportFileType:e.options.crop.exportFileType,currentImageMimeType:null!==(i=null===(t=e.getCurrentImageMimeType)||void 0===t?void 0:t.call(e))&&void 0!==i?i:null,cropExportQuality:e.options.crop.exportQuality,downsampleQuality:e.options.downsampleQuality}),m={format:d.format,multiplier:1,left:u.left,top:u.top,width:u.width,height:u.height};void 0!==d.quality&&(m.quality=d.quality);const g=n.toDataURL(m);await e.loadImage(g),h.length>0&&(!function(e,t,i){var a;if(0===i.length)return;const{canvas:n}=e;let o=0;for(const e of i)try{X(e.styleBackup),e.mask.set({left:e.left-t.left,top:e.top-t.top,angle:e.angle,scaleX:e.scaleX,scaleY:e.scaleY,visible:!0}),e.mask.setCoords(),n.add(e.mask),n.bringObjectToFront(e.mask),q(e.mask);const i=Number(e.mask.maskId);Number.isFinite(i)&&i>o&&(o=i)}catch{}if("function"==typeof e.getMaskCounter&&"function"==typeof e.setMaskCounter){const t=Number(e.getMaskCounter()),i=Number.isFinite(t)?t:0;e.setMaskCounter(Math.max(i,o))}try{null===(a=e.updateMaskList)||void 0===a||a.call(e)}catch{}}(e,u,h),n.renderAll());const p=e.saveState();e.setCropSession(null),o&&p&&o!==p&&e.historyManager.push(new j(()=>e.loadFromState(p),()=>e.loadFromState(o)))}catch(t){me(e,a),e.setCropSession(null);try{await e.loadFromState(o)}catch(e){console.warn("[ImageEditor] applyCrop: rollback failed",e)}if(t instanceof W)throw t;const i=t instanceof Error?`applyCrop failed: ${t.message}`:"applyCrop failed";throw new W(i,t)}}function be(e,t){const i=Number(e);if(Number.isFinite(i)&&i>0)return i;const a=Number(t);return Number.isFinite(a)&&a>0?a:1}function ve(e,t,i){const a=e,n=a[t],o="function"==typeof n?n.call(a):a[i];return Math.max(1,Math.ceil(Number.isFinite(o)?Number(o):1))}async function ye(e,t,i){return t?async function(e,t,i){if(!e.canvas)return await i();const a=e.canvas.getObjects().filter(S),n=a.map(Y);try{return a.forEach((e,i)=>t(e,i)),await i()}finally{for(const e of n)X(e)}}({canvas:e.canvas,options:e.options},ke,i):async function(e,t){const i=Ie(e.canvas).filter(S).map(e=>({mask:e,visible:e.visible}));for(const e of i)try{"function"==typeof e.mask.set?e.mask.set({visible:!1}):e.mask.visible=!1}catch{}try{return await t()}finally{for(const e of i)try{"function"==typeof e.mask.set?e.mask.set({visible:e.visible}):e.mask.visible=e.visible}catch{}}}(e,i)}function Ie(e){try{return e.getObjects()}catch{return[]}}function Ce(e,t){return Ie(e).includes(t)}function ke(e){try{e.set({opacity:1,fill:"#000",strokeWidth:0,stroke:null,selectable:!1}),"function"==typeof e.setCoords&&e.setCoords()}catch{}}function Me(e){return{width:Math.max(1,e.naturalWidth||e.width||1),height:Math.max(1,e.naturalHeight||e.height||1)}}function we(e){return new Promise((t,i)=>{const a=new Image;a.crossOrigin="anonymous";const n=()=>{"function"==typeof a.removeEventListener?(a.removeEventListener("load",o),a.removeEventListener("error",r)):(a.onload=null,a.onerror=null)},o=()=>{n(),t(a)},r=()=>{n(),i(new Error("Failed to decode export data URL"))};"function"==typeof a.addEventListener?(a.addEventListener("load",o,{once:!0}),a.addEventListener("error",r,{once:!0})):(a.onload=o,a.onerror=r),a.src=e})}function xe(e){return function(e,t="#ffffff"){const i=String(null!=e?e:"").trim();if(!i||function(e){const t=e.trim().toLowerCase();if("transparent"===t)return!0;const i=t.match(/^#([0-9a-f]{4}|[0-9a-f]{8})$/i);if(i){const e=i[1],t=4===e.length?e[3]:e.slice(6,8);return/^0+$/.test(t)}const a=t.match(/^(?:rgba|hsla)\((.*),\s*([^,/)]+)\)$/i);if(a&&Se(a[2]))return!0;const n=t.match(/^[a-z][a-z0-9-]*\([^/]+\/\s*([^)]+)\)$/i);return!(!n||!Se(n[1]))}(i))return"#ffffff";const a=function(){try{return"undefined"==typeof document||"function"!=typeof document.createElement?null:document.createElement("canvas").getContext("2d")}catch{return null}}();if(!a)return t;a.fillStyle="#000001";const n=a.fillStyle;a.fillStyle=i;const o=a.fillStyle;if(o!==n)return o;a.fillStyle="#000002";const r=a.fillStyle;a.fillStyle=i;const s=a.fillStyle;return s!==r?s:t}(e)}function Se(e){const t=e.trim();if(t.endsWith("%")){const e=Number.parseFloat(t.slice(0,-1));return Number.isFinite(e)&&0===e}const i=Number.parseFloat(t);return Number.isFinite(i)&&0===i}function Oe(e){console.warn(`[ImageEditor] ${e} skipped: no image is loaded on the canvas.`)}async function Ee(e,t){if(!e.isImageLoaded())return Oe("exportImageBase64"),"";const i=function(e){var t;try{const i=e;return"function"!=typeof i.getActiveObject?null:null!==(t=i.getActiveObject())&&void 0!==t?t:null}catch{return null}}(e.canvas),a=function(e){const t=[];for(const i of Ie(e)){if(!S(i))continue;const a=i.labelObject;if(!a)continue;const n=Ce(e,a);t.push({mask:i,label:a,wasOnCanvas:n,visible:a.visible});try{"function"==typeof a.set&&a.set({visible:!1}),n&&e.remove(a)}catch{}}return t}(e.canvas);try{e.canvas.discardActiveObject();const i=function(e,t){const i=null!=t?t:{};return{exportArea:(a=i.exportArea,n=e.options.exportAreaByDefault,"canvas"===a||"image"===a?a:"canvas"===n?"canvas":"image"),mergeMask:"boolean"==typeof i.mergeMask?i.mergeMask:e.options.mergeMaskByDefault,multiplier:be(i.multiplier,e.options.exportMultiplier),format:re(i,e.options.downsampleQuality)};var a,n}(e,t),{region:a,partialEdges:n}=function(e,t){if("canvas"===t)return{region:null,partialEdges:null};const i=e.getOriginalImage();if(!i)return{region:null,partialEdges:null};const a=ee(i),n=e.canvas,o="function"==typeof n.getWidth?n.getWidth():n.width,r="function"==typeof n.getHeight?n.getHeight():n.height;if(!V(a,o,r))throw new U("exportImageBase64 failed: image export region is empty.");return{region:J(a,o,r,{includePartialPixels:!0}),partialEdges:Z(a,Number(i.angle)||0)}}(e,i.exportArea);!function(e,t,i){var a,n;const o=null!==(a=null==i?void 0:i.width)&&void 0!==a?a:ve(e.canvas,"getWidth","width"),r=null!==(n=null==i?void 0:i.height)&&void 0!==n?n:ve(e.canvas,"getHeight","height"),s=Math.max(1,Math.ceil(o*t)),l=Math.max(1,Math.ceil(r*t)),c=s*l,u=e.options.maxExportPixels;if(!Number.isFinite(c)||c>u)throw new RangeError(`[ImageEditor] Export size ${s}x${l} (${c} pixels) exceeds maxExportPixels (${u}).`)}(e,i.multiplier,a);const o=a&&"jpeg"===i.format.format?"png":i.format.format,r="png"===o?void 0:i.format.quality;let s=await ye(e,i.mergeMask,async()=>function(e,t,i,a,n){const o={format:t,multiplier:a};return void 0!==i&&(o.quality=i),n&&(o.left=n.left,o.top=n.top,o.width=n.width,o.height=n.height),e.toDataURL(o)}(e.canvas,o,r,i.multiplier,a));return a&&(s=await async function(e,t){if(!function(e){return!!e&&(e.left||e.top||e.right||e.bottom)}(t))return e;const i=await we(e),{width:a,height:n}=Me(i),o=document.createElement("canvas");o.width=a,o.height=n;const r=o.getContext("2d");if(!r)throw new Error("2D canvas context is unavailable");r.drawImage(i,0,0,a,n);const s=r.getImageData(0,0,a,n),l=s.data,c=(e,t,i,n)=>{var o,r,s,c,u,h;const d=4*(t*a+e),m=4*(n*a+i),g=null!==(o=l[d+3])&&void 0!==o?o:0,p=null!==(r=l[m+3])&&void 0!==r?r:0;0===g&&p>0&&(l[d]=null!==(s=l[m])&&void 0!==s?s:0,l[d+1]=null!==(c=l[m+1])&&void 0!==c?c:0,l[d+2]=null!==(u=l[m+2])&&void 0!==u?u:0,l[d+3]=p);const f=null!==(h=l[d+3])&&void 0!==h?h:0;f>0&&f<255&&(l[d+3]=255)};if((null==t?void 0:t.left)&&a>1)for(let e=0;e<n;e+=1)c(0,e,1,e);if((null==t?void 0:t.right)&&a>1)for(let e=0;e<n;e+=1)c(a-1,e,a-2,e);if((null==t?void 0:t.top)&&n>1)for(let e=0;e<a;e+=1)c(e,0,e,1);if((null==t?void 0:t.bottom)&&n>1)for(let e=0;e<a;e+=1)c(e,n-1,e,n-2);return r.putImageData(s,0,0),o.toDataURL("image/png")}(s,n),"jpeg"===i.format.format&&(s=await async function(e,t,i){const a=await we(e),{width:n,height:o}=Me(a),r=document.createElement("canvas");r.width=n,r.height=o;const s=r.getContext("2d");if(!s)throw new Error("2D canvas context is unavailable");return s.fillStyle=xe(t),s.fillRect(0,0,n,o),s.drawImage(a,0,0,n,o),r.toDataURL("image/jpeg",i)}(s,e.options.backgroundColor,i.format.quality))),s}finally{!function(e,t){for(const i of t)try{i.mask.labelObject=i.label,"function"==typeof i.label.set?i.label.set({visible:i.visible}):i.label.visible=i.visible,i.wasOnCanvas&&!Ce(e,i.label)&&(e.add(i.label),e.bringObjectToFront(i.label))}catch{}}(e.canvas,a),function(e,t){if(t)try{const i=e;"function"==typeof i.setActiveObject&&i.setActiveObject(t)}catch{}}(e.canvas,i),function(e){try{"function"==typeof e.requestRenderAll?e.requestRenderAll():e.renderAll()}catch{}}(e.canvas)}}async function Le(e,t){var i;if(!e.isImageLoaded())throw Oe("exportImageFile"),new H("exportImageFile");const a=null!=t?t:{},n=null!==(i=a.fileName)&&void 0!==i?i:e.options.defaultDownloadFileName,o=re(a,e.options.downsampleQuality),r=await Ee(e,{exportArea:a.exportArea,mergeMask:a.mergeMask,multiplier:a.multiplier,quality:a.quality,fileType:a.fileType});if(!r)throw new H("exportImageFile");const s=await async function(e,t,i){if(e.startsWith(`data:${t.mimeType}`))return e;const a=await we(e),{width:n,height:o}=Me(a),r=document.createElement("canvas");r.width=n,r.height=o;const s=r.getContext("2d");if(!s)throw new Error("Unable to acquire 2D context for export conversion");return"jpeg"===t.format&&(s.fillStyle=xe(i),s.fillRect(0,0,n,o)),s.drawImage(a,0,0,n,o),r.toDataURL(t.mimeType,t.quality)}(r,o,e.options.backgroundColor);let l;try{l=function(e){var t;const i=/^data:image\/[a-z0-9.+-]+;base64,([A-Za-z0-9+/=\s]+)$/i.exec(e);if(!i||!(null===(t=i[1])||void 0===t?void 0:t.trim()))throw new Error("exportImageFile received a malformed or empty image data URL.");const a=e.indexOf(","),n=e.slice(a+1).replace(/\s/g,"");if("function"==typeof globalThis.atob){const e=globalThis.atob(n),t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let t=e.length-1;t>=0;t-=1)i[t]=e.charCodeAt(t);return i}const o=globalThis.Buffer;if(o&&"function"==typeof o.from){const e=o.from(n,"base64"),t=new ArrayBuffer(e.length),i=new Uint8Array(t);return i.set(e),i}throw new Error("No base64 decoder is available for exportImageFile.")}(s)}catch(e){throw new U("exportImageFile failed to decode rendered data URL.",e)}return new File([l],n,{type:o.mimeType})}function Be(e,t,i){return new Promise((a,n)=>{const o=Date.now(),r=setTimeout(()=>{n(new R(i,Date.now()-o))},t);e.then(e=>{clearTimeout(r),a(e)},e=>{clearTimeout(r),n(e)})})}function je(e){return e.fitImageToCanvas?"fit":e.coverImageToCanvas?"cover":"expand"}class Ae{constructor(){Object.defineProperty(this,"lastVisible",{enumerable:!0,configurable:!0,writable:!0,value:null})}measure(e,t,i){var a;if(!e)return t;const n=Math.floor(e.clientWidth),o=Math.floor(e.clientHeight);return n>0&&o>0?(this.lastVisible=function(e,t,i){if(!e)return t;const a=Math.floor(e.clientWidth||0),n=Math.floor(e.clientHeight||0);if(a<=0||n<=0)return t;const o=function(e){var t,i;const a=e.style;let n="",o="",r="";const s=null!==(i=null===(t=e.ownerDocument)||void 0===t?void 0:t.defaultView)&&void 0!==i?i:"undefined"==typeof window?null:window;if("function"==typeof(null==s?void 0:s.getComputedStyle)){const t=s.getComputedStyle(e);n=t.overflow,o=t.overflowX,r=t.overflowY}const l=[Te(null==a?void 0:a.overflow),Te(null==a?void 0:a.overflowX),Te(n),Te(o)],c=[Te(null==a?void 0:a.overflow),Te(null==a?void 0:a.overflowY),Te(n),Te(r)];return{x:l,y:c,all:[...l,...c]}}(e);if(o.all.includes("scroll"))return{width:a,height:n};const r=Pe(i),s=o.x.some(Fe),l=o.y.some(Fe),c=Math.ceil(e.scrollWidth||0),u=Math.ceil(e.scrollHeight||0),h=s&&c>a+Ne;return{width:a+(l&&u>n+Ne?r.width:0),height:n+(h?r.height:0)}}(e,t,i),this.lastVisible):null!==(a=this.lastVisible)&&void 0!==a?a:t}peek(){return this.lastVisible}clear(){this.lastVisible=null}}const Ne=.5;function Te(e){return String(null!=e?e:"").trim().toLowerCase()}function Fe(e){return"auto"===e||"overlay"===e}function Re(e){const t=null!=e?e:"undefined"==typeof document?null:document;if(!(null==t?void 0:t.body))return{width:0,height:0};const i=t.createElement("div");i.style.position="absolute",i.style.left="-9999px",i.style.top="-9999px",i.style.width="100px",i.style.height="100px",i.style.overflow="scroll",i.style.visibility="hidden",i.style.pointerEvents="none",t.body.appendChild(i);const a=Math.max(0,i.offsetWidth-i.clientWidth),n=Math.max(0,i.offsetHeight-i.clientHeight);return i.remove(),{width:a,height:n}}function Pe(e){return{width:Math.max(0,Number(null==e?void 0:e.width)||0),height:Math.max(0,Number(null==e?void 0:e.height)||0)}}function De(e,t,i,a){const n=Math.max(1,i.width||1),o=Math.max(1,i.height||1),r=Pe(a);let s=!1,l=!1;for(let i=0;i<4;i+=1){const i=Math.max(1,n-(l?r.width:0)),a=Math.max(1,o-(s?r.height:0)),c=e>i+Ne,u=t>a+Ne;if(c===s&&u===l)break;s=c,l=u}const c=Math.max(1,n-(l?r.width:0)),u=Math.max(1,o-(s?r.height:0));return{width:s?Math.ceil(e):c,height:l?Math.ceil(t):u}}function We(e,t,i,a){const n=Math.max(1,Math.round(Number(t)||1)),o=Math.max(1,Math.round(Number(i)||1));var r;e.setDimensions({width:n,height:o}),(r=a)&&r.offsetWidth}function He(e,t,i,a){if(!(Ue(e)&&Ue(t)&&Ue(i)&&Ue(a)))return{width:Math.max(1,Math.round(e)||1),height:Math.max(1,Math.round(t)||1),needsResize:!1};if(!(e>i||t>a))return{width:e,height:t,needsResize:!1};const n=Math.min(i/e,a/t);return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n)),needsResize:!0}}function Ue(e){return Number.isFinite(e)&&e>0}function ze(e){const t=/^data:(image\/[a-z0-9+\-.]+)\s*;/i.exec(e);return t?t[1].toLowerCase():null}async function Qe(e,t,n={}){if("string"!=typeof t||!t.startsWith("data:image/"))return;const o={placeholderHidden:e.placeholderElement?!!e.placeholderElement.hidden:null,containerScrollTop:e.containerElement?e.containerElement.scrollTop:null,containerScrollLeft:e.containerElement?e.containerElement.scrollLeft:null,containerOverflow:e.containerElement?e.containerElement.style.overflow:null,originalImage:e.getOriginalImage(),isImageLoadedToCanvas:e.getIsImageLoadedToCanvas(),lastSnapshot:e.getLastSnapshot(),canvasJson:Ge(e.canvas),maskCounter:e.getMaskCounter(),currentScale:e.getCurrentScale(),currentRotation:e.getCurrentRotation(),baseImageScale:e.getBaseImageScale(),currentImageMimeType:e.getCurrentImageMimeType()};try{e.setPlaceholderVisible(!1);const a=function(e){const t=new Image,i=(e=!1)=>{"function"==typeof t.removeEventListener?(t.removeEventListener("load",a),t.removeEventListener("error",n)):(t.onload=null,t.onerror=null),e&&(t.src="")},a=()=>{if(!function(e){return Number.isFinite(e.naturalWidth)&&Number.isFinite(e.naturalHeight)&&e.naturalWidth>0&&e.naturalHeight>0}(t))return i(!0),void r(new F("Failed to decode image data URL: image has no natural dimensions.",null));i(!1),o(t)},n=e=>{i(!0),r(new F("Failed to decode image data URL.",e))};let o,r;const s=new Promise((i,s)=>{o=i,r=s,"function"==typeof t.addEventListener?(t.addEventListener("load",a,{once:!0}),t.addEventListener("error",n,{once:!0})):(t.onload=a,t.onerror=n),t.src=e});return{promise:s,cleanup:i}}(t);let r;try{r=await Be(a.promise,e.options.imageLoadTimeoutMs,"image decode")}catch(e){throw a.cleanup(!0),e}const s=function(e,t,a){const n=qe(ze(t));if(!a.downsampleOnLoad)return{dataUrl:t,mimeType:n};if(!$e(a.downsampleMaxWidth)||!$e(a.downsampleMaxHeight))return i(a,null,"loadImage skipped downsampling because downsample bounds are invalid."),{dataUrl:t,mimeType:n};const o=He(e.naturalWidth,e.naturalHeight,a.downsampleMaxWidth,a.downsampleMaxHeight);if(!o.needsResize)return{dataUrl:t,mimeType:n};const r=ze(t),s=function(e,t,i,a,n,o,r){const{width:s,height:l}=He(e.naturalWidth,e.naturalHeight,t,i),c=function(e,t,i){return i||(!t||"image/png"!==e&&"image/webp"!==e?"image/jpeg":e)}(a,n,o),u=document.createElement("canvas");u.width=s,u.height=l;const h=u.getContext("2d");if(!h)throw new P("Failed to obtain a 2D context for downsampling.");return h.drawImage(e,0,0,e.naturalWidth,e.naturalHeight,0,0,s,l),{dataUrl:"image/png"===c?u.toDataURL(c):u.toDataURL(c,r),width:s,height:l,mimeType:c}}(e,a.downsampleMaxWidth,a.downsampleMaxHeight,r,a.preserveSourceFormat,a.downsampleMimeType,a.downsampleQuality),l=qe(ze(s.dataUrl));return{dataUrl:s.dataUrl,mimeType:null!=l?l:s.mimeType}}(r,t,e.options),l=await Be(e.fabric.FabricImage.fromURL(s.dataUrl,{crossOrigin:"anonymous"}),e.options.imageLoadTimeoutMs,"FabricImage.fromURL");e.canvas.discardActiveObject(),e.canvas.clear(),e.canvas.backgroundColor=e.options.backgroundColor,l.set({originX:"left",originY:"top",selectable:!1,evented:!1});const c=function(e,t){var i,a,n,o;const r=null!==(i=t.width)&&void 0!==i?i:0,s=null!==(a=t.height)&&void 0!==a?a:0,l=Re(null!==(o=null===(n=e.containerElement)||void 0===n?void 0:n.ownerDocument)&&void 0!==o?o:null),c=e.viewportCache.measure(e.containerElement,{width:e.options.canvasWidth,height:e.options.canvasHeight},l),u=je(e.options);if("fit"===u)return function(e,t,i,a,n){const o=Math.max(1,(n.width||i)-1),r=Math.max(1,(n.height||a)-1),s=Math.min(o/e,r/t,1);return{canvasWidth:o,canvasHeight:r,imageScale:s,imageLeft:0,imageTop:0,baseImageScale:s}}(r,s,e.options.canvasWidth,e.options.canvasHeight,c);if("cover"===u)return function(e,t,i,a,n,o){const r=n.width||i,s=n.height||a,l=Pe(o);let c=!1,u=!1,h=1,d=e,m=t;for(let i=0;i<4;i+=1){const i=Math.max(1,r-(u?l.width:0)),a=Math.max(1,s-(c?l.height:0));h=Math.min(1,Math.max(i/e,a/t)),d=e*h,m=t*h;const n=d>i+Ne,o=m>a+Ne;if(n===c&&o===u)break;c=n,u=o}const g=De(d,m,{width:r,height:s},l);return{canvasWidth:g.width,canvasHeight:g.height,imageScale:h,imageLeft:0,imageTop:0,baseImageScale:h}}(r,s,e.options.canvasWidth,e.options.canvasHeight,c,l);return function(e,t,i,a,n){return{canvasWidth:Math.max(n.width,Math.floor(e)),canvasHeight:Math.max(n.height,Math.floor(t)),imageScale:1,imageLeft:0,imageTop:0,baseImageScale:1}}(r,s,e.options.canvasWidth,e.options.canvasHeight,c)}(e,l);if(We(e.canvas,c.canvasWidth,c.canvasHeight,e.containerElement),l.set({left:c.imageLeft,top:c.imageTop}),l.scale(c.imageScale),e.canvas.add(l),e.canvas.sendObjectToBack(l),e.setOriginalImage(l),e.setBaseImageScale(c.baseImageScale),e.setCurrentScale(1),e.setCurrentRotation(0),e.setMaskCounter(0),e.setIsImageLoadedToCanvas(!0),e.setCurrentImageMimeType(s.mimeType),e.canvas.renderAll(),e.setLastSnapshot(E({canvas:e.canvas,currentScale:1,currentRotation:0,baseImageScale:c.baseImageScale,currentImageMimeType:s.mimeType})),!0===n.preserveScroll&&e.containerElement)try{null!==o.containerScrollTop&&(e.containerElement.scrollTop=o.containerScrollTop),null!==o.containerScrollLeft&&(e.containerElement.scrollLeft=o.containerScrollLeft)}catch(e){console.warn("[ImageEditor] preserveScroll restore failed",e)}}catch(t){await async function(e,t){if(e.containerElement&&null!==t.containerOverflow)try{e.containerElement.style.overflow=t.containerOverflow}catch(e){console.warn("[ImageEditor] rollback: overflow restore failed",e)}try{await e.canvas.loadFromJSON(JSON.parse(t.canvasJson)),e.canvas.renderAll()}catch(e){console.warn("[ImageEditor] rollback: loadFromJSON failed",e)}if(e.setOriginalImage(t.originalImage),e.setIsImageLoadedToCanvas(t.isImageLoadedToCanvas),e.setLastSnapshot(t.lastSnapshot),e.setMaskCounter(t.maskCounter),e.setCurrentScale(t.currentScale),e.setCurrentRotation(t.currentRotation),e.setBaseImageScale(t.baseImageScale),e.setCurrentImageMimeType(t.currentImageMimeType),e.containerElement)try{null!==t.containerScrollTop&&(e.containerElement.scrollTop=t.containerScrollTop),null!==t.containerScrollLeft&&(e.containerElement.scrollLeft=t.containerScrollLeft)}catch(e){console.warn("[ImageEditor] rollback: scroll restore failed",e)}null!==t.placeholderHidden&&e.setPlaceholderVisible(!t.placeholderHidden)}(e,o);const i=t instanceof Error?`loadImage failed: ${t.message}`:"loadImage failed";throw a(e.options,t,i),t}}function $e(e){return Number.isFinite(e)&&e>0}function qe(e){return"image/jpeg"===e||"image/png"===e||"image/webp"===e?e:null}function Ge(e){e.discardActiveObject();const t=e.toJSON(O);return JSON.stringify(t)}function Ye(e,t,i,a){return new Promise((n,o)=>{const r=Object.keys(t).length;if(0===r)return void n();let s=0;try{e.animate(t,{duration:i.duration,onChange:()=>{var e;a.isDisposed()||null===(e=i.onChange)||void 0===e||e.call(i)},onComplete:()=>{++s>=r&&n()}})}catch(e){o(e)}})}class Xe{constructor(e){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.context=e}async scaleImage(e){if(!Number.isFinite(e))return;const t=this.context.getOriginalImage();if(!t)return;if(this.context.guard.isAnimating())return;if(this.context.guard.isDisposed())return;const i=Math.max(this.context.options.minScale,Math.min(this.context.options.maxScale,e));this.context.setCurrentScale(i);const a=this.context.getBaseImageScale()*i;try{const e=_e(t);t.set({originX:"left",originY:"top"}),t.setPositionByOrigin(e,"left","top"),t.setCoords()}catch(e){console.warn("[ImageEditor] scaleImage: origin pre-anchor failed",e)}try{await this.context.guard.runAnimation(()=>Ye(t,{scaleX:a,scaleY:a},{duration:this.context.options.animationDuration,onChange:()=>this.context.canvas.requestRenderAll()},this.context.guard))}catch(e){return void console.warn("[ImageEditor] scaleImage animation error",e)}this.context.guard.isDisposed()||(t.set({scaleX:a,scaleY:a}),t.setCoords(),this.context.afterTransformSnap&&this.context.afterTransformSnap(),this.context.saveCanvasState())}async rotateImage(e){if(!Number.isFinite(e))return;const t=this.context.getOriginalImage();if(!t)return;if(this.context.guard.isAnimating())return;if(this.context.guard.isDisposed())return;this.context.setCurrentRotation(e);try{const e=t.getCenterPoint();t.set({originX:"center",originY:"center"}),t.setPositionByOrigin(e,"center","center"),t.setCoords()}catch(e){console.warn("[ImageEditor] rotateImage: origin pre-anchor failed",e)}let i=!1;try{await this.context.guard.runAnimation(()=>Ye(t,{angle:e},{duration:this.context.options.animationDuration,onChange:()=>this.context.canvas.requestRenderAll()},this.context.guard))}catch(e){i=!0,console.warn("[ImageEditor] rotateImage animation error",e)}finally{this.context.guard.isDisposed()&&function(e,t,i){try{e.set({originX:t,originY:i}),e.setCoords()}catch{}}(t,"left","top")}if(!i&&!this.context.guard.isDisposed()){t.set("angle",e),t.setCoords(),this.context.afterTransformSnap&&this.context.afterTransformSnap();try{const e=_e(t);t.set({originX:"left",originY:"top"}),t.setPositionByOrigin(e,"left","top"),t.setCoords()}catch(e){console.warn("[ImageEditor] rotateImage: origin post-restore failed",e)}this.context.saveCanvasState()}}async resetImageTransform(){if(this.context.getOriginalImage()){this.context.setSuppressSaveState(!0);try{await this.scaleImage(1),await this.rotateImage(0)}finally{this.context.setSuppressSaveState(!1)}this.context.guard.isDisposed()||this.context.saveCanvasState()}}}function _e(e){e.setCoords();const t=e.getCoords()[0];if(t)return t;const i=e.getBoundingRect();return{x:i.left,y:i.top}}function Ve(e,t,i,a,n){if("number"==typeof e)return e;if("function"==typeof e)return e(a,n);if("string"==typeof e&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isFinite(n))return i;const o="x"===t?a.getWidth():a.getHeight();return Math.floor(o*(n/100))}return i}function Je(e){return Array.isArray(e)?{x:Number(e[0]),y:Number(e[1])}:{x:Number(e.x),y:Number(e.y)}}let Ke=0;function Ze(e,t){i(e,null,`createMask skipped: ${t}.`)}function et(e){return void 0===e||("number"==typeof e?Number.isFinite(e):"function"==typeof e||!("string"!=typeof e||!e.endsWith("%"))&&Number.isFinite(Number.parseFloat(e)))}function tt(e){return"number"==typeof e&&Number.isFinite(e)}function it(e,t,i){return!!tt(i)||(Ze(e,`${t} must resolve to a finite number`),!1)}function at(e,t,i){return!!(tt(i)&&i>0)||(Ze(e,`${t} must resolve to a positive number`),!1)}function nt(e,t,i){return!!(tt(i)&&i>=0)||(Ze(e,`${t} must resolve to a non-negative number`),!1)}function ot(e,t){if(!Array.isArray(t)||t.length<3)return Ze(e,"polygon masks require at least three points"),null;const i=t.map(Je);return i.every(e=>Number.isFinite(e.x)&&Number.isFinite(e.y))?function(e){let t=0;for(let i=0;i<e.length;i+=1){const a=e[i],n=e[(i+1)%e.length];t+=a.x*n.y-n.x*a.y}return Math.abs(t)/2}(i)<=1e-6?(Ze(e,"polygon points must describe a non-zero area"),null):i:(Ze(e,"polygon points must contain finite x/y values"),null)}function rt(e,t={}){var a,n,o,r,s,l,c,u,h,d,m,g,p,f,b,v;const{canvas:y,options:I,fabric:C}=e;if(!y)return null;const k=null!==(a=t.shape)&&void 0!==a?a:"rect";if(!function(e,t){const i=[["width",t.width],["height",t.height],["rx",t.rx],["ry",t.ry],["radius",t.radius],["left",t.left],["top",t.top]];for(const[t,a]of i)if(!et(a))return Ze(e,`${t} is not a supported numeric value`),!1;return!0}(I,t))return null;const M={shape:k,width:I.defaultMaskWidth,height:I.defaultMaskHeight,color:"rgba(0,0,0,0.5)",alpha:.5,gap:5,left:void 0,top:void 0,angle:0,selectable:!0,...t};let w,x;const S=e.getLastMask();if(void 0===t.left&&S){const e=(null!==(n=S.left)&&void 0!==n?n:0)+("function"==typeof S.getScaledWidth?S.getScaledWidth():(null!==(o=S.width)&&void 0!==o?o:0)*(null!==(r=S.scaleX)&&void 0!==r?r:1));w=Math.round(e+(null!==(s=M.gap)&&void 0!==s?s:5)),x=null!==(l=S.top)&&void 0!==l?l:10}else w=Ve(t.left,"x",10,y,I),x=Ve(t.top,"y",10,y,I);M.width=Ve(t.width,"x",I.defaultMaskWidth,y,I),M.height=Ve(t.height,"y",I.defaultMaskHeight,y,I);const O=void 0!==t.rx?Ve(t.rx,"x",0,y,I):void 0,E=void 0!==t.ry?Ve(t.ry,"y",0,y,I):void 0,L="circle"===k?Ve(t.radius,"x",Math.min(M.width,M.height)/2,y,I):void 0,B="polygon"===k?ot(I,t.points):null;if(!(it(I,"left",w)&&it(I,"top",x)&&at(I,"width",M.width)&&at(I,"height",M.height)&&it(I,"gap",M.gap)&&it(I,"angle",M.angle)&&it(I,"alpha",M.alpha)))return null;if(void 0!==O&&!nt(I,"rx",O)||void 0!==E&&!nt(I,"ry",E)||void 0!==L&&!at(I,"radius",L)||"polygon"===k&&null===B)return null;if(I.expandCanvasToImage){const t=Math.ceil(w+M.width+10),i=Math.ceil(x+M.height+10),a=Math.max(y.getWidth(),t),n=Math.max(y.getHeight(),i);a===y.getWidth()&&n===y.getHeight()||(e.expandCanvasIfNeeded?e.expandCanvasIfNeeded(a,n):y.setDimensions({width:a,height:n}))}let j;if("function"==typeof M.fabricGenerator){const e=M.fabricGenerator(M,y,I);if(!function(e){if(!e||"object"!=typeof e)return!1;const t=e;return"function"==typeof t.set&&"function"==typeof t.on}(e))return i(I,e,"createMask skipped: fabricGenerator did not return a Fabric object."),null;j=e}else{const e={originX:"left",originY:"top"};switch(k){case"circle":j=new C.Circle({left:w,top:x,...e,radius:L,fill:M.color,opacity:M.alpha,angle:null!==(c=M.angle)&&void 0!==c?c:0,...M.styles});break;case"ellipse":j=new C.Ellipse({left:w,top:x,...e,rx:null!=O?O:M.width/2,ry:null!=E?E:M.height/2,fill:M.color,opacity:M.alpha,angle:null!==(u=M.angle)&&void 0!==u?u:0,...M.styles});break;case"polygon":{const t=new C.Polygon(B,{...e,fill:M.color,opacity:M.alpha,angle:null!==(h=M.angle)&&void 0!==h?h:0,...M.styles});t.setCoords();const i=t.getBoundingRect(),a=w-i.left,n=x-i.top;t.set({left:(null!==(d=t.left)&&void 0!==d?d:0)+a,top:(null!==(m=t.top)&&void 0!==m?m:0)+n}),t.setCoords(),j=t;break}default:j=new C.Rect({left:w,top:x,...e,width:M.width,height:M.height,fill:M.color,opacity:M.alpha,angle:null!==(g=M.angle)&&void 0!==g?g:0,...void 0!==O?{rx:O}:{},...void 0!==E?{ry:E}:{},...M.styles})}}const A=j;A.selectable=!("selectable"in t)||!!t.selectable,A.evented=!("evented"in t)||!!t.evented,A.hasControls=!("hasControls"in t)||!!t.hasControls,A.transparentCorners="transparentCorners"in t&&!!t.transparentCorners,A.strokeUniform=!("strokeUniform"in t)||!!t.strokeUniform,A.lockRotation=!I.maskRotatable,A.borderColor=null!==(p=t.borderColor)&&void 0!==p?p:"red",A.cornerColor=null!==(f=t.cornerColor)&&void 0!==f?f:"black",A.cornerSize=null!==(b=t.cornerSize)&&void 0!==b?b:8;const N=null!==(v=M.styles)&&void 0!==v?v:{};A.stroke="stroke"in N?N.stroke:"#ccc",A.strokeWidth="strokeWidth"in N?N.strokeWidth:1,"strokeDashArray"in N&&(A.strokeDashArray=N.strokeDashArray),A.originalAlpha=M.alpha,A.originalStroke=A.stroke,A.originalStrokeWidth=A.strokeWidth,$(A);const T=e.getMaskCounter()+1;if(e.setMaskCounter(T),A.maskId=T,A.maskUid=(Ke+=1,`mask-${T}-${Ke}`),A.maskName=`${I.maskName}${T}`,e.setLastMask(A),y.add(A),y.bringObjectToFront(A),e.updateMaskList(),!1!==M.selectable&&y.setActiveObject(A),y.renderAll(),e.saveCanvasState(),"function"==typeof M.onCreate)try{M.onCreate(A,y)}catch(e){i(I,e,"createMask onCreate callback threw.")}return A}function st(e,t={}){const i=e.canvas.getObjects().filter(S);if(0!==i.length){for(const t of i)e.removeLabelForMask(t),G(t),e.canvas.remove(t);e.canvas.discardActiveObject(),e.setLastMask(null),e.updateMaskList(),e.canvas.renderAll(),!1!==t.saveHistory&&e.saveCanvasState()}}function lt(e,t){if(e.canvas&&t.labelObject){try{e.canvas.getObjects().includes(t.labelObject)&&e.canvas.remove(t.labelObject)}catch{}try{delete t.labelObject}catch{}}}function ct(e,t){var a;const{canvas:n,options:o,fabric:r}=e;if(!n||!o.maskLabelOnSelect)return;lt(e,t);let s=null;if("function"==typeof o.label.create)try{s=o.label.create(t,r)}catch(e){i(o,e,"label.create callback threw."),s=null}if(!s){const e=t.maskId-1;let n=t.maskName;if("function"==typeof o.label.getText)try{n=o.label.getText(t,e)}catch(e){i(o,e,"label.getText callback threw."),n=t.maskName}const l={left:0,top:0,...null!==(a=o.label.textOptions)&&void 0!==a?a:{},originX:"left",originY:"top"};s=new r.FabricText(n,l)}s.maskLabel=!0,t.labelObject=s,n.add(s),n.bringObjectToFront(s),ut(e,t)}function ut(e,t){var i,a,n;const{canvas:o,options:r}=e;if(!o||!r.maskLabelOnSelect||!t.labelObject)return;const s=null===(i=t.getCoords)||void 0===i?void 0:i.call(t);if(!(null==s?void 0:s.length))return;const l=s[0];if(!l)return;const c=t.getCenterPoint(),u=c.x-l.x,h=c.y-l.y,d=Math.sqrt(u*u+h*h)||1,m=Math.max(0,null!==(a=r.maskLabelOffset)&&void 0!==a?a:3);t.labelObject.set({left:Math.round(l.x+u/d*m),top:Math.round(l.y+h/d*m),angle:null!==(n=t.angle)&&void 0!==n?n:0,originX:"left",originY:"top",visible:!0}),t.labelObject.setCoords(),o.renderAll()}class ht{constructor(e,t){Object.defineProperty(this,"registry",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"resolveElementId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isDisposed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.resolveElementId=e,this.isDisposed=t}bindIfExists(e,t,i){const a=this.resolveElementId(e);if(!a)return!1;const n=document.getElementById(a);if(!n)return!1;const o=e=>{this.isDisposed()||i(e)};return n.addEventListener(t,o),this.registry.push({elementKey:e,eventType:t,handler:o}),!0}removeAll(){for(const e of this.registry){const t=this.resolveElementId(e.elementKey);if(!t)continue;const i=document.getElementById(t);if(i)try{i.removeEventListener(e.eventType,e.handler)}catch{}}this.registry=[]}size(){return this.registry.length}}function dt(e,t,i){e&&(e.hidden=!i,e.setAttribute("aria-hidden",i?"false":"true")),t&&(t.hidden=i,t.setAttribute("aria-hidden",i?"true":"false"))}const mt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp"},gt=new Set(Object.values(mt));function pt(e){if(e)try{e.value=""}catch{}}const ft=.5,bt=Symbol.for("ImageEditorInternalOperation"),vt=Symbol.for("ImageEditorAllowDuringAnimationQueue"),yt=["scalePercentageInput","rotateLeftDegreesInput","rotateRightDegreesInput","rotateLeftButton","rotateRightButton","createMaskButton","removeSelectedMaskButton","removeAllMasksButton","mergeMasksButton","downloadImageButton","zoomInButton","zoomOutButton","resetImageTransformButton","undoButton","redoButton","imageInput","enterCropModeButton","applyCropButton","cancelCropButton"],It=["applyCropButton","cancelCropButton"],Ct=new Set(["applyCrop","cancelCrop"]);class kt{constructor(e={},a={}){var n;Object.defineProperty(this,"fabricModule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isFabricLoaded",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"canvasElement",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"containerElement",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"placeholderElement",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"elements",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"elementOriginalDisabledMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"elementOriginalAriaDisabledMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"elementOriginalPointerEventsMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"originalImage",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"baseImageScale",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"currentScale",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"currentRotation",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"isImageLoadedToCanvas",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"currentImageMimeType",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"maskCounter",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"lastMask",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"lastSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"historyManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"operationGuard",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"animQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transformController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"viewportCache",{enumerable:!0,configurable:!0,writable:!0,value:new Ae}),Object.defineProperty(this,"cropSession",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"domBindings",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isDisposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"shouldSuppressSaveState",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lastEmittedIsBusy",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"activeStateRestoreOperation",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextSelectionChangeContext",{enumerable:!0,configurable:!0,writable:!0,value:null});const o=function(e,t,i=globalThis){var a;if(N(e))return{fabric:e,isFabricLoaded:!0,options:null!=t?t:{}};const n=null!==(a=e)&&void 0!==a?a:{},o=function(e){return e.fabric}(i);return N(o)?{fabric:o,isFabricLoaded:!0,options:n}:(console.error("[ImageEditor] fabric.js v7 is not available. Pass it as the first constructor argument (ESM) or load it as a global <script> before instantiation."),{fabric:null,isFabricLoaded:!1,options:n})}(e,a);this.fabricModule=null!==(n=o.fabric)&&void 0!==n?n:{},this.isFabricLoaded=o.isFabricLoaded,this.options=w(o.options);const r=function(e){if(!e.fitImageToCanvas||!e.coverImageToCanvas)return null;const t=["fit","cover"];e.expandCanvasToImage&&t.push("expand");const i=je(e);return{enabled:t,selected:i,message:`Layout flags ${t.map(e=>`\`${e}\``).join(", ")} are enabled simultaneously. Using precedence \`fit > cover > expand\`; selected \`${i}\`.`}}(this.options);r&&i(this.options,null,r.message),this.operationGuard=new x,this.animQueue=new t,this.historyManager=new A(this.options.maxHistorySize)}init(e={}){if(!this.isFabricLoaded){const e=globalThis.fabric;if(!e||"function"!=typeof e.Canvas)return;this.fabricModule=e,this.isFabricLoaded=!0}if(this.isDisposed)return;this.elements={canvas:"canvas",canvasContainer:null,imagePlaceholder:"imagePlaceholder",scalePercentageInput:"scalePercentageInput",rotateLeftDegreesInput:"rotateLeftDegreesInput",rotateRightDegreesInput:"rotateRightDegreesInput",rotateLeftButton:"rotateLeftButton",rotateRightButton:"rotateRightButton",createMaskButton:"createMaskButton",removeSelectedMaskButton:"removeSelectedMaskButton",removeAllMasksButton:"removeAllMasksButton",mergeMasksButton:"mergeMasksButton",downloadImageButton:"downloadImageButton",maskList:"maskList",zoomInButton:"zoomInButton",zoomOutButton:"zoomOutButton",resetImageTransformButton:"resetImageTransformButton",undoButton:"undoButton",redoButton:"redoButton",imageInput:"imageInput",enterCropModeButton:"enterCropModeButton",applyCropButton:"applyCropButton",cancelCropButton:"cancelCropButton",uploadArea:"uploadArea",...e},this.domBindings=new ht(e=>this.elements[e],()=>this.isDisposed),this.initCanvas(),this.transformController=new Xe(this.buildTransformContext()),this.bindDomEvents(),this.updateInputs(),this.updateMaskList(),this.updateUi(),this.options.initialImageBase64?this.loadImage(this.options.initialImageBase64).catch(()=>{}):this.updatePlaceholderStatus()}initCanvas(){var e;const t=this.elements.canvas,i=t?document.getElementById(t):null;if(!i)throw new Error(`[ImageEditor] Canvas element not found: "${t}"`);this.canvasElement=i;const a=this.elements.canvasContainer;this.containerElement=a&&null!==(e=document.getElementById(a))&&void 0!==e?e:i.parentElement;const n=this.elements.imagePlaceholder;this.placeholderElement=n?document.getElementById(n):null;let o=this.options.canvasWidth,r=this.options.canvasHeight;if(this.containerElement){const e=Math.floor(this.containerElement.clientWidth),t=Math.floor(this.containerElement.clientHeight);e>0&&t>0&&(o=e,r=t)}this.canvas=new this.fabricModule.Canvas(i,{width:o,height:r,backgroundColor:this.options.backgroundColor,selection:this.options.groupSelection,preserveObjectStacking:!0}),this.canvas.on("selection:created",e=>{this.handleSelectionChanged(e.selected)}),this.canvas.on("selection:updated",e=>{this.handleSelectionChanged(e.selected)}),this.canvas.on("selection:cleared",()=>this.handleSelectionChanged([]));const s=e=>{e.target&&S(e.target)&&this.syncMaskLabel(e.target)};this.canvas.on("object:moving",s),this.canvas.on("object:scaling",s),this.canvas.on("object:rotating",s),this.canvas.on("object:modified",e=>{e.target&&S(e.target)&&(this.syncMaskLabel(e.target),this.saveState())})}bindDomEvents(){this.bindElementIfExists("uploadArea","click",()=>{var e;const t=this.elements.imageInput;t&&(null===(e=document.getElementById(t))||void 0===e||e.click())}),this.bindElementIfExists("imageInput","change",e=>{var t;const i=null===(t=e.target.files)||void 0===t?void 0:t[0];i&&this.loadImageFile(i)}),this.bindElementIfExists("zoomInButton","click",()=>{this.scaleImage(this.currentScale+this.options.scaleStep)}),this.bindElementIfExists("zoomOutButton","click",()=>{this.scaleImage(this.currentScale-this.options.scaleStep)}),this.bindElementIfExists("resetImageTransformButton","click",()=>{this.resetImageTransform()}),this.bindElementIfExists("createMaskButton","click",()=>{this.createMask()}),this.bindElementIfExists("removeSelectedMaskButton","click",()=>{this.removeSelectedMask()}),this.bindElementIfExists("removeAllMasksButton","click",()=>{this.removeAllMasks()}),this.bindElementIfExists("mergeMasksButton","click",()=>{this.mergeMasks()}),this.bindElementIfExists("downloadImageButton","click",()=>{this.downloadImage()}),this.bindElementIfExists("undoButton","click",()=>{this.undo()}),this.bindElementIfExists("redoButton","click",()=>{this.redo()}),this.bindElementIfExists("rotateLeftButton","click",()=>{const e=this.elements.rotateLeftDegreesInput,t=e?document.getElementById(e):null;let i=this.options.rotationStep;if(t){const e=parseFloat(t.value);isNaN(e)||(i=e)}this.rotateImage(this.currentRotation-i)}),this.bindElementIfExists("rotateRightButton","click",()=>{const e=this.elements.rotateRightDegreesInput,t=e?document.getElementById(e):null;let i=this.options.rotationStep;if(t){const e=parseFloat(t.value);isNaN(e)||(i=e)}this.rotateImage(this.currentRotation+i)}),this.bindElementIfExists("enterCropModeButton","click",()=>{this.enterCropMode()}),this.bindElementIfExists("applyCropButton","click",()=>{this.applyCrop().catch(e=>{a(this.options,e,"Crop apply failed.")})}),this.bindElementIfExists("cancelCropButton","click",()=>{this.cancelCrop()})}bindElementIfExists(e,t,i){var a;null===(a=this.domBindings)||void 0===a||a.bindIfExists(e,t,i)}async loadImageFile(e){const t=this.elements.imageInput,n=t?document.getElementById(t):null,o=function(e){var t,i;if(e.type&&gt.has(e.type))return e.type;if(e.type)return null;const a=/\.([a-z0-9]+)$/i.exec(e.name),n=null===(t=null==a?void 0:a[1])||void 0===t?void 0:t.toLowerCase();return n&&null!==(i=mt[n])&&void 0!==i?i:null}(e);if(!o)return i(this.options,null,`Unsupported image file type: ${e.type||e.name||"unknown"}.`),void pt(n);let r;try{r=await function(e){return new Promise((t,i)=>{const a=new FileReader;a.onload=()=>{const e=a.result;"string"==typeof e?t(e):i(new Error("FileReader returned a non-string result"))},a.onerror=()=>{var e;i(null!==(e=a.error)&&void 0!==e?e:new Error("FileReader error"))},a.onabort=()=>{i(new Error("FileReader read aborted"))},a.readAsDataURL(e)})}(e)}catch(e){return a(this.options,e,"Failed to read selected image file."),void pt(n)}try{await this.loadImage(r)}catch{}finally{pt(n)}}async loadImage(e,t={}){if(!this.isFabricLoaded||!this.canvas)return;if(this.isDisposed)return;if("string"!=typeof e||!e.startsWith("data:image/"))return;if(!this.canRunIdleOperation("loadImage",t))return;const i=this.getOperationContext("loadImage",t),a=this.originalImage,n=this.getMasks().length>0;this.emitOptionCallback("onImageLoadStart",[i]),this.operationGuard.beginLoading(),this.emitBusyChangeIfChanged(i),this.updateUi(),this.hideAllMaskLabels();const o={fabric:this.fabricModule,canvas:this.canvas,options:this.options,containerElement:this.containerElement,placeholderElement:this.placeholderElement,viewportCache:this.viewportCache,getOriginalImage:()=>this.originalImage,setOriginalImage:e=>{this.originalImage=e},getIsImageLoadedToCanvas:()=>this.isImageLoadedToCanvas,setIsImageLoadedToCanvas:e=>{this.isImageLoadedToCanvas=e},getLastSnapshot:()=>this.lastSnapshot,setLastSnapshot:e=>{this.lastSnapshot=e},getMaskCounter:()=>this.maskCounter,setMaskCounter:e=>{this.maskCounter=e},getCurrentScale:()=>this.currentScale,setCurrentScale:e=>{this.currentScale=e},getCurrentRotation:()=>this.currentRotation,setCurrentRotation:e=>{this.currentRotation=e},getBaseImageScale:()=>this.baseImageScale,setBaseImageScale:e=>{this.baseImageScale=e},getCurrentImageMimeType:()=>this.currentImageMimeType,setCurrentImageMimeType:e=>{this.currentImageMimeType=e},setPlaceholderVisible:e=>{dt(this.placeholderElement,this.containerElement,!!this.options.showPlaceholder&&e)}};try{await Qe(o,e,t)}finally{this.operationGuard.endLoading(),this.emitBusyChangeIfChanged(i),!this.isDisposed&&this.canvas&&this.updateUi()}this.lastMask=null,this.updateInputs(),this.updateMaskList(),this.updateUi(),a&&a!==this.originalImage&&this.emitOptionCallback("onImageCleared",[a,i]);const r=this.getImageInfo();r&&this.emitOptionCallback("onImageLoaded",[r,i]),n&&this.emitMasksChanged(i),this.emitImageChanged(i)}getInternalOperationToken(e){var t;return null!==(t=null==e?void 0:e[bt])&&void 0!==t?t:null}canRunDuringAnimationQueue(e){return!!(null==e?void 0:e[vt])}withInternalOperationOptions(e,t={}){return{...t,...e?{[bt]:e}:{}}}withAnimationQueueBypass(e={}){return{...e,[vt]:!0}}assertIdleForOperation(e,t){const i=this.getInternalOperationToken(t);if(this.operationGuard.assertIdleForOperation(e,i),this.cropSession&&!this.operationGuard.isOwnOperation(i)&&!Ct.has(e))throw new Error(`[ImageEditor] Cannot run "${e}" while crop mode is active.`);if(this.animQueue.isBusy()&&!this.canRunDuringAnimationQueue(t))throw new Error(`[ImageEditor] Cannot run "${e}" while an animation is queued.`)}canRunIdleOperation(e,t){try{return this.assertIdleForOperation(e,t),!0}catch{return!1}}assertCanQueueAnimation(e,t){this.operationGuard.assertCanQueueAnimation(e,this.getInternalOperationToken(t))}isImageLoaded(){var e,t;return!!(this.originalImage&&this.originalImage instanceof this.fabricModule.FabricImage&&(null!==(e=this.originalImage.width)&&void 0!==e?e:0)>0&&(null!==(t=this.originalImage.height)&&void 0!==t?t:0)>0)}isBusy(){return this.operationGuard.isBusy()||this.animQueue.isBusy()||null!==this.cropSession}setLayoutMode(e){"fit"===e||"cover"===e||"expand"===e?(this.options.fitImageToCanvas="fit"===e,this.options.coverImageToCanvas="cover"===e,this.options.expandCanvasToImage="expand"===e):i(this.options,new TypeError(`[ImageEditor] Unsupported layout mode ${JSON.stringify(e)}. Expected "fit", "cover", or "expand".`),"Ignored invalid layout mode.")}buildCallbackContext(e,t=!1){return{operation:e,isInternalOperation:t}}getOperationContext(e,t){const i=this.getInternalOperationToken(t),a=this.operationGuard.activeOperationName();return i&&a?this.buildCallbackContext(a,!0):this.buildCallbackContext(e,!1)}emitOptionCallback(e,t){const i=this.options[e];if("function"==typeof i)try{i(...t)}catch(t){console.error(`[ImageEditor] ${e} callback threw`,t)}}getImageInfo(){if(!this.canvas||!this.originalImage)return null;const e=this.canvas.getWidth(),t=this.canvas.getHeight();let i,a;try{this.originalImage.setCoords();const e=this.originalImage.getBoundingRect();i=Math.max(0,Number(e.width)||0),a=Math.max(0,Number(e.height)||0)}catch{i=Math.max(0,(Number(this.originalImage.width)||0)*Math.abs(Number(this.originalImage.scaleX)||1)),a=Math.max(0,(Number(this.originalImage.height)||0)*Math.abs(Number(this.originalImage.scaleY)||1))}return{width:Math.max(0,Number(this.originalImage.width)||0),height:Math.max(0,Number(this.originalImage.height)||0),displayWidth:i,displayHeight:a,scale:this.currentScale,rotation:this.currentRotation,canvasWidth:e,canvasHeight:t}}getMasks(){return this.canvas?this.canvas.getObjects().filter(S).slice():[]}getMaskCollectionSignature(){return this.getMasks().map(e=>`${e.maskId}:${e.maskName}`).join("|")}getEditorState(){const e=this.canvas?this.canvas.getWidth():0,t=this.canvas?this.canvas.getHeight():0,i=this.getImageInfo();return{hasImage:null!==i,image:i,maskCount:this.getMasks().length,currentScale:this.currentScale,currentRotation:this.currentRotation,isBusy:this.isBusy(),isCropMode:null!==this.cropSession,canUndo:this.historyManager.canUndo(),canRedo:this.historyManager.canRedo(),canvasWidth:e,canvasHeight:t}}emitImageChanged(e){this.emitOptionCallback("onImageChanged",[this.getEditorState(),e])}emitMasksChanged(e){this.emitOptionCallback("onMasksChanged",[this.getMasks(),e])}emitBusyChangeIfChanged(e){const t=this.isBusy();this.lastEmittedIsBusy!==t&&(this.lastEmittedIsBusy=t,this.emitOptionCallback("onBusyChange",[t,e]))}buildSelection(e){var t;const i=e.filter(S);return{selectedMask:null!==(t=i[0])&&void 0!==t?t:null,selectedMasks:i}}withSelectionChangeContext(e,t){const i=this.nextSelectionChangeContext;this.nextSelectionChangeContext=e;try{return t()}finally{this.nextSelectionChangeContext=i}}isSupportedImageMimeType(e){return"image/jpeg"===e||"image/png"===e||"image/webp"===e}inferCurrentImageMimeType(){const e=this.originalImage;if(!e)return null;let t=null;try{"function"==typeof e.getSrc?t=e.getSrc():"string"==typeof e.src&&(t=e.src)}catch{t=null}const i=t?ze(t):null;return this.isSupportedImageMimeType(i)?i:null}setCanvasSizePx(e,t){this.canvas&&We(this.canvas,e,t,this.containerElement)}alignObjectBoundingBoxToCanvasTopLeft(e){var t,i;e.setCoords();const a=e.getBoundingRect();e.set({left:(null!==(t=e.left)&&void 0!==t?t:0)-a.left,top:(null!==(i=e.top)&&void 0!==i?i:0)-a.top}),e.setCoords(),this.canvas.renderAll()}measureLayoutViewport(e){return this.viewportCache.measure(this.containerElement,{width:this.options.canvasWidth,height:this.options.canvasHeight},e)}updateCanvasSizeToImageBounds(){var e,t;if(!this.originalImage)return;this.originalImage.setCoords();const i=this.originalImage.getBoundingRect(),a=Re(null!==(t=null===(e=this.containerElement)||void 0===e?void 0:e.ownerDocument)&&void 0!==t?t:null),n=this.measureLayoutViewport(a);if(this.options.fitImageToCanvas||this.options.coverImageToCanvas){const e=De(i.width,i.height,n,a);return void this.setCanvasSizePx(e.width,e.height)}i.width<=n.width&&i.height<=n.height?this.setCanvasSizePx(n.width,n.height):this.setCanvasSizePx(Math.max(n.width,Math.ceil(i.width)),Math.max(n.height,Math.ceil(i.height)))}shouldNormalizeCanvasSizeAfterStateRestore(){var e,t;if(!this.canvas||!this.originalImage)return!1;this.originalImage.setCoords();const i=this.originalImage.getBoundingRect(),a=this.measureLayoutViewport(Re(null!==(t=null===(e=this.containerElement)||void 0===e?void 0:e.ownerDocument)&&void 0!==t?t:null)),n=Math.ceil(this.canvas.getWidth()),o=Math.ceil(this.canvas.getHeight()),r=i.width>n+ft||i.height>o+ft;if(this.options.fitImageToCanvas||this.options.coverImageToCanvas){const e=n>a.width+ft&&i.width<=a.width+ft,t=o>a.height+ft&&i.height<=a.height+ft;return r||e||t}if(this.options.expandCanvasToImage){const e=Math.max(a.width,Math.ceil(i.width)),t=Math.max(a.height,Math.ceil(i.height));return Math.abs(n-e)>ft||Math.abs(o-t)>ft}return r}captureImageDisplayGeometry(){if(!this.canvas||!this.originalImage)return null;this.originalImage.setCoords();const e=this.originalImage.getBoundingRect();return{canvasWidth:this.canvas.getWidth(),canvasHeight:this.canvas.getHeight(),imageDisplayWidth:Math.max(1,e.width),imageDisplayHeight:Math.max(1,e.height)}}restoreMergedImageDisplayGeometry(e){if(!e||!this.canvas||!this.originalImage)return;this.setCanvasSizePx(e.canvasWidth,e.canvasHeight);const t=Math.max(1,this.originalImage.width||e.imageDisplayWidth),i=Math.max(1,this.originalImage.height||e.imageDisplayHeight),a=Math.min(e.imageDisplayWidth/t,e.imageDisplayHeight/i);this.originalImage.set({left:0,top:0,angle:0,scaleX:a,scaleY:a,originX:"left",originY:"top",selectable:!1,evented:!1,hasControls:!1,hoverCursor:"default"}),this.originalImage.setCoords(),this.canvas.sendObjectToBack(this.originalImage),this.currentScale=1,this.currentRotation=0,this.baseImageScale=a,this.lastSnapshot=this.captureSnapshotInternal(),this.canvas.renderAll()}buildTransformContext(){return{canvas:this.canvas,options:this.options,guard:this.operationGuard,getOriginalImage:()=>this.originalImage,getCurrentScale:()=>this.currentScale,setCurrentScale:e=>{this.currentScale=e},getCurrentRotation:()=>this.currentRotation,setCurrentRotation:e=>{this.currentRotation=e},getBaseImageScale:()=>this.baseImageScale,saveCanvasState:()=>{this.saveStateInternal(this.withAnimationQueueBypass())},setSuppressSaveState:e=>{this.shouldSuppressSaveState=e},afterTransformSnap:()=>{!this.isDisposed&&this.canvas&&this.originalImage&&((this.options.expandCanvasToImage||this.options.coverImageToCanvas||this.options.fitImageToCanvas)&&this.updateCanvasSizeToImageBounds(),this.alignObjectBoundingBoxToCanvasTopLeft(this.originalImage),this.canvas.getObjects().filter(S).forEach(e=>this.syncMaskLabel(e)))}}}scaleImage(e){if(this.isDisposed||!this.transformController)return Promise.resolve();if(!Number.isFinite(e))return Promise.resolve();try{this.assertCanQueueAnimation("scaleImage")}catch(e){return Promise.reject(e)}const t=this.transformController,i=this.buildCallbackContext("scaleImage",!1),a=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await t.scaleImage(e),this.isDisposed||this.emitImageChanged(i)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(i),a.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(i)})}rotateImage(e){if(this.isDisposed||!this.transformController)return Promise.resolve();if(!Number.isFinite(e))return Promise.resolve();try{this.assertCanQueueAnimation("rotateImage")}catch(e){return Promise.reject(e)}const t=this.transformController,i=this.buildCallbackContext("rotateImage",!1),a=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await t.rotateImage(e),this.isDisposed||this.emitImageChanged(i)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(i),a.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(i)})}resetImageTransform(){if(this.isDisposed||!this.transformController)return Promise.resolve();try{this.assertCanQueueAnimation("resetImageTransform")}catch(e){return Promise.reject(e)}const e=this.transformController,t=this.buildCallbackContext("resetImageTransform",!1),i=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await e.resetImageTransform(),this.isDisposed||this.emitImageChanged(t)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(t),i.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(t)})}refreshUiAfterQueuedAnimation(){!this.isDisposed&&this.canvas&&(this.updateInputs(),this.updateUi())}async loadFromState(e){return this.loadFromStateInternal(e)}async loadFromStateInternal(e,t){var i;if(!e||!this.canvas)return;if(this.isDisposed)return;if(!this.canRunIdleOperation("loadFromState",t))return;const n=this.activeStateRestoreOperation,o=this.buildCallbackContext(null!=n?n:"loadFromState","undo"===n||"redo"===n),r=this.originalImage,s=this.getMaskCollectionSignature();try{const t=await L({canvas:this.canvas,jsonString:e,setCanvasSize:(e,t)=>this.setCanvasSizePx(e,t)});if(this.isDisposed||!this.canvas)return;this.hideAllMaskLabels(),this.originalImage=t.originalImage,this.originalImage&&(this.originalImage.set({originX:"left",originY:"top",selectable:!1,evented:!1,hasControls:!1,hoverCursor:"default"}),this.canvas.sendObjectToBack(this.originalImage)),this.maskCounter=t.maxMaskId;const a=t.editorState;a&&(this.currentScale=a.currentScale,this.currentRotation=a.currentRotation,this.baseImageScale=a.baseImageScale),this.originalImage?this.currentImageMimeType=a&&"currentImageMimeType"in a?null!==(i=a.currentImageMimeType)&&void 0!==i?i:null:this.inferCurrentImageMimeType():this.currentImageMimeType=null,this.isImageLoadedToCanvas=!!this.originalImage,this.originalImage&&(this.options.expandCanvasToImage||this.options.coverImageToCanvas||this.options.fitImageToCanvas)&&this.shouldNormalizeCanvasSizeAfterStateRestore()&&(this.updateCanvasSizeToImageBounds(),this.alignObjectBoundingBoxToCanvasTopLeft(this.originalImage));const n=t.objects.filter(S);this.lastMask=n.reduce((e,t)=>!e||t.maskId>e.maskId?t:e,null),n.forEach(e=>{Q(e),q(e)}),this.lastSnapshot=this.captureSnapshotInternal(),this.canvas.renderAll(),this.updateInputs(),this.updateMaskList(),this.updateUi(),r&&r!==this.originalImage&&this.emitOptionCallback("onImageCleared",[r,o]),s!==this.getMaskCollectionSignature()&&this.emitMasksChanged(o),this.emitImageChanged(o);const l=null==a?void 0:a.activeMaskId;if("number"==typeof l){const e=n.find(e=>e.maskId===l);e&&this.withSelectionChangeContext(o,()=>{this.canvas.setActiveObject(e),this.handleSelectionChanged([e])})}}catch(e){throw a(this.options,e,"Failed to restore canvas state."),e}}saveState(){this.saveStateInternal()}saveStateInternal(e){var t,a;if(!this.canvas||this.shouldSuppressSaveState)return;if(!this.canRunIdleOperation("saveState",e))return;const n=this.canvas.getActiveObject(),o=this.getActiveMaskForSnapshot();this.hideAllMaskLabels();try{const e=E({canvas:this.canvas,activeMaskId:null!==(t=null==o?void 0:o.maskId)&&void 0!==t?t:null,currentScale:this.currentScale,currentRotation:this.currentRotation,baseImageScale:this.baseImageScale,currentImageMimeType:this.currentImageMimeType}),i=null!==(a=this.lastSnapshot)&&void 0!==a?a:e;if(e===i)return;let n=!1;const r=new j(async()=>{n&&await this.loadFromStateInternal(e,this.withAnimationQueueBypass()),n=!0},async()=>{await this.loadFromStateInternal(i,this.withAnimationQueueBypass())});this.historyManager.execute(r),this.lastSnapshot=e}catch(e){i(this.options,e,"Failed to capture canvas snapshot.")}finally{this.restoreActiveMaskAfterSnapshot(n,o),this.updateUi()}}restoreActiveMaskAfterSnapshot(e,t){if(!this.canvas)return;const i=e&&S(e)?e:t;i&&this.canvas.getObjects().includes(i)&&(this.canvas.setActiveObject(i),this.showLabelForMask(i),this.updateMaskListSelection(i))}undo(){if(this.isDisposed)return Promise.resolve();if(!this.canRunIdleOperation("undo"))return Promise.resolve();const e=this.buildCallbackContext("undo",!0),t=this.animQueue.add(async()=>{if(!this.isDisposed){this.activeStateRestoreOperation="undo";try{await this.historyManager.undo()}finally{this.activeStateRestoreOperation=null}}});return this.emitBusyChangeIfChanged(e),t.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(e)})}redo(){if(this.isDisposed)return Promise.resolve();if(!this.canRunIdleOperation("redo"))return Promise.resolve();const e=this.buildCallbackContext("redo",!0),t=this.animQueue.add(async()=>{if(!this.isDisposed){this.activeStateRestoreOperation="redo";try{await this.historyManager.redo()}finally{this.activeStateRestoreOperation=null}}});return this.emitBusyChangeIfChanged(e),t.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(e)})}createMask(e={}){if(!this.canvas)return null;if(!this.canRunIdleOperation("createMask"))return null;const t=this.buildCallbackContext("createMask",!1),i=this.buildCreateMaskContext(),a=this.withSelectionChangeContext(t,()=>rt(i,e));return a&&(this.emitMasksChanged(t),this.emitImageChanged(t)),a}removeSelectedMask(){if(!this.canvas)return;if(!this.canRunIdleOperation("removeSelectedMask"))return;const e=this.getMasks().length,t=this.buildCallbackContext("removeSelectedMask",!1),i=this.buildRemoveMaskContext();this.withSelectionChangeContext(t,()=>function(e){const t=e.canvas.getActiveObject();t&&S(t)&&(e.removeLabelForMask(t),G(t),e.canvas.remove(t),e.canvas.discardActiveObject(),e.updateMaskList(),e.canvas.renderAll(),e.saveCanvasState())}(i)),this.updateUi(),this.getMasks().length!==e&&(this.emitMasksChanged(t),this.emitImageChanged(t))}removeAllMasks(e={}){if(!this.canvas)return;if(!this.canRunIdleOperation("removeAllMasks",e))return;const t=this.getMasks().length,i=this.buildCallbackContext("removeAllMasks",!1),a=this.buildRemoveMaskContext();this.withSelectionChangeContext(i,()=>st(a,e)),this.updateUi(),this.getMasks().length!==t&&(this.emitMasksChanged(i),this.emitImageChanged(i))}buildCreateMaskContext(){return{fabric:this.fabricModule,canvas:this.canvas,options:this.options,getLastMask:()=>this.lastMask,setLastMask:e=>{this.lastMask=e},getMaskCounter:()=>this.maskCounter,setMaskCounter:e=>{this.maskCounter=e},updateMaskList:()=>{this.updateMaskList()},saveCanvasState:()=>{this.saveState()},expandCanvasIfNeeded:(e,t)=>{this.setCanvasSizePx(e,t)}}}buildRemoveMaskContext(){return{canvas:this.canvas,removeLabelForMask:e=>{this.removeLabelForMask(e)},updateMaskList:()=>{this.updateMaskList()},saveCanvasState:()=>{this.saveState()},setLastMask:e=>{this.lastMask=e}}}buildMaskLabelContext(){return this.canvas?{fabric:this.fabricModule,canvas:this.canvas,options:this.options}:null}removeLabelForMask(e){const t=this.buildMaskLabelContext();t&&lt(t,e)}createLabelForMask(e){const t=this.buildMaskLabelContext();t&&ct(t,e)}hideAllMaskLabels(){const e=this.buildMaskLabelContext();e&&function(e){const{canvas:t}=e;if(!t)return;const i=t.getObjects();i.filter(e=>e.maskLabel).forEach(e=>{try{t.remove(e)}catch{}}),i.filter(S).forEach(e=>{try{delete e.labelObject}catch{}})}(e)}syncMaskLabel(e){const t=this.buildMaskLabelContext();t&&ut(t,e)}showLabelForMask(e){const t=this.buildMaskLabelContext();t&&function(e,t){e.options.maskLabelOnSelect&&(t.labelObject||ct(e,t),t.labelObject&&(t.labelObject.visible=!0,ut(e,t)))}(t,e)}handleSelectionChanged(e){var t,i,a;if(!this.canvas)return;const n=null!==(t=e.find(S))&&void 0!==t?t:null;this.canvas.getObjects().filter(S).forEach(e=>{e!==n?(e.labelObject&&this.removeLabelForMask(e),Q(e)):e.set({stroke:"#ff0000",strokeWidth:1})}),n&&this.showLabelForMask(n),this.updateMaskListSelection(n),this.canvas.requestRenderAll(),this.updateUi();const o=null!==(i=this.nextSelectionChangeContext)&&void 0!==i?i:this.buildCallbackContext(null!==(a=this.activeStateRestoreOperation)&&void 0!==a?a:"createMask","undo"===this.activeStateRestoreOperation||"redo"===this.activeStateRestoreOperation);this.emitOptionCallback("onSelectionChange",[this.buildSelection(e),o])}buildMaskListContext(){return{canvas:this.canvas,getListElementId:()=>this.elements.maskList,onMaskSelected:e=>this.handleSelectionChanged([e])}}updateMaskList(){!function(e){const t=e.getListElementId();if(!t)return;const i=document.getElementById(t);if(!i||!e.canvas)return;i.innerHTML="";const a=e.canvas;a.getObjects().filter(S).forEach(t=>{const n=document.createElement("li");n.className="list-group-item mask-item",n.textContent=t.maskName,n.dataset.maskId=String(t.maskId),n.onclick=()=>{const t=Number(n.dataset.maskId);if(!Number.isFinite(t))return;const i=a.getObjects().find(e=>S(e)&&e.maskId===t);i&&(a.setActiveObject(i),e.onMaskSelected(i))},i.appendChild(n)})}(this.buildMaskListContext())}updateMaskListSelection(e){!function(e,t){const i=e.getListElementId();if(!i)return;const a=document.getElementById(i);if(!a)return;const n=t?String(t.maskId):null;a.querySelectorAll(".mask-item").forEach(e=>{const t=null!==n&&e.dataset.maskId===n;e.classList.toggle("active",t)})}(this.buildMaskListContext(),e)}async mergeMasks(){if(!this.canvas)return;if(!this.canRunIdleOperation("mergeMasks"))return;if(!this.canvas.getObjects().some(S))return;const e=this.buildCallbackContext("mergeMasks",!1),t=this.operationGuard.beginBusyOperation("mergeMasks");this.emitBusyChangeIfChanged(e),this.updateUi();try{const i=this.buildMergeMasksContext(t);await async function(e){if(!e.isImageLoaded())return;if(0===e.canvas.getObjects().filter(e=>"maskId"in e&&"number"==typeof e.maskId).length)return;const t=e.saveState();e.canvas.discardActiveObject(),e.canvas.renderAll();const i=e.containerElement?e.containerElement.scrollTop:null,a=e.containerElement?e.containerElement.scrollLeft:null;try{const n=await Ee(e,{exportArea:"image",mergeMask:!0,multiplier:e.options.exportMultiplier,fileType:"png"});if(!n)throw new D("mergeMasks: exportImageBase64 returned an empty data URL.");e.removeAllMasksNoHistory(),await e.loadImage(n,{preserveScroll:!0});const o=e.saveState();if(e.containerElement)try{null!==i&&(e.containerElement.scrollTop=i),null!==a&&(e.containerElement.scrollLeft=a)}catch(e){console.warn("[ImageEditor] mergeMasks: scroll restore failed",e)}t&&o&&t!==o&&e.historyManager.push(new j(()=>e.loadFromState(o),()=>e.loadFromState(t)))}catch(i){try{await e.loadFromState(t)}catch(e){console.warn("[ImageEditor] mergeMasks: rollback failed",e)}if(i instanceof D)throw i;const a=i instanceof Error?`mergeMasks failed: ${i.message}`:"mergeMasks failed";throw new D(a,i)}}(i),this.updateInputs(),this.updateMaskList(),this.emitMasksChanged(e),this.emitImageChanged(e)}finally{this.operationGuard.endBusyOperation(t),this.emitBusyChangeIfChanged(e),this.updateUi()}}downloadImage(e){if(!this.canvas)return;if(!this.canRunIdleOperation("downloadImage"))return;const t=this.buildCallbackContext("downloadImage",!1),i=this.operationGuard.beginBusyOperation("downloadImage");this.emitBusyChangeIfChanged(t);const n=this.buildExportServiceContext();try{!function(e,t){if(!e.isImageLoaded())return void Oe("downloadImage");const i=null!=t?t:e.options.defaultDownloadFileName;Ee(e,{exportArea:e.options.exportAreaByDefault,mergeMask:e.options.mergeMaskByDefault,multiplier:e.options.exportMultiplier}).then(e=>{if(!e)return;const t=document.createElement("a");t.download=i,t.href=e,document.body.appendChild(t);try{t.click()}finally{document.body.removeChild(t)}}).catch(t=>{a(e.options,t,"downloadImage failed."),console.error("[ImageEditor] downloadImage failed",t)})}(n,e)}finally{this.operationGuard.endBusyOperation(i),this.emitBusyChangeIfChanged(t)}}async exportImageBase64(e){if(!this.canvas)return"";if(!this.canRunIdleOperation("exportImageBase64",e))return"";const t=this.buildCallbackContext("exportImageBase64",!1),i=this.operationGuard.beginBusyOperation("exportImageBase64");this.emitBusyChangeIfChanged(t);const a=this.buildExportServiceContext();try{return await Ee(a,e)}finally{this.operationGuard.endBusyOperation(i),this.emitBusyChangeIfChanged(t)}}async exportImageFile(e){this.assertIdleForOperation("exportImageFile",e);const t=this.buildCallbackContext("exportImageFile",!1),i=this.operationGuard.beginBusyOperation("exportImageFile");this.emitBusyChangeIfChanged(t);const a=this.buildExportServiceContext();try{return await Le(a,e)}finally{this.operationGuard.endBusyOperation(i),this.emitBusyChangeIfChanged(t)}}buildExportServiceContext(){return{fabric:this.fabricModule,canvas:this.canvas,options:this.options,isImageLoaded:()=>this.isImageLoaded(),getOriginalImage:()=>this.originalImage}}buildMergeMasksContext(e){return{...this.buildExportServiceContext(),historyManager:this.historyManager,containerElement:this.containerElement,loadImage:async(t,i)=>{const a=this.captureImageDisplayGeometry();await this.loadImage(t,this.withInternalOperationOptions(e,i)),this.restoreMergedImageDisplayGeometry(a)},saveState:()=>this.captureSnapshotInternal(),loadFromState:t=>this.loadFromStateInternal(t,this.withInternalOperationOptions(e,this.withAnimationQueueBypass())),removeAllMasksNoHistory:()=>{st(this.buildRemoveMaskContext(),{saveHistory:!1})}}}captureSnapshotInternal(){var e;if(!this.canvas)return"";const t=this.getActiveMaskForSnapshot();return this.hideAllMaskLabels(),E({canvas:this.canvas,activeMaskId:null!==(e=null==t?void 0:t.maskId)&&void 0!==e?e:null,currentScale:this.currentScale,currentRotation:this.currentRotation,baseImageScale:this.baseImageScale,currentImageMimeType:this.currentImageMimeType})}getActiveMaskForSnapshot(){var e;if(!this.canvas)return null;const t=this.canvas.getActiveObject();return t&&S(t)?t:null!==(e=this.canvas.getObjects().find(e=>S(e)&&!!e.labelObject))&&void 0!==e?e:null}enterCropMode(){if(!this.canvas||!this.originalImage)return;if(this.cropSession)return;if(!this.isImageLoaded())return;if(!this.canRunIdleOperation("enterCropMode"))return;!function(e){const{canvas:t,options:i}=e;if(e.getCropSession())return;const a=e.getOriginalImage();if(!a)return;if(!e.isImageLoaded())return;t.discardActiveObject();const n=e.saveState(),o=!!t.selection;t.selection=!1,a.setCoords();const r=a.getBoundingRect(),s=Number.isFinite(Number(i.crop.padding))?Number(i.crop.padding):10,l=Math.max(0,Math.floor(r.left)),c=Math.max(0,Math.floor(r.top)),u=Math.max(1,Math.floor(r.width)),h=Math.max(1,Math.floor(r.height)),d=Math.min(l+u-1,Math.max(l,Math.floor(r.left+s))),m=Math.min(c+h-1,Math.max(c,Math.floor(r.top+s))),g=Math.max(1,Number(i.crop.minWidth)||1),p=Math.max(1,Number(i.crop.minHeight)||1),f=Math.min(g,u),b=Math.min(p,h),v=!!i.crop.allowRotationOfCropRect,y=new e.fabric.Rect({left:d,top:m,width:f,height:b,originX:"left",originY:"top",fill:"rgba(0,0,0,0.12)",stroke:"#00aaff",strokeDashArray:se,strokeWidth:1,strokeUniform:!0,selectable:!0,lockRotation:!v,cornerSize:8,objectCaching:!1,lockScalingFlip:!0});v||y.setControlVisible("mtr",!1),t.add(y),y.isCropRect=!0,t.bringObjectToFront(y),t.setActiveObject(y);const I=!!i.crop.hideMasksDuringCrop,C=[];I&&t.getObjects().forEach(e=>{e!==y&&S(e)&&C.push(Y(e))});const k=[];if(t.getObjects().forEach(e=>{var t,i;if(e!==y){k.push({object:e,evented:null===(t=e.evented)||void 0===t||t,selectable:null===(i=e.selectable)||void 0===i||i});try{e.set({evented:!1,selectable:!1})}catch{}}}),I)for(const e of C)_(e.object);const M=()=>{try{const e=Math.max(1,Number(y.width)||1),i=Math.max(1,Number(y.height)||1),a=Math.min(u/e,Math.max(f/e,Number(y.scaleX)||1)),n=Math.min(h/i,Math.max(b/i,Number(y.scaleY)||1)),o=e*a,r=i*n,s=Math.max(l,l+u-o),d=Math.max(c,c+h-r),m=Math.min(s,Math.max(l,Number(y.left)||l)),g=Math.min(d,Math.max(c,Number(y.top)||c));y.set({left:m,top:g,scaleX:a,scaleY:n}),y.setCoords(),t.requestRenderAll()}catch{}};y.on("modified",M),y.on("moving",M),y.on("scaling",M);const w={beforeJson:n,prevSelection:o,prevEvented:k,maskBackups:C,cropRect:y,handlers:[{target:y,handlers:[{eventName:"modified",callback:M},{eventName:"moving",callback:M},{eventName:"scaling",callback:M}]}]};e.setCropSession(w),t.renderAll()}(this.buildCropControllerContext()),this.updateUi();const e=this.buildCallbackContext("enterCropMode",!1);this.emitBusyChangeIfChanged(e),this.emitImageChanged(e)}cancelCrop(){if(!this.canvas||!this.cropSession)return;if(!this.canRunIdleOperation("cancelCrop"))return;pe(this.buildCropControllerContext()),this.cropSession=null,this.updateUi(),this.canvas.requestRenderAll();const e=this.buildCallbackContext("cancelCrop",!1);this.emitBusyChangeIfChanged(e),this.emitImageChanged(e)}async applyCrop(){if(!this.canvas||!this.cropSession)return;if(!this.canRunIdleOperation("applyCrop"))return;const e=this.buildCallbackContext("applyCrop",!1),t=this.getMasks().length>0,i=this.operationGuard.beginBusyOperation("applyCrop");this.emitBusyChangeIfChanged(e),this.updateUi();try{const a=this.buildCropControllerContext(i);await fe(a),this.updateInputs(),this.updateMaskList(),(t||this.getMasks().length>0)&&this.emitMasksChanged(e),this.emitImageChanged(e)}finally{this.operationGuard.endBusyOperation(i),this.emitBusyChangeIfChanged(e),this.updateUi()}}buildCropControllerContext(e){return{fabric:this.fabricModule,canvas:this.canvas,options:this.options,historyManager:this.historyManager,isImageLoaded:()=>this.isImageLoaded(),getOriginalImage:()=>this.originalImage,getCurrentImageMimeType:()=>this.currentImageMimeType,getCropSession:()=>this.cropSession,setCropSession:e=>{this.cropSession=e},saveState:()=>this.captureSnapshotInternal(),loadFromState:t=>this.loadFromStateInternal(t,this.withInternalOperationOptions(e,this.withAnimationQueueBypass())),loadImage:(t,i)=>this.loadImage(t,this.withInternalOperationOptions(e,i)),getMaskCounter:()=>this.maskCounter,setMaskCounter:e=>{this.maskCounter=e},updateMaskList:()=>{this.updateMaskList()}}}updateInputs(){const e=this.elements.scalePercentageInput;if(!e)return;const t=document.getElementById(e);t&&(t.value=String(Math.round(100*this.currentScale)))}updateUi(){if(!this.canvas)return;const e=!!this.originalImage,t=(e?this.canvas.getObjects().filter(S):[]).length>0,i=this.canvas.getActiveObject(),a=!(!i||!S(i)),n=1===this.currentScale&&0===this.currentRotation,o=this.historyManager.canUndo(),r=this.historyManager.canRedo(),s=null!==this.cropSession,l=this.operationGuard.isBusy()||this.animQueue.isBusy();s?yt.forEach(e=>{this.setControlEnabled(e,!l&&It.includes(e))}):(this.setControlEnabled("scalePercentageInput",e&&!l),this.setControlEnabled("rotateLeftDegreesInput",e&&!l),this.setControlEnabled("rotateRightDegreesInput",e&&!l),this.setControlEnabled("zoomInButton",e&&!l&&this.currentScale<this.options.maxScale),this.setControlEnabled("zoomOutButton",e&&!l&&this.currentScale>this.options.minScale),this.setControlEnabled("rotateLeftButton",e&&!l),this.setControlEnabled("rotateRightButton",e&&!l),this.setControlEnabled("createMaskButton",e&&!l),this.setControlEnabled("removeSelectedMaskButton",a&&!l),this.setControlEnabled("removeAllMasksButton",t&&!l),this.setControlEnabled("mergeMasksButton",e&&t&&!l),this.setControlEnabled("downloadImageButton",e&&!l),this.setControlEnabled("resetImageTransformButton",e&&!n&&!l),this.setControlEnabled("undoButton",e&&!l&&o),this.setControlEnabled("redoButton",e&&!l&&r),this.setControlEnabled("enterCropModeButton",e&&!l),this.setControlEnabled("imageInput",!l),this.setControlEnabled("applyCropButton",!1),this.setControlEnabled("cancelCropButton",!1))}setControlEnabled(e,t){var i;const a=this.elements[e];if(!a)return;const n=document.getElementById(a);if(n)if(this.recordElementOriginalState(e,n),"disabled"in n)n.disabled=!t;else if(t){const t=this.elementOriginalAriaDisabledMap.get(e);null==t?n.removeAttribute("aria-disabled"):n.setAttribute("aria-disabled",t),n.style.pointerEvents=null!==(i=this.elementOriginalPointerEventsMap.get(e))&&void 0!==i?i:""}else n.setAttribute("aria-disabled","true"),n.style.pointerEvents="none"}recordElementOriginalState(e,t){this.elementOriginalAriaDisabledMap.has(e)||this.elementOriginalAriaDisabledMap.set(e,t.getAttribute("aria-disabled")),this.elementOriginalPointerEventsMap.has(e)||this.elementOriginalPointerEventsMap.set(e,t.style.pointerEvents||""),"disabled"in t&&!this.elementOriginalDisabledMap.has(e)&&this.elementOriginalDisabledMap.set(e,!!t.disabled)}restoreElementOriginalStates(){var e,t;for(const i of Object.keys(this.elements)){const a=this.elements[i];if(!a)continue;const n=document.getElementById(a);if(n){if("disabled"in n&&this.elementOriginalDisabledMap.has(i)&&(n.disabled=null!==(e=this.elementOriginalDisabledMap.get(i))&&void 0!==e&&e),this.elementOriginalAriaDisabledMap.has(i)){const e=this.elementOriginalAriaDisabledMap.get(i);null==e?n.removeAttribute("aria-disabled"):n.setAttribute("aria-disabled",e)}this.elementOriginalPointerEventsMap.has(i)&&(n.style.pointerEvents=null!==(t=this.elementOriginalPointerEventsMap.get(i))&&void 0!==t?t:"")}}this.elementOriginalDisabledMap.clear(),this.elementOriginalAriaDisabledMap.clear(),this.elementOriginalPointerEventsMap.clear()}updatePlaceholderStatus(){dt(this.placeholderElement,this.containerElement,!!this.options.showPlaceholder&&!this.originalImage)}dispose(){var e;if(this.isDisposed)return;const t=this.buildCallbackContext("dispose",!1),i=this.originalImage;if(this.isDisposed=!0,this.operationGuard.markDisposed(),this.animQueue.clear(),null===(e=this.domBindings)||void 0===e||e.removeAll(),this.restoreElementOriginalStates(),this.cropSession&&this.canvas){try{pe(this.buildCropControllerContext())}catch{}this.cropSession=null}if(this.canvas){try{Promise.resolve(this.canvas.dispose()).catch(()=>{})}catch{}this.canvas=null,this.canvasElement=null,this.isImageLoadedToCanvas=!1}this.originalImage=null,this.currentImageMimeType=null,this.lastMask=null,this.maskCounter=0,this.currentScale=1,this.currentRotation=0,this.baseImageScale=1,this.lastSnapshot=null,this.transformController=null,this.viewportCache.clear(),i&&this.emitOptionCallback("onImageCleared",[i,t]),this.emitImageChanged(t),this.emitBusyChangeIfChanged(t),this.emitOptionCallback("onEditorDisposed",[t])}}e.ImageEditor=kt,e.default=kt,e.isMaskObject=S,Object.defineProperty(e,"__esModule",{value:!0})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).ImageEditor={})}(this,function(t){"use strict";class e{constructor(){Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"running",{enumerable:!0,configurable:!0,writable:!0,value:!1})}add(t){return new Promise((e,n)=>{this.queue.push({run:t,resolve:e,reject:n}),this.running||this.drainQueue()})}clear(t){const e=this.queue;if(this.queue=[],void 0!==t)for(const n of e)n.reject(t);else for(const t of e)t.resolve()}isRunning(){return this.running}isBusy(){return this.running||this.queue.length>0}waitForIdle(){return this.running||0!==this.queue.length?this.add(()=>Promise.resolve()).then(()=>{},()=>{}):Promise.resolve()}async drainQueue(){if(!this.running){this.running=!0;try{for(;this.queue.length>0;){const t=this.queue.shift();try{await t.run(),t.resolve()}catch(e){t.reject(e)}}}finally{this.running=!1,this.queue.length>0&&this.drainQueue()}}}}function n(t,e,n){const i=t.onWarning;if("function"==typeof i)try{i(e,n)}catch(t){console.warn("[ImageEditor] onWarning callback threw",t)}}function i(t,e,n){const i=t.onError;if("function"==typeof i)try{i(e,n)}catch(t){console.error("[ImageEditor] onError callback threw",t)}}const o=Object.freeze({jpeg:"jpeg",jpg:"jpeg","image/jpeg":"jpeg",png:"png","image/png":"png",webp:"webp","image/webp":"webp"}),a=Object.freeze({jpeg:"image/jpeg",png:"image/png",webp:"image/webp"});function r(t){var e;if(!t)return null;const n=String(t).toLowerCase();return Object.prototype.hasOwnProperty.call(o,n)&&null!==(e=o[n])&&void 0!==e?e:null}function s(t){return a[t]}function l(t,e){const n=Number(t);return Number.isFinite(n)?Math.max(0,Math.min(1,n)):e}function c(t,e){var n;const i=null!=t?t:{},o=i.fileType,a=i.format,c=function(t){var e;return null!==(e=r(t))&&void 0!==e?e:"jpeg"}(o||a),u=s(c);if("png"===c)return{format:c,mimeType:u,quality:void 0};return{format:c,mimeType:u,quality:l(null!==(n=i.quality)&&void 0!==n?n:e,e)}}const u=Object.freeze({}),d="expand",h={canvasWidth:800,canvasHeight:600,backgroundColor:"transparent",animationDuration:300,minScale:.1,maxScale:5,scaleStep:.05,rotationStep:90,defaultLayoutMode:d,layoutMode:d,downsampleOnLoad:!0,downsampleMaxWidth:4e3,downsampleMaxHeight:3e3,downsampleQuality:.92,preserveSourceFormat:!0,downsampleMimeType:null,imageLoadTimeoutMs:3e4,maxHistorySize:50,exportMultiplier:1,maxExportPixels:5e7,exportAreaByDefault:"image",mergeMasksByDefault:!0,mergeAnnotationsByDefault:!0,defaultMaskWidth:50,defaultMaskHeight:80,defaultMaskConfig:u,maskRotatable:!1,maskLabelOnSelect:!0,maskLabelOffset:3,maskName:"mask",textAnnotationName:"text",drawAnnotationName:"draw",groupSelection:!1,showPlaceholder:!0,initialImageBase64:null,defaultDownloadFileName:"edited_image.jpg",onImageLoadStart:null,onImageLoaded:null,onImageCleared:null,onImageChanged:null,onBusyChange:null,onEditorDisposed:null,onMasksChanged:null,onAnnotationsChanged:null,onSelectionChange:null,onError:null,onWarning:null},g={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"},m={getText:t=>t.maskName},f=100,p=100,b=10,v=!0,y=!1,C=!1,S="source",I=Object.freeze({brushSize:48,blockSize:8,previewStroke:"#333",previewStrokeWidth:1,previewStrokeDashArray:Object.freeze([4,4]),previewFill:"rgba(0,0,0,0)",outputFileType:"source",outputQuality:void 0}),M=Object.freeze({text:"Text",left:void 0,top:void 0,width:200,fontSize:32,fontFamily:"sans-serif",fontWeight:"normal",fill:"#ff0000",backgroundColor:"rgba(255,255,255,0)",textAlign:"left",angle:0,selectable:!0,evented:!0,editable:!0,enterEditing:!0,annotationHidden:!1,annotationLocked:!1,styles:Object.freeze({})}),w=Object.freeze({brushSize:8,color:"#ff0000",opacity:1,lineCap:"round",lineJoin:"round",selectable:!0,evented:!0,annotationHidden:!1,annotationLocked:!1}),x=new Set(["canvasWidth","canvasHeight","backgroundColor","animationDuration","minScale","maxScale","scaleStep","rotationStep","defaultLayoutMode","downsampleOnLoad","downsampleMaxWidth","downsampleMaxHeight","downsampleQuality","preserveSourceFormat","downsampleMimeType","imageLoadTimeoutMs","maxHistorySize","exportMultiplier","maxExportPixels","exportAreaByDefault","mergeMasksByDefault","mergeAnnotationsByDefault","defaultMaskWidth","defaultMaskHeight","defaultMaskConfig","maskRotatable","maskLabelOnSelect","maskLabelOffset","maskName","textAnnotationName","drawAnnotationName","groupSelection","showPlaceholder","initialImageBase64","defaultDownloadFileName","onImageLoadStart","onImageLoaded","onImageCleared","onImageChanged","onBusyChange","onEditorDisposed","onMasksChanged","onAnnotationsChanged","onSelectionChange","onError","onWarning","label","crop","defaultMosaicConfig","defaultTextConfig","defaultDrawConfig"]);function k(t){return"function"==typeof t?t:null}function O(t){return"fit"===t||"cover"===t||"expand"===t}function A(t){return O(t)?t:d}function E(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function j(t){return Array.isArray(t)?[...t]:t}function T(t){if(!E(t))return u;const e={};for(const[n,i]of Object.entries(t))"onCreate"!==n&&"fabricGenerator"!==n&&"styles"!==n&&(e[n]=j(i));const n=t.styles;if(E(n)){const t={};for(const[e,i]of Object.entries(n))t[e]=j(i);Object.freeze(t),e.styles=t}return Object.freeze(e),e}function B(t,e){const n=Number(t);return!Number.isFinite(n)||n<=0?e:Math.max(1,Math.floor(n))}function L(t,e){const n=Number(t);return!Number.isFinite(n)||n<=0?e:n}function D(t,e){const n=Number(t);return!Number.isFinite(n)||n<0?e:n}function F(t,e){const n=Number(t);return Number.isFinite(n)?n:e}function N(t){if(null==t)return h.downsampleQuality;const e=Number(t);return Number.isFinite(e)?Math.max(0,Math.min(1,e)):h.downsampleQuality}function P(t){const e=Number(t);return!Number.isFinite(e)||e<=0?h.maxExportPixels:Math.max(1,Math.floor(e))}function z(t){return"canvas"===t||"image"===t?t:h.exportAreaByDefault}function R(t){if(null==t)return;const e=Number(t);return Number.isFinite(e)?Math.max(0,Math.min(1,e)):void 0}function W(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function H(t){return"number"==typeof t&&Number.isFinite(t)}function U(t){return{...t,previewStrokeDashArray:t.previewStrokeDashArray?[...t.previewStrokeDashArray]:null}}function $(t,e,n=t){const i=E(e)?e:{},o=U(t);return W(i,"brushSize")&&(o.brushSize=function(t,e){return H(t)&&t>0?t:e}(i.brushSize,n.brushSize)),W(i,"blockSize")&&(o.blockSize=function(t,e){return H(t)&&t>0?Math.max(1,Math.floor(t)):e}(i.blockSize,n.blockSize)),W(i,"previewStroke")&&(o.previewStroke="string"==typeof i.previewStroke?i.previewStroke:n.previewStroke),W(i,"previewStrokeWidth")&&(o.previewStrokeWidth=function(t,e){return H(t)&&t>=0?t:e}(i.previewStrokeWidth,n.previewStrokeWidth)),W(i,"previewStrokeDashArray")&&(o.previewStrokeDashArray=function(t,e){return null===t?null:Array.isArray(t)&&t.every(t=>"number"==typeof t&&Number.isFinite(t)&&t>=0)?[...t]:e?[...e]:null}(i.previewStrokeDashArray,n.previewStrokeDashArray)),W(i,"previewFill")&&(o.previewFill="string"==typeof i.previewFill?i.previewFill:n.previewFill),W(i,"outputFileType")&&(o.outputFileType=function(t,e){var n;return"source"===t?"source":"string"!=typeof t?e:null!==(n=r(t))&&void 0!==n?n:e}(i.outputFileType,n.outputFileType)),W(i,"outputQuality")&&(o.outputQuality=function(t,e){if(null!=t)return H(t)?Math.max(0,Math.min(1,t)):e}(i.outputQuality,n.outputQuality)),o}function Q(t,e){const n=t.previewStrokeDashArray,i=e.previewStrokeDashArray,o=n===i||Array.isArray(n)&&Array.isArray(i)&&n.length===i.length&&n.every((t,e)=>t===i[e]);return t.brushSize===e.brushSize&&t.blockSize===e.blockSize&&t.previewStroke===e.previewStroke&&t.previewStrokeWidth===e.previewStrokeWidth&&o&&t.previewFill===e.previewFill&&t.outputFileType===e.outputFileType&&t.outputQuality===e.outputQuality}function q(t){return{...t,styles:{...t.styles}}}function Y(t){return{...t}}function X(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>0?t:e}function G(t,e){return"boolean"==typeof t?t:e}function K(t,e){return"string"==typeof t?t:e}function V(t){return"number"==typeof t&&Number.isFinite(t)?t:void 0}function _(t,e,n=t){const i=E(e)?e:{},o=q(t);var a;return W(i,"text")&&(o.text=K(i.text,n.text)),W(i,"left")&&(o.left=V(i.left)),W(i,"top")&&(o.top=V(i.top)),W(i,"width")&&(o.width=X(i.width,n.width)),W(i,"fontSize")&&(o.fontSize=X(i.fontSize,n.fontSize)),W(i,"fontFamily")&&(o.fontFamily=K(i.fontFamily,n.fontFamily)),W(i,"fontWeight")&&(o.fontWeight="string"==typeof i.fontWeight||"number"==typeof i.fontWeight?i.fontWeight:n.fontWeight),W(i,"fill")&&(o.fill=K(i.fill,n.fill)),W(i,"backgroundColor")&&(o.backgroundColor=K(i.backgroundColor,n.backgroundColor)),W(i,"textAlign")&&(o.textAlign=function(t,e){return"left"===t||"center"===t||"right"===t||"justify"===t?t:e}(i.textAlign,n.textAlign)),W(i,"angle")&&(o.angle=F(i.angle,n.angle)),W(i,"selectable")&&(o.selectable=G(i.selectable,n.selectable)),W(i,"evented")&&(o.evented=G(i.evented,n.evented)),W(i,"editable")&&(o.editable=G(i.editable,n.editable)),W(i,"enterEditing")&&(o.enterEditing=G(i.enterEditing,n.enterEditing)),W(i,"annotationHidden")&&(o.annotationHidden=G(i.annotationHidden,n.annotationHidden)),W(i,"annotationLocked")&&(o.annotationLocked=G(i.annotationLocked,n.annotationLocked)),W(i,"styles")&&(o.styles={...o.styles,...(a=i.styles,E(a)?{...a}:{})}),o}function J(t,e,n=t){const i=E(e)?e:{},o=Y(t);return W(i,"brushSize")&&(o.brushSize=X(i.brushSize,n.brushSize)),W(i,"color")&&(o.color=K(i.color,n.color)),W(i,"opacity")&&(o.opacity=function(t,e){return"number"==typeof t&&Number.isFinite(t)?Math.max(0,Math.min(1,t)):e}(i.opacity,n.opacity)),W(i,"lineCap")&&(o.lineCap=function(t,e){return"butt"===t||"round"===t||"square"===t?t:e}(i.lineCap,n.lineCap)),W(i,"lineJoin")&&(o.lineJoin=function(t,e){return"bevel"===t||"round"===t||"miter"===t?t:e}(i.lineJoin,n.lineJoin)),W(i,"selectable")&&(o.selectable=G(i.selectable,n.selectable)),W(i,"evented")&&(o.evented=G(i.evented,n.evented)),W(i,"annotationHidden")&&(o.annotationHidden=G(i.annotationHidden,n.annotationHidden)),W(i,"annotationLocked")&&(o.annotationLocked=G(i.annotationLocked,n.annotationLocked)),o}function Z(t){var e,n,i,o;const a=null!=t?t:{},r={...h};for(const t of Object.keys(a)){if(!x.has(t))continue;if("label"===t||"crop"===t||"defaultMosaicConfig"===t||"defaultTextConfig"===t||"defaultDrawConfig"===t)continue;if("onImageLoadStart"===t||"onImageLoaded"===t||"onImageCleared"===t||"onImageChanged"===t||"onBusyChange"===t||"onEditorDisposed"===t||"onMasksChanged"===t||"onAnnotationsChanged"===t||"onSelectionChange"===t||"onError"===t||"onWarning"===t)continue;const e=a[t];if(void 0!==e)if("downsampleQuality"!==t)if("maxExportPixels"!==t)if("exportAreaByDefault"!==t){if("defaultLayoutMode"===t){const t=A(e);r.defaultLayoutMode=t,r.layoutMode=t;continue}"canvasWidth"!==t?"canvasHeight"!==t?"animationDuration"!==t?"minScale"!==t?"maxScale"!==t?"scaleStep"!==t?"rotationStep"!==t?"downsampleMaxWidth"!==t?"downsampleMaxHeight"!==t?"imageLoadTimeoutMs"!==t?"exportMultiplier"!==t?"defaultMaskWidth"!==t?"defaultMaskHeight"!==t?"defaultMaskConfig"!==t?"maskLabelOffset"!==t?r[t]=e:r.maskLabelOffset=D(e,h.maskLabelOffset):r.defaultMaskConfig=T(e):r.defaultMaskHeight=L(e,h.defaultMaskHeight):r.defaultMaskWidth=L(e,h.defaultMaskWidth):r.exportMultiplier=L(e,h.exportMultiplier):r.imageLoadTimeoutMs=B(e,h.imageLoadTimeoutMs):r.downsampleMaxHeight=B(e,h.downsampleMaxHeight):r.downsampleMaxWidth=B(e,h.downsampleMaxWidth):r.rotationStep=F(e,h.rotationStep):r.scaleStep=L(e,h.scaleStep):r.maxScale=L(e,h.maxScale):r.minScale=L(e,h.minScale):r.animationDuration=D(e,h.animationDuration):r.canvasHeight=B(e,h.canvasHeight):r.canvasWidth=B(e,h.canvasWidth)}else r.exportAreaByDefault=z(e);else r.maxExportPixels=P(e);else r.downsampleQuality=N(e)}if(r.onImageLoadStart=k(a.onImageLoadStart),r.onImageLoaded=k(a.onImageLoaded),r.onImageCleared=k(a.onImageCleared),r.onImageChanged=k(a.onImageChanged),r.onBusyChange=k(a.onBusyChange),r.onEditorDisposed=k(a.onEditorDisposed),r.onMasksChanged=k(a.onMasksChanged),r.onAnnotationsChanged=k(a.onAnnotationsChanged),r.onSelectionChange=k(a.onSelectionChange),r.onError=k(a.onError),r.onWarning=k(a.onWarning),r.maxHistorySize=function(t){const e=Number(t);return Number.isFinite(e)?Math.max(1,Math.floor(e)):h.maxHistorySize}(r.maxHistorySize),r.maxExportPixels=P(r.maxExportPixels),r.minScale>r.maxScale){const t=r.minScale;r.minScale=r.maxScale,r.maxScale=t}const s=a.label&&"object"==typeof a.label?a.label:{},l={...g,...s.textOptions&&"object"==typeof s.textOptions?s.textOptions:{}},c={getText:"function"==typeof s.getText?s.getText:m.getText,textOptions:l};"function"==typeof s.create&&(c.create=s.create),Object.freeze(c.textOptions),Object.freeze(c);const u=a.crop&&"object"==typeof a.crop?a.crop:{},d={minWidth:L(u.minWidth,f),minHeight:L(u.minHeight,p),padding:D(u.padding,b),hideMasksDuringCrop:null!==(e=u.hideMasksDuringCrop)&&void 0!==e?e:v,preserveMasksAfterCrop:null!==(n=u.preserveMasksAfterCrop)&&void 0!==n?n:y,allowRotationOfCropRect:null!==(i=u.allowRotationOfCropRect)&&void 0!==i?i:C,exportFileType:null!==(o=u.exportFileType)&&void 0!==o?o:S,exportQuality:R(u.exportQuality)};Object.freeze(d);const O=function(t,e){return E(t)?$(e,t):U(e)}(a.defaultMosaicConfig,I);O.previewStrokeDashArray&&Object.freeze(O.previewStrokeDashArray),Object.freeze(O);const j=function(t,e){return E(t)?_(e,t):q(e)}(a.defaultTextConfig,M);Object.freeze(j.styles),Object.freeze(j);const W=function(t,e){return E(t)?J(e,t):Y(e)}(a.defaultDrawConfig,w);return Object.freeze(W),Object.freeze({...r,label:c,crop:d,defaultMosaicConfig:O,defaultTextConfig:j,defaultDrawConfig:W})}class tt{constructor(){Object.defineProperty(this,"isAnimationActive",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isDisposedFlag",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"isLoadingActive",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"currentOperationName",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"currentOperationToken",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"animationAborters",{enumerable:!0,configurable:!0,writable:!0,value:new Set})}isAnimating(){return this.isAnimationActive}isDisposed(){return this.isDisposedFlag}isLoading(){return this.isLoadingActive}activeOperationName(){return this.currentOperationName}isBusy(){return this.isAnimationActive||this.isLoadingActive||null!==this.currentOperationToken}beginAnimation(){this.isAnimationActive=!0}endAnimation(){this.isAnimationActive=!1}markDisposed(){this.isDisposedFlag=!0,this.isAnimationActive=!1,this.isLoadingActive=!1,this.currentOperationName=null,this.currentOperationToken=null;for(const t of this.animationAborters)try{t()}catch{}this.animationAborters.clear()}registerAnimationAborter(t){if(this.isDisposedFlag){try{t()}catch{}return()=>{}}return this.animationAborters.add(t),()=>{this.animationAborters.delete(t)}}beginLoading(){this.isLoadingActive=!0}endLoading(){this.isLoadingActive=!1}beginBusyOperation(t){const e=Symbol(t);return this.currentOperationName=t,this.currentOperationToken=e,e}endBusyOperation(t){t&&t===this.currentOperationToken&&(this.currentOperationName=null,this.currentOperationToken=null)}isOwnOperation(t){return!!t&&t===this.currentOperationToken}async runAnimation(t){this.beginAnimation();try{return await t()}finally{this.endAnimation()}}assertNotAnimating(t){if(this.isAnimationActive)throw new Error(`[ImageEditor] Cannot run "${t}" while an animation is in progress.`)}assertIdleForOperation(t,e){var n;if(this.isDisposedFlag)throw new Error(`[ImageEditor] Cannot run "${t}" after dispose.`);const i=this.isOwnOperation(e);if(this.isAnimationActive)throw new Error(`[ImageEditor] Cannot run "${t}" while an animation is in progress.`);if(this.isLoadingActive&&!i)throw new Error(`[ImageEditor] Cannot run "${t}" while an image is loading.`);if(this.currentOperationToken&&!i)throw new Error(`[ImageEditor] Cannot run "${t}" while ${null!==(n=this.currentOperationName)&&void 0!==n?n:"another operation"} is running.`)}assertCanQueueAnimation(t,e){var n;if(this.isDisposedFlag)throw new Error(`[ImageEditor] Cannot run "${t}" after dispose.`);const i=this.isOwnOperation(e);if(this.isLoadingActive&&!i)throw new Error(`[ImageEditor] Cannot run "${t}" while an image is loading.`);if(this.currentOperationToken&&!i)throw new Error(`[ImageEditor] Cannot run "${t}" while ${null!==(n=this.currentOperationName)&&void 0!==n?n:"another operation"} is running.`)}}function et(t){return!!t&&"object"==typeof t&&"baseImage"===t.editorObjectKind}function nt(t){const e=t;return!!e&&"mask"===e.editorObjectKind&&"number"==typeof e.maskId&&"string"==typeof e.maskUid&&"string"==typeof e.maskName}function it(t){const e=t;return!!e&&"annotation"===e.editorObjectKind&&"number"==typeof e.annotationId&&"string"==typeof e.annotationType&&"string"==typeof e.annotationName}function ot(t){return it(t)&&"text"===t.annotationType}function at(t){return it(t)&&"draw"===t.annotationType}function rt(t){const e=t;return!!e&&"session"===e.editorObjectKind&&"string"==typeof e.sessionObjectType}function st(t){return nt(t)||it(t)}function lt(t){const e=t;return e.editorObjectKind="baseImage",e}function ct(t,e){const n=t;return n.editorObjectKind="mask",n.maskId=e.maskId,n.maskUid=e.maskUid,n.maskName=e.maskName,n.originalAlpha=e.originalAlpha,"originalStroke"in e&&(n.originalStroke=e.originalStroke),"number"==typeof e.originalStrokeWidth&&(n.originalStrokeWidth=e.originalStrokeWidth),n}function ut(t,e){var n,i;const o=t;return o.editorObjectKind="annotation",o.annotationId=e.annotationId,o.annotationType=e.annotationType,o.annotationName=e.annotationName,o.annotationHidden=null!==(n=e.annotationHidden)&&void 0!==n&&n,o.annotationLocked=null!==(i=e.annotationLocked)&&void 0!==i&&i,o}function dt(t,e){const n=t;return n.editorObjectKind="session",n.sessionObjectType=e,n}const ht=["editorObjectKind","sessionObjectType","maskId","maskUid","maskName","isCropRect","maskLabel","originalAlpha","originalStroke","originalStrokeWidth","hasControls","selectable","strokeUniform","lockRotation","transparentCorners","borderColor","cornerColor","cornerSize","isMosaicPreview","annotationId","annotationType","annotationName","annotationHidden","annotationLocked"];function gt(t){var e,n,i;const{canvas:o,currentScale:a,currentRotation:r,baseImageScale:s}=t,l=null===(n=(e=o).getActiveObject)||void 0===n?void 0:n.call(e),c=l&&nt(l)?l.maskId:"number"==typeof t.activeMaskId?t.activeMaskId:null,u=l&&it(l)?l.annotationId:"number"==typeof t.activeAnnotationId?t.activeAnnotationId:null;(function(t){if(!t)return!1;if("activeselection"===("string"==typeof t.type?t.type.toLowerCase():""))return!0;const e=t.isType;return"function"==typeof e&&(e.call(t,"ActiveSelection")||e.call(t,"activeSelection"))})(l)&&o.discardActiveObject();const d=o.toJSON(ht);return function(t,e){if(Array.isArray(e))for(let n=0;n<e.length;n+=1){const i=t[n],o=e[n];i&&o&&("string"==typeof i.editorObjectKind&&(o.editorObjectKind=i.editorObjectKind),"string"==typeof i.sessionObjectType&&(o.sessionObjectType=i.sessionObjectType),"number"==typeof i.maskId&&(o.maskId=i.maskId),"string"==typeof i.maskUid&&(o.maskUid=i.maskUid),"string"==typeof i.maskName&&(o.maskName=i.maskName),"number"==typeof i.originalAlpha&&(o.originalAlpha=i.originalAlpha),"originalStroke"in i&&(o.originalStroke=i.originalStroke),"number"==typeof i.originalStrokeWidth&&(o.originalStrokeWidth=i.originalStrokeWidth),"boolean"==typeof i.hasControls&&(o.hasControls=i.hasControls),"boolean"==typeof i.selectable&&(o.selectable=i.selectable),"boolean"==typeof i.strokeUniform&&(o.strokeUniform=i.strokeUniform),"boolean"==typeof i.lockRotation&&(o.lockRotation=i.lockRotation),"boolean"==typeof i.transparentCorners&&(o.transparentCorners=i.transparentCorners),"string"==typeof i.borderColor&&(o.borderColor=i.borderColor),"string"==typeof i.cornerColor&&(o.cornerColor=i.cornerColor),"number"==typeof i.cornerSize&&(o.cornerSize=i.cornerSize),!0===i.isCropRect&&(o.isCropRect=!0),!0===i.maskLabel&&(o.maskLabel=!0),!0===i.isMosaicPreview&&(o.isMosaicPreview=!0),"number"==typeof i.annotationId&&(o.annotationId=i.annotationId),"string"==typeof i.annotationType&&(o.annotationType=i.annotationType),"string"==typeof i.annotationName&&(o.annotationName=i.annotationName),"boolean"==typeof i.annotationHidden&&(o.annotationHidden=i.annotationHidden),"boolean"==typeof i.annotationLocked&&(o.annotationLocked=i.annotationLocked))}}(o.getObjects(),d.objects),Array.isArray(d.objects)&&(d.objects=d.objects.filter(t=>"session"!==t.editorObjectKind&&!0!==t.isCropRect&&!0!==t.maskLabel&&!0!==t.isMosaicPreview)),d._editorState={currentScale:a,currentRotation:r,baseImageScale:s,currentImageMimeType:null!==(i=t.currentImageMimeType)&&void 0!==i?i:null,activeObjectKind:null!==c?"mask":null!==u?"annotation":null},null!==c&&(d._editorState.activeMaskId=c),null!==u&&(d._editorState.activeAnnotationId=u),JSON.stringify(d)}async function mt(t){var e,n;const{canvas:i,jsonString:o,setCanvasSize:a}=t,r="string"==typeof o?o:JSON.stringify(o),s=JSON.parse(r);"number"==typeof s.width&&s.width>0&&"number"==typeof s.height&&s.height>0&&a(s.width,s.height),await i.loadFromJSON(s);const l=i.getObjects();!function(t,e){var n,i,o,a;e.forEach((e,n)=>{const i=t[n];i&&("baseImage"!==e.editorObjectKind?"annotation"!==e.editorObjectKind||"number"!=typeof e.annotationId||"string"!=typeof e.annotationType||"string"!=typeof e.annotationName?"session"===e.editorObjectKind&&"string"==typeof e.sessionObjectType&&(i.editorObjectKind="session",i.sessionObjectType=e.sessionObjectType):ut(i,{annotationId:e.annotationId,annotationType:"draw"===e.annotationType?"draw":"text",annotationName:e.annotationName,annotationHidden:"boolean"==typeof e.annotationHidden&&e.annotationHidden,annotationLocked:"boolean"==typeof e.annotationLocked&&e.annotationLocked}):lt(i))});const r=new Set;for(const s of e){if("mask"!==s.editorObjectKind||"number"!=typeof s.maskId)continue;const e=String(null!==(n=s.type)&&void 0!==n?n:""),l=Number(null!==(i=s.left)&&void 0!==i?i:0),c=Number(null!==(o=s.top)&&void 0!==o?o:0),u="string"==typeof s.maskUid?s.maskUid:null;let d=-1;if(u&&(d=t.findIndex((t,e)=>!r.has(e)&&t.maskUid===u)),d<0&&(d=t.findIndex((t,n)=>{var i,o;return!r.has(n)&&((!e||t.type===e)&&(Math.abs((null!==(i=t.left)&&void 0!==i?i:0)-l)<.5&&Math.abs((null!==(o=t.top)&&void 0!==o?o:0)-c)<.5))})),d<0)continue;r.add(d);const h=t[d],g="originalStroke"in s?s.originalStroke:void 0;ct(h,{maskId:s.maskId,maskUid:"string"==typeof s.maskUid?s.maskUid:`mask-${s.maskId}`,maskName:"string"==typeof s.maskName?s.maskName:"",originalAlpha:"number"==typeof s.originalAlpha?s.originalAlpha:null!==(a=h.opacity)&&void 0!==a?a:.5,originalStroke:g,originalStrokeWidth:"number"==typeof s.originalStrokeWidth?s.originalStrokeWidth:void 0}),"originalStroke"in s&&(h.originalStroke=s.originalStroke),"number"==typeof s.originalStrokeWidth&&(h.originalStrokeWidth=s.originalStrokeWidth),"boolean"==typeof s.hasControls&&(h.hasControls=s.hasControls),"boolean"==typeof s.selectable&&(h.selectable=s.selectable),"boolean"==typeof s.strokeUniform&&(h.strokeUniform=s.strokeUniform),"boolean"==typeof s.lockRotation&&(h.lockRotation=s.lockRotation),"boolean"==typeof s.transparentCorners&&(h.transparentCorners=s.transparentCorners),"string"==typeof s.borderColor&&(h.borderColor=s.borderColor),"string"==typeof s.cornerColor&&(h.cornerColor=s.cornerColor),"number"==typeof s.cornerSize&&(h.cornerSize=s.cornerSize)}e.forEach((e,n)=>{if(!0!==e.maskLabel)return;const i=t[n];i&&(i.maskLabel=!0)})}(l,null!==(e=s.objects)&&void 0!==e?e:[]);const c=s._editorState&&"object"==typeof s._editorState?{currentScale:"number"==typeof s._editorState.currentScale?s._editorState.currentScale:1,currentRotation:"number"==typeof s._editorState.currentRotation?s._editorState.currentRotation:0,baseImageScale:"number"==typeof s._editorState.baseImageScale?s._editorState.baseImageScale:1}:null;if(c&&s._editorState&&"number"==typeof s._editorState.activeMaskId&&(c.activeMaskId=s._editorState.activeMaskId),c&&s._editorState&&"number"==typeof s._editorState.activeAnnotationId&&(c.activeAnnotationId=s._editorState.activeAnnotationId),c&&s._editorState&&"activeObjectKind"in s._editorState){const t=s._editorState.activeObjectKind;c.activeObjectKind="mask"===t||"annotation"===t||null===t?t:null}if(c&&s._editorState&&"currentImageMimeType"in s._editorState){const t=s._editorState.currentImageMimeType;c.currentImageMimeType="image/jpeg"===t||"image/png"===t||"image/webp"===t?t:null}const u=l.filter(nt).reduce((t,e)=>Math.max(t,e.maskId),0),d=l.filter(it).reduce((t,e)=>Math.max(t,e.annotationId),0),h=l.filter(nt),g=l.filter(it);return{editorState:c,maxMaskId:u,maxAnnotationId:d,originalImage:null!==(n=l.find(et))&&void 0!==n?n:null,objects:l,masks:h,annotations:g,jsonString:r}}class ft{constructor(t,e){Object.defineProperty(this,"execute",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"undo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.execute=t,this.undo=e}}class pt{constructor(t=50){Object.defineProperty(this,"history",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"currentIndex",{enumerable:!0,configurable:!0,writable:!0,value:-1}),Object.defineProperty(this,"isProcessing",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}async execute(t){await t.execute(),this.pushAndTrim(t)}push(t){this.pushAndTrim(t)}canUndo(){return this.currentIndex>=0}canRedo(){return this.currentIndex<this.history.length-1}async undo(){if(!this.isProcessing&&this.canUndo()){this.isProcessing=!0;try{const t=this.history[this.currentIndex];if(!t)return;await t.undo(),this.currentIndex--}finally{this.isProcessing=!1}}}async redo(){if(!this.isProcessing&&this.canRedo()){this.isProcessing=!0;try{const t=this.history[this.currentIndex+1];if(!t)return;await t.execute(),this.currentIndex++}finally{this.isProcessing=!1}}}pushAndTrim(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++}}function bt(t){if(null===t||"object"!=typeof t)return!1;return"function"==typeof t.Canvas}function vt(t){return!0===t.annotationLocked}function yt(t){return!vt(t)}function Ct(t,e){try{t.set(e)}catch{Object.assign(t,e)}}function St(t){var e;const n=!0===t.annotationHidden,i=vt(t);Ct(t,{visible:!n,selectable:!i,evented:!i,hasControls:!i,lockMovementX:i,lockMovementY:i,lockScalingX:i,lockScalingY:i,lockRotation:i}),i||Ct(t,{selectable:!0,evented:!0,hasControls:!0,lockMovementX:!1,lockMovementY:!1,lockScalingX:!1,lockScalingY:!1,lockRotation:!1}),ot(t)&&function(t,e){t.editable=e}(t,!i),null===(e=t.setCoords)||void 0===e||e.call(t)}function It(t){t.forEach(St)}function Mt(t){return t.getObjects().filter(it).slice()}function wt(t){return function(t){const e=t.getActiveObject();if(!e)return[];if(!function(t){if(!t)return!1;if("activeselection"===("string"==typeof t.type?t.type.toLowerCase():""))return!0;const e=t.isType;return"function"==typeof e&&(e.call(t,"ActiveSelection")||e.call(t,"activeSelection"))}(e))return[e];const n=e.getObjects;return"function"==typeof n?n.call(e):[]}(t).filter(it)}function xt(t){return JSON.stringify({text:t.text,fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fill:t.fill,backgroundColor:t.backgroundColor,textAlign:t.textAlign,width:t.width,stroke:t.stroke,strokeWidth:t.strokeWidth,opacity:t.opacity,visible:t.visible,selectable:t.selectable,evented:t.evented,annotationHidden:t.annotationHidden,annotationLocked:t.annotationLocked})}function kt(t,e){try{t.set(e)}catch{Object.assign(t,e)}}function Ot(t,e){const n=xt(t),i=e;"boolean"==typeof i.annotationHidden&&(t.annotationHidden=i.annotationHidden),"boolean"==typeof i.annotationLocked&&(t.annotationLocked=i.annotationLocked);return vt(t)||("boolean"==typeof i.selectable&&(t.selectable=i.selectable),"boolean"==typeof i.evented&&(t.evented=i.evented),ot(t)&&function(t,e){const n={},i=e;"string"==typeof i.text&&(n.text=i.text),"number"==typeof i.fontSize&&Number.isFinite(i.fontSize)&&i.fontSize>0&&(n.fontSize=i.fontSize),"string"==typeof i.fontFamily&&(n.fontFamily=i.fontFamily),"string"!=typeof i.fontWeight&&"number"!=typeof i.fontWeight||(n.fontWeight=i.fontWeight),"string"==typeof i.fill&&(n.fill=i.fill),"string"==typeof i.backgroundColor&&(n.backgroundColor=i.backgroundColor),"left"!==i.textAlign&&"center"!==i.textAlign&&"right"!==i.textAlign&&"justify"!==i.textAlign||(n.textAlign=i.textAlign),"number"==typeof i.width&&Number.isFinite(i.width)&&i.width>0&&(n.width=i.width),Object.keys(n).length>0&&kt(t,n)}(t,e),at(t)&&function(t,e){const n={},i=e;"string"==typeof i.stroke&&(n.stroke=i.stroke),"number"==typeof i.strokeWidth&&Number.isFinite(i.strokeWidth)&&i.strokeWidth>0&&(n.strokeWidth=i.strokeWidth),"number"==typeof i.opacity&&Number.isFinite(i.opacity)&&(n.opacity=Math.max(0,Math.min(1,i.opacity))),Object.keys(n).length>0&&kt(t,n)}(t,e)),St(t),xt(t)!==n}function At(t,e,n={}){const i=!0===n.force,o=e.filter(t=>i||yt(t));if(0===o.length)return 0;for(const e of o)t.canvas.remove(e);return t.canvas.discardActiveObject(),t.canvas.renderAll(),!1!==n.saveHistory&&t.saveCanvasState(),t.updateUi(),o.length}function Et(t,e={}){return At(t,Mt(t.canvas),e)}function jt(t){var e,n,i,o,a;const r=t.canvas;return null!==(a=null!==(i=null===(n=null===(e=null==r?void 0:r.getElement)||void 0===e?void 0:e.call(r))||void 0===n?void 0:n.ownerDocument)&&void 0!==i?i:null===(o=null==r?void 0:r.lowerCanvasEl)||void 0===o?void 0:o.ownerDocument)&&void 0!==a?a:document}function Tt(t){const e=t;return!0===e.isCropRect||!0===e.maskLabel||!0===e.isMosaicPreview}function Bt(t,e,n){const i=t;if("function"!=typeof i.moveObjectTo)try{t.remove(e),t.insertAt(n,e)}catch{t.add(e)}else i.moveObjectTo(e,n)}function Lt(t,e){t.getObjects().includes(e)||t.add(e)}function Dt(t,e){return t.getObjects().filter(t=>t!==e)}function Ft(t){return t.findIndex(t=>rt(t)||Tt(t))}function Nt(t){const e=function(t){const e=[],n=[],i=[],o=[];for(const a of t.getObjects())et(a)?e.push(a):st(a)?n.push(a):rt(a)||Tt(a)?i.push(a):o.push(a);return{baseImages:e,overlays:n,sessions:i,others:o}}(t);[...e.baseImages,...e.others,...e.overlays,...e.sessions].forEach((e,n)=>{Bt(t,e,n)})}function Pt(t,e){Lt(t,e);const n=Dt(t,e),i=Ft(n);Bt(t,e,-1===i?n.length:i)}function zt(t,e,n){const i=Number(t.left),o=Number(t.top),a=Number(t.width),r=Number(t.height);if(!Number.isFinite(i)||!Number.isFinite(o)||!Number.isFinite(a)||!Number.isFinite(r)||a<=0||r<=0)return!1;const s=i+a,l=o+r;if(!Number.isFinite(s)||!Number.isFinite(l))return!1;const c=Number(e),u=Number(n);if(!Number.isFinite(c)||!Number.isFinite(u)||c<=0||u<=0)return!0;const d=Math.min(s,c)-Math.max(i,0),h=Math.min(l,u)-Math.max(o,0);return d>0&&h>0}function Rt(t,e,n,i={}){const o=Number.isFinite(t.left)?t.left:0,a=Number.isFinite(t.top)?t.top:0,r=Math.max(0,Number.isFinite(t.width)?t.width:0),s=Math.max(0,Number.isFinite(t.height)?t.height:0),l=!1!==i.includePartialPixels?Math.ceil:Math.floor,c=Number.isFinite(e),u=Number.isFinite(n),d=c?Math.max(1,Math.round(Number(e))):Number.POSITIVE_INFINITY,h=u?Math.max(1,Math.round(Number(n))):Number.POSITIVE_INFINITY,g=Math.min(d-1,Math.max(0,Math.floor(o))),m=Math.min(h-1,Math.max(0,Math.floor(a))),f=Math.min(d,Math.max(g+1,l(o+r))),p=Math.min(h,Math.max(m+1,l(a+s)));return{left:g,top:m,width:Math.max(1,f-g),height:Math.max(1,p-m)}}function Wt(t){const e=Number(t);return!!Number.isFinite(e)&&Math.abs(e-Math.round(e))>.01}function Ht(t,e=0){if(!t)return null;const n=Math.abs((Number(e)||0)%90);if(!(n<.01||Math.abs(n-90)<.01))return null;const i=Number(t.left)||0,o=Number(t.top)||0;return{left:Wt(i),top:Wt(o),right:Wt(i+(Number(t.width)||0)),bottom:Wt(o+(Number(t.height)||0))}}function Ut(t){t.setCoords();const e=t.getBoundingRect();return{left:e.left,top:e.top,width:e.width,height:e.height}}function $t(t,e,n,i,o){if("number"==typeof t)return t;if("function"==typeof t)return t(i,o);if("string"==typeof t&&t.endsWith("%")){const o=parseFloat(t);if(!Number.isFinite(o))return n;const a="x"===e?i.getWidth():i.getHeight();return Math.floor(a*(o/100))}return n}function Qt(t){return Array.isArray(t)?{x:Number(t[0]),y:Number(t[1])}:{x:Number(t.x),y:Number(t.y)}}function qt(t){const e=t;return!!e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function Yt(t,e){const n=e&&"object"==typeof e?e:null;if(!n)return null;if(qt(n.scenePoint))return{...n.scenePoint};if(qt(n.pointer))return{...n.pointer};if(qt(n.absolutePointer))return{...n.absolutePointer};if(n.e&&"function"==typeof t.getPointer){const e=t.getPointer(n.e);if(qt(e))return{...e}}return null}function Xt(t,e){var n,i;const o=_(t.getTextConfig(),e),a=function(t){const e=t.getOriginalImage();if(e){const t=Ut(e);return{left:Math.round(t.left+10),top:Math.round(t.top+10)}}return{left:10,top:10}}(t),r=null!==(n=e.left)&&void 0!==n?n:o.left,s=null!==(i=e.top)&&void 0!==i?i:o.top;return{...o,left:$t(r,"x",a.left,t.canvas,t.options),top:$t(s,"y",a.top,t.canvas,t.options)}}function Gt(t,e){const n=e;if(n.imageEditorTextEditingHandlers)try{n.off("editing:entered",n.imageEditorTextEditingHandlers.entered),n.off("editing:exited",n.imageEditorTextEditingHandlers.exited)}catch{}const i=()=>{var t;n.imageEditorTextEditingInitialText=String(null!==(t=n.text)&&void 0!==t?t:""),n.imageEditorTextEditingCancel=!1},o=()=>{var e;const i=n.imageEditorTextEditingInitialText,o=String(null!==(e=n.text)&&void 0!==e?e:""),a=!0===n.imageEditorTextEditingCancel;if(a&&void 0!==i&&n.set({text:i}),delete n.imageEditorTextEditingInitialText,delete n.imageEditorTextEditingCancel,!a&&void 0!==i&&i!==o){t.saveCanvasState();const e=t.buildCallbackContext("createTextAnnotation");t.emitAnnotationsChanged(e),t.emitImageChanged(e)}};n.on("editing:entered",i),n.on("editing:exited",o),n.imageEditorTextEditingHandlers={entered:i,exited:o}}function Kt(t,e={}){var n,i;if(!t.isImageLoaded())return null;const o=Xt(t,e),a=new t.fabric.Textbox(o.text,{left:o.left,top:o.top,width:o.width,fontSize:o.fontSize,fontFamily:o.fontFamily,fontWeight:o.fontWeight,fill:o.fill,backgroundColor:o.backgroundColor,textAlign:o.textAlign,angle:o.angle,selectable:o.selectable,evented:o.evented,editable:o.editable,originX:"left",originY:"top",...o.styles}),r=function(t,e){const n=t.getAnnotationCounter()+1;return t.setAnnotationCounter(n),{annotationId:n,annotationName:`${t.options.textAnnotationName}${n}`,annotationHidden:e.annotationHidden,annotationLocked:e.annotationLocked}}(t,o),s=ut(a,{annotationId:r.annotationId,annotationType:"text",annotationName:r.annotationName,annotationHidden:r.annotationHidden,annotationLocked:r.annotationLocked});St(s),Gt(t,s),Pt(t.canvas,s),!1!==o.selectable&&yt(s)&&t.canvas.setActiveObject(s),t.canvas.renderAll(),t.updateAnnotationList(),t.saveCanvasState();const l=t.buildCallbackContext("createTextAnnotation");return t.emitAnnotationsChanged(l),t.emitImageChanged(l),o.enterEditing&&yt(s)&&(null===(i=(n=s).enterEditing)||void 0===i||i.call(n),function(t){var e;const n=t,i=String(null!==(e=n.text)&&void 0!==e?e:"").length;if(!(i<=0))if("function"!=typeof n.selectAll){if("function"==typeof n.setSelectionStart&&"function"==typeof n.setSelectionEnd)return n.setSelectionStart(0),void n.setSelectionEnd(i);n.selectionStart=0,n.selectionEnd=i}else n.selectAll()}(s)),s}function Vt(t){if(t.getTextSession())return;if(!t.isImageLoaded())return;const{canvas:e}=t,n=!!e.selection,i=e.defaultCursor;e.selection=!0,e.defaultCursor="text";const o=e=>function(t,e){var n,i;const o=e.target;if(o)return void(ot(o)&&yt(o)?(t.canvas.setActiveObject(o),null===(i=(n=o).enterEditing)||void 0===i||i.call(n)):st(o)&&t.canvas.setActiveObject(o));const a=Yt(t.canvas,e);a&&Kt(t,{left:a.x,top:a.y})}(t,e);e.on("mouse:down",o);const a={mode:"text",previousCanvasSelection:n,previousDefaultCursor:i,handlers:[{eventName:"mouse:down",callback:o}],dispose:()=>{try{e.off("mouse:down",o)}catch{}e.selection=n,e.defaultCursor=null!=i?i:"default"}};dt(new t.fabric.Rect({left:-1,top:-1,width:1,height:1,selectable:!1,evented:!1,visible:!1,excludeFromExport:!0}),"textPreview"),t.setTextSession(a),t.updateUi()}function _t(t){const e=t.getTextSession();e&&(e.dispose(),t.setTextSession(null),t.canvas.requestRenderAll(),t.updateUi())}function Jt(t,e){var n;const i=t.canvas.getActiveObject();if(!i||!ot(i))return;const o=i;!0===o.isEditing&&(o.imageEditorTextEditingCancel=!e.commit,null===(n=o.exitEditing)||void 0===n||n.call(o),t.canvas.requestRenderAll())}function Zt(t,e){e.filter(ot).forEach(e=>{Gt(t,e)})}function te(t){const e=t.getDrawConfig(),n=t.canvas;n.freeDrawingBrush=new t.fabric.PencilBrush(t.canvas),n.freeDrawingBrush.width=e.brushSize,n.freeDrawingBrush.color=function(t,e){const n=Math.max(0,Math.min(1,e));if(n>=1)return t;if(/^#([0-9a-f]{6})$/i.test(t)){const e=t.slice(1);return`rgba(${Number.parseInt(e.slice(0,2),16)},${Number.parseInt(e.slice(2,4),16)},${Number.parseInt(e.slice(4,6),16)},${n})`}return t}(e.color,e.opacity),n.freeDrawingBrush.strokeLineCap=e.lineCap,n.freeDrawingBrush.strokeLineJoin=e.lineJoin}function ee(t,e){const n=e.path;if(!n)return;const i=function(t,e){const n=t.getDrawConfig(),i=t.getAnnotationCounter()+1;t.setAnnotationCounter(i),e.set({selectable:n.selectable,evented:n.evented,opacity:n.opacity,stroke:n.color,strokeWidth:n.brushSize});const o=ut(e,{annotationId:i,annotationType:"draw",annotationName:`${t.options.drawAnnotationName}${i}`,annotationHidden:n.annotationHidden,annotationLocked:n.annotationLocked});return St(o),o}(t,n);Pt(t.canvas,i),t.canvas.setActiveObject(i),t.canvas.renderAll(),t.updateAnnotationList(),t.saveCanvasState();const o=t.buildCallbackContext("enterDrawMode");t.emitAnnotationsChanged(o),t.emitImageChanged(o)}function ne(t){const e=t.getDrawSession();e&&(e.dispose(),t.setDrawSession(null),t.canvas.requestRenderAll(),t.updateUi())}function ie(t,e){Object.setPrototypeOf(t,e.prototype)}class oe extends Error{constructor(t="Failed to decode image data URL.",e=null){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ImageDecodeError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=e,ie(this,oe)}}class ae extends Error{constructor(t,e){super(`Image load timed out after ${e}ms during ${t}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ImageLoadTimeoutError"}),Object.defineProperty(this,"label",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"elapsedMs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.label=t,this.elapsedMs=e,ie(this,ae)}}class re extends Error{constructor(t="Failed to obtain a 2D context for downsampling.",e=null){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"DownsampleError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=e,ie(this,re)}}class se extends Error{constructor(t="Failed to merge masks into the image.",e=null){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"MergeMasksError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=e,ie(this,se)}}class le extends Error{constructor(t="Failed to merge annotations into the image.",e=null){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"MergeAnnotationsError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=e,ie(this,le)}}class ce extends Error{constructor(t="Failed to apply crop to the image.",e=null){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CropApplyError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=e,ie(this,ce)}}class ue extends Error{constructor(t="exportImageFile"){super(`Cannot ${t}: no image is loaded on the canvas.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ExportNotReadyError"}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.operation=t,ie(this,ue)}}class de extends Error{constructor(t="Failed to export image.",e=null){super(t),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"ExportError"}),Object.defineProperty(this,"originalError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.originalError=e,ie(this,de)}}const he="#ccc";function ge(t){var e;const n=Number(t.originalStrokeWidth);t.set({stroke:null!==(e=t.originalStroke)&&void 0!==e?e:he,strokeWidth:Number.isFinite(n)?n:1})}function me(t){const e=t,n=()=>{var t;e.set(function(t){const e=Number(t.originalAlpha),n=Number.isFinite(e)?e:.5;return{stroke:"#ff5500",strokeWidth:2,opacity:Math.min(n+.2,1)}}(e)),null===(t=e.canvas)||void 0===t||t.requestRenderAll()},i=()=>{var t;e.set(function(t){var e;const n=Number(t.originalStrokeWidth),i=Number(t.originalAlpha);return{stroke:null!==(e=t.originalStroke)&&void 0!==e?e:he,strokeWidth:Number.isFinite(n)?n:1,opacity:Number.isFinite(i)?i:.5}}(e)),null===(t=e.canvas)||void 0===t||t.requestRenderAll()};e.on("mouseover",n),e.on("mouseout",i),e.imageEditorMaskHandlers={mouseover:n,mouseout:i}}function fe(t){var e;const n=t;if(n.imageEditorMaskHandlers){try{n.off("mouseover",n.imageEditorMaskHandlers.mouseover),n.off("mouseout",n.imageEditorMaskHandlers.mouseout)}catch{}delete n.imageEditorMaskHandlers}const i={};if(!Number.isFinite(Number(n.originalAlpha))){const t=Number(n.opacity);i.originalAlpha=Number.isFinite(t)?t:.5}if(null==n.originalStroke&&(i.originalStroke=null!==(e=n.stroke)&&void 0!==e?e:he),!Number.isFinite(Number(n.originalStrokeWidth))){const t=Number(n.strokeWidth);i.originalStrokeWidth=Number.isFinite(t)?t:1}Object.keys(i).length>0&&n.set(i),me(n)}function pe(t){const e=t;if(e.imageEditorMaskHandlers){try{e.off("mouseover",e.imageEditorMaskHandlers.mouseover),e.off("mouseout",e.imageEditorMaskHandlers.mouseout)}catch{}delete e.imageEditorMaskHandlers}}function be(t){var e,n,i,o,a,r,s;return{object:t,opacity:null!==(e=t.opacity)&&void 0!==e?e:1,fill:null!==(n=t.fill)&&void 0!==n?n:null,strokeWidth:null!==(i=t.strokeWidth)&&void 0!==i?i:0,stroke:null!==(o=t.stroke)&&void 0!==o?o:null,selectable:null===(a=t.selectable)||void 0===a||a,evented:null===(r=t.evented)||void 0===r||r,lockRotation:null!==(s=t.lockRotation)&&void 0!==s&&s}}function ve(t){try{t.object.set({opacity:t.opacity,fill:t.fill,strokeWidth:t.strokeWidth,stroke:t.stroke,selectable:t.selectable,evented:t.evented,lockRotation:t.lockRotation}),"function"==typeof t.object.setCoords&&t.object.setCoords()}catch{}}function ye(t){try{t.set({opacity:0,evented:!1,selectable:!1})}catch{}}const Ce=[6,4],Se=.92;function Ie(t,e){const n=Number(t);return Number.isFinite(n)?n:e}function Me(t,e){const n=Number(t);if(Number.isFinite(n))return l(n,Se);const i=Number(e);return Number.isFinite(i)?l(i,Se):Se}function we(t,e){for(const t of e.handlers)for(const e of t.handlers)try{t.target.off(e.eventName,e.callback)}catch{}if(e.handlers=[],e.cropRect){try{t.canvas.remove(e.cropRect)}catch{}e.cropRect=null}}function xe(t){for(const e of t.prevEvented)try{e.object.set({evented:e.evented,selectable:e.selectable})}catch{}t.prevEvented=[]}function ke(t,e){we(t,e),xe(e),function(t){for(const e of t.maskBackups)ve(e);t.maskBackups=[]}(e);try{t.canvas.selection=!!e.prevSelection}catch{}}function Oe(t,e){const n=Ut(t);return n.left<e.left+e.width&&n.left+n.width>e.left&&n.top<e.top+e.height&&n.top+n.height>e.top}function Ae(t){const e=t.getCropSession();if(e){t.canvas.discardActiveObject(),ke(t,e),t.setCropSession(null);try{t.canvas.renderAll()}catch{}}}async function Ee(t){var e,n;const i=t.getCropSession();if(!i||!i.cropRect)return;const{canvas:o}=t;o.discardActiveObject();const a=i.beforeJson,l=i.cropRect,c=!!t.options.crop.preserveMasksAfterCrop;try{l.setCoords();const u=Number(l.angle)||0;if(!t.options.crop.allowRotationOfCropRect&&Math.abs(u%360)>.01)throw new ce("applyCrop failed: rotated crop rectangles are disabled.");const d=function(t){const e=Number(t.angle)||0,n=Math.abs(e%360);return n>.01&&Math.abs(n-360)>.01?Ut(t):{left:Number(t.left)||0,top:Number(t.top)||0,width:Math.max(0,(Number(t.width)||0)*Math.abs(Number(t.scaleX)||1)),height:Math.max(0,(Number(t.height)||0)*Math.abs(Number(t.scaleY)||1))}}(l);if(!zt(d,o.getWidth(),o.getHeight()))throw new ce("applyCrop failed: crop region is empty or outside the canvas.");const h=Rt(d,o.getWidth(),o.getHeight(),{includePartialPixels:!1}),g=c?function(t,e,n=[]){var i;const o=[],a=n.length>0?new Map(n.map(t=>[t.object,t])):null,r=t.getObjects().filter(nt);for(const n of r)try{if(n.setCoords(),Oe(n,e)){const t=null!==(i=null==a?void 0:a.get(n))&&void 0!==i?i:be(n);o.push({mask:n,left:Ie(n.left,0),top:Ie(n.top,0),angle:Ie(n.angle,0),scaleX:Ie(n.scaleX,1),scaleY:Ie(n.scaleY,1),styleBackup:t})}t.remove(n)}catch{}return o}(o,h,i.maskBackups):[];xe(i),we(t,i),o.selection=!!i.prevSelection;const m=function(t){var e,n;const i=t.cropExportFileType,o=null==i||"source"===i?null!==(e=function(t){return"image/jpeg"===t?"jpeg":"image/png"===t?"png":"image/webp"===t?"webp":null}(t.currentImageMimeType))&&void 0!==e?e:"png":null!==(n=r(String(i)))&&void 0!==n?n:"png",a=s(o);return"png"===o?{format:o,mimeType:a}:{format:o,mimeType:a,quality:Me(t.cropExportQuality,t.downsampleQuality)}}({cropExportFileType:t.options.crop.exportFileType,currentImageMimeType:null!==(n=null===(e=t.getCurrentImageMimeType)||void 0===e?void 0:e.call(t))&&void 0!==n?n:null,cropExportQuality:t.options.crop.exportQuality,downsampleQuality:t.options.downsampleQuality}),f={format:m.format,multiplier:1,left:h.left,top:h.top,width:h.width,height:h.height};void 0!==m.quality&&(f.quality=m.quality);const p=o.toDataURL(f);await t.loadImage(p),g.length>0&&(!function(t,e,n){var i;if(0===n.length)return;const{canvas:o}=t;let a=0;for(const t of n)try{ve(t.styleBackup),t.mask.set({left:t.left-e.left,top:t.top-e.top,angle:t.angle,scaleX:t.scaleX,scaleY:t.scaleY,visible:!0}),t.mask.setCoords(),o.add(t.mask),o.bringObjectToFront(t.mask),fe(t.mask);const n=Number(t.mask.maskId);Number.isFinite(n)&&n>a&&(a=n)}catch{}if("function"==typeof t.getMaskCounter&&"function"==typeof t.setMaskCounter){const e=Number(t.getMaskCounter()),n=Number.isFinite(e)?e:0;t.setMaskCounter(Math.max(n,a))}try{null===(i=t.updateMaskList)||void 0===i||i.call(t)}catch{}}(t,h,g),o.renderAll());const b=t.saveState();t.setCropSession(null),a&&b&&a!==b&&t.historyManager.push(new ft(()=>t.loadFromState(b),()=>t.loadFromState(a)))}catch(e){ke(t,i),t.setCropSession(null);try{await t.loadFromState(a)}catch(t){console.warn("[ImageEditor] applyCrop: rollback failed",t)}if(e instanceof ce)throw e;const n=e instanceof Error?`applyCrop failed: ${e.message}`:"applyCrop failed";throw new ce(n,e)}}function je(t,e,n,i){if(!(Te(t)&&Te(e)&&Te(n)&&Te(i)))return{width:Math.max(1,Math.round(t)||1),height:Math.max(1,Math.round(e)||1),needsResize:!1};if(!(t>n||e>i))return{width:t,height:e,needsResize:!1};const o=Math.min(n/t,i/e);return{width:Math.max(1,Math.round(t*o)),height:Math.max(1,Math.round(e*o)),needsResize:!0}}function Te(t){return Number.isFinite(t)&&t>0}function Be(t){const e=/^data:(image\/[a-z0-9+\-.]+)\s*;/i.exec(t);return e?e[1].toLowerCase():null}function Le(t,e,n){return new Promise((i,o)=>{const a=Date.now(),r=setTimeout(()=>{o(new ae(n,Date.now()-a))},e);t.then(t=>{clearTimeout(r),i(t)},t=>{clearTimeout(r),o(t)})})}function De(t,e){const n=Math.hypot(t.a,t.b),i=Math.hypot(t.c,t.d),o=Math.min(n>1e-8?n:Number.POSITIVE_INFINITY,i>1e-8?i:Number.POSITIVE_INFINITY);return!Number.isFinite(o)||o<=0?e:e/o}function Fe(t,e,n,i){const o=Number(e.width)||0,a=Number(e.height)||0,r=Number(i);if(o<=0||a<=0||!Number.isFinite(n.x)||!Number.isFinite(n.y)||!Number.isFinite(r)||r<=0)return null;const s=function(t){if(t.length<6)return null;const e=t[0],n=t[1],i=t[2],o=t[3],a=t[4],r=t[5];return Number.isFinite(e)&&Number.isFinite(n)&&Number.isFinite(i)&&Number.isFinite(o)&&Number.isFinite(a)&&Number.isFinite(r)?{a:e,b:n,c:i,d:o,e:a,f:r}:null}(e.calcTransformMatrix());if(!s)return null;const l=function(t){const e=t.a*t.d-t.b*t.c;return!Number.isFinite(e)||Math.abs(e)<1e-8?null:{a:t.d/e,b:-t.b/e,c:-t.c/e,d:t.a/e,e:(t.c*t.f-t.d*t.e)/e,f:(t.b*t.e-t.a*t.f)/e}}(s);if(!l)return null;const c=function(t,e){return{x:e.a*t.x+e.c*t.y+e.e,y:e.b*t.x+e.d*t.y+e.f}}(n,l),u=c.x+o/2,d=c.y+a/2;return u<0||d<0||u>o||d>a?null:{sourceX:u,sourceY:d,sourceRadius:De(s,r/2)}}function Ne(t,e,n,i,o){const a=t-n,r=e-i;return a*a+r*r<=o}function Pe(t,e,n){return 4*(n*t+e)}function ze(t){var e,n,i,o;const{imageData:a}=t,{width:r,height:s,data:l}=a,c=Number(t.centerX),u=Number(t.centerY),d=Number(t.radius);if(!Number.isFinite(c)||!Number.isFinite(u)||!Number.isFinite(d)||d<=0||r<=0||s<=0)return!1;const h=(g=t.blockSize,Number.isFinite(g)&&g>0?Math.max(1,Math.floor(g)):1);var g;const m=Math.max(0,Math.floor(c-d)),f=Math.min(r-1,Math.ceil(c+d)),p=Math.max(0,Math.floor(u-d)),b=Math.min(s-1,Math.ceil(u+d));if(m>f||p>b)return!1;const v=d*d;let y=!1;for(let t=p;t<=b;t+=h)for(let a=m;a<=f;a+=h){const s=Math.min(f,a+h-1),d=Math.min(b,t+h-1);let g=-1;for(let e=t;e<=d&&g<0;e+=1)for(let t=a;t<=s;t+=1)if(Ne(t,e,c,u,v)){g=Pe(r,t,e);break}if(g<0)continue;const m=null!==(e=l[g])&&void 0!==e?e:0,p=null!==(n=l[g+1])&&void 0!==n?n:0,C=null!==(i=l[g+2])&&void 0!==i?i:0,S=null!==(o=l[g+3])&&void 0!==o?o:0;for(let e=t;e<=d;e+=1)for(let t=a;t<=s;t+=1){if(!Ne(t,e,c,u,v))continue;const n=Pe(r,t,e);l[n]=m,l[n+1]=p,l[n+2]=C,l[n+3]=S,y=!0}}return y}function Re(t){try{t.requestRenderAll()}catch{try{t.renderAll()}catch{}}}function We(t,e){var n;const{canvas:i}=t,o=null!==(n=e.previewCircle)&&void 0!==n?n:function(t){const e=t.getMosaicConfig(),n=new t.fabric.Circle({left:0,top:0,radius:e.brushSize/2,originX:"center",originY:"center",fill:e.previewFill,stroke:e.previewStroke,strokeWidth:e.previewStrokeWidth,strokeDashArray:e.previewStrokeDashArray?[...e.previewStrokeDashArray]:void 0,selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!1});return dt(n,"mosaicPreviewCircle"),n.isMosaicPreview=!0,n}(t);return e.previewCircle=o,i.getObjects().includes(o)||i.add(o),i.bringObjectToFront(o),rn(t),o}function He(t,e){const n=e.previewCircle;if(n){try{t.canvas.remove(n)}catch{}e.previewCircle=null}}function Ue(t,e,n){var i;const o=e.rasterCache;if(!o)return null;const a=null!==(i=e.previewImage)&&void 0!==i?i:function(t,e,n){const i=new t.fabric.FabricImage(n.offscreenCanvas,{selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!0});return Ke(i,e),i.set({selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!0}),dt(i,"mosaicPreviewImage"),i.isMosaicPreview=!0,i}(t,n,o);e.previewImage=a,Ke(a,n),a.set({selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!0}),a.dirty=!0,t.canvas.getObjects().includes(a)||t.canvas.add(a),function(t,e,n){var i,o;const a=t.canvas.getObjects().indexOf(n);if(!(a<0))try{null===(o=(i=t.canvas).moveObjectTo)||void 0===o||o.call(i,e,a+1)}catch{}}(t,a,n);const r=e.previewCircle;return r&&t.canvas.getObjects().includes(r)&&t.canvas.bringObjectToFront(r),a}function $e(t,e){const n=e.previewImage;if(n){try{t.canvas.remove(n)}catch{}e.previewImage=null}}function Qe(t){var e;const n=null===(e=t.getMosaicSession())||void 0===e?void 0:e.previewCircle;n&&(n.set({visible:!1}),Re(t.canvas))}function qe(t,e){const n=t.getMosaicSession();if(!n)return;We(t,n).set({left:e.x,top:e.y,visible:!0}),Re(t.canvas)}function Ye(t,e,n,i){t.canvas.on(n,i),e.handlers.push({eventName:n,callback:i})}function Xe(t){var e;const n=t;try{const t=null===(e=n.getSrc)||void 0===e?void 0:e.call(n);if("string"==typeof t&&t.length>0)return t}catch{}return"string"==typeof n.src&&n.src.length>0?n.src:null}function Ge(t){const e=Number(t);return Number.isFinite(e)&&e>0?Math.floor(e):0}function Ke(t,e){t.set({left:e.left,top:e.top,scaleX:e.scaleX,scaleY:e.scaleY,angle:e.angle,skewX:e.skewX,skewY:e.skewY,flipX:e.flipX,flipY:e.flipY,originX:e.originX,originY:e.originY,selectable:e.selectable,evented:e.evented,hasControls:e.hasControls,hoverCursor:e.hoverCursor}),t.setCoords()}async function Ve(t,e,n){if(e.rasterCache)return e.rasterCache;const o=function(t){var e,n,i,o,a;const r=null===(n=(e=t.canvas).getElement)||void 0===n?void 0:n.call(e);return null!==(a=null!==(i=null==r?void 0:r.ownerDocument)&&void 0!==i?i:null===(o=t.canvas.lowerCanvasEl)||void 0===o?void 0:o.ownerDocument)&&void 0!==a?a:document}(t),a=await function(t,e){return new Promise((n,i)=>{const o=t.createElement("img"),a=()=>{"function"==typeof o.removeEventListener?(o.removeEventListener("load",r),o.removeEventListener("error",s)):(o.onload=null,o.onerror=null)},r=()=>{const t=Ge(o.naturalWidth||o.width),e=Ge(o.naturalHeight||o.height);a(),t<=0||e<=0?i(new Error("Mosaic image decode failed: source image has no dimensions.")):n({element:o,width:t,height:e})},s=t=>{a(),i(new Error("string"==typeof t?`Mosaic image decode failed: ${t}`:"Mosaic image decode failed."))};e.startsWith("data:")||(o.crossOrigin="anonymous"),"function"==typeof o.addEventListener?(o.addEventListener("load",r,{once:!0}),o.addEventListener("error",s,{once:!0})):(o.onload=r,o.onerror=s),o.src=e})}(o,n),r=o.createElement("canvas");r.width=a.width,r.height=a.height;const s=r.getContext("2d");if(!s)return i(t.options,new Error("Mosaic could not obtain a 2D canvas context."),"Mosaic apply failed."),null;let l;s.drawImage(a.element,0,0,a.width,a.height);try{l=s.getImageData(0,0,a.width,a.height)}catch(e){return i(t.options,e,"Mosaic apply failed because the source image pixels could not be read."),null}const c={offscreenCanvas:r,renderingContext:s,imageData:l,source:n,width:a.width,height:a.height};return e.rasterCache=c,c}function _e(t,e,n,i){const o=e.rasterCache;if(!o)return!1;const a=t.getMosaicConfig(),r=e.lastImagePoint,s=r?function(t,e){const n=e.sourceX-t.sourceX,i=e.sourceY-t.sourceY,o=Math.hypot(n,i),a=Math.min(t.sourceRadius,e.sourceRadius),r=Math.max(1,a/2),s=Math.max(1,Math.ceil(o/r)),l=[];for(let o=1;o<=s;o+=1){const a=o/s;l.push({sourceX:t.sourceX+n*a,sourceY:t.sourceY+i*a,sourceRadius:t.sourceRadius+(e.sourceRadius-t.sourceRadius)*a})}return l}(r,i):[i];let l=!1;for(const t of s)l=ze({imageData:o.imageData,centerX:t.sourceX,centerY:t.sourceY,radius:t.sourceRadius,blockSize:a.blockSize})||l;return e.lastImagePoint=i,l&&(e.hasUncommittedChanges=!0,o.renderingContext.putImageData(o.imageData,0,0),Ue(t,e,n),Re(t.canvas)),l}async function Je(t,e,i){const o=t.getMosaicSession();if(!o||o!==e)return;const a=t.getOriginalImage();if(!a||!t.isImageLoaded())return;const r=t.getMosaicConfig(),s=Fe(t.fabric,a,i,r.brushSize);if(!s)return void(o.lastImagePoint=null);const l=Xe(a);if(!l)return void n(t.options,new Error("Mosaic cannot read the current image source."),"Mosaic skipped because the image source is unavailable.");await Ve(t,o,l)&&_e(t,o,a,s)}async function Ze(t,e,n){var i;if(e.commitRequested=!1,e.lastImagePoint=null,!e.hasUncommittedChanges||!e.rasterCache)return;const o=t.getOriginalImage();if(!o||!t.isImageLoaded())return;const a=null!==(i=Xe(o))&&void 0!==i?i:e.rasterCache.source,l=e.rasterCache;l.renderingContext.putImageData(l.imageData,0,0);const c=function(t,e){var n,i,o,a;const l=t.getMosaicConfig(),c=l.outputFileType,u="source"===c?function(t){return"image/jpeg"===t?"jpeg":"image/webp"===t?"webp":"png"}(null!==(i=null!==(n=t.getCurrentImageMimeType())&&void 0!==n?n:function(t){return"image/jpeg"===t||"image/png"===t||"image/webp"===t?t:null}(Be(e)))&&void 0!==i?i:"image/png"):null!==(o=r(String(c)))&&void 0!==o?o:"png",d=s(u);return"png"===u?{mimeType:d}:{mimeType:d,quality:null!==(a=l.outputQuality)&&void 0!==a?a:t.options.downsampleQuality}}(t,a),u=void 0===c.quality?l.offscreenCanvas.toDataURL(c.mimeType):l.offscreenCanvas.toDataURL(c.mimeType,c.quality),d=await async function(t,e){return await Le(t.fabric.FabricImage.fromURL(e,{crossOrigin:"anonymous"}),t.options.imageLoadTimeoutMs,"Mosaic FabricImage.fromURL")}(t,u);He(t,e),$e(t,e);try{!function(t,e,n,i){const{canvas:o}=t;let a=!1,r=!1;try{Ke(n,e),o.remove(e),a=!0,o.add(n),r=!0,o.sendObjectToBack(n),t.setOriginalImage(lt(n)),t.setCurrentImageMimeType(i),o.renderAll()}catch(i){try{r&&o.remove(n),a&&!o.getObjects().includes(e)&&(o.add(e),o.sendObjectToBack(e)),t.setOriginalImage(e)}catch{}throw i}}(t,o,d,c.mimeType);const n=t.captureSnapshot();!function(t,e){var n;const i=null!==(n=t.getLastSnapshot())&&void 0!==n?n:e;i&&e&&i!==e&&(t.historyManager.push(new ft(async()=>{await t.loadFromState(e)},async()=>{await t.loadFromState(i)})),t.setLastSnapshot(e))}(t,n),l.source=u,e.hasUncommittedChanges=!1}finally{t.getMosaicSession()===e&&We(t,e)}t.updateInputs(),t.updateUi(),t.emitImageChanged(n)}async function tn(t,e){const n=t.getMosaicSession();if(!n||n!==e||n.isApplying)return;n.isApplying=!0;const o=t.buildCallbackContext("applyMosaic",!1);t.emitBusyChangeIfChanged(o),t.updateUi();try{for(;t.getMosaicSession()===n&&n.pendingCanvasPoints.length>0;){const e=n.pendingCanvasPoints.shift();e&&await Je(t,n,e)}t.getMosaicSession()===n&&n.commitRequested&&await Ze(t,n,o)}finally{t.getMosaicSession()===n&&(n.isApplying=!1),t.emitBusyChangeIfChanged(o),t.updateUi(),t.getMosaicSession()===n&&(n.pendingCanvasPoints.length>0||n.commitRequested)&&tn(t,n).catch(e=>{i(t.options,e,"Mosaic apply failed.")})}}function en(t,e){const n=t.getMosaicSession();n&&(n.pendingCanvasPoints.push(e),n.pendingCanvasPoints.length>4096&&n.pendingCanvasPoints.splice(0,n.pendingCanvasPoints.length-4096),tn(t,n).catch(e=>{i(t.options,e,"Mosaic apply failed.")}))}function nn(t,e){e.commitRequested=!0,tn(t,e).catch(e=>{i(t.options,e,"Mosaic apply failed.")})}function on(t){if(t.getMosaicSession())return;if(!t.isImageLoaded()||!t.getOriginalImage())return;const{canvas:e}=t;t.hideAllMaskLabels(),e.discardActiveObject();const n=!!e.selection,i=e.defaultCursor,o=e.getObjects().map(t=>{var e,n;return{object:t,evented:null===(e=t.evented)||void 0===e||e,selectable:null===(n=t.selectable)||void 0===n||n}});for(const t of o)try{t.object.set({evented:!1,selectable:!1})}catch{}e.selection=!1,e.defaultCursor="crosshair";const a={previewCircle:null,previewImage:null,prevSelection:n,prevDefaultCursor:i,prevObjectStates:o,handlers:[],rasterCache:null,pendingCanvasPoints:[],isPointerDown:!1,isApplying:!1,commitRequested:!1,hasUncommittedChanges:!1,lastImagePoint:null};t.setMosaicSession(a),We(t,a),function(t,e){Ye(t,e,"mouse:move",e=>{const n=Yt(t.canvas,e);if(!n)return void Qe(t);qe(t,n);const i=t.getMosaicSession();(null==i?void 0:i.isPointerDown)&&en(t,n)}),Ye(t,e,"mouse:out",()=>{Qe(t);const e=t.getMosaicSession();(null==e?void 0:e.isPointerDown)&&(e.isPointerDown=!1,nn(t,e))}),Ye(t,e,"mouse:down",e=>{const n=Yt(t.canvas,e);if(!n)return;const i=t.getMosaicSession();i&&(i.isPointerDown=!0,i.lastImagePoint=null,en(t,n))}),Ye(t,e,"mouse:up",e=>{const n=t.getMosaicSession();if(!n)return;const i=Yt(t.canvas,e);i&&(qe(t,i),en(t,i)),n.isPointerDown=!1,nn(t,n)})}(t,a),e.renderAll()}function an(t){var e;const n=t.getMosaicSession();n&&(!function(t,e){for(const n of e.handlers)try{t.canvas.off(n.eventName,n.callback)}catch{}e.handlers=[]}(t,n),He(t,n),$e(t,n),function(t){const e=t.rasterCache;if(e){try{e.offscreenCanvas.width=0,e.offscreenCanvas.height=0}catch{}t.rasterCache=null}}(n),function(t){for(const e of t.prevObjectStates)try{e.object.set({evented:e.evented,selectable:e.selectable})}catch{}t.prevObjectStates=[]}(n),t.canvas.selection=!!n.prevSelection,t.canvas.defaultCursor=null!==(e=n.prevDefaultCursor)&&void 0!==e?e:"default",t.setMosaicSession(null),t.canvas.renderAll())}function rn(t){const e=t.getMosaicSession(),n=null==e?void 0:e.previewCircle;if(!e||!n)return;const i=t.getMosaicConfig();n.set({radius:i.brushSize/2,fill:i.previewFill,stroke:i.previewStroke,strokeWidth:i.previewStrokeWidth,strokeDashArray:i.previewStrokeDashArray?[...i.previewStrokeDashArray]:void 0}),t.canvas.bringObjectToFront(n),Re(t.canvas)}function sn(t,e){const n=new Image;void 0!==e.crossOrigin&&(n.crossOrigin=e.crossOrigin);const i=(t=!1)=>{if("function"==typeof n.removeEventListener?(n.removeEventListener("load",o),n.removeEventListener("error",a)):(n.onload=null,n.onerror=null),t)try{n.src=""}catch{}},o=()=>{var t,o;const a=null!==(o=null===(t=e.validate)||void 0===t?void 0:t.call(e,n))&&void 0!==o?o:null;if(a)return i(!0),void s(a);i(!1),r(n)},a=t=>{i(!0),s(e.createError(t))};let r,s;return{promise:new Promise((e,i)=>{r=e,s=i,"function"==typeof n.addEventListener?(n.addEventListener("load",o,{once:!0}),n.addEventListener("error",a,{once:!0})):(n.onload=o,n.onerror=a),n.src=t}),cleanup:i}}function ln(t,e){if("mergeAnnotations"===t){if(e instanceof le)return e;const t=e instanceof Error?`mergeAnnotations failed: ${e.message}`:"mergeAnnotations failed";return new le(t,e)}if(e instanceof se)return e;const n=e instanceof Error?`mergeMasks failed: ${e.message}`:"mergeMasks failed";return new se(n,e)}async function cn(t,e){if(!t.isImageLoaded())return;if(0===e.getTargets().length)return;const n=t.captureSnapshot(),i=e.getPreservedObjects(),o=t.containerElement?t.containerElement.scrollTop:null,a=t.containerElement?t.containerElement.scrollLeft:null;try{!function(t,e){for(const n of e)t.getObjects().includes(n)&&t.remove(n);t.discardActiveObject(),t.renderAll()}(t.canvas,i);const r=await t.exportImageBase64(e.exportOptions);if(!r)throw ln(e.operation,`${e.operation}: exportImageBase64 returned an empty data URL.`);if(e.removeTargetsNoHistory(),await t.loadImage(r,{preserveScroll:!0}),await e.restorePreservedObjects(i),Nt(t.canvas),t.canvas.renderAll(),t.updateInputs(),t.updateUi(),t.containerElement)try{null!==o&&(t.containerElement.scrollTop=o),null!==a&&(t.containerElement.scrollLeft=a)}catch(t){console.warn(`[ImageEditor] ${e.operation}: scroll restore failed`,t)}const s=t.captureSnapshot();n&&s&&n!==s&&t.historyManager.push(new ft(()=>t.loadFromState(s),()=>t.loadFromState(n)))}catch(i){try{await t.loadFromState(n)}catch(t){console.warn(`[ImageEditor] ${e.operation}: rollback failed`,t)}throw ln(e.operation,i)}}function un(t,e){const n=Number(t);if(Number.isFinite(n)&&n>0)return n;const i=Number(e);return Number.isFinite(i)&&i>0?i:1}function dn(t,e,n){const i=t,o=i[e],a="function"==typeof o?o.call(i):i[n];return Math.max(1,Math.ceil(Number.isFinite(a)?Number(a):1))}async function hn(t,e,n){return e?async function(t,e,n){if(!t.canvas)return await n();const i=t.canvas.getObjects().filter(nt),o=i.map(be);try{return i.forEach((t,n)=>e(t,n)),await n()}finally{for(const t of o)ve(t)}}({canvas:t.canvas,options:t.options},bn,n):gn(t.canvas,nt,n)}async function gn(t,e,n){const i=mn(t).filter(e).map(t=>({object:t,visible:t.visible}));for(const t of i)try{"function"==typeof t.object.set?t.object.set({visible:!1}):t.object.visible=!1}catch{}try{return await n()}finally{for(const t of i)try{"function"==typeof t.object.set?t.object.set({visible:t.visible}):t.object.visible=t.visible}catch{}pn(t)}}function mn(t){try{return t.getObjects()}catch{return[]}}function fn(t,e){return mn(t).includes(e)}function pn(t){try{"function"==typeof t.requestRenderAll?t.requestRenderAll():t.renderAll()}catch{}}function bn(t){try{t.set({opacity:1,fill:"#000",strokeWidth:0,stroke:null,selectable:!1}),"function"==typeof t.setCoords&&t.setCoords()}catch{}}function vn(t){return!!t&&(t.left||t.top||t.right||t.bottom)}function yn(t){return{width:Math.max(1,t.naturalWidth||t.width||1),height:Math.max(1,t.naturalHeight||t.height||1)}}function Cn(t){return sn(t,{crossOrigin:"anonymous",createError:()=>new Error("Failed to decode export data URL")}).promise}function Sn(t,e){return function(t,e,n="#ffffff"){const i=String(null!=t?t:"").trim();if(!i||function(t){const e=t.trim().toLowerCase();if("transparent"===e)return!0;const n=e.match(/^#([0-9a-f]{4}|[0-9a-f]{8})$/i);if(n){const t=n[1],e=4===t.length?t[3]:t.slice(6,8);return/^0+$/.test(e)}const i=e.match(/^(?:rgba|hsla)\((.*),\s*([^,/)]+)\)$/i);if(i&&Mn(i[2]))return!0;const o=e.match(/^[a-z][a-z0-9-]*\([^/]+\/\s*([^)]+)\)$/i);return!(!o||!Mn(o[1]))}(i))return"#ffffff";const o=function(t){try{return t.createElement("canvas").getContext("2d")}catch{return null}}(e);if(!o)return n;o.fillStyle="#000001";const a=o.fillStyle;o.fillStyle=i;const r=o.fillStyle;if(r!==a)return r;o.fillStyle="#000002";const s=o.fillStyle;o.fillStyle=i;const l=o.fillStyle;return l!==s?l:n}(t,e)}function In(t){var e,n,i,o;const a=t,r=null!==(i=null===(n=null===(e=a.getElement)||void 0===e?void 0:e.call(a))||void 0===n?void 0:n.ownerDocument)&&void 0!==i?i:null===(o=a.lowerCanvasEl)||void 0===o?void 0:o.ownerDocument;if(r)return r;if("undefined"!=typeof document)return document;throw new Error("Document is unavailable for export canvas creation.")}function Mn(t){const e=t.trim();if(e.endsWith("%")){const t=Number.parseFloat(e.slice(0,-1));return Number.isFinite(t)&&0===t}const n=Number.parseFloat(e);return Number.isFinite(n)&&0===n}function wn(t){console.warn(`[ImageEditor] ${t} skipped: no image is loaded on the canvas.`)}async function xn(t,e){if(!t.isImageLoaded())return wn("exportImageBase64"),"";const n=function(t){var e;try{const n=t;return"function"!=typeof n.getActiveObject?null:null!==(e=n.getActiveObject())&&void 0!==e?e:null}catch{return null}}(t.canvas),i=function(t){const e=[];for(const n of mn(t)){if(!nt(n))continue;const i=n.labelObject;if(!i)continue;const o=fn(t,i);e.push({mask:n,label:i,wasOnCanvas:o,visible:i.visible});try{"function"==typeof i.set&&i.set({visible:!1}),o&&t.remove(i)}catch{}}return e}(t.canvas);try{t.canvas.discardActiveObject();const n=function(t,e){const n=null!=e?e:{};return{exportArea:(i=n.exportArea,o=t.options.exportAreaByDefault,"canvas"===i||"image"===i?i:"canvas"===o?"canvas":"image"),mergeMasks:"boolean"==typeof n.mergeMasks?n.mergeMasks:t.options.mergeMasksByDefault,mergeAnnotations:"boolean"==typeof n.mergeAnnotations?n.mergeAnnotations:t.options.mergeAnnotationsByDefault,multiplier:un(n.multiplier,t.options.exportMultiplier),format:c(n,t.options.downsampleQuality)};var i,o}(t,e),{region:i,partialEdges:o}=function(t,e){if("canvas"===e)return{region:null,partialEdges:null};const n=t.getOriginalImage();if(!n)return{region:null,partialEdges:null};const i=Ut(n),o=t.canvas,a="function"==typeof o.getWidth?o.getWidth():o.width,r="function"==typeof o.getHeight?o.getHeight():o.height;if(!zt(i,a,r))throw new de("exportImageBase64 failed: image export region is empty.");return{region:Rt(i,a,r,{includePartialPixels:!0}),partialEdges:Ht(i,Number(n.angle)||0)}}(t,n.exportArea);!function(t,e,n){var i,o;const a=null!==(i=null==n?void 0:n.width)&&void 0!==i?i:dn(t.canvas,"getWidth","width"),r=null!==(o=null==n?void 0:n.height)&&void 0!==o?o:dn(t.canvas,"getHeight","height"),s=Math.max(1,Math.ceil(a*e)),l=Math.max(1,Math.ceil(r*e)),c=s*l,u=t.options.maxExportPixels;if(!Number.isFinite(c)||c>u)throw new RangeError(`[ImageEditor] Export size ${s}x${l} (${c} pixels) exceeds maxExportPixels (${u}).`)}(t,n.multiplier,i);const a=i&&"jpeg"===n.format.format?"png":n.format.format,r="png"===a?void 0:n.format.quality;let s=await async function(t,e){return gn(t.canvas,t=>rt(t)||!0===t.isCropRect||!0===t.maskLabel||!0===t.isMosaicPreview,e)}(t,async()=>hn(t,n.mergeMasks,async()=>async function(t,e,n){return gn(t.canvas,e?t=>it(t)&&!0===t.annotationHidden:it,n)}(t,n.mergeAnnotations,async()=>function(t,e,n,i,o){const a={format:e,multiplier:i};return void 0!==n&&(a.quality=n),o&&(a.left=o.left,a.top=o.top,a.width=o.width,a.height=o.height),t.toDataURL(a)}(t.canvas,a,r,n.multiplier,i))));if(i){const e="jpeg"===n.format.format?{format:"png",mimeType:"image/png",quality:void 0}:n.format;vn(o)&&(s=await async function(t,e,n,i){if(!vn(e))return t;const o=await Cn(t),{width:a,height:r}=yn(o),s=i.createElement("canvas");s.width=a,s.height=r;const l=s.getContext("2d");if(!l)throw new Error("2D canvas context is unavailable");l.drawImage(o,0,0,a,r);const c=l.getImageData(0,0,a,r),u=c.data,d=(t,e,n,i)=>{var o,r,s,l,c,d;const h=4*(e*a+t),g=4*(i*a+n),m=null!==(o=u[h+3])&&void 0!==o?o:0,f=null!==(r=u[g+3])&&void 0!==r?r:0;0===m&&f>0&&(u[h]=null!==(s=u[g])&&void 0!==s?s:0,u[h+1]=null!==(l=u[g+1])&&void 0!==l?l:0,u[h+2]=null!==(c=u[g+2])&&void 0!==c?c:0,u[h+3]=f);const p=null!==(d=u[h+3])&&void 0!==d?d:0;p>0&&p<255&&(u[h+3]=255)};if((null==e?void 0:e.left)&&a>1)for(let t=0;t<r;t+=1)d(0,t,1,t);if((null==e?void 0:e.right)&&a>1)for(let t=0;t<r;t+=1)d(a-1,t,a-2,t);if((null==e?void 0:e.top)&&r>1)for(let t=0;t<a;t+=1)d(t,0,t,1);if((null==e?void 0:e.bottom)&&r>1)for(let t=0;t<a;t+=1)d(t,r-1,t,r-2);return l.putImageData(c,0,0),void 0===n.quality?s.toDataURL(n.mimeType):s.toDataURL(n.mimeType,n.quality)}(s,o,e,In(t.canvas))),"jpeg"===n.format.format&&(s=await async function(t,e,n,i){const o=await Cn(t),{width:a,height:r}=yn(o),s=i.createElement("canvas");s.width=a,s.height=r;const l=s.getContext("2d");if(!l)throw new Error("2D canvas context is unavailable");return l.fillStyle=Sn(e,i),l.fillRect(0,0,a,r),l.drawImage(o,0,0,a,r),s.toDataURL("image/jpeg",n)}(s,t.options.backgroundColor,n.format.quality,In(t.canvas)))}return s}finally{!function(t,e){for(const n of e)try{n.mask.labelObject=n.label,"function"==typeof n.label.set?n.label.set({visible:n.visible}):n.label.visible=n.visible,n.wasOnCanvas&&!fn(t,n.label)&&(t.add(n.label),t.bringObjectToFront(n.label))}catch{}}(t.canvas,i),function(t,e){if(e)try{const n=t;"function"==typeof n.setActiveObject&&n.setActiveObject(e)}catch{}}(t.canvas,n),pn(t.canvas)}}async function kn(t,e){var n;if(!t.isImageLoaded())throw wn("exportImageFile"),new ue("exportImageFile");const i=null!=e?e:{},o=null!==(n=i.fileName)&&void 0!==n?n:t.options.defaultDownloadFileName,a=c(i,t.options.downsampleQuality),r=await xn(t,{exportArea:i.exportArea,mergeMasks:i.mergeMasks,mergeAnnotations:i.mergeAnnotations,multiplier:i.multiplier,quality:i.quality,fileType:i.fileType});if(!r)throw new ue("exportImageFile");const s=await async function(t,e,n,i){if(t.startsWith(`data:${e.mimeType}`))return t;const o=await Cn(t),{width:a,height:r}=yn(o),s=In(i),l=s.createElement("canvas");l.width=a,l.height=r;const c=l.getContext("2d");if(!c)throw new Error("Unable to acquire 2D context for export conversion");return"jpeg"===e.format&&(c.fillStyle=Sn(n,s),c.fillRect(0,0,a,r)),c.drawImage(o,0,0,a,r),l.toDataURL(e.mimeType,e.quality)}(r,a,t.options.backgroundColor,t.canvas);let l;try{l=function(t){var e;const n=/^data:image\/[a-z0-9.+-]+;base64,([A-Za-z0-9+/=]+)$/i.exec(t),i=null!==(e=null==n?void 0:n[1])&&void 0!==e?e:"";if(!i)throw new Error("exportImageFile received a malformed or empty image data URL.");if("function"==typeof globalThis.atob){const t=globalThis.atob(i),e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let e=t.length-1;e>=0;e-=1)n[e]=t.charCodeAt(e);return n}const o=globalThis.Buffer;if(o&&"function"==typeof o.from){const t=o.from(i,"base64"),e=new ArrayBuffer(t.length),n=new Uint8Array(e);return n.set(t),n}throw new Error("No base64 decoder is available for exportImageFile.")}(s)}catch(t){throw new de("exportImageFile failed to decode rendered data URL.",t)}return new File([l],o,{type:a.mimeType})}class On{constructor(){Object.defineProperty(this,"lastVisible",{enumerable:!0,configurable:!0,writable:!0,value:null})}measure(t,e,n){var i;if(!t)return e;const o=Math.floor(t.clientWidth),a=Math.floor(t.clientHeight);return o>0&&a>0?(this.lastVisible=function(t,e,n){if(!t)return e;const i=Math.floor(t.clientWidth||0),o=Math.floor(t.clientHeight||0);if(i<=0||o<=0)return e;const a=function(t){var e,n;const i=t.style;let o="",a="",r="";const s=null!==(n=null===(e=t.ownerDocument)||void 0===e?void 0:e.defaultView)&&void 0!==n?n:"undefined"==typeof window?null:window;if("function"==typeof(null==s?void 0:s.getComputedStyle)){const e=s.getComputedStyle(t);o=e.overflow,a=e.overflowX,r=e.overflowY}const l=[En(null==i?void 0:i.overflow),En(null==i?void 0:i.overflowX),En(o),En(a)],c=[En(null==i?void 0:i.overflow),En(null==i?void 0:i.overflowY),En(o),En(r)];return{x:l,y:c,all:[...l,...c]}}(t);if(a.all.includes("scroll"))return{width:i,height:o};const r=Bn(n),s=a.x.some(jn),l=a.y.some(jn),c=Math.ceil(t.scrollWidth||0),u=Math.ceil(t.scrollHeight||0),d=s&&c>i+An;return{width:i+(l&&u>o+An?r.width:0),height:o+(d?r.height:0)}}(t,e,n),this.lastVisible):null!==(i=this.lastVisible)&&void 0!==i?i:e}peek(){return this.lastVisible}clear(){this.lastVisible=null}}const An=.5;function En(t){return String(null!=t?t:"").trim().toLowerCase()}function jn(t){return"auto"===t||"overlay"===t}function Tn(t){const e=null!=t?t:"undefined"==typeof document?null:document;if(!(null==e?void 0:e.body))return{width:0,height:0};const n=e.createElement("div");n.style.position="absolute",n.style.left="-9999px",n.style.top="-9999px",n.style.width="100px",n.style.height="100px",n.style.overflow="scroll",n.style.visibility="hidden",n.style.pointerEvents="none",e.body.appendChild(n);const i=Math.max(0,n.offsetWidth-n.clientWidth),o=Math.max(0,n.offsetHeight-n.clientHeight);return n.remove(),{width:i,height:o}}function Bn(t){return{width:Math.max(0,Number(null==t?void 0:t.width)||0),height:Math.max(0,Number(null==t?void 0:t.height)||0)}}function Ln(t,e,n,i){const o=Math.max(1,n.width||1),a=Math.max(1,n.height||1),r=Bn(i);let s=!1,l=!1;for(let n=0;n<4;n+=1){const n=Math.max(1,o-(l?r.width:0)),i=Math.max(1,a-(s?r.height:0)),c=t>n+An,u=e>i+An;if(c===s&&u===l)break;s=c,l=u}const c=Math.max(1,o-(l?r.width:0)),u=Math.max(1,a-(s?r.height:0));return{width:s?Math.ceil(t):c,height:l?Math.ceil(e):u}}function Dn(t,e,n,i){const o=Math.max(1,Math.round(Number(e)||1)),a=Math.max(1,Math.round(Number(n)||1));var r;t.setDimensions({width:o,height:a}),(r=i)&&r.offsetWidth}async function Fn(t,e,o={}){if("string"!=typeof e||!e.startsWith("data:image/"))return;const a={placeholderHidden:t.placeholderElement?!!t.placeholderElement.hidden:null,containerScrollTop:t.containerElement?t.containerElement.scrollTop:null,containerScrollLeft:t.containerElement?t.containerElement.scrollLeft:null,originalImage:t.getOriginalImage(),isImageLoadedToCanvas:t.getIsImageLoadedToCanvas(),lastSnapshot:t.getLastSnapshot(),canvasJson:zn(t.canvas),maskCounter:t.getMaskCounter(),annotationCounter:t.getAnnotationCounter(),currentScale:t.getCurrentScale(),currentRotation:t.getCurrentRotation(),baseImageScale:t.getBaseImageScale(),currentImageMimeType:t.getCurrentImageMimeType()};try{t.setPlaceholderVisible(!1);const i=sn(e,{validate:t=>function(t){return Number.isFinite(t.naturalWidth)&&Number.isFinite(t.naturalHeight)&&t.naturalWidth>0&&t.naturalHeight>0}(t)?null:new oe("Failed to decode image data URL: image has no natural dimensions.",null),createError:t=>new oe("Failed to decode image data URL.",t)});let r;try{r=await Le(i.promise,t.options.imageLoadTimeoutMs,"image decode")}catch(t){throw i.cleanup(!0),t}const s=function(t,e,i,o){const a=Pn(Be(e));if(!i.downsampleOnLoad)return{dataUrl:e,mimeType:a};if(!Nn(i.downsampleMaxWidth)||!Nn(i.downsampleMaxHeight))return n(i,null,"loadImage skipped downsampling because downsample bounds are invalid."),{dataUrl:e,mimeType:a};const r=je(t.naturalWidth,t.naturalHeight,i.downsampleMaxWidth,i.downsampleMaxHeight);if(!r.needsResize)return{dataUrl:e,mimeType:a};const s=Be(e),l=function(t,e,n,i,o,a,r,s){var l;const{width:c,height:u}=je(t.naturalWidth,t.naturalHeight,e,n),d=function(t,e,n){return n||(!e||"image/png"!==t&&"image/webp"!==t?"image/jpeg":t)}(i,o,a),h=null!==(l=null!=s?s:t.ownerDocument)&&void 0!==l?l:"undefined"!=typeof document?document:null;if(!h)throw new re("Failed to obtain an owner document for downsampling.");const g=h.createElement("canvas");g.width=c,g.height=u;const m=g.getContext("2d");if(!m)throw new re("Failed to obtain a 2D context for downsampling.");return m.drawImage(t,0,0,t.naturalWidth,t.naturalHeight,0,0,c,u),{dataUrl:"image/png"===d?g.toDataURL(d):g.toDataURL(d,r),width:c,height:u,mimeType:d}}(t,i.downsampleMaxWidth,i.downsampleMaxHeight,s,i.preserveSourceFormat,i.downsampleMimeType,i.downsampleQuality,o),c=Pn(Be(l.dataUrl));return{dataUrl:l.dataUrl,mimeType:null!=c?c:l.mimeType}}(r,e,t.options,function(t){var e,n,i,o,a;const r=t;return null!==(a=null!==(i=null===(n=null===(e=r.getElement)||void 0===e?void 0:e.call(r))||void 0===n?void 0:n.ownerDocument)&&void 0!==i?i:null===(o=r.lowerCanvasEl)||void 0===o?void 0:o.ownerDocument)&&void 0!==a?a:"undefined"!=typeof document?document:void 0}(t.canvas)),l=await Le(t.fabric.FabricImage.fromURL(s.dataUrl,{crossOrigin:"anonymous"}),t.options.imageLoadTimeoutMs,"FabricImage.fromURL");t.canvas.discardActiveObject(),t.canvas.clear(),t.canvas.backgroundColor=t.options.backgroundColor;const c=lt(l);c.set({originX:"left",originY:"top",selectable:!1,evented:!1});const u=function(t,e){var n,i,o,a;const r=null!==(n=e.width)&&void 0!==n?n:0,s=null!==(i=e.height)&&void 0!==i?i:0,l=Tn(null!==(a=null===(o=t.containerElement)||void 0===o?void 0:o.ownerDocument)&&void 0!==a?a:null),c=t.viewportCache.measure(t.containerElement,{width:t.options.canvasWidth,height:t.options.canvasHeight},l),u=t.options.layoutMode;if("fit"===u)return function(t,e,n,i,o){const a=Math.max(1,(o.width||n)-1),r=Math.max(1,(o.height||i)-1),s=Math.min(a/t,r/e,1);return{canvasWidth:a,canvasHeight:r,imageScale:s,imageLeft:0,imageTop:0,baseImageScale:s}}(r,s,t.options.canvasWidth,t.options.canvasHeight,c);if("cover"===u)return function(t,e,n,i,o,a){const r=o.width||n,s=o.height||i,l=Bn(a);let c=!1,u=!1,d=1,h=t,g=e;for(let n=0;n<4;n+=1){const n=Math.max(1,r-(u?l.width:0)),i=Math.max(1,s-(c?l.height:0));d=Math.min(1,Math.max(n/t,i/e)),h=t*d,g=e*d;const o=h>n+An,a=g>i+An;if(o===c&&a===u)break;c=o,u=a}const m=Ln(h,g,{width:r,height:s},l);return{canvasWidth:m.width,canvasHeight:m.height,imageScale:d,imageLeft:0,imageTop:0,baseImageScale:d}}(r,s,t.options.canvasWidth,t.options.canvasHeight,c,l);return function(t,e,n,i,o){return{canvasWidth:Math.max(o.width,Math.floor(t)),canvasHeight:Math.max(o.height,Math.floor(e)),imageScale:1,imageLeft:0,imageTop:0,baseImageScale:1}}(r,s,t.options.canvasWidth,t.options.canvasHeight,c)}(t,c);if(Dn(t.canvas,u.canvasWidth,u.canvasHeight,t.containerElement),c.set({left:u.imageLeft,top:u.imageTop}),c.scale(u.imageScale),t.canvas.add(c),t.canvas.sendObjectToBack(c),t.setOriginalImage(c),t.setBaseImageScale(u.baseImageScale),t.setCurrentScale(1),t.setCurrentRotation(0),t.setMaskCounter(0),t.setAnnotationCounter(0),t.setIsImageLoadedToCanvas(!0),t.setCurrentImageMimeType(s.mimeType),t.canvas.renderAll(),t.setLastSnapshot(gt({canvas:t.canvas,currentScale:1,currentRotation:0,baseImageScale:u.baseImageScale,currentImageMimeType:s.mimeType})),!0===o.preserveScroll&&t.containerElement)try{null!==a.containerScrollTop&&(t.containerElement.scrollTop=a.containerScrollTop),null!==a.containerScrollLeft&&(t.containerElement.scrollLeft=a.containerScrollLeft)}catch(t){console.warn("[ImageEditor] preserveScroll restore failed",t)}}catch(e){await async function(t,e){try{await t.canvas.loadFromJSON(JSON.parse(e.canvasJson)),t.canvas.renderAll()}catch(t){console.warn("[ImageEditor] rollback: loadFromJSON failed",t)}if(t.setOriginalImage(e.originalImage),t.setIsImageLoadedToCanvas(e.isImageLoadedToCanvas),t.setLastSnapshot(e.lastSnapshot),t.setMaskCounter(e.maskCounter),t.setAnnotationCounter(e.annotationCounter),t.setCurrentScale(e.currentScale),t.setCurrentRotation(e.currentRotation),t.setBaseImageScale(e.baseImageScale),t.setCurrentImageMimeType(e.currentImageMimeType),t.containerElement)try{null!==e.containerScrollTop&&(t.containerElement.scrollTop=e.containerScrollTop),null!==e.containerScrollLeft&&(t.containerElement.scrollLeft=e.containerScrollLeft)}catch(t){console.warn("[ImageEditor] rollback: scroll restore failed",t)}null!==e.placeholderHidden&&t.setPlaceholderVisible(!e.placeholderHidden)}(t,a);const n=e instanceof Error?`loadImage failed: ${e.message}`:"loadImage failed";throw i(t.options,e,n),e}}function Nn(t){return Number.isFinite(t)&&t>0}function Pn(t){return"image/jpeg"===t||"image/png"===t||"image/webp"===t?t:null}function zn(t){t.discardActiveObject();const e=t.toJSON(ht);return JSON.stringify(e)}function Rn(t,e,n,i){return new Promise((o,a)=>{const r=Object.keys(e).length;if(0===r||i.isDisposed())return void o();let s=0,l=!1,c=[],u=null,d=null;const h=()=>{null!==u&&(clearTimeout(u),u=null),null==d||d(),d=null},g=()=>{l||(l=!0,h(),o())},m=()=>{for(const t of c)try{t()}catch{}g()},f=Number.isFinite(n.duration)?Math.max(0,n.duration):0;u=setTimeout(m,f+1e3),d=i.registerAnimationAborter(m);try{const o=t.animate(e,{duration:n.duration,onChange:()=>{var t;i.isDisposed()||null===(t=n.onChange)||void 0===t||t.call(n)},onComplete:()=>{++s>=r&&g()}});c=function(t){const e=Array.isArray(t)?t:t&&"object"==typeof t?Object.values(t):[t];return e.flatMap(t=>{const e=null==t?void 0:t.abort;return"function"==typeof e?[()=>e.call(t)]:[]})}(o)}catch(t){(t=>{l||(l=!0,h(),a(t))})(t)}})}class Wn{constructor(t){Object.defineProperty(this,"context",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.context=t}async scaleImage(t){if(!Number.isFinite(t))return;const e=this.context.getOriginalImage();if(!e)return;if(this.context.guard.isAnimating())return;if(this.context.guard.isDisposed())return;const n=Math.max(this.context.options.minScale,Math.min(this.context.options.maxScale,t));this.context.setCurrentScale(n);const i=this.context.getBaseImageScale()*n;try{const t=Hn(e);e.set({originX:"left",originY:"top"}),e.setPositionByOrigin(t,"left","top"),e.setCoords()}catch(t){console.warn("[ImageEditor] scaleImage: origin pre-anchor failed",t)}try{await this.context.guard.runAnimation(()=>Rn(e,{scaleX:i,scaleY:i},{duration:this.context.options.animationDuration,onChange:()=>this.context.canvas.requestRenderAll()},this.context.guard))}catch(t){return void console.warn("[ImageEditor] scaleImage animation error",t)}this.context.guard.isDisposed()||(e.set({scaleX:i,scaleY:i}),e.setCoords(),this.context.afterTransformSnap&&this.context.afterTransformSnap(),this.context.saveCanvasState())}async rotateImage(t){if(!Number.isFinite(t))return;const e=this.context.getOriginalImage();if(!e)return;if(this.context.guard.isAnimating())return;if(this.context.guard.isDisposed())return;this.context.setCurrentRotation(t);try{const t=e.getCenterPoint();e.set({originX:"center",originY:"center"}),e.setPositionByOrigin(t,"center","center"),e.setCoords()}catch(t){console.warn("[ImageEditor] rotateImage: origin pre-anchor failed",t)}let n=!1;try{await this.context.guard.runAnimation(()=>Rn(e,{angle:t},{duration:this.context.options.animationDuration,onChange:()=>this.context.canvas.requestRenderAll()},this.context.guard))}catch(t){n=!0,console.warn("[ImageEditor] rotateImage animation error",t)}finally{this.context.guard.isDisposed()&&function(t,e,n){try{t.set({originX:e,originY:n}),t.setCoords()}catch{}}(e,"left","top")}if(!n&&!this.context.guard.isDisposed()){e.set("angle",t),e.setCoords(),this.context.afterTransformSnap&&this.context.afterTransformSnap();try{const t=Hn(e);e.set({originX:"left",originY:"top"}),e.setPositionByOrigin(t,"left","top"),e.setCoords()}catch(t){console.warn("[ImageEditor] rotateImage: origin post-restore failed",t)}this.context.saveCanvasState()}}async resetImageTransform(){if(this.context.getOriginalImage()){this.context.setSuppressSaveState(!0);try{await this.scaleImage(1),await this.rotateImage(0)}finally{this.context.setSuppressSaveState(!1)}this.context.guard.isDisposed()||this.context.saveCanvasState()}}}function Hn(t){t.setCoords();const e=t.getCoords()[0];if(e)return e;const n=t.getBoundingRect();return{x:n.left,y:n.top}}function Un(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function $n(t,e){n(t,null,`createMask skipped: ${e}.`)}function Qn(t){return void 0===t||("number"==typeof t?Number.isFinite(t):"function"==typeof t||!("string"!=typeof t||!t.endsWith("%"))&&Number.isFinite(Number.parseFloat(t)))}function qn(t){return"number"==typeof t&&Number.isFinite(t)}function Yn(t,e,n){return!!qn(n)||($n(t,`${e} must resolve to a finite number`),!1)}function Xn(t,e,n){return!!(qn(n)&&n>0)||($n(t,`${e} must resolve to a positive number`),!1)}function Gn(t,e,n){return!!(qn(n)&&n>=0)||($n(t,`${e} must resolve to a non-negative number`),!1)}function Kn(t,e){if(!Array.isArray(e)||e.length<3)return $n(t,"polygon masks require at least three points"),null;const n=e.map(Qt);return n.every(t=>Number.isFinite(t.x)&&Number.isFinite(t.y))?function(t){let e=0;for(let n=0;n<t.length;n+=1){const i=t[n],o=t[(n+1)%t.length];e+=i.x*o.y-o.x*i.y}return Math.abs(e)/2}(n)<=1e-6?($n(t,"polygon points must describe a non-zero area"),null):n:($n(t,"polygon points must contain finite x/y values"),null)}function Vn(t,e={}){var i,o,a,r,s,l,c,u,d,h,g,m,f,p,b,v;const{canvas:y,options:C,fabric:S}=t;if(!y)return null;const I=function(t,e){const n={...t},i=n.styles;delete n.onCreate,delete n.fabricGenerator,delete n.styles;const o=Un(e.styles)?e.styles:{},a=Un(i)?i:{};return{...n,...e,styles:{...a,...o}}}(C.defaultMaskConfig,e),M=null!==(i=I.shape)&&void 0!==i?i:"rect";if(!function(t,e){const n=[["width",e.width],["height",e.height],["rx",e.rx],["ry",e.ry],["radius",e.radius],["left",e.left],["top",e.top]];for(const[e,i]of n)if(!Qn(i))return $n(t,`${e} is not a supported numeric value`),!1;return!0}(C,I))return null;const w={width:C.defaultMaskWidth,height:C.defaultMaskHeight,color:"rgba(0,0,0,0.5)",alpha:.5,gap:5,left:void 0,top:void 0,angle:0,selectable:!0,...I,shape:M};let x,k;const O=t.getLastMask();if(void 0===I.left&&O){const t=(null!==(o=O.left)&&void 0!==o?o:0)+("function"==typeof O.getScaledWidth?O.getScaledWidth():(null!==(a=O.width)&&void 0!==a?a:0)*(null!==(r=O.scaleX)&&void 0!==r?r:1));x=Math.round(t+(null!==(s=w.gap)&&void 0!==s?s:5)),k=null!==(l=O.top)&&void 0!==l?l:10}else x=$t(I.left,"x",10,y,C),k=$t(I.top,"y",10,y,C);w.width=$t(I.width,"x",C.defaultMaskWidth,y,C),w.height=$t(I.height,"y",C.defaultMaskHeight,y,C);const A=void 0!==I.rx?$t(I.rx,"x",0,y,C):void 0,E=void 0!==I.ry?$t(I.ry,"y",0,y,C):void 0,j="circle"===M?$t(I.radius,"x",Math.min(w.width,w.height)/2,y,C):void 0,T="polygon"===M?Kn(C,I.points):null;if(!(Yn(C,"left",x)&&Yn(C,"top",k)&&Xn(C,"width",w.width)&&Xn(C,"height",w.height)&&Yn(C,"gap",w.gap)&&Yn(C,"angle",w.angle)&&Yn(C,"alpha",w.alpha)))return null;if(void 0!==A&&!Gn(C,"rx",A)||void 0!==E&&!Gn(C,"ry",E)||void 0!==j&&!Xn(C,"radius",j)||"polygon"===M&&null===T)return null;if("expand"===C.layoutMode){const e=Math.ceil(x+w.width+10),n=Math.ceil(k+w.height+10),i=Math.max(y.getWidth(),e),o=Math.max(y.getHeight(),n);i===y.getWidth()&&o===y.getHeight()||(t.expandCanvasIfNeeded?t.expandCanvasIfNeeded(i,o):y.setDimensions({width:i,height:o}))}let B;if("function"==typeof e.fabricGenerator){const t=e.fabricGenerator(w,y,C);if(!function(t){if(!t||"object"!=typeof t)return!1;const e=t;return"function"==typeof e.set&&"function"==typeof e.on}(t))return n(C,t,"createMask skipped: fabricGenerator did not return a Fabric object."),null;B=t}else{const t={originX:"left",originY:"top"};switch(M){case"circle":B=new S.Circle({left:x,top:k,...t,radius:j,fill:w.color,opacity:w.alpha,angle:null!==(c=w.angle)&&void 0!==c?c:0,...w.styles});break;case"ellipse":B=new S.Ellipse({left:x,top:k,...t,rx:null!=A?A:w.width/2,ry:null!=E?E:w.height/2,fill:w.color,opacity:w.alpha,angle:null!==(u=w.angle)&&void 0!==u?u:0,...w.styles});break;case"polygon":{const e=new S.Polygon(T,{...t,fill:w.color,opacity:w.alpha,angle:null!==(d=w.angle)&&void 0!==d?d:0,...w.styles});e.setCoords();const n=e.getBoundingRect(),i=x-n.left,o=k-n.top;e.set({left:(null!==(h=e.left)&&void 0!==h?h:0)+i,top:(null!==(g=e.top)&&void 0!==g?g:0)+o}),e.setCoords(),B=e;break}default:B=new S.Rect({left:x,top:k,...t,width:w.width,height:w.height,fill:w.color,opacity:w.alpha,angle:null!==(m=w.angle)&&void 0!==m?m:0,...void 0!==A?{rx:A}:{},...void 0!==E?{ry:E}:{},...w.styles})}}const L=B;L.selectable=!("selectable"in I)||!!I.selectable,L.evented=!("evented"in I)||!!I.evented,L.hasControls=!("hasControls"in I)||!!I.hasControls,L.transparentCorners="transparentCorners"in I&&!!I.transparentCorners,L.strokeUniform=!("strokeUniform"in I)||!!I.strokeUniform,L.lockRotation=!C.maskRotatable,L.borderColor=null!==(f=I.borderColor)&&void 0!==f?f:"red",L.cornerColor=null!==(p=I.cornerColor)&&void 0!==p?p:"black",L.cornerSize=null!==(b=I.cornerSize)&&void 0!==b?b:8;const D=null!==(v=w.styles)&&void 0!==v?v:{};L.stroke="stroke"in D?D.stroke:"#ccc",L.strokeWidth="strokeWidth"in D?D.strokeWidth:1,"strokeDashArray"in D&&(L.strokeDashArray=D.strokeDashArray);const F=t.getMaskCounter()+1;var N;if(t.setMaskCounter(F),ct(L,{maskId:F,maskUid:(N=F,`mask-${N}`),maskName:`${C.maskName}${F}`,originalAlpha:w.alpha,originalStroke:L.stroke,originalStrokeWidth:L.strokeWidth}),me(L),t.setLastMask(L),function(t,e){Lt(t,e);const n=Dt(t,e),i=Ft(n);Bt(t,e,-1===i?n.length:i)}(y,L),t.updateMaskList(),!1!==w.selectable&&y.setActiveObject(L),y.renderAll(),t.saveCanvasState(),"function"==typeof e.onCreate)try{e.onCreate(L,y)}catch(t){n(C,t,"createMask onCreate callback threw.")}return L}function _n(t){const e=function(t){const e=t.getActiveObject();if(!e)return[];if(!function(t){if(!t)return!1;if("activeselection"===("string"==typeof t.type?t.type.toLowerCase():""))return!0;const e=t.isType;return"function"==typeof e&&(e.call(t,"ActiveSelection")||e.call(t,"activeSelection"))}(e))return nt(e)?[e]:[];const n=e.getObjects;return("function"==typeof n?n.call(e):[]).filter(nt)}(t.canvas);if(0!==e.length){for(const n of e)t.removeLabelForMask(n),pe(n),t.canvas.remove(n);t.canvas.discardActiveObject(),t.updateMaskList(),t.canvas.renderAll(),t.saveCanvasState()}}function Jn(t,e={}){const n=t.canvas.getObjects().filter(nt);if(0!==n.length){for(const e of n)t.removeLabelForMask(e),pe(e),t.canvas.remove(e);t.canvas.discardActiveObject(),t.setLastMask(null),t.updateMaskList(),t.canvas.renderAll(),!1!==e.saveHistory&&t.saveCanvasState()}}function Zn(t,e){if(t.canvas&&e.labelObject){try{t.canvas.getObjects().includes(e.labelObject)&&t.canvas.remove(e.labelObject)}catch{}try{delete e.labelObject}catch{}}}function ti(t,e){var i;const{canvas:o,options:a,fabric:r}=t;if(!o||!a.maskLabelOnSelect)return;Zn(t,e);let s=null;if("function"==typeof a.label.create)try{s=a.label.create(e,r)}catch(t){n(a,t,"label.create callback threw."),s=null}if(!s){const t=e.maskId-1;let o=e.maskName;if("function"==typeof a.label.getText)try{o=a.label.getText(e,t)}catch(t){n(a,t,"label.getText callback threw."),o=e.maskName}const l={left:0,top:0,...null!==(i=a.label.textOptions)&&void 0!==i?i:{},originX:"left",originY:"top"};s=new r.FabricText(o,l)}dt(s,"maskLabel"),s.maskLabel=!0,e.labelObject=s,o.add(s),o.bringObjectToFront(s),ei(t,e)}function ei(t,e){var n,i,o;const{canvas:a,options:r}=t;if(!a||!r.maskLabelOnSelect||!e.labelObject)return;const s=null===(n=e.getCoords)||void 0===n?void 0:n.call(e);if(!(null==s?void 0:s.length))return;const l=s[0];if(!l)return;const c=e.getCenterPoint(),u=c.x-l.x,d=c.y-l.y,h=Math.sqrt(u*u+d*d)||1,g=Math.max(0,null!==(i=r.maskLabelOffset)&&void 0!==i?i:3);e.labelObject.set({left:Math.round(l.x+u/h*g),top:Math.round(l.y+d/h*g),angle:null!==(o=e.angle)&&void 0!==o?o:0,originX:"left",originY:"top",visible:!0}),e.labelObject.setCoords(),a.renderAll()}function ni(t){var e,n,i,o,a;const r=t.canvas;return null!==(a=null!==(i=null===(n=null===(e=null==r?void 0:r.getElement)||void 0===e?void 0:e.call(r))||void 0===n?void 0:n.ownerDocument)&&void 0!==i?i:null===(o=null==r?void 0:r.lowerCanvasEl)||void 0===o?void 0:o.ownerDocument)&&void 0!==a?a:document}class ii{constructor(t,e,n=()=>document){Object.defineProperty(this,"registry",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"resolveElementId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isDisposed",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"resolveDocument",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.resolveElementId=t,this.isDisposed=e,this.resolveDocument=n}bindIfExists(t,e,n){const i=this.resolveElementId(t);if(!i)return!1;const o=this.resolveDocument().getElementById(i);if(!o)return!1;const a=t=>{this.isDisposed()||n(t)};return o.addEventListener(e,a),this.registry.push({elementKey:t,eventType:e,handler:a}),!0}removeAll(){for(const t of this.registry){const e=this.resolveElementId(t.elementKey);if(!e)continue;const n=this.resolveDocument().getElementById(e);if(n)try{n.removeEventListener(t.eventType,t.handler)}catch{}}this.registry=[]}size(){return this.registry.length}}function oi(t,e,n){t&&(t.hidden=!n,t.setAttribute("aria-hidden",n?"false":"true")),e&&(e.hidden=n,e.setAttribute("aria-hidden",n?"true":"false"))}const ai={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp"},ri=new Set(Object.values(ai));function si(t){if(t)try{t.value=""}catch{}}const li=.5,ci=Symbol("ImageEditorInternalOperation"),ui=Symbol("ImageEditorAllowDuringAnimationQueue"),di=["scalePercentageInput","rotateLeftDegreesInput","rotateRightDegreesInput","rotateLeftButton","rotateRightButton","createMaskButton","removeSelectedMaskButton","removeAllMasksButton","mergeMasksButton","mergeAnnotationsButton","enterTextModeButton","exitTextModeButton","textColorInput","textFontSizeInput","enterDrawModeButton","exitDrawModeButton","drawColorInput","drawBrushSizeInput","removeSelectedAnnotationButton","removeAllAnnotationsButton","deleteSelectedObjectButton","bringSelectedObjectForwardButton","sendSelectedObjectBackwardButton","bringSelectedObjectToFrontButton","sendSelectedObjectToBackButton","downloadImageButton","zoomInButton","zoomOutButton","resetImageTransformButton","undoButton","redoButton","imageInput","enterCropModeButton","applyCropButton","cancelCropButton","enterMosaicModeButton","exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],hi=["applyCropButton","cancelCropButton"],gi=new Set(["applyCrop","cancelCrop"]),mi=["exitTextModeButton","textColorInput","textFontSizeInput"],fi=["exitDrawModeButton","drawColorInput","drawBrushSizeInput"],pi=["scalePercentageInput","rotateLeftDegreesInput","rotateRightDegreesInput","rotateLeftButton","rotateRightButton","createMaskButton","removeSelectedMaskButton","removeAllMasksButton","mergeMasksButton","mergeAnnotationsButton","enterTextModeButton","exitTextModeButton","textColorInput","textFontSizeInput","enterDrawModeButton","exitDrawModeButton","drawColorInput","drawBrushSizeInput","removeSelectedAnnotationButton","removeAllAnnotationsButton","deleteSelectedObjectButton","bringSelectedObjectForwardButton","sendSelectedObjectBackwardButton","bringSelectedObjectToFrontButton","sendSelectedObjectToBackButton","downloadImageButton","zoomInButton","zoomOutButton","resetImageTransformButton","undoButton","redoButton","imageInput","enterCropModeButton","applyCropButton","cancelCropButton","enterMosaicModeButton","exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],bi=["exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],vi=new Set(["exitMosaicMode","applyMosaic","setMosaicConfig","resetMosaicConfig","setMosaicBrushSize","setMosaicBlockSize","saveState"]),yi=new Set(["init","loadImage","loadFromState","saveState","scaleImage","rotateImage","resetImageTransform","createMask","removeSelectedMask","removeAllMasks","mergeMasks","createTextAnnotation","enterTextMode","exitTextMode","setTextConfig","resetTextConfig","setTextColor","setTextFontSize","enterDrawMode","exitDrawMode","setDrawConfig","resetDrawConfig","setDrawColor","setDrawBrushSize","updateSelectedAnnotation","updateAnnotation","removeSelectedAnnotation","removeAllAnnotations","deleteSelectedObject","mergeAnnotations","bringSelectedObjectForward","sendSelectedObjectBackward","bringSelectedObjectToFront","sendSelectedObjectToBack","enterCropMode","applyCrop","cancelCrop","enterMosaicMode","exitMosaicMode","applyMosaic","setMosaicConfig","resetMosaicConfig","setMosaicBrushSize","setMosaicBlockSize","undo","redo","exportImageBase64","exportImageFile","downloadImage","dispose"]),Ci={crop:gi,mosaic:vi,text:new Set(["exitTextMode","createTextAnnotation","setTextConfig","resetTextConfig","setTextColor","setTextFontSize","saveState"]),draw:new Set(["exitDrawMode","setDrawConfig","resetDrawConfig","setDrawColor","setDrawBrushSize","saveState"])};class Si{constructor(t={},i={}){var o;Object.defineProperty(this,"fabricModule",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isFabricLoaded",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentLayoutMode",{enumerable:!0,configurable:!0,writable:!0,value:"expand"}),Object.defineProperty(this,"defaultMosaicConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentMosaicConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"defaultTextConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentTextConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"defaultDrawConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"currentDrawConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"canvas",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"canvasElement",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"containerElement",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"placeholderElement",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"elements",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"elementOriginalDisabledMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"elementOriginalAriaDisabledMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"elementOriginalPointerEventsMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"originalImage",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"baseImageScale",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"currentScale",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"currentRotation",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"isImageLoadedToCanvas",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"currentImageMimeType",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"maskCounter",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"lastMask",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"annotationCounter",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"lastSnapshot",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"historyManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"operationGuard",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"animQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"transformController",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"viewportCache",{enumerable:!0,configurable:!0,writable:!0,value:new On}),Object.defineProperty(this,"cropSession",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"mosaicSession",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"textSession",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"drawSession",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"domBindings",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"keyboardDocument",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"keyboardHandler",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isDisposed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"shouldSuppressSaveState",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lastEmittedIsBusy",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"activeStateRestoreOperation",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextSelectionChangeContext",{enumerable:!0,configurable:!0,writable:!0,value:null});const a=function(t,e,n=globalThis){var i;if(bt(t))return{fabric:t,isFabricLoaded:!0,options:null!=e?e:{}};const o=null!==(i=t)&&void 0!==i?i:{},a=function(t){return t.fabric}(n);return bt(a)?{fabric:a,isFabricLoaded:!0,options:o}:(console.error("[ImageEditor] fabric.js v7 is not available. Pass it as the first constructor argument (ESM) or load it as a global <script> before instantiation."),{fabric:null,isFabricLoaded:!1,options:o})}(t,i);this.fabricModule=null!==(o=a.fabric)&&void 0!==o?o:{},this.isFabricLoaded=a.isFabricLoaded,this.options=Z(a.options),this.currentLayoutMode=this.options.layoutMode,this.defaultMosaicConfig=this.options.defaultMosaicConfig,this.currentMosaicConfig=U(this.defaultMosaicConfig),this.defaultTextConfig=this.options.defaultTextConfig,this.currentTextConfig=q(this.defaultTextConfig),this.defaultDrawConfig=this.options.defaultDrawConfig,this.currentDrawConfig=Y(this.defaultDrawConfig);const r=a.options.defaultLayoutMode;void 0===r||O(r)||n(this.options,new TypeError(`[ImageEditor] Unsupported defaultLayoutMode ${JSON.stringify(r)}. Expected "fit", "cover", or "expand".`),'Invalid defaultLayoutMode fell back to "expand".'),this.operationGuard=new tt,this.animQueue=new e,this.historyManager=new pt(this.options.maxHistorySize)}init(t={}){if(!this.isFabricLoaded){const t=globalThis.fabric;if(!t||"function"!=typeof t.Canvas)return;this.fabricModule=t,this.isFabricLoaded=!0}if(this.isDisposed)return;this.elements={canvas:"canvas",canvasContainer:null,imagePlaceholder:"imagePlaceholder",scalePercentageInput:"scalePercentageInput",rotateLeftDegreesInput:"rotateLeftDegreesInput",rotateRightDegreesInput:"rotateRightDegreesInput",rotateLeftButton:"rotateLeftButton",rotateRightButton:"rotateRightButton",createMaskButton:"createMaskButton",removeSelectedMaskButton:"removeSelectedMaskButton",removeAllMasksButton:"removeAllMasksButton",mergeMasksButton:"mergeMasksButton",annotationList:"annotationList",enterTextModeButton:"enterTextModeButton",exitTextModeButton:"exitTextModeButton",textColorInput:"textColorInput",textFontSizeInput:"textFontSizeInput",enterDrawModeButton:"enterDrawModeButton",exitDrawModeButton:"exitDrawModeButton",drawColorInput:"drawColorInput",drawBrushSizeInput:"drawBrushSizeInput",removeSelectedAnnotationButton:"removeSelectedAnnotationButton",removeAllAnnotationsButton:"removeAllAnnotationsButton",deleteSelectedObjectButton:"deleteSelectedObjectButton",mergeAnnotationsButton:"mergeAnnotationsButton",bringSelectedObjectForwardButton:"bringSelectedObjectForwardButton",sendSelectedObjectBackwardButton:"sendSelectedObjectBackwardButton",bringSelectedObjectToFrontButton:"bringSelectedObjectToFrontButton",sendSelectedObjectToBackButton:"sendSelectedObjectToBackButton",downloadImageButton:"downloadImageButton",maskList:"maskList",zoomInButton:"zoomInButton",zoomOutButton:"zoomOutButton",resetImageTransformButton:"resetImageTransformButton",undoButton:"undoButton",redoButton:"redoButton",imageInput:"imageInput",enterCropModeButton:"enterCropModeButton",applyCropButton:"applyCropButton",cancelCropButton:"cancelCropButton",enterMosaicModeButton:"enterMosaicModeButton",exitMosaicModeButton:"exitMosaicModeButton",mosaicBrushSizeInput:"mosaicBrushSizeInput",mosaicBlockSizeInput:"mosaicBlockSizeInput",uploadArea:"uploadArea",...t},this.initCanvas(),this.domBindings=new ii(t=>this.elements[t],()=>this.isDisposed,()=>{var t,e;return null!==(e=null===(t=this.canvasElement)||void 0===t?void 0:t.ownerDocument)&&void 0!==e?e:document}),this.transformController=new Wn(this.buildTransformContext()),this.bindDomEvents(),this.updateInputs(),this.updateMaskList(),this.updateAnnotationList(),this.updateUi(),this.options.initialImageBase64?this.loadImage(this.options.initialImageBase64).catch(()=>{}):this.updatePlaceholderStatus()}initCanvas(){var t;const e=this.elements.canvas,n=e?document.getElementById(e):null;if(!n)throw new Error(`[ImageEditor] Canvas element not found: "${e}"`);this.canvasElement=n;const i=this.elements.canvasContainer;this.containerElement=i&&null!==(t=document.getElementById(i))&&void 0!==t?t:n.parentElement;const o=this.elements.imagePlaceholder;this.placeholderElement=o?document.getElementById(o):null;let a=this.options.canvasWidth,r=this.options.canvasHeight;if(this.containerElement){const t=Math.floor(this.containerElement.clientWidth),e=Math.floor(this.containerElement.clientHeight);t>0&&e>0&&(a=t,r=e)}this.canvas=new this.fabricModule.Canvas(n,{width:a,height:r,backgroundColor:this.options.backgroundColor,selection:this.options.groupSelection,preserveObjectStacking:!0}),this.canvas.on("selection:created",t=>{this.handleSelectionChanged(t.selected)}),this.canvas.on("selection:updated",t=>{this.handleSelectionChanged(t.selected)}),this.canvas.on("selection:cleared",()=>this.handleSelectionChanged([]));const s=t=>{t.target&&this.handleObjectMovingScalingRotating(t.target)};this.canvas.on("object:moving",s),this.canvas.on("object:scaling",s),this.canvas.on("object:rotating",s),this.canvas.on("object:modified",t=>{t.target&&this.handleObjectModified(t.target)})}getLiveCanvasOrThrow(t){if(this.isDisposed||!this.canvas)throw new Error(`[ImageEditor] Cannot run "${t}" after dispose.`);return this.canvas}bindDomEvents(){this.bindElementIfExists("uploadArea","click",()=>{var t;const e=this.elements.imageInput;e&&(null===(t=document.getElementById(e))||void 0===t||t.click())}),this.bindElementIfExists("imageInput","change",t=>{var e;const n=null===(e=t.target.files)||void 0===e?void 0:e[0];n&&this.loadImageFile(n)}),this.bindElementIfExists("zoomInButton","click",()=>{this.scaleImage(this.currentScale+this.options.scaleStep)}),this.bindElementIfExists("zoomOutButton","click",()=>{this.scaleImage(this.currentScale-this.options.scaleStep)}),this.bindElementIfExists("resetImageTransformButton","click",()=>{this.resetImageTransform()}),this.bindElementIfExists("createMaskButton","click",()=>{this.createMask()}),this.bindElementIfExists("removeSelectedMaskButton","click",()=>{this.removeSelectedMask()}),this.bindElementIfExists("removeAllMasksButton","click",()=>{this.removeAllMasks()}),this.bindElementIfExists("mergeMasksButton","click",()=>{this.mergeMasks()}),this.bindElementIfExists("mergeAnnotationsButton","click",()=>{this.mergeAnnotations()}),this.bindElementIfExists("enterTextModeButton","click",()=>{this.enterTextMode()}),this.bindElementIfExists("exitTextModeButton","click",()=>{this.exitTextMode()}),this.bindElementIfExists("enterDrawModeButton","click",()=>{this.enterDrawMode()}),this.bindElementIfExists("exitDrawModeButton","click",()=>{this.exitDrawMode()}),this.bindElementIfExists("removeSelectedAnnotationButton","click",()=>{this.removeSelectedAnnotation()}),this.bindElementIfExists("removeAllAnnotationsButton","click",()=>{this.removeAllAnnotations()}),this.bindElementIfExists("deleteSelectedObjectButton","click",()=>{this.deleteSelectedObject()}),this.bindElementIfExists("bringSelectedObjectForwardButton","click",()=>{this.bringSelectedObjectForward()}),this.bindElementIfExists("sendSelectedObjectBackwardButton","click",()=>{this.sendSelectedObjectBackward()}),this.bindElementIfExists("bringSelectedObjectToFrontButton","click",()=>{this.bringSelectedObjectToFront()}),this.bindElementIfExists("sendSelectedObjectToBackButton","click",()=>{this.sendSelectedObjectToBack()}),this.bindElementIfExists("downloadImageButton","click",()=>{this.downloadImage()}),this.bindElementIfExists("undoButton","click",()=>{this.undo()}),this.bindElementIfExists("redoButton","click",()=>{this.redo()}),this.bindElementIfExists("rotateLeftButton","click",()=>{const t=this.elements.rotateLeftDegreesInput,e=t?document.getElementById(t):null;let n=this.options.rotationStep;if(e){const t=parseFloat(e.value);isNaN(t)||(n=t)}this.rotateImage(this.currentRotation-n)}),this.bindElementIfExists("rotateRightButton","click",()=>{const t=this.elements.rotateRightDegreesInput,e=t?document.getElementById(t):null;let n=this.options.rotationStep;if(e){const t=parseFloat(e.value);isNaN(t)||(n=t)}this.rotateImage(this.currentRotation+n)}),this.bindElementIfExists("enterCropModeButton","click",()=>{this.enterCropMode()}),this.bindElementIfExists("applyCropButton","click",()=>{this.applyCrop().catch(t=>{i(this.options,t,"Crop apply failed.")})}),this.bindElementIfExists("cancelCropButton","click",()=>{this.cancelCrop()}),this.bindElementIfExists("enterMosaicModeButton","click",()=>{this.enterMosaicMode()}),this.bindElementIfExists("exitMosaicModeButton","click",()=>{this.exitMosaicMode()});const t=(t,e)=>{const n=t=>{const n=parseFloat(t.target.value);e(n)};this.bindElementIfExists(t,"input",n),this.bindElementIfExists(t,"change",n)};t("mosaicBrushSizeInput",t=>{this.setMosaicBrushSize(t)}),t("mosaicBlockSizeInput",t=>{this.setMosaicBlockSize(t)});const e=(t,e)=>{const n=t=>{e(t.target.value)};this.bindElementIfExists(t,"input",n),this.bindElementIfExists(t,"change",n)},n=(t,e)=>{const n=t=>{e(parseFloat(t.target.value))};this.bindElementIfExists(t,"input",n),this.bindElementIfExists(t,"change",n)};e("textColorInput",t=>this.applyTextColorInput(t)),n("textFontSizeInput",t=>this.applyTextFontSizeInput(t)),e("drawColorInput",t=>this.applyDrawColorInput(t)),n("drawBrushSizeInput",t=>this.applyDrawBrushSizeInput(t)),this.bindKeyboardEvents()}bindElementIfExists(t,e,n){var i;null===(i=this.domBindings)||void 0===i||i.bindIfExists(t,e,n)}bindKeyboardEvents(){var t,e;const n=null!==(e=null===(t=this.canvasElement)||void 0===t?void 0:t.ownerDocument)&&void 0!==e?e:document;this.keyboardHandler&&this.keyboardDocument&&this.keyboardDocument.removeEventListener("keydown",this.keyboardHandler),this.keyboardDocument=n,this.keyboardHandler=t=>this.handleKeyboardEvent(t),n.addEventListener("keydown",this.keyboardHandler)}isNativeTextInputActive(){var t;const e=null===(t=this.keyboardDocument)||void 0===t?void 0:t.activeElement;if(!e)return!1;const n=e.tagName.toLowerCase();return"input"===n||"textarea"===n||"select"===n||!0===e.isContentEditable}isFabricTextEditingActive(){var t;const e=null===(t=this.canvas)||void 0===t?void 0:t.getActiveObject();return!(!e||!ot(e)||!0!==e.isEditing)}handleKeyboardEvent(t){if(!this.isDisposed)if("Delete"!==t.key&&"Backspace"!==t.key){if("Escape"===t.key)return this.isFabricTextEditingActive()&&this.canvas?(Jt(this.buildTextControllerContext(),{commit:!1}),void t.preventDefault()):void(this.textSession?this.exitTextMode():this.drawSession?this.exitDrawMode():this.mosaicSession?this.exitMosaicMode():this.cropSession&&this.cancelCrop())}else{if(this.isNativeTextInputActive()||this.isFabricTextEditingActive())return;this.deleteSelectedObject()}}finalizeActiveTextEditingIfNeeded(){this.canvas&&this.isFabricTextEditingActive()&&Jt(this.buildTextControllerContext(),{commit:!0})}async loadImageFile(t){const e=this.elements.imageInput,o=e?document.getElementById(e):null,a=function(t){var e,n;if(t.type&&ri.has(t.type))return t.type;if(t.type)return null;const i=/\.([a-z0-9]+)$/i.exec(t.name),o=null===(e=null==i?void 0:i[1])||void 0===e?void 0:e.toLowerCase();return o&&null!==(n=ai[o])&&void 0!==n?n:null}(t);if(!a)return n(this.options,null,`Unsupported image file type: ${t.type||t.name||"unknown"}.`),void si(o);let r;try{r=await function(t){return new Promise((e,n)=>{const i=new FileReader;i.onload=()=>{const t=i.result;"string"==typeof t?e(t):n(new Error("FileReader returned a non-string result"))},i.onerror=()=>{var t;n(null!==(t=i.error)&&void 0!==t?t:new Error("FileReader error"))},i.onabort=()=>{n(new Error("FileReader read aborted"))},i.readAsDataURL(t)})}(t)}catch(t){return i(this.options,t,"Failed to read selected image file."),void si(o)}try{await this.loadImage(r)}catch{}finally{si(o)}}async loadImage(t,e={}){return this.loadImageInternal(t,e)}async loadImageInternal(t,e={}){if(!this.isFabricLoaded||!this.canvas)return;if(this.isDisposed)return;if("string"!=typeof t||!t.startsWith("data:image/"))return;if(!this.canRunIdleOperation("loadImage",e))return;this.finalizeActiveTextEditingIfNeeded();const n=this.getOperationContext("loadImage",e),i=this.originalImage,o=this.getMasks().length>0,a=this.getAnnotations().length>0;this.emitOptionCallback("onImageLoadStart",[n]),this.operationGuard.beginLoading(),this.emitBusyChangeIfChanged(n),this.updateUi(),this.hideAllMaskLabels();const r={fabric:this.fabricModule,canvas:this.canvas,options:this.getRuntimeOptions(),containerElement:this.containerElement,placeholderElement:this.placeholderElement,viewportCache:this.viewportCache,getOriginalImage:()=>this.originalImage,setOriginalImage:t=>{this.originalImage=t},getIsImageLoadedToCanvas:()=>this.isImageLoadedToCanvas,setIsImageLoadedToCanvas:t=>{this.isImageLoadedToCanvas=t},getLastSnapshot:()=>this.lastSnapshot,setLastSnapshot:t=>{this.lastSnapshot=t},getMaskCounter:()=>this.maskCounter,setMaskCounter:t=>{this.maskCounter=t},getAnnotationCounter:()=>this.annotationCounter,setAnnotationCounter:t=>{this.annotationCounter=t},getCurrentScale:()=>this.currentScale,setCurrentScale:t=>{this.currentScale=t},getCurrentRotation:()=>this.currentRotation,setCurrentRotation:t=>{this.currentRotation=t},getBaseImageScale:()=>this.baseImageScale,setBaseImageScale:t=>{this.baseImageScale=t},getCurrentImageMimeType:()=>this.currentImageMimeType,setCurrentImageMimeType:t=>{this.currentImageMimeType=t},setPlaceholderVisible:t=>{oi(this.placeholderElement,this.containerElement,!!this.options.showPlaceholder&&t)}};try{await Fn(r,t,e)}finally{this.operationGuard.endLoading(),this.emitBusyChangeIfChanged(n),!this.isDisposed&&this.canvas&&this.updateUi()}this.lastMask=null,this.updateInputs(),this.updateMaskList(),this.updateAnnotationList(),this.updateUi(),i&&i!==this.originalImage&&this.emitOptionCallback("onImageCleared",[i,n]);const s=this.getImageInfo();s&&this.emitOptionCallback("onImageLoaded",[s,n]),o&&this.emitMasksChanged(n),a&&this.emitAnnotationsChanged(n),this.emitImageChanged(n)}getInternalOperationToken(t){var e;return null!==(e=null==t?void 0:t[ci])&&void 0!==e?e:null}canRunDuringAnimationQueue(t){return!!(null==t?void 0:t[ui])}withInternalOperationOptions(t,e={}){return{...e,...t?{[ci]:t}:{}}}withAnimationQueueBypass(t={}){return{...t,[ui]:!0}}assertIdleForOperation(t,e){const n=this.getInternalOperationToken(e);this.operationGuard.assertIdleForOperation(t,n);const i=this.getActiveToolMode();if(i&&!this.operationGuard.isOwnOperation(n)&&!Ci[i].has(t))throw new Error(`[ImageEditor] Cannot run "${t}" while ${i} mode is active.`);if(this.animQueue.isBusy()&&!this.canRunDuringAnimationQueue(e))throw new Error(`[ImageEditor] Cannot run "${t}" while an animation is queued.`)}canRunIdleOperation(t,e){try{return this.assertIdleForOperation(t,e),!0}catch(e){if(!this.isExpectedIdleGuardError(e,t))throw e;return!1}}isExpectedIdleGuardError(t,e){return t instanceof Error&&t.message.startsWith(`[ImageEditor] Cannot run "${e}" `)}assertCanQueueAnimation(t,e){this.operationGuard.assertCanQueueAnimation(t,this.getInternalOperationToken(e))}isImageLoaded(){var t,e;return!!(this.originalImage&&this.originalImage instanceof this.fabricModule.FabricImage&&(null!==(t=this.originalImage.width)&&void 0!==t?t:0)>0&&(null!==(e=this.originalImage.height)&&void 0!==e?e:0)>0)}isBusy(){return this.operationGuard.isBusy()||this.animQueue.isBusy()||this.isToolModeActive()}setLayoutMode(t){O(t)?this.currentLayoutMode=t:n(this.options,new TypeError(`[ImageEditor] Unsupported layout mode ${JSON.stringify(t)}. Expected "fit", "cover", or "expand".`),"Ignored invalid layout mode.")}getRuntimeOptions(){return this.currentLayoutMode===this.options.layoutMode?this.options:Object.freeze({...this.options,layoutMode:this.currentLayoutMode})}buildCallbackContext(t,e=!1){return{operation:t,isInternalOperation:e}}getOperationContext(t,e){const n=this.getInternalOperationToken(e),i=this.operationGuard.activeOperationName();return n&&i?this.buildCallbackContext(null!==(o=i)&&yi.has(o)?i:t,!0):this.buildCallbackContext(t,!1);var o}emitOptionCallback(t,e){const n=this.options[t];if("function"==typeof n)try{n(...e)}catch(e){console.error(`[ImageEditor] ${t} callback threw`,e)}}getImageInfo(){if(!this.canvas||!this.originalImage)return null;const t=this.canvas.getWidth(),e=this.canvas.getHeight();let n,i;try{this.originalImage.setCoords();const t=this.originalImage.getBoundingRect();n=Math.max(0,Number(t.width)||0),i=Math.max(0,Number(t.height)||0)}catch{n=Math.max(0,(Number(this.originalImage.width)||0)*Math.abs(Number(this.originalImage.scaleX)||1)),i=Math.max(0,(Number(this.originalImage.height)||0)*Math.abs(Number(this.originalImage.scaleY)||1))}return{width:Math.max(0,Number(this.originalImage.width)||0),height:Math.max(0,Number(this.originalImage.height)||0),displayWidth:n,displayHeight:i,scale:this.currentScale,rotation:this.currentRotation,canvasWidth:t,canvasHeight:e}}getMasks(){return this.canvas?this.canvas.getObjects().filter(nt).slice():[]}getAnnotations(){return this.canvas?Mt(this.canvas):[]}getMaskCollectionSignature(){return this.getMasks().map(t=>`${t.maskId}:${t.maskName}`).join("|")}getAnnotationCollectionSignature(){return this.getAnnotations().map(t=>`${t.annotationId}:${t.annotationName}`).join("|")}getActiveToolMode(){return this.cropSession?"crop":this.mosaicSession?"mosaic":this.textSession?"text":this.drawSession?"draw":null}isToolModeActive(){return null!==this.getActiveToolMode()}getEditorState(){const t=this.canvas?this.canvas.getWidth():0,e=this.canvas?this.canvas.getHeight():0,n=this.getImageInfo();return{hasImage:null!==n,image:n,maskCount:this.getMasks().length,annotationCount:this.getAnnotations().length,currentScale:this.currentScale,currentRotation:this.currentRotation,isBusy:this.isBusy(),activeToolMode:this.getActiveToolMode(),isCropMode:null!==this.cropSession,isMosaicMode:null!==this.mosaicSession,isTextMode:null!==this.textSession,isDrawMode:null!==this.drawSession,canUndo:this.historyManager.canUndo(),canRedo:this.historyManager.canRedo(),canvasWidth:t,canvasHeight:e}}emitImageChanged(t){this.emitOptionCallback("onImageChanged",[this.getEditorState(),t])}emitMasksChanged(t){this.emitOptionCallback("onMasksChanged",[this.getMasks(),t])}emitAnnotationsChanged(t){this.emitOptionCallback("onAnnotationsChanged",[this.getAnnotations(),t])}emitBusyChangeIfChanged(t){const e=this.isBusy();this.lastEmittedIsBusy!==e&&(this.lastEmittedIsBusy=e,this.emitOptionCallback("onBusyChange",[e,t]))}buildSelection(t){var e,n;const i=t.filter(nt),o=t.filter(it),a=1===i.length&&0===o.length?"mask":1===o.length&&0===i.length?"annotation":null;return{selectedMask:null!==(e=i[0])&&void 0!==e?e:null,selectedMasks:i,selectedAnnotation:null!==(n=o[0])&&void 0!==n?n:null,selectedAnnotations:o,selectedObjectKind:a}}withSelectionChangeContext(t,e){const n=this.nextSelectionChangeContext;this.nextSelectionChangeContext=t;try{return e()}finally{this.nextSelectionChangeContext=n}}isSupportedImageMimeType(t){return"image/jpeg"===t||"image/png"===t||"image/webp"===t}inferCurrentImageMimeType(){const t=this.originalImage;if(!t)return null;let e=null;try{"function"==typeof t.getSrc?e=t.getSrc():"string"==typeof t.src&&(e=t.src)}catch{e=null}const n=e?Be(e):null;return this.isSupportedImageMimeType(n)?n:null}setCanvasSizePx(t,e){this.canvas&&Dn(this.canvas,t,e,this.containerElement)}alignObjectBoundingBoxToCanvasTopLeft(t){var e,n,i;t.setCoords();const o=t.getBoundingRect();t.set({left:(null!==(e=t.left)&&void 0!==e?e:0)-o.left,top:(null!==(n=t.top)&&void 0!==n?n:0)-o.top}),t.setCoords(),null===(i=this.canvas)||void 0===i||i.renderAll()}measureLayoutViewport(t){return this.viewportCache.measure(this.containerElement,{width:this.options.canvasWidth,height:this.options.canvasHeight},t)}getScrollbarStableViewportCanvasSize(t){return{width:Math.max(1,t.width-1),height:Math.max(1,t.height-1)}}updateCanvasSizeToImageBounds(t={}){var e,n;if(!this.originalImage)return;this.originalImage.setCoords();const i=this.originalImage.getBoundingRect(),o=Tn(null!==(n=null===(e=this.containerElement)||void 0===e?void 0:e.ownerDocument)&&void 0!==n?n:null),a=this.measureLayoutViewport(o),r=!1!==t.stabilizeContainedViewport,s=i.width<=a.width+li&&i.height<=a.height+li;if("fit"===this.currentLayoutMode||"cover"===this.currentLayoutMode){if(s){const t=r?this.getScrollbarStableViewportCanvasSize(a):a;return void this.setCanvasSizePx(t.width,t.height)}const t=Ln(i.width,i.height,a,o);return void this.setCanvasSizePx(t.width,t.height)}if(s){const t=r?this.getScrollbarStableViewportCanvasSize(a):a;return void this.setCanvasSizePx(t.width,t.height)}this.setCanvasSizePx(Math.max(a.width,Math.ceil(i.width)),Math.max(a.height,Math.ceil(i.height)))}shouldNormalizeCanvasSizeAfterStateRestore(){var t,e;if(!this.canvas||!this.originalImage)return!1;this.originalImage.setCoords();const n=this.originalImage.getBoundingRect(),i=this.measureLayoutViewport(Tn(null!==(e=null===(t=this.containerElement)||void 0===t?void 0:t.ownerDocument)&&void 0!==e?e:null)),o=Math.ceil(this.canvas.getWidth()),a=Math.ceil(this.canvas.getHeight()),r=n.width>o+li||n.height>a+li;if("fit"===this.currentLayoutMode||"cover"===this.currentLayoutMode){const t=o>i.width+li&&n.width<=i.width+li,e=a>i.height+li&&n.height<=i.height+li;return r||t||e}if("expand"===this.currentLayoutMode){const t=Math.max(i.width,Math.ceil(n.width)),e=Math.max(i.height,Math.ceil(n.height));return Math.abs(o-t)>li||Math.abs(a-e)>li}return r}settleFitCoverScrollbarsAfterStateRestore(){if(!this.canvas||!this.containerElement||"fit"!==this.currentLayoutMode&&"cover"!==this.currentLayoutMode)return;const t=Math.ceil(this.canvas.getWidth()),e=Math.ceil(this.canvas.getHeight());if(t<=1||e<=1)return;const n=Math.floor(this.containerElement.clientWidth||0),i=Math.floor(this.containerElement.clientHeight||0);if(n<=0||i<=0)return;const o=Math.ceil(this.containerElement.scrollWidth||0),a=Math.ceil(this.containerElement.scrollHeight||0),r=o>n+li,s=a>i+li;if(!r&&!s)return;const l=s&&Math.abs(t-n)<=1,c=r&&Math.abs(e-i)<=1;(l||c)&&(this.setCanvasSizePx(l?t-1:t,c?e-1:e),this.setCanvasSizePx(t,e))}captureImageDisplayGeometry(){if(!this.canvas||!this.originalImage)return null;this.originalImage.setCoords();const t=this.originalImage.getBoundingRect();return{canvasWidth:this.canvas.getWidth(),canvasHeight:this.canvas.getHeight(),imageDisplayWidth:Math.max(1,t.width),imageDisplayHeight:Math.max(1,t.height)}}restoreMergedImageDisplayGeometry(t){if(!t||!this.canvas||!this.originalImage)return;this.setCanvasSizePx(t.canvasWidth,t.canvasHeight);const e=Math.max(1,this.originalImage.width||t.imageDisplayWidth),n=Math.max(1,this.originalImage.height||t.imageDisplayHeight),i=Math.min(t.imageDisplayWidth/e,t.imageDisplayHeight/n);this.originalImage.set({left:0,top:0,angle:0,scaleX:i,scaleY:i,originX:"left",originY:"top",selectable:!1,evented:!1,hasControls:!1,hoverCursor:"default"}),this.originalImage.setCoords(),this.canvas.sendObjectToBack(this.originalImage),this.currentScale=1,this.currentRotation=0,this.baseImageScale=i,this.lastSnapshot=this.captureSnapshotInternal(),this.canvas.renderAll()}buildTransformContext(){return{canvas:this.getLiveCanvasOrThrow("buildTransformContext"),options:this.options,guard:this.operationGuard,getOriginalImage:()=>this.originalImage,getCurrentScale:()=>this.currentScale,setCurrentScale:t=>{this.currentScale=t},getCurrentRotation:()=>this.currentRotation,setCurrentRotation:t=>{this.currentRotation=t},getBaseImageScale:()=>this.baseImageScale,saveCanvasState:()=>{this.saveStateInternal(this.withAnimationQueueBypass())},setSuppressSaveState:t=>{this.shouldSuppressSaveState=t},afterTransformSnap:()=>{!this.isDisposed&&this.canvas&&this.originalImage&&(this.updateCanvasSizeToImageBounds(),this.alignObjectBoundingBoxToCanvasTopLeft(this.originalImage),this.canvas.getObjects().filter(nt).forEach(t=>this.syncMaskLabel(t)))}}}scaleImage(t){if(this.isDisposed||!this.transformController)return Promise.resolve();if(!Number.isFinite(t))return Promise.resolve();try{this.assertCanQueueAnimation("scaleImage")}catch(t){return Promise.reject(t)}const e=this.transformController,n=this.buildCallbackContext("scaleImage",!1),i=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await e.scaleImage(t),this.isDisposed||this.emitImageChanged(n)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(n),i.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(n)})}rotateImage(t){if(this.isDisposed||!this.transformController)return Promise.resolve();if(!Number.isFinite(t))return Promise.resolve();try{this.assertCanQueueAnimation("rotateImage")}catch(t){return Promise.reject(t)}const e=this.transformController,n=this.buildCallbackContext("rotateImage",!1),i=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await e.rotateImage(t),this.isDisposed||this.emitImageChanged(n)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(n),i.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(n)})}resetImageTransform(){if(this.isDisposed||!this.transformController)return Promise.resolve();try{this.assertCanQueueAnimation("resetImageTransform")}catch(t){return Promise.reject(t)}const t=this.transformController,e=this.buildCallbackContext("resetImageTransform",!1),n=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await t.resetImageTransform(),this.isDisposed||this.emitImageChanged(e)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(e),n.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(e)})}refreshUiAfterQueuedAnimation(){!this.isDisposed&&this.canvas&&(this.updateInputs(),this.updateUi())}async loadFromState(t){return this.loadFromStateInternal(t)}async loadFromStateInternal(t,e){var n;if(!t||!this.canvas)return;if(this.isDisposed)return;if(!this.canRunIdleOperation("loadFromState",e))return;const o=this.activeStateRestoreOperation,a=this.buildCallbackContext(null!=o?o:"loadFromState","undo"===o||"redo"===o),r=this.originalImage,s=this.getMaskCollectionSignature(),l=this.getAnnotationCollectionSignature();try{const e=await mt({canvas:this.canvas,jsonString:t,setCanvasSize:(t,e)=>this.setCanvasSizePx(t,e)});if(this.isDisposed||!this.canvas)return;this.hideAllMaskLabels(),this.originalImage=e.originalImage,this.originalImage&&(this.originalImage.set({originX:"left",originY:"top",selectable:!1,evented:!1,hasControls:!1,hoverCursor:"default"}),this.canvas.sendObjectToBack(this.originalImage)),this.maskCounter=e.maxMaskId,this.annotationCounter=e.maxAnnotationId;const i=e.editorState;i&&(this.currentScale=i.currentScale,this.currentRotation=i.currentRotation,this.baseImageScale=i.baseImageScale),this.originalImage?this.currentImageMimeType=i&&"currentImageMimeType"in i?null!==(n=i.currentImageMimeType)&&void 0!==n?n:null:this.inferCurrentImageMimeType():this.currentImageMimeType=null,this.isImageLoadedToCanvas=!!this.originalImage,this.originalImage&&this.shouldNormalizeCanvasSizeAfterStateRestore()&&(this.updateCanvasSizeToImageBounds({stabilizeContainedViewport:!1}),this.alignObjectBoundingBoxToCanvasTopLeft(this.originalImage)),this.originalImage&&this.settleFitCoverScrollbarsAfterStateRestore();const o=e.masks;this.lastMask=o.reduce((t,e)=>!t||e.maskId>t.maskId?e:t,null),o.forEach(t=>{ge(t),fe(t)}),It(e.annotations),Zt(this.buildTextControllerContext(),e.annotations),this.lastSnapshot=this.captureSnapshotInternal(),this.canvas.renderAll(),this.updateInputs(),this.updateMaskList(),this.updateAnnotationList(),this.updateUi(),r&&r!==this.originalImage&&this.emitOptionCallback("onImageCleared",[r,a]),s!==this.getMaskCollectionSignature()&&this.emitMasksChanged(a),l!==this.getAnnotationCollectionSignature()&&this.emitAnnotationsChanged(a),this.emitImageChanged(a);const c=this.getLiveCanvasOrThrow("loadFromState"),u=null==i?void 0:i.activeMaskId,d=null==i?void 0:i.activeAnnotationId;if("mask"===(null==i?void 0:i.activeObjectKind)&&"number"==typeof u){const t=o.find(t=>t.maskId===u);t&&this.withSelectionChangeContext(a,()=>{c.setActiveObject(t),this.handleSelectionChanged([t])})}else if("annotation"===(null==i?void 0:i.activeObjectKind)&&"number"==typeof d){const t=e.annotations.find(t=>t.annotationId===d);t&&this.withSelectionChangeContext(a,()=>{c.setActiveObject(t),this.handleSelectionChanged([t])})}}catch(t){throw i(this.options,t,"Failed to restore canvas state."),t}}saveState(){this.saveStateInternal()}saveStateInternal(t){var e,i,o;if(!this.canvas||this.shouldSuppressSaveState)return;if(!this.canRunIdleOperation("saveState",t))return;const a=this.canvas.getActiveObject(),r=this.getActiveMaskForSnapshot(),s=this.getActiveAnnotationForSnapshot();this.hideAllMaskLabels();try{const t=gt({canvas:this.canvas,activeMaskId:null!==(e=null==r?void 0:r.maskId)&&void 0!==e?e:null,activeAnnotationId:null!==(i=null==s?void 0:s.annotationId)&&void 0!==i?i:null,currentScale:this.currentScale,currentRotation:this.currentRotation,baseImageScale:this.baseImageScale,currentImageMimeType:this.currentImageMimeType}),n=null!==(o=this.lastSnapshot)&&void 0!==o?o:t;if(t===n)return;const a=new ft(async()=>{await this.loadFromStateInternal(t,this.withAnimationQueueBypass())},async()=>{await this.loadFromStateInternal(n,this.withAnimationQueueBypass())});this.historyManager.push(a),this.lastSnapshot=t}catch(t){n(this.options,t,"Failed to capture canvas snapshot.")}finally{this.restoreActiveObjectAfterSnapshot(a,r,s),this.updateUi()}}restoreActiveObjectAfterSnapshot(t,e,n){if(!this.canvas)return;const i=t&&nt(t)?t:e,o=t&&it(t)?t:n;if(i&&this.canvas.getObjects().includes(i))return this.canvas.setActiveObject(i),this.showLabelForMask(i),void this.updateMaskListSelection(i);o&&this.canvas.getObjects().includes(o)&&(this.canvas.setActiveObject(o),this.updateAnnotationListSelection(o))}undo(){if(this.isDisposed)return Promise.resolve();if(!this.canRunIdleOperation("undo"))return Promise.resolve();this.finalizeActiveTextEditingIfNeeded();const t=this.buildCallbackContext("undo",!0),e=this.animQueue.add(async()=>{if(!this.isDisposed){this.activeStateRestoreOperation="undo";try{await this.historyManager.undo()}finally{this.activeStateRestoreOperation=null}}});return this.emitBusyChangeIfChanged(t),e.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(t)})}redo(){if(this.isDisposed)return Promise.resolve();if(!this.canRunIdleOperation("redo"))return Promise.resolve();this.finalizeActiveTextEditingIfNeeded();const t=this.buildCallbackContext("redo",!0),e=this.animQueue.add(async()=>{if(!this.isDisposed){this.activeStateRestoreOperation="redo";try{await this.historyManager.redo()}finally{this.activeStateRestoreOperation=null}}});return this.emitBusyChangeIfChanged(t),e.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(t)})}createMask(t={}){if(!this.canvas)return null;if(!this.canRunIdleOperation("createMask"))return null;const e=this.buildCallbackContext("createMask",!1),n=this.buildCreateMaskContext(),i=this.withSelectionChangeContext(e,()=>Vn(n,t));return i&&(this.emitMasksChanged(e),this.emitImageChanged(e)),i}removeSelectedMask(){if(!this.canvas)return;if(!this.canRunIdleOperation("removeSelectedMask"))return;const t=this.getMasks().length,e=this.buildCallbackContext("removeSelectedMask",!1),n=this.buildRemoveMaskContext();this.withSelectionChangeContext(e,()=>_n(n)),this.updateUi(),this.getMasks().length!==t&&(this.emitMasksChanged(e),this.emitImageChanged(e))}removeAllMasks(t={}){if(!this.canvas)return;if(!this.canRunIdleOperation("removeAllMasks",t))return;const e=this.getMasks().length,n=this.buildCallbackContext("removeAllMasks",!1),i=this.buildRemoveMaskContext();this.withSelectionChangeContext(n,()=>Jn(i,t)),this.updateUi(),this.getMasks().length!==e&&(this.emitMasksChanged(n),this.emitImageChanged(n))}buildCreateMaskContext(){return{fabric:this.fabricModule,canvas:this.getLiveCanvasOrThrow("createMask"),options:this.getRuntimeOptions(),getLastMask:()=>this.lastMask,setLastMask:t=>{this.lastMask=t},getMaskCounter:()=>this.maskCounter,setMaskCounter:t=>{this.maskCounter=t},updateMaskList:()=>{this.updateMaskList()},saveCanvasState:()=>{this.saveState()},expandCanvasIfNeeded:(t,e)=>{this.setCanvasSizePx(t,e)}}}buildRemoveMaskContext(){return{canvas:this.getLiveCanvasOrThrow("removeMask"),removeLabelForMask:t=>{this.removeLabelForMask(t)},updateMaskList:()=>{this.updateMaskList()},saveCanvasState:()=>{this.saveState()},setLastMask:t=>{this.lastMask=t}}}buildMaskLabelContext(){return this.canvas?{fabric:this.fabricModule,canvas:this.canvas,options:this.options}:null}removeLabelForMask(t){const e=this.buildMaskLabelContext();e&&Zn(e,t)}createLabelForMask(t){const e=this.buildMaskLabelContext();e&&ti(e,t)}hideAllMaskLabels(){const t=this.buildMaskLabelContext();t&&function(t){const{canvas:e}=t;if(!e)return;const n=e.getObjects();n.filter(t=>t.maskLabel).forEach(t=>{try{e.remove(t)}catch{}}),n.filter(nt).forEach(t=>{try{delete t.labelObject}catch{}})}(t)}syncMaskLabel(t){const e=this.buildMaskLabelContext();e&&ei(e,t)}showLabelForMask(t){const e=this.buildMaskLabelContext();e&&function(t,e){t.options.maskLabelOnSelect&&(e.labelObject||ti(t,e),e.labelObject&&(e.labelObject.visible=!0,ei(t,e)))}(e,t)}handleObjectMovingScalingRotating(t){nt(t)&&this.syncMaskLabel(t)}handleObjectModified(t){if(nt(t)){this.syncMaskLabel(t);const e=this.buildCallbackContext("saveState",!1);return this.saveState(),this.emitMasksChanged(e),void this.emitImageChanged(e)}if(it(t)){if(vt(t))return;const e=this.buildCallbackContext("updateAnnotation",!1);this.saveState(),this.emitAnnotationsChanged(e),this.emitImageChanged(e)}}handleSelectionChanged(t){var e,n,i,o;if(!this.canvas)return;const a=null!==(e=t.find(nt))&&void 0!==e?e:null,r=null!==(n=t.find(it))&&void 0!==n?n:null;this.canvas.getObjects().filter(nt).forEach(t=>{t!==a?(t.labelObject&&this.removeLabelForMask(t),ge(t)):t.set({stroke:"#ff0000",strokeWidth:1})}),a&&this.showLabelForMask(a),this.updateMaskListSelection(a),this.updateAnnotationListSelection(r),this.canvas.requestRenderAll(),this.updateUi();const s=null!==(i=this.nextSelectionChangeContext)&&void 0!==i?i:this.buildCallbackContext(null!==(o=this.activeStateRestoreOperation)&&void 0!==o?o:"createMask","undo"===this.activeStateRestoreOperation||"redo"===this.activeStateRestoreOperation);this.emitOptionCallback("onSelectionChange",[this.buildSelection(t),s])}buildMaskListContext(){return{canvas:this.canvas,getListElementId:()=>this.elements.maskList,onMaskSelected:t=>this.handleSelectionChanged([t])}}updateMaskList(){!function(t){const e=t.getListElementId();if(!e)return;const n=ni(t),i=n.getElementById(e);if(!i||!t.canvas)return;i.innerHTML="";const o=t.canvas;o.getObjects().filter(nt).forEach(e=>{const a=n.createElement("li");a.className="list-group-item mask-item",a.textContent=e.maskName,a.dataset.maskId=String(e.maskId),a.onclick=()=>{const e=Number(a.dataset.maskId);if(!Number.isFinite(e))return;const n=o.getObjects().find(t=>nt(t)&&t.maskId===e);n&&(o.setActiveObject(n),t.onMaskSelected(n))},i.appendChild(a)})}(this.buildMaskListContext())}updateMaskListSelection(t){!function(t,e){const n=t.getListElementId();if(!n)return;const i=ni(t).getElementById(n);if(!i)return;const o=e?String(e.maskId):null;i.querySelectorAll(".mask-item").forEach(t=>{const e=null!==o&&t.dataset.maskId===o;t.classList.toggle("active",e)})}(this.buildMaskListContext(),t)}enterTextMode(){if(!this.canvas)return;if(!this.canRunIdleOperation("enterTextMode"))return;if(this.isToolModeActive())return;Vt(this.buildTextControllerContext());const t=this.buildCallbackContext("enterTextMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}exitTextMode(){if(!this.canvas||!this.textSession)return;if(!this.canRunIdleOperation("exitTextMode"))return;_t(this.buildTextControllerContext());const t=this.buildCallbackContext("exitTextMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}isTextMode(){return null!==this.textSession}createTextAnnotation(t={}){return this.canvas&&this.canRunIdleOperation("createTextAnnotation")?Kt(this.buildTextControllerContext(),t):null}enterDrawMode(){if(!this.canvas)return;if(!this.canRunIdleOperation("enterDrawMode"))return;if(this.isToolModeActive())return;!function(t){if(t.getDrawSession())return;if(!t.isImageLoaded())return;const{canvas:e}=t,n=e,i=!!n.isDrawingMode,o=n.freeDrawingBrush,a=!!e.selection,r=e.defaultCursor;e.selection=!1,e.defaultCursor="crosshair",n.isDrawingMode=!0,te(t);const s=e=>ee(t,e);e.on("path:created",s);const l={mode:"draw",previousDrawingMode:i,previousBrush:o,previousCanvasSelection:a,previousDefaultCursor:r,handlers:[{eventName:"path:created",callback:s}],dispose:()=>{try{e.off("path:created",s)}catch{}n.isDrawingMode=i,n.freeDrawingBrush=o,e.selection=a,e.defaultCursor=null!=r?r:"default"}};t.setDrawSession(l),t.updateUi()}(this.buildDrawControllerContext());const t=this.buildCallbackContext("enterDrawMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}exitDrawMode(){if(!this.canvas||!this.drawSession)return;if(!this.canRunIdleOperation("exitDrawMode"))return;ne(this.buildDrawControllerContext());const t=this.buildCallbackContext("exitDrawMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}isDrawMode(){return null!==this.drawSession}getTextConfig(){return q(this.currentTextConfig)}setTextConfig(t){this.applyTextConfigPatch(t,"setTextConfig")}resetTextConfig(){this.applyTextConfigPatch(this.defaultTextConfig,"resetTextConfig")}setTextColor(t){this.applyTextConfigPatch({fill:t},"setTextColor")}setTextFontSize(t){this.applyTextConfigPatch({fontSize:t},"setTextFontSize")}getDrawConfig(){return Y(this.currentDrawConfig)}setDrawConfig(t){this.applyDrawConfigPatch(t,"setDrawConfig")}resetDrawConfig(){this.applyDrawConfigPatch(this.defaultDrawConfig,"resetDrawConfig")}setDrawColor(t){this.applyDrawConfigPatch({color:t},"setDrawColor")}setDrawBrushSize(t){this.applyDrawConfigPatch({brushSize:t},"setDrawBrushSize")}removeSelectedAnnotation(){if(!this.canvas)return;if(!this.canRunIdleOperation("removeSelectedAnnotation"))return;const t=this.getAnnotations().length,e=this.buildCallbackContext("removeSelectedAnnotation",!1);this.withSelectionChangeContext(e,()=>{var t;At(t=this.buildAnnotationManagerContext(),wt(t.canvas))}),this.updateAnnotationList(),this.updateUi(),this.getAnnotations().length!==t&&(this.emitAnnotationsChanged(e),this.emitImageChanged(e))}removeAllAnnotations(t={}){if(!this.canvas)return;if(!this.canRunIdleOperation("removeAllAnnotations",t))return;const e=this.getAnnotations().length,n=this.buildCallbackContext("removeAllAnnotations",!1);this.withSelectionChangeContext(n,()=>{Et(this.buildAnnotationManagerContext(),t)}),this.updateAnnotationList(),this.updateUi(),this.getAnnotations().length!==e&&(this.emitAnnotationsChanged(n),this.emitImageChanged(n))}updateAnnotation(t,e){if(!this.canvas)return;if(!this.canRunIdleOperation("updateAnnotation"))return;const n=this.buildCallbackContext("updateAnnotation",!1),i=function(t,e,n){const i=Mt(t.canvas).find(t=>t.annotationId===e);return!!i&&(!!Ot(i,n)&&(t.canvas.requestRenderAll(),t.saveCanvasState(),t.updateUi(),!0))}(this.buildAnnotationManagerContext(),t,e);i&&(this.updateAnnotationList(),this.emitAnnotationsChanged(n),this.emitImageChanged(n))}updateSelectedAnnotation(t){if(!this.canvas)return;if(!this.canRunIdleOperation("updateSelectedAnnotation"))return;const e=this.buildCallbackContext("updateSelectedAnnotation",!1),n=function(t,e){const n=wt(t.canvas);return 0!==n.length&&(!!n.map(t=>Ot(t,e)).some(Boolean)&&(t.canvas.requestRenderAll(),t.saveCanvasState(),t.updateUi(),!0))}(this.buildAnnotationManagerContext(),t);n&&(this.updateAnnotationList(),this.emitAnnotationsChanged(e),this.emitImageChanged(e))}deleteSelectedObject(){if(!this.canvas)return;if(!this.canRunIdleOperation("deleteSelectedObject"))return;this.finalizeActiveTextEditingIfNeeded();const t=this.getSelectedCanvasObjects(),e=t.filter(nt),n=t.filter(t=>it(t)&&yt(t));if(0===e.length&&0===n.length)return;const i=this.getLiveCanvasOrThrow("deleteSelectedObject"),o=this.buildCallbackContext("deleteSelectedObject",!1);this.withSelectionChangeContext(o,()=>{for(const t of e)this.removeLabelForMask(t),i.remove(t);At(this.buildAnnotationManagerContext(),n,{saveHistory:!1,force:!0}),i.discardActiveObject(),i.renderAll(),this.saveState()}),this.updateMaskList(),this.updateAnnotationList(),this.updateUi(),e.length>0&&this.emitMasksChanged(o),n.length>0&&this.emitAnnotationsChanged(o),this.emitImageChanged(o)}bringSelectedObjectForward(){this.moveSelectedEditableObject("bringSelectedObjectForward")}sendSelectedObjectBackward(){this.moveSelectedEditableObject("sendSelectedObjectBackward")}bringSelectedObjectToFront(){this.moveSelectedEditableObject("bringSelectedObjectToFront")}sendSelectedObjectToBack(){this.moveSelectedEditableObject("sendSelectedObjectToBack")}buildAnnotationManagerContext(){return{canvas:this.getLiveCanvasOrThrow("annotationManager"),saveCanvasState:()=>this.saveState(),updateUi:()=>this.updateUi()}}buildAnnotationListContext(){return{canvas:this.canvas,getListElementId:()=>this.elements.annotationList,onAnnotationSelected:t=>this.handleSelectionChanged([t])}}updateAnnotationList(){!function(t){const e=t.getListElementId();if(!e)return;const n=jt(t),i=n.getElementById(e);if(!i||!t.canvas)return;i.innerHTML="";const o=t.canvas;Mt(o).forEach(e=>{const a=n.createElement("li");a.className="list-group-item annotation-item",a.textContent=e.annotationName,a.dataset.annotationId=String(e.annotationId),a.onclick=()=>{const e=Number(a.dataset.annotationId);if(!Number.isFinite(e))return;const n=Mt(o).find(t=>t.annotationId===e);n&&(o.setActiveObject(n),t.onAnnotationSelected(n))},i.appendChild(a)})}(this.buildAnnotationListContext())}updateAnnotationListSelection(t){!function(t,e){const n=t.getListElementId();if(!n)return;const i=jt(t).getElementById(n);if(!i)return;const o=e?String(e.annotationId):null;i.querySelectorAll(".annotation-item").forEach(t=>{t.classList.toggle("active",null!==o&&t.dataset.annotationId===o)})}(this.buildAnnotationListContext(),t)}buildTextControllerContext(){return{fabric:this.fabricModule,canvas:this.getLiveCanvasOrThrow("textController"),options:this.options,getOriginalImage:()=>this.originalImage,getTextConfig:()=>this.currentTextConfig,isImageLoaded:()=>this.isImageLoaded(),getAnnotationCounter:()=>this.annotationCounter,setAnnotationCounter:t=>{this.annotationCounter=t},getTextSession:()=>this.textSession,setTextSession:t=>{this.textSession=t},saveCanvasState:()=>this.saveState(),updateAnnotationList:()=>this.updateAnnotationList(),updateUi:()=>this.updateUi(),emitAnnotationsChanged:t=>this.emitAnnotationsChanged(t),emitImageChanged:t=>this.emitImageChanged(t),buildCallbackContext:t=>this.buildCallbackContext(t,!1)}}buildDrawControllerContext(){return{fabric:this.fabricModule,canvas:this.getLiveCanvasOrThrow("drawController"),options:this.options,getDrawConfig:()=>this.currentDrawConfig,isImageLoaded:()=>this.isImageLoaded(),getAnnotationCounter:()=>this.annotationCounter,setAnnotationCounter:t=>{this.annotationCounter=t},getDrawSession:()=>this.drawSession,setDrawSession:t=>{this.drawSession=t},saveCanvasState:()=>this.saveState(),updateAnnotationList:()=>this.updateAnnotationList(),updateUi:()=>this.updateUi(),emitAnnotationsChanged:t=>this.emitAnnotationsChanged(t),emitImageChanged:t=>this.emitImageChanged(t),buildCallbackContext:t=>this.buildCallbackContext(t,!1)}}applyTextConfigPatch(t,e){if(!this.canRunIdleOperation(e))return;const i=function(t){const e=E(t)?t:{},n=[];return W(e,"text")&&"string"!=typeof e.text&&n.push("text"),W(e,"width")&&!H(e.width)&&n.push("width"),W(e,"fontSize")&&!H(e.fontSize)&&n.push("fontSize"),W(e,"fontFamily")&&"string"!=typeof e.fontFamily&&n.push("fontFamily"),W(e,"fill")&&"string"!=typeof e.fill&&n.push("fill"),n}(t);i.length>0&&n(this.options,null,`${e} ignored invalid Text config fields: ${i.join(", ")}.`);const o=_(this.currentTextConfig,t,this.defaultTextConfig);var a,r;(a=this.currentTextConfig,r=o,JSON.stringify(a)!==JSON.stringify(r))&&(this.currentTextConfig=o,this.updateInputs(),this.updateUi(),this.emitImageChanged(this.buildCallbackContext(e,!1)))}applyDrawConfigPatch(t,e){if(!this.canRunIdleOperation(e))return;const i=function(t){const e=E(t)?t:{},n=[];return W(e,"brushSize")&&!H(e.brushSize)&&n.push("brushSize"),W(e,"color")&&"string"!=typeof e.color&&n.push("color"),W(e,"opacity")&&!H(e.opacity)&&n.push("opacity"),n}(t);i.length>0&&n(this.options,null,`${e} ignored invalid Draw config fields: ${i.join(", ")}.`);const o=J(this.currentDrawConfig,t,this.defaultDrawConfig);var a,r,s;(a=this.currentDrawConfig,r=o,a.brushSize!==r.brushSize||a.color!==r.color||a.opacity!==r.opacity||a.lineCap!==r.lineCap||a.lineJoin!==r.lineJoin||a.selectable!==r.selectable||a.evented!==r.evented||a.annotationHidden!==r.annotationHidden||a.annotationLocked!==r.annotationLocked)&&(this.currentDrawConfig=o,(s=this.buildDrawControllerContext()).getDrawSession()&&te(s),this.updateInputs(),this.updateUi(),this.emitImageChanged(this.buildCallbackContext(e,!1)))}applyTextColorInput(t){var e;if(this.isTextMode())return void this.setTextColor(t);const n=null===(e=this.canvas)||void 0===e?void 0:e.getActiveObject();n&&ot(n)?this.updateSelectedAnnotation({fill:t}):this.setTextColor(t)}applyTextFontSizeInput(t){var e;if(this.isTextMode())return void this.setTextFontSize(t);const n=null===(e=this.canvas)||void 0===e?void 0:e.getActiveObject();n&&ot(n)?this.updateSelectedAnnotation({fontSize:t}):this.setTextFontSize(t)}applyDrawColorInput(t){var e;if(this.isDrawMode())return void this.setDrawColor(t);const n=null===(e=this.canvas)||void 0===e?void 0:e.getActiveObject();n&&at(n)?this.updateSelectedAnnotation({stroke:t}):this.setDrawColor(t)}applyDrawBrushSizeInput(t){var e;if(this.isDrawMode())return void this.setDrawBrushSize(t);const n=null===(e=this.canvas)||void 0===e?void 0:e.getActiveObject();n&&at(n)?this.updateSelectedAnnotation({strokeWidth:t}):this.setDrawBrushSize(t)}getSelectedCanvasObjects(){var t,e,n;if(!this.canvas)return[];const i=this.canvas.getActiveObject();if(!i)return[];if(!("activeselection"===("string"==typeof i.type?i.type.toLowerCase():"")||null!==(n=null===(e=(t=i).isType)||void 0===e?void 0:e.call(t,"ActiveSelection"))&&void 0!==n&&n))return[i];const o=i.getObjects;return"function"==typeof o?o.call(i):[]}moveSelectedEditableObject(t){if(!this.canvas)return;if(!this.canRunIdleOperation(t))return;const e=this.getSelectedCanvasObjects().filter(st);if(1!==e.length)return void(e.length>1&&n(this.options,null,`${t} skipped: ActiveSelection layer moves are not supported.`));const i=e[0],o=function(t){const e=t.getObjects().map((t,e)=>({object:t,index:e})).filter(({object:t})=>st(t));return 0===e.length?{start:-1,end:-1,overlays:[]}:{start:e[0].index,end:e[e.length-1].index,overlays:e.map(({object:t})=>t)}}(this.canvas),a=o.overlays,r=a.indexOf(i);if(r<0)return;let s=r;if("bringSelectedObjectForward"===t?s=Math.min(a.length-1,r+1):"sendSelectedObjectBackward"===t?s=Math.max(0,r-1):"bringSelectedObjectToFront"===t?s=a.length-1:"sendSelectedObjectToBack"===t&&(s=0),s===r)return;const l=a.slice();l.splice(r,1),l.splice(s,0,i),l.forEach((t,e)=>{var n,i;null===(i=(n=this.canvas).moveObjectTo)||void 0===i||i.call(n,t,o.start+e)}),Nt(this.canvas),this.canvas.setActiveObject(i),this.canvas.renderAll(),this.saveState(),this.updateMaskList(),this.updateAnnotationList(),this.updateUi();const c=this.buildCallbackContext(t,!1);nt(i)&&this.emitMasksChanged(c),it(i)&&this.emitAnnotationsChanged(c),this.emitImageChanged(c)}async mergeMasks(){if(!this.canvas)return;if(!this.canRunIdleOperation("mergeMasks"))return;this.finalizeActiveTextEditingIfNeeded();if(!this.canvas.getObjects().some(nt))return;const t=this.buildCallbackContext("mergeMasks",!1),e=this.operationGuard.beginBusyOperation("mergeMasks");this.emitBusyChangeIfChanged(t),this.updateUi();try{const n=this.buildMergeMasksContext(e);await async function(t){await cn(t,{operation:"mergeMasks",exportOptions:{exportArea:"image",mergeMasks:!0,mergeAnnotations:!1,multiplier:t.options.exportMultiplier,fileType:"png"},getTargets:()=>t.canvas.getObjects().filter(nt),getPreservedObjects:()=>t.getAnnotations(),removeTargetsNoHistory:()=>{t.removeAllMasksNoHistory()},restorePreservedObjects:e=>t.restoreAnnotations(e)})}(n),this.updateInputs(),this.updateMaskList(),this.updateAnnotationList(),this.emitMasksChanged(t),this.getAnnotations().length>0&&this.emitAnnotationsChanged(t),this.emitImageChanged(t)}finally{this.operationGuard.endBusyOperation(e),this.emitBusyChangeIfChanged(t),this.updateUi()}}downloadImage(t){if(!this.canvas)return;if(!this.canRunIdleOperation("downloadImage"))return;this.finalizeActiveTextEditingIfNeeded();const e=this.buildCallbackContext("downloadImage",!1),n=this.operationGuard.beginBusyOperation("downloadImage");this.emitBusyChangeIfChanged(e);const o=this.buildExportServiceContext();try{!function(t,e){if(!t.isImageLoaded())return void wn("downloadImage");const n=function(t,e){var n;const i="string"==typeof e?{fileName:e}:null!=e?e:{};return{fileName:null!==(n=i.fileName)&&void 0!==n?n:t.options.defaultDownloadFileName,exportOptions:{exportArea:t.options.exportAreaByDefault,mergeMasks:i.mergeMasks,mergeAnnotations:i.mergeAnnotations,multiplier:t.options.exportMultiplier}}}(t,e);xn(t,n.exportOptions).then(e=>{if(!e)return;const i=In(t.canvas),o=i.createElement("a");o.download=n.fileName,o.href=e;const a=i.body;a.appendChild(o);try{o.click()}finally{a.removeChild(o)}}).catch(e=>{i(t.options,e,"downloadImage failed."),console.error("[ImageEditor] downloadImage failed",e)})}(o,t)}finally{this.operationGuard.endBusyOperation(n),this.emitBusyChangeIfChanged(e)}}async exportImageBase64(t){if(!this.canvas)return"";if(!this.canRunIdleOperation("exportImageBase64",t))return"";this.finalizeActiveTextEditingIfNeeded();const e=this.buildCallbackContext("exportImageBase64",!1),n=this.operationGuard.beginBusyOperation("exportImageBase64");this.emitBusyChangeIfChanged(e);const i=this.buildExportServiceContext();try{return await xn(i,t)}finally{this.operationGuard.endBusyOperation(n),this.emitBusyChangeIfChanged(e)}}async exportImageFile(t){this.assertIdleForOperation("exportImageFile",t),this.finalizeActiveTextEditingIfNeeded();const e=this.buildCallbackContext("exportImageFile",!1),n=this.operationGuard.beginBusyOperation("exportImageFile");this.emitBusyChangeIfChanged(e);const i=this.buildExportServiceContext();try{return await kn(i,t)}finally{this.operationGuard.endBusyOperation(n),this.emitBusyChangeIfChanged(e)}}buildExportServiceContext(){return{fabric:this.fabricModule,canvas:this.getLiveCanvasOrThrow("export"),options:this.options,isImageLoaded:()=>this.isImageLoaded(),getOriginalImage:()=>this.originalImage}}buildMergeMasksContext(t){return{...this.buildExportServiceContext(),historyManager:this.historyManager,containerElement:this.containerElement,loadImage:async(e,n)=>{const i=this.captureImageDisplayGeometry();await this.loadImageInternal(e,this.withInternalOperationOptions(t,null!=n?n:{})),this.restoreMergedImageDisplayGeometry(i)},captureSnapshot:()=>this.captureSnapshotInternal(),loadFromState:e=>this.loadFromStateInternal(e,this.withInternalOperationOptions(t,this.withAnimationQueueBypass())),exportImageBase64:t=>xn(this.buildExportServiceContext(),t),updateUi:()=>this.updateUi(),updateInputs:()=>this.updateInputs(),removeAllMasksNoHistory:()=>{Jn(this.buildRemoveMaskContext(),{saveHistory:!1})},getAnnotations:()=>this.getAnnotations(),restoreAnnotations:t=>{const e=this.getLiveCanvasOrThrow("restoreAnnotations");t.forEach(t=>{e.add(t)}),It(t),Zt(this.buildTextControllerContext(),t),this.annotationCounter=Math.max(this.annotationCounter,...t.map(t=>t.annotationId),0),this.updateAnnotationList()}}}buildMergeAnnotationsContext(t){return{...this.buildExportServiceContext(),historyManager:this.historyManager,containerElement:this.containerElement,loadImage:async(e,n)=>{const i=this.captureImageDisplayGeometry();await this.loadImageInternal(e,this.withInternalOperationOptions(t,null!=n?n:{})),this.restoreMergedImageDisplayGeometry(i)},captureSnapshot:()=>this.captureSnapshotInternal(),loadFromState:e=>this.loadFromStateInternal(e,this.withInternalOperationOptions(t,this.withAnimationQueueBypass())),exportImageBase64:t=>xn(this.buildExportServiceContext(),t),updateUi:()=>this.updateUi(),updateInputs:()=>this.updateInputs(),removeAllAnnotationsNoHistory:()=>{Et(this.buildAnnotationManagerContext(),{saveHistory:!1,force:!0})},getMasks:()=>this.getMasks(),restoreMasks:t=>{const e=this.getLiveCanvasOrThrow("restoreMasks");t.forEach(t=>{e.add(t),fe(t)}),this.lastMask=t.reduce((t,e)=>!t||e.maskId>t.maskId?e:t,null),this.maskCounter=Math.max(this.maskCounter,...t.map(t=>t.maskId),0),this.updateMaskList()}}}captureSnapshotInternal(){var t,e;if(!this.canvas)throw new Error("[ImageEditor] Cannot capture canvas snapshot before init or after dispose.");const n=this.getActiveMaskForSnapshot(),i=this.getActiveAnnotationForSnapshot();return this.hideAllMaskLabels(),gt({canvas:this.canvas,activeMaskId:null!==(t=null==n?void 0:n.maskId)&&void 0!==t?t:null,activeAnnotationId:null!==(e=null==i?void 0:i.annotationId)&&void 0!==e?e:null,currentScale:this.currentScale,currentRotation:this.currentRotation,baseImageScale:this.baseImageScale,currentImageMimeType:this.currentImageMimeType})}getActiveMaskForSnapshot(){var t;if(!this.canvas)return null;const e=this.canvas.getActiveObject();if(e&&nt(e))return e;const n=this.canvas.getObjects().filter(t=>nt(t)&&!!t.labelObject);return 1===n.length&&null!==(t=n[0])&&void 0!==t?t:null}getActiveAnnotationForSnapshot(){if(!this.canvas)return null;const t=this.canvas.getActiveObject();return t&&it(t)?t:null}enterMosaicMode(){if(!this.canvas||!this.originalImage)return;if(this.mosaicSession)return;if(!this.isImageLoaded())return;if(!this.canRunIdleOperation("enterMosaicMode"))return;on(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi();const t=this.buildCallbackContext("enterMosaicMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}exitMosaicMode(){if(!this.canvas||!this.mosaicSession)return;if(!this.canRunIdleOperation("exitMosaicMode"))return;an(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi();const t=this.buildCallbackContext("exitMosaicMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}isMosaicMode(){return null!==this.mosaicSession}getMosaicConfig(){return U(this.currentMosaicConfig)}setMosaicConfig(t){this.applyMosaicConfigPatch(t,"setMosaicConfig")}resetMosaicConfig(){if(this.isDisposed)return;const t=U(this.defaultMosaicConfig);Q(this.currentMosaicConfig,t)||(this.currentMosaicConfig=t,this.mosaicSession&&this.canvas&&rn(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi(),this.emitImageChanged(this.buildCallbackContext("resetMosaicConfig",!1)))}setMosaicBrushSize(t){this.applyMosaicConfigPatch({brushSize:t},"setMosaicBrushSize")}setMosaicBlockSize(t){this.applyMosaicConfigPatch({blockSize:t},"setMosaicBlockSize")}applyMosaicConfigPatch(t,e){if(this.isDisposed)return;if(null===t||"object"!=typeof t||Array.isArray(t))return void n(this.options,new TypeError("[ImageEditor] Invalid Mosaic config object."),"Ignored invalid Mosaic config.");const i=function(t){const e=E(t)?t:{},n=[];if(!W(e,"brushSize")||"number"==typeof e.brushSize&&Number.isFinite(e.brushSize)&&e.brushSize>0||n.push("brushSize"),!W(e,"blockSize")||"number"==typeof e.blockSize&&Number.isFinite(e.blockSize)&&e.blockSize>0||n.push("blockSize"),W(e,"previewStroke")&&"string"!=typeof e.previewStroke&&n.push("previewStroke"),!W(e,"previewStrokeWidth")||"number"==typeof e.previewStrokeWidth&&Number.isFinite(e.previewStrokeWidth)&&e.previewStrokeWidth>=0||n.push("previewStrokeWidth"),W(e,"previewStrokeDashArray")){const t=e.previewStrokeDashArray;null===t||Array.isArray(t)&&t.every(t=>"number"==typeof t&&Number.isFinite(t)&&t>=0)||n.push("previewStrokeDashArray")}if(W(e,"previewFill")&&"string"!=typeof e.previewFill&&n.push("previewFill"),W(e,"outputFileType")){const t=e.outputFileType;"source"===t||"string"==typeof t&&r(t)||n.push("outputFileType")}return!W(e,"outputQuality")||void 0===e.outputQuality||null===e.outputQuality||"number"==typeof e.outputQuality&&Number.isFinite(e.outputQuality)||n.push("outputQuality"),n}(t);i.length>0&&n(this.options,new TypeError(`[ImageEditor] Ignored invalid Mosaic config field(s): ${i.join(", ")}.`),"Ignored invalid Mosaic config fields.");const o=$(this.currentMosaicConfig,t);Q(this.currentMosaicConfig,o)||(this.currentMosaicConfig=o,this.mosaicSession&&this.canvas&&rn(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi(),this.emitImageChanged(this.buildCallbackContext(e,!1)))}buildMosaicControllerContext(){return{fabric:this.fabricModule,canvas:this.getLiveCanvasOrThrow("mosaicController"),options:this.options,historyManager:this.historyManager,getMosaicConfig:()=>U(this.currentMosaicConfig),isImageLoaded:()=>this.isImageLoaded(),getOriginalImage:()=>this.originalImage,setOriginalImage:t=>{this.originalImage=t},getCurrentImageMimeType:()=>this.currentImageMimeType,setCurrentImageMimeType:t=>{this.currentImageMimeType=t},getLastSnapshot:()=>this.lastSnapshot,setLastSnapshot:t=>{this.lastSnapshot=t},captureSnapshot:()=>this.captureSnapshotInternal(),loadFromState:t=>this.loadFromStateInternal(t,this.withAnimationQueueBypass()),updateUi:()=>{this.updateUi()},updateInputs:()=>{this.updateInputs()},hideAllMaskLabels:()=>{this.hideAllMaskLabels()},emitImageChanged:t=>{this.emitImageChanged(t)},emitBusyChangeIfChanged:t=>{this.emitBusyChangeIfChanged(t)},buildCallbackContext:(t,e)=>this.buildCallbackContext(t,e),getMosaicSession:()=>this.mosaicSession,setMosaicSession:t=>{this.mosaicSession=t}}}enterCropMode(){if(!this.canvas||!this.originalImage)return;if(this.cropSession)return;if(!this.isImageLoaded())return;if(!this.canRunIdleOperation("enterCropMode"))return;!function(t){const{canvas:e,options:n}=t;if(t.getCropSession())return;const i=t.getOriginalImage();if(!i)return;if(!t.isImageLoaded())return;e.discardActiveObject();const o=t.saveState(),a=!!e.selection;e.selection=!1,i.setCoords();const r=i.getBoundingRect(),s=Number.isFinite(Number(n.crop.padding))?Number(n.crop.padding):10,l=Math.max(0,Math.floor(r.left)),c=Math.max(0,Math.floor(r.top)),u=Math.max(1,Math.floor(r.width)),d=Math.max(1,Math.floor(r.height)),h=Math.min(l+u-1,Math.max(l,Math.floor(r.left+s))),g=Math.min(c+d-1,Math.max(c,Math.floor(r.top+s))),m=Math.max(1,Number(n.crop.minWidth)||1),f=Math.max(1,Number(n.crop.minHeight)||1),p=Math.min(m,u),b=Math.min(f,d),v=!!n.crop.allowRotationOfCropRect,y=new t.fabric.Rect({left:h,top:g,width:p,height:b,originX:"left",originY:"top",fill:"rgba(0,0,0,0.12)",stroke:"#00aaff",strokeDashArray:Ce,strokeWidth:1,strokeUniform:!0,selectable:!0,lockRotation:!v,cornerSize:8,objectCaching:!1,lockScalingFlip:!0});v||y.setControlVisible("mtr",!1),e.add(y),dt(y,"cropRect"),y.isCropRect=!0,e.bringObjectToFront(y),e.setActiveObject(y);const C=!!n.crop.hideMasksDuringCrop,S=[];C&&e.getObjects().forEach(t=>{t!==y&&nt(t)&&S.push(be(t))});const I=[];if(e.getObjects().forEach(t=>{var e,n;if(t!==y){I.push({object:t,evented:null===(e=t.evented)||void 0===e||e,selectable:null===(n=t.selectable)||void 0===n||n});try{t.set({evented:!1,selectable:!1})}catch{}}}),C)for(const t of S)ye(t.object);const M=()=>{try{const t=Math.max(1,Number(y.width)||1),n=Math.max(1,Number(y.height)||1),i=Math.min(u/t,Math.max(p/t,Number(y.scaleX)||1)),o=Math.min(d/n,Math.max(b/n,Number(y.scaleY)||1)),a=t*i,r=n*o,s=Math.max(l,l+u-a),h=Math.max(c,c+d-r),g=Math.min(s,Math.max(l,Number(y.left)||l)),m=Math.min(h,Math.max(c,Number(y.top)||c));y.set({left:g,top:m,scaleX:i,scaleY:o}),y.setCoords(),e.requestRenderAll()}catch{}};y.on("modified",M),y.on("moving",M),y.on("scaling",M);const w={beforeJson:o,prevSelection:a,prevEvented:I,maskBackups:S,cropRect:y,handlers:[{target:y,handlers:[{eventName:"modified",callback:M},{eventName:"moving",callback:M},{eventName:"scaling",callback:M}]}]};t.setCropSession(w),e.renderAll()}(this.buildCropControllerContext()),this.updateUi();const t=this.buildCallbackContext("enterCropMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}cancelCrop(){if(!this.canvas||!this.cropSession)return;if(!this.canRunIdleOperation("cancelCrop"))return;Ae(this.buildCropControllerContext()),this.cropSession=null,this.updateUi(),this.canvas.requestRenderAll();const t=this.buildCallbackContext("cancelCrop",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}async applyCrop(){if(!this.canvas||!this.cropSession)return;if(!this.canRunIdleOperation("applyCrop"))return;const t=this.buildCallbackContext("applyCrop",!1),e=this.getMasks().length>0,n=this.operationGuard.beginBusyOperation("applyCrop");this.emitBusyChangeIfChanged(t),this.updateUi();try{const i=this.buildCropControllerContext(n);await Ee(i),this.updateInputs(),this.updateMaskList(),(e||this.getMasks().length>0)&&this.emitMasksChanged(t),this.emitImageChanged(t)}finally{this.operationGuard.endBusyOperation(n),this.emitBusyChangeIfChanged(t),this.updateUi()}}buildCropControllerContext(t){return{fabric:this.fabricModule,canvas:this.getLiveCanvasOrThrow("cropController"),options:this.options,historyManager:this.historyManager,isImageLoaded:()=>this.isImageLoaded(),getOriginalImage:()=>this.originalImage,getCurrentImageMimeType:()=>this.currentImageMimeType,getCropSession:()=>this.cropSession,setCropSession:t=>{this.cropSession=t},saveState:()=>this.captureSnapshotInternal(),loadFromState:e=>this.loadFromStateInternal(e,this.withInternalOperationOptions(t,this.withAnimationQueueBypass())),loadImage:(e,n)=>this.loadImageInternal(e,this.withInternalOperationOptions(t,null!=n?n:{})),getMaskCounter:()=>this.maskCounter,setMaskCounter:t=>{this.maskCounter=t},updateMaskList:()=>{this.updateMaskList()}}}syncInputValue(t,e){if(!t)return;(t.ownerDocument.activeElement!==t||t.readOnly)&&t.value!==e&&(t.value=e)}updateInputs(){const t=this.elements.scalePercentageInput;if(t){const e=document.getElementById(t);this.syncInputValue(e,String(Math.round(100*this.currentScale)))}const e=this.getMosaicConfig(),n=this.elements.mosaicBrushSizeInput;if(n){const t=document.getElementById(n);this.syncInputValue(t,String(e.brushSize))}const i=this.elements.mosaicBlockSizeInput;if(i){const t=document.getElementById(i);this.syncInputValue(t,String(e.blockSize))}const o=this.getTextConfig(),a=this.elements.textColorInput;if(a){const t=document.getElementById(a);this.syncInputValue(t,o.fill)}const r=this.elements.textFontSizeInput;if(r){const t=document.getElementById(r);this.syncInputValue(t,String(o.fontSize))}const s=this.getDrawConfig(),l=this.elements.drawColorInput;if(l){const t=document.getElementById(l);this.syncInputValue(t,s.color)}const c=this.elements.drawBrushSizeInput;if(c){const t=document.getElementById(c);this.syncInputValue(t,String(s.brushSize))}}async mergeAnnotations(){if(!this.canvas)return;if(!this.canRunIdleOperation("mergeAnnotations"))return;this.finalizeActiveTextEditingIfNeeded();if(!this.canvas.getObjects().some(it))return;const t=this.buildCallbackContext("mergeAnnotations",!1),e=this.operationGuard.beginBusyOperation("mergeAnnotations");this.emitBusyChangeIfChanged(t),this.updateUi();try{await async function(t){await cn(t,{operation:"mergeAnnotations",exportOptions:{exportArea:"image",mergeMasks:!1,mergeAnnotations:!0,multiplier:t.options.exportMultiplier,fileType:"png"},getTargets:()=>t.canvas.getObjects().filter(it),getPreservedObjects:()=>t.getMasks(),removeTargetsNoHistory:()=>{t.removeAllAnnotationsNoHistory()},restorePreservedObjects:e=>t.restoreMasks(e)})}(this.buildMergeAnnotationsContext(e)),this.updateInputs(),this.updateMaskList(),this.updateAnnotationList(),this.emitAnnotationsChanged(t),this.getMasks().length>0&&this.emitMasksChanged(t),this.emitImageChanged(t)}finally{this.operationGuard.endBusyOperation(e),this.emitBusyChangeIfChanged(t),this.updateUi()}}updateUi(){var t;if(!this.canvas)return;const e=!!this.originalImage,n=e?this.canvas.getObjects().filter(nt):[],i=e?this.canvas.getObjects().filter(it):[],o=n.length>0,a=i.length>0,r=this.canvas.getActiveObject(),s=!(!r||!nt(r)),l=!(!r||!it(r)),c=!!r&&st(r),u=1===this.currentScale&&0===this.currentRotation,d=this.historyManager.canUndo(),h=this.historyManager.canRedo(),g=null!==this.cropSession,m=null!==this.mosaicSession,f=null!==this.textSession,p=null!==this.drawSession,b=this.operationGuard.isBusy()||this.animQueue.isBusy(),v=!0===(null===(t=this.mosaicSession)||void 0===t?void 0:t.isApplying);if(g)di.forEach(t=>{this.setControlEnabled(t,!b&&hi.includes(t))});else if(f)di.forEach(t=>{this.setControlEnabled(t,!b&&mi.includes(t))});else if(p)di.forEach(t=>{this.setControlEnabled(t,!b&&fi.includes(t))});else{if(m)return pi.forEach(t=>{this.setControlEnabled(t,!b&&!v&&bi.includes(t))}),void this.setControlEnabled("imageInput",!1);this.setControlEnabled("scalePercentageInput",e&&!b),this.setControlEnabled("rotateLeftDegreesInput",e&&!b),this.setControlEnabled("rotateRightDegreesInput",e&&!b),this.setControlEnabled("zoomInButton",e&&!b&&this.currentScale<this.options.maxScale),this.setControlEnabled("zoomOutButton",e&&!b&&this.currentScale>this.options.minScale),this.setControlEnabled("rotateLeftButton",e&&!b),this.setControlEnabled("rotateRightButton",e&&!b),this.setControlEnabled("createMaskButton",e&&!b),this.setControlEnabled("removeSelectedMaskButton",s&&!b),this.setControlEnabled("removeAllMasksButton",o&&!b),this.setControlEnabled("mergeMasksButton",e&&o&&!b),this.setControlEnabled("removeSelectedAnnotationButton",l&&!b),this.setControlEnabled("removeAllAnnotationsButton",a&&!b),this.setControlEnabled("deleteSelectedObjectButton",c&&!b),this.setControlEnabled("mergeAnnotationsButton",e&&a&&!b),this.setControlEnabled("bringSelectedObjectForwardButton",c&&!b),this.setControlEnabled("sendSelectedObjectBackwardButton",c&&!b),this.setControlEnabled("bringSelectedObjectToFrontButton",c&&!b),this.setControlEnabled("sendSelectedObjectToBackButton",c&&!b),this.setControlEnabled("downloadImageButton",e&&!b),this.setControlEnabled("resetImageTransformButton",e&&!u&&!b),this.setControlEnabled("undoButton",e&&!b&&d),this.setControlEnabled("redoButton",e&&!b&&h),this.setControlEnabled("enterCropModeButton",e&&!b),this.setControlEnabled("enterMosaicModeButton",e&&!b),this.setControlEnabled("enterTextModeButton",e&&!b),this.setControlEnabled("enterDrawModeButton",e&&!b),this.setControlEnabled("exitMosaicModeButton",!1),this.setControlEnabled("exitTextModeButton",!1),this.setControlEnabled("exitDrawModeButton",!1),this.setControlEnabled("mosaicBrushSizeInput",!this.isDisposed),this.setControlEnabled("mosaicBlockSizeInput",!this.isDisposed),this.setControlEnabled("textColorInput",!this.isDisposed),this.setControlEnabled("textFontSizeInput",!this.isDisposed),this.setControlEnabled("drawColorInput",!this.isDisposed),this.setControlEnabled("drawBrushSizeInput",!this.isDisposed),this.setControlEnabled("imageInput",!b),this.setControlEnabled("applyCropButton",!1),this.setControlEnabled("cancelCropButton",!1)}}setControlEnabled(t,e){var n;const i=this.elements[t];if(!i)return;const o=document.getElementById(i);if(o){if(this.recordElementOriginalState(t,o),"disabled"in o){const t=o,n=!e;return void(t.disabled!==n&&(t.disabled=n))}if(e){const e=this.elementOriginalAriaDisabledMap.get(t);null==e?o.removeAttribute("aria-disabled"):o.setAttribute("aria-disabled",e),o.style.pointerEvents=null!==(n=this.elementOriginalPointerEventsMap.get(t))&&void 0!==n?n:""}else o.setAttribute("aria-disabled","true"),o.style.pointerEvents="none"}}recordElementOriginalState(t,e){this.elementOriginalAriaDisabledMap.has(t)||this.elementOriginalAriaDisabledMap.set(t,e.getAttribute("aria-disabled")),this.elementOriginalPointerEventsMap.has(t)||this.elementOriginalPointerEventsMap.set(t,e.style.pointerEvents||""),"disabled"in e&&!this.elementOriginalDisabledMap.has(t)&&this.elementOriginalDisabledMap.set(t,!!e.disabled)}restoreElementOriginalStates(){var t,e;for(const n of Object.keys(this.elements)){const i=this.elements[n];if(!i)continue;const o=document.getElementById(i);if(o){if("disabled"in o&&this.elementOriginalDisabledMap.has(n)&&(o.disabled=null!==(t=this.elementOriginalDisabledMap.get(n))&&void 0!==t&&t),this.elementOriginalAriaDisabledMap.has(n)){const t=this.elementOriginalAriaDisabledMap.get(n);null==t?o.removeAttribute("aria-disabled"):o.setAttribute("aria-disabled",t)}this.elementOriginalPointerEventsMap.has(n)&&(o.style.pointerEvents=null!==(e=this.elementOriginalPointerEventsMap.get(n))&&void 0!==e?e:"")}}this.elementOriginalDisabledMap.clear(),this.elementOriginalAriaDisabledMap.clear(),this.elementOriginalPointerEventsMap.clear()}updatePlaceholderStatus(){oi(this.placeholderElement,this.containerElement,!!this.options.showPlaceholder&&!this.originalImage)}dispose(){var t;if(this.isDisposed)return;const e=this.buildCallbackContext("dispose",!1),n=this.originalImage;if(this.isDisposed=!0,this.operationGuard.markDisposed(),this.animQueue.clear(),null===(t=this.domBindings)||void 0===t||t.removeAll(),this.keyboardHandler&&this.keyboardDocument)try{this.keyboardDocument.removeEventListener("keydown",this.keyboardHandler)}catch{}if(this.keyboardHandler=null,this.keyboardDocument=null,this.restoreElementOriginalStates(),this.cropSession&&this.canvas){try{Ae(this.buildCropControllerContext())}catch{}this.cropSession=null}if(this.mosaicSession&&this.canvas){try{an(this.buildMosaicControllerContext())}catch{}this.mosaicSession=null}if(this.textSession&&this.canvas){try{_t(this.buildTextControllerContext())}catch{}this.textSession=null}if(this.drawSession&&this.canvas){try{ne(this.buildDrawControllerContext())}catch{}this.drawSession=null}if(this.canvas){try{Promise.resolve(this.canvas.dispose()).catch(()=>{})}catch{}this.canvas=null,this.canvasElement=null,this.isImageLoadedToCanvas=!1}this.originalImage=null,this.currentImageMimeType=null,this.lastMask=null,this.maskCounter=0,this.annotationCounter=0,this.currentScale=1,this.currentRotation=0,this.baseImageScale=1,this.lastSnapshot=null,this.transformController=null,this.viewportCache.clear(),n&&this.emitOptionCallback("onImageCleared",[n,e]),this.emitImageChanged(e),this.emitBusyChangeIfChanged(e),this.emitOptionCallback("onEditorDisposed",[e])}}t.ImageEditor=Si,t.default=Si,t.isAnnotationObject=it,t.isBaseImageObject=et,t.isDrawAnnotationObject=at,t.isEditableOverlayObject=st,t.isMaskObject=nt,t.isSessionObject=rt,t.isTextAnnotationObject=ot,Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=image-editor.umd.js.map