@bensitu/image-editor 2.1.0 → 2.3.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 (118) hide show
  1. package/README.md +305 -95
  2. package/dist/cjs/index.cjs +3460 -843
  3. package/dist/cjs/index.cjs.map +1 -1
  4. package/dist/esm/annotation/annotation-lock.js +7 -0
  5. package/dist/esm/annotation/annotation-lock.js.map +1 -0
  6. package/dist/esm/annotation/annotation-manager.js +217 -0
  7. package/dist/esm/annotation/annotation-manager.js.map +1 -0
  8. package/dist/esm/annotation/annotation-style.js +50 -0
  9. package/dist/esm/annotation/annotation-style.js.map +1 -0
  10. package/dist/esm/annotation/draw-controller.js +114 -0
  11. package/dist/esm/annotation/draw-controller.js.map +1 -0
  12. package/dist/esm/annotation/text-controller.js +234 -0
  13. package/dist/esm/annotation/text-controller.js.map +1 -0
  14. package/dist/esm/core/default-options.js +240 -9
  15. package/dist/esm/core/default-options.js.map +1 -1
  16. package/dist/esm/core/editor-object-kind.js +37 -0
  17. package/dist/esm/core/editor-object-kind.js.map +1 -0
  18. package/dist/esm/core/errors.js +19 -0
  19. package/dist/esm/core/errors.js.map +1 -1
  20. package/dist/esm/core/layer-order.js +100 -0
  21. package/dist/esm/core/layer-order.js.map +1 -0
  22. package/dist/esm/core/public-types.js +34 -1
  23. package/dist/esm/core/public-types.js.map +1 -1
  24. package/dist/esm/core/state-serializer.js +112 -24
  25. package/dist/esm/core/state-serializer.js.map +1 -1
  26. package/dist/esm/crop/crop-controller.js +220 -10
  27. package/dist/esm/crop/crop-controller.js.map +1 -1
  28. package/dist/esm/export/export-format.js.map +1 -1
  29. package/dist/esm/export/export-service.js +157 -168
  30. package/dist/esm/export/export-service.js.map +1 -1
  31. package/dist/esm/export/overlay-merge-service.js +75 -0
  32. package/dist/esm/export/overlay-merge-service.js.map +1 -0
  33. package/dist/esm/history/history-manager.js +2 -2
  34. package/dist/esm/history/history-manager.js.map +1 -1
  35. package/dist/esm/image/image-loader.js +20 -51
  36. package/dist/esm/image/image-loader.js.map +1 -1
  37. package/dist/esm/image/transform-controller.js +42 -0
  38. package/dist/esm/image/transform-controller.js.map +1 -1
  39. package/dist/esm/image-editor.js +1200 -72
  40. package/dist/esm/image-editor.js.map +1 -1
  41. package/dist/esm/index.js +1 -1
  42. package/dist/esm/index.js.map +1 -1
  43. package/dist/esm/mask/mask-factory.js +39 -14
  44. package/dist/esm/mask/mask-factory.js.map +1 -1
  45. package/dist/esm/mask/mask-label-manager.js +2 -0
  46. package/dist/esm/mask/mask-label-manager.js.map +1 -1
  47. package/dist/esm/mask/mask-list.js.map +1 -1
  48. package/dist/esm/mask/mask-style.js.map +1 -1
  49. package/dist/esm/mosaic/mosaic-controller.js +24 -28
  50. package/dist/esm/mosaic/mosaic-controller.js.map +1 -1
  51. package/dist/esm/utils/file.js +10 -0
  52. package/dist/esm/utils/file.js.map +1 -1
  53. package/dist/esm/utils/image-element-loader.js +55 -0
  54. package/dist/esm/utils/image-element-loader.js.map +1 -0
  55. package/dist/esm/utils/pointer.js +28 -0
  56. package/dist/esm/utils/pointer.js.map +1 -0
  57. package/dist/types/annotation/annotation-lock.d.ts +12 -0
  58. package/dist/types/annotation/annotation-lock.d.ts.map +1 -0
  59. package/dist/types/annotation/annotation-manager.d.ts +33 -0
  60. package/dist/types/annotation/annotation-manager.d.ts.map +1 -0
  61. package/dist/types/annotation/annotation-style.d.ts +13 -0
  62. package/dist/types/annotation/annotation-style.d.ts.map +1 -0
  63. package/dist/types/annotation/draw-controller.d.ts +43 -0
  64. package/dist/types/annotation/draw-controller.d.ts.map +1 -0
  65. package/dist/types/annotation/text-controller.d.ts +47 -0
  66. package/dist/types/annotation/text-controller.d.ts.map +1 -0
  67. package/dist/types/core/default-options.d.ts +14 -2
  68. package/dist/types/core/default-options.d.ts.map +1 -1
  69. package/dist/types/core/editor-object-kind.d.ts +29 -0
  70. package/dist/types/core/editor-object-kind.d.ts.map +1 -0
  71. package/dist/types/core/errors.d.ts +11 -1
  72. package/dist/types/core/errors.d.ts.map +1 -1
  73. package/dist/types/core/layer-order.d.ts +21 -0
  74. package/dist/types/core/layer-order.d.ts.map +1 -0
  75. package/dist/types/core/public-types.d.ts +272 -56
  76. package/dist/types/core/public-types.d.ts.map +1 -1
  77. package/dist/types/core/state-serializer.d.ts +34 -5
  78. package/dist/types/core/state-serializer.d.ts.map +1 -1
  79. package/dist/types/crop/crop-controller.d.ts +18 -14
  80. package/dist/types/crop/crop-controller.d.ts.map +1 -1
  81. package/dist/types/export/export-format.d.ts +9 -40
  82. package/dist/types/export/export-format.d.ts.map +1 -1
  83. package/dist/types/export/export-service.d.ts +45 -41
  84. package/dist/types/export/export-service.d.ts.map +1 -1
  85. package/dist/types/export/overlay-merge-service.d.ts +38 -0
  86. package/dist/types/export/overlay-merge-service.d.ts.map +1 -0
  87. package/dist/types/history/history-manager.d.ts +11 -14
  88. package/dist/types/history/history-manager.d.ts.map +1 -1
  89. package/dist/types/image/image-loader.d.ts +27 -22
  90. package/dist/types/image/image-loader.d.ts.map +1 -1
  91. package/dist/types/image/image-resampler.d.ts +1 -1
  92. package/dist/types/image/transform-controller.d.ts +19 -14
  93. package/dist/types/image/transform-controller.d.ts.map +1 -1
  94. package/dist/types/image-editor.d.ts +93 -15
  95. package/dist/types/image-editor.d.ts.map +1 -1
  96. package/dist/types/index.d.cts +3 -3
  97. package/dist/types/index.d.cts.map +1 -1
  98. package/dist/types/index.d.ts +3 -3
  99. package/dist/types/index.d.ts.map +1 -1
  100. package/dist/types/mask/mask-factory.d.ts.map +1 -1
  101. package/dist/types/mask/mask-label-manager.d.ts +10 -9
  102. package/dist/types/mask/mask-label-manager.d.ts.map +1 -1
  103. package/dist/types/mask/mask-list.d.ts +11 -12
  104. package/dist/types/mask/mask-list.d.ts.map +1 -1
  105. package/dist/types/mask/mask-style.d.ts +19 -20
  106. package/dist/types/mask/mask-style.d.ts.map +1 -1
  107. package/dist/types/mosaic/mosaic-controller.d.ts +3 -3
  108. package/dist/types/mosaic/mosaic-controller.d.ts.map +1 -1
  109. package/dist/types/ui/visibility-state.d.ts +2 -2
  110. package/dist/types/utils/file.d.ts +13 -0
  111. package/dist/types/utils/file.d.ts.map +1 -1
  112. package/dist/types/utils/image-element-loader.d.ts +19 -0
  113. package/dist/types/utils/image-element-loader.d.ts.map +1 -0
  114. package/dist/types/utils/pointer.d.ts +16 -0
  115. package/dist/types/utils/pointer.d.ts.map +1 -0
  116. package/dist/umd/image-editor.umd.js +1 -1
  117. package/dist/umd/image-editor.umd.js.map +1 -1
  118. 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(!this.running){this.running=!0;try{for(;this.queue.length>0;){const e=this.queue.shift();try{await e.run(),e.resolve()}catch(t){e.reject(t)}}}finally{this.running=!1,this.queue.length>0&&this.drainQueue()}}}}function i(e,t,i){const n=e.onWarning;if("function"==typeof n)try{n(t,i)}catch(e){console.warn("[ImageEditor] onWarning callback threw",e)}}function n(e,t,i){const n=e.onError;if("function"==typeof n)try{n(t,i)}catch(e){console.error("[ImageEditor] onError callback threw",e)}}const a=Object.freeze({jpeg:"jpeg",jpg:"jpeg","image/jpeg":"jpeg",png:"png","image/png":"png",webp:"webp","image/webp":"webp"}),o=Object.freeze({jpeg:"image/jpeg",png:"image/png",webp:"image/webp"});function r(e){var t;if(!e)return null;const i=String(e).toLowerCase();return Object.prototype.hasOwnProperty.call(a,i)&&null!==(t=a[i])&&void 0!==t?t:null}function s(e){return o[e]}function l(e,t){const i=Number(e);return Number.isFinite(i)?Math.max(0,Math.min(1,i)):t}function c(e,t){var i;const n=null!=e?e:{},a=n.fileType,o=n.format,c=function(e){var t;return null!==(t=r(e))&&void 0!==t?t:"jpeg"}(a||o),u=s(c);if("png"===c)return{format:c,mimeType:u,quality:void 0};return{format:c,mimeType:u,quality:l(null!==(i=n.quality)&&void 0!==i?i:t,t)}}const u=Object.freeze({}),h="expand",d={canvasWidth:800,canvasHeight:600,backgroundColor:"transparent",animationDuration:300,minScale:.1,maxScale:5,scaleStep:.05,rotationStep:90,defaultLayoutMode:h,layoutMode:h,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,defaultMaskConfig:u,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},m={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"},g={getText:e=>e.maskName},p=100,f=100,b=10,v=!0,y=!1,M=!1,C="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}),k=new Set(["canvasWidth","canvasHeight","backgroundColor","animationDuration","minScale","maxScale","scaleStep","rotationStep","defaultLayoutMode","downsampleOnLoad","downsampleMaxWidth","downsampleMaxHeight","downsampleQuality","preserveSourceFormat","downsampleMimeType","imageLoadTimeoutMs","maxHistorySize","exportMultiplier","maxExportPixels","exportAreaByDefault","mergeMaskByDefault","defaultMaskWidth","defaultMaskHeight","defaultMaskConfig","maskRotatable","maskLabelOnSelect","maskLabelOffset","maskName","groupSelection","showPlaceholder","initialImageBase64","defaultDownloadFileName","onImageLoadStart","onImageLoaded","onImageCleared","onImageChanged","onBusyChange","onEditorDisposed","onMasksChanged","onSelectionChange","onError","onWarning","label","crop","defaultMosaicConfig"]);function w(e){return"function"==typeof e?e:null}function S(e){return"fit"===e||"cover"===e||"expand"===e}function x(e){return S(e)?e:h}function O(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function E(e){return Array.isArray(e)?[...e]:e}function B(e){if(!O(e))return u;const t={};for(const[i,n]of Object.entries(e))"onCreate"!==i&&"fabricGenerator"!==i&&"styles"!==i&&(t[i]=E(n));const i=e.styles;if(O(i)){const e={};for(const[t,n]of Object.entries(i))e[t]=E(n);Object.freeze(e),t.styles=e}return Object.freeze(t),t}function A(e,t){const i=Number(e);return!Number.isFinite(i)||i<=0?t:Math.max(1,Math.floor(i))}function L(e,t){const i=Number(e);return!Number.isFinite(i)||i<=0?t:i}function j(e,t){const i=Number(e);return!Number.isFinite(i)||i<0?t:i}function F(e,t){const i=Number(e);return Number.isFinite(i)?i:t}function N(e){if(null==e)return d.downsampleQuality;const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):d.downsampleQuality}function T(e){const t=Number(e);return!Number.isFinite(t)||t<=0?d.maxExportPixels:Math.max(1,Math.floor(t))}function D(e){return"canvas"===e||"image"===e?e:d.exportAreaByDefault}function P(e){if(null==e)return;const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.min(1,t)):void 0}function R(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function z(e){return"number"==typeof e&&Number.isFinite(e)}function W(e){return{...e,previewStrokeDashArray:e.previewStrokeDashArray?[...e.previewStrokeDashArray]:null}}function U(e,t,i=e){const n=O(t)?t:{},a=W(e);return R(n,"brushSize")&&(a.brushSize=function(e,t){return z(e)&&e>0?e:t}(n.brushSize,i.brushSize)),R(n,"blockSize")&&(a.blockSize=function(e,t){return z(e)&&e>0?Math.max(1,Math.floor(e)):t}(n.blockSize,i.blockSize)),R(n,"previewStroke")&&(a.previewStroke="string"==typeof n.previewStroke?n.previewStroke:i.previewStroke),R(n,"previewStrokeWidth")&&(a.previewStrokeWidth=function(e,t){return z(e)&&e>=0?e:t}(n.previewStrokeWidth,i.previewStrokeWidth)),R(n,"previewStrokeDashArray")&&(a.previewStrokeDashArray=function(e,t){return null===e?null:Array.isArray(e)&&e.every(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0)?[...e]:t?[...t]:null}(n.previewStrokeDashArray,i.previewStrokeDashArray)),R(n,"previewFill")&&(a.previewFill="string"==typeof n.previewFill?n.previewFill:i.previewFill),R(n,"outputFileType")&&(a.outputFileType=function(e,t){var i;return"source"===e?"source":"string"!=typeof e?t:null!==(i=r(e))&&void 0!==i?i:t}(n.outputFileType,i.outputFileType)),R(n,"outputQuality")&&(a.outputQuality=function(e,t){if(null!=e)return z(e)?Math.max(0,Math.min(1,e)):t}(n.outputQuality,i.outputQuality)),a}function H(e,t){const i=e.previewStrokeDashArray,n=t.previewStrokeDashArray,a=i===n||Array.isArray(i)&&Array.isArray(n)&&i.length===n.length&&i.every((e,t)=>e===n[t]);return e.brushSize===t.brushSize&&e.blockSize===t.blockSize&&e.previewStroke===t.previewStroke&&e.previewStrokeWidth===t.previewStrokeWidth&&a&&e.previewFill===t.previewFill&&e.outputFileType===t.outputFileType&&e.outputQuality===t.outputQuality}function Q(e){var t,i,n,a;const o=null!=e?e:{},r={...d};for(const e of Object.keys(o)){if(!k.has(e))continue;if("label"===e||"crop"===e||"defaultMosaicConfig"===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=o[e];if(void 0!==t)if("downsampleQuality"!==e)if("maxExportPixels"!==e)if("exportAreaByDefault"!==e){if("defaultLayoutMode"===e){const e=x(t);r.defaultLayoutMode=e,r.layoutMode=e;continue}"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?"defaultMaskConfig"!==e?"maskLabelOffset"!==e?r[e]=t:r.maskLabelOffset=j(t,d.maskLabelOffset):r.defaultMaskConfig=B(t):r.defaultMaskHeight=L(t,d.defaultMaskHeight):r.defaultMaskWidth=L(t,d.defaultMaskWidth):r.exportMultiplier=L(t,d.exportMultiplier):r.imageLoadTimeoutMs=A(t,d.imageLoadTimeoutMs):r.downsampleMaxHeight=A(t,d.downsampleMaxHeight):r.downsampleMaxWidth=A(t,d.downsampleMaxWidth):r.rotationStep=F(t,d.rotationStep):r.scaleStep=L(t,d.scaleStep):r.maxScale=L(t,d.maxScale):r.minScale=L(t,d.minScale):r.animationDuration=j(t,d.animationDuration):r.canvasHeight=A(t,d.canvasHeight):r.canvasWidth=A(t,d.canvasWidth)}else r.exportAreaByDefault=D(t);else r.maxExportPixels=T(t);else r.downsampleQuality=N(t)}if(r.onImageLoadStart=w(o.onImageLoadStart),r.onImageLoaded=w(o.onImageLoaded),r.onImageCleared=w(o.onImageCleared),r.onImageChanged=w(o.onImageChanged),r.onBusyChange=w(o.onBusyChange),r.onEditorDisposed=w(o.onEditorDisposed),r.onMasksChanged=w(o.onMasksChanged),r.onSelectionChange=w(o.onSelectionChange),r.onError=w(o.onError),r.onWarning=w(o.onWarning),r.maxHistorySize=function(e){const t=Number(e);return Number.isFinite(t)?Math.max(1,Math.floor(t)):d.maxHistorySize}(r.maxHistorySize),r.maxExportPixels=T(r.maxExportPixels),r.minScale>r.maxScale){const e=r.minScale;r.minScale=r.maxScale,r.maxScale=e}const s=o.label&&"object"==typeof o.label?o.label:{},l={...m,...s.textOptions&&"object"==typeof s.textOptions?s.textOptions:{}},c={getText:"function"==typeof s.getText?s.getText:g.getText,textOptions:l};"function"==typeof s.create&&(c.create=s.create),Object.freeze(c.textOptions),Object.freeze(c);const u=o.crop&&"object"==typeof o.crop?o.crop:{},h={minWidth:L(u.minWidth,p),minHeight:L(u.minHeight,f),padding:j(u.padding,b),hideMasksDuringCrop:null!==(t=u.hideMasksDuringCrop)&&void 0!==t?t:v,preserveMasksAfterCrop:null!==(i=u.preserveMasksAfterCrop)&&void 0!==i?i:y,allowRotationOfCropRect:null!==(n=u.allowRotationOfCropRect)&&void 0!==n?n:M,exportFileType:null!==(a=u.exportFileType)&&void 0!==a?a:C,exportQuality:P(u.exportQuality)};Object.freeze(h);const S=function(e,t){return O(e)?U(t,e):W(t)}(o.defaultMosaicConfig,I);return S.previewStrokeDashArray&&Object.freeze(S.previewStrokeDashArray),Object.freeze(S),Object.freeze({...r,label:c,crop:h,defaultMosaicConfig:S})}class ${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 e of this.animationAborters)try{e()}catch{}this.animationAborters.clear()}registerAnimationAborter(e){if(this.isDisposedFlag){try{e()}catch{}return()=>{}}return this.animationAborters.add(e),()=>{this.animationAborters.delete(e)}}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 n=this.isOwnOperation(t);if(this.isAnimationActive)throw new Error(`[ImageEditor] Cannot run "${e}" while an animation is in progress.`);if(this.isLoadingActive&&!n)throw new Error(`[ImageEditor] Cannot run "${e}" while an image is loading.`);if(this.currentOperationToken&&!n)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 n=this.isOwnOperation(t);if(this.isLoadingActive&&!n)throw new Error(`[ImageEditor] Cannot run "${e}" while an image is loading.`);if(this.currentOperationToken&&!n)throw new Error(`[ImageEditor] Cannot run "${e}" while ${null!==(i=this.currentOperationName)&&void 0!==i?i:"another operation"} is running.`)}}function q(e){return"maskId"in e&&"number"==typeof e.maskId}const Y=["maskId","maskUid","maskName","isCropRect","maskLabel","originalAlpha","originalStroke","originalStrokeWidth","hasControls","selectable","strokeUniform","lockRotation","transparentCorners","borderColor","cornerColor","cornerSize","isMosaicPreview"];function X(e){var t,i,n;const{canvas:a,currentScale:o,currentRotation:r,baseImageScale:s}=e,l=null===(i=(t=a).getActiveObject)||void 0===i?void 0:i.call(t),c=l&&q(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"))})(l)&&a.discardActiveObject();const u=a.toJSON(Y);return function(e,t){if(Array.isArray(t))for(let i=0;i<t.length;i+=1){const n=e[i],a=t[i];n&&a&&("number"==typeof n.maskId&&(a.maskId=n.maskId),"string"==typeof n.maskUid&&(a.maskUid=n.maskUid),"string"==typeof n.maskName&&(a.maskName=n.maskName),"number"==typeof n.originalAlpha&&(a.originalAlpha=n.originalAlpha),"originalStroke"in n&&(a.originalStroke=n.originalStroke),"number"==typeof n.originalStrokeWidth&&(a.originalStrokeWidth=n.originalStrokeWidth),"boolean"==typeof n.hasControls&&(a.hasControls=n.hasControls),"boolean"==typeof n.selectable&&(a.selectable=n.selectable),"boolean"==typeof n.strokeUniform&&(a.strokeUniform=n.strokeUniform),"boolean"==typeof n.lockRotation&&(a.lockRotation=n.lockRotation),"boolean"==typeof n.transparentCorners&&(a.transparentCorners=n.transparentCorners),"string"==typeof n.borderColor&&(a.borderColor=n.borderColor),"string"==typeof n.cornerColor&&(a.cornerColor=n.cornerColor),"number"==typeof n.cornerSize&&(a.cornerSize=n.cornerSize),!0===n.isCropRect&&(a.isCropRect=!0),!0===n.maskLabel&&(a.maskLabel=!0),!0===n.isMosaicPreview&&(a.isMosaicPreview=!0))}}(a.getObjects(),u.objects),Array.isArray(u.objects)&&(u.objects=u.objects.filter(e=>!0!==e.isCropRect&&!0!==e.maskLabel&&!0!==e.isMosaicPreview)),u._editorState={currentScale:o,currentRotation:r,baseImageScale:s,currentImageMimeType:null!==(n=e.currentImageMimeType)&&void 0!==n?n:null},null!==c&&(u._editorState.activeMaskId=c),JSON.stringify(u)}async function G(e){var t,i;const{canvas:n,jsonString:a,setCanvasSize:o}=e,r="string"==typeof a?a:JSON.stringify(a),s=JSON.parse(r);"number"==typeof s.width&&s.width>0&&"number"==typeof s.height&&s.height>0&&o(s.width,s.height),await n.loadFromJSON(s);const l=n.getObjects();!function(e,t){var i,n,a,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!==(n=l.left)&&void 0!==n?n:0),u=Number(null!==(a=l.top)&&void 0!==a?a: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 n,a;return!s.has(i)&&((!t||e.type===t)&&(Math.abs((null!==(n=e.left)&&void 0!==n?n:0)-c)<.5&&Math.abs((null!==(a=e.top)&&void 0!==a?a: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 n=e[i];n&&(n.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(q).reduce((e,t)=>Math.max(e,t.maskId),0),originalImage:null!==(i=l.find(_))&&void 0!==i?i:null,objects:l,jsonString:r}}function _(e){if(q(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 V{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 J{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 K(e){if(null===e||"object"!=typeof e)return!1;return"function"==typeof e.Canvas}function Z(e,t){Object.setPrototypeOf(e,t.prototype)}class ee 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,Z(this,ee)}}class te 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,Z(this,te)}}class ie 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,Z(this,ie)}}class ne 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,Z(this,ne)}}class ae 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,Z(this,ae)}}class oe 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,Z(this,oe)}}class re 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,Z(this,re)}}const se="#ccc";function le(e){var t;const i=Number(e.originalStrokeWidth);e.set({stroke:null!==(t=e.originalStroke)&&void 0!==t?t:se,strokeWidth:Number.isFinite(i)?i:1})}function ce(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()},n=()=>{var e;t.set(function(e){var t;const i=Number(e.originalStrokeWidth),n=Number(e.originalAlpha);return{stroke:null!==(t=e.originalStroke)&&void 0!==t?t:se,strokeWidth:Number.isFinite(i)?i:1,opacity:Number.isFinite(n)?n:.5}}(t)),null===(e=t.canvas)||void 0===e||e.requestRenderAll()};t.on("mouseover",i),t.on("mouseout",n),t.imageEditorMaskHandlers={mouseover:i,mouseout:n}}function ue(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 n={};if(!Number.isFinite(Number(i.originalAlpha))){const e=Number(i.opacity);n.originalAlpha=Number.isFinite(e)?e:.5}if(null==i.originalStroke&&(n.originalStroke=null!==(t=i.stroke)&&void 0!==t?t:se),!Number.isFinite(Number(i.originalStrokeWidth))){const e=Number(i.strokeWidth);n.originalStrokeWidth=Number.isFinite(e)?e:1}Object.keys(n).length>0&&i.set(n),ce(i)}function he(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 de(e){var t,i,n,a,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!==(n=e.strokeWidth)&&void 0!==n?n:0,stroke:null!==(a=e.stroke)&&void 0!==a?a: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 me(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 ge(e){try{e.set({opacity:0,evented:!1,selectable:!1})}catch{}}function pe(e,t,i){const n=Number(e.left),a=Number(e.top),o=Number(e.width),r=Number(e.height);if(!Number.isFinite(n)||!Number.isFinite(a)||!Number.isFinite(o)||!Number.isFinite(r)||o<=0||r<=0)return!1;const s=n+o,l=a+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(n,0),d=Math.min(l,u)-Math.max(a,0);return h>0&&d>0}function fe(e,t,i,n={}){const a=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!==n.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(a))),g=Math.min(d-1,Math.max(0,Math.floor(o))),p=Math.min(h,Math.max(m+1,l(a+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 be(e){const t=Number(e);return!!Number.isFinite(t)&&Math.abs(t-Math.round(t))>.01}function ve(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 n=Number(e.left)||0,a=Number(e.top)||0;return{left:be(n),top:be(a),right:be(n+(Number(e.width)||0)),bottom:be(a+(Number(e.height)||0))}}function ye(e){e.setCoords();const t=e.getBoundingRect();return{left:t.left,top:t.top,width:t.width,height:t.height}}const Me=[6,4],Ce=.92;function Ie(e,t){const i=Number(e);return Number.isFinite(i)?i:t}function ke(e,t){const i=Number(e);if(Number.isFinite(i))return l(i,Ce);const n=Number(t);return Number.isFinite(n)?l(n,Ce):Ce}function we(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 Se(e){for(const t of e.prevEvented)try{t.object.set({evented:t.evented,selectable:t.selectable})}catch{}e.prevEvented=[]}function xe(e,t){we(e,t),Se(t),function(e){for(const t of e.maskBackups)me(t);e.maskBackups=[]}(t);try{e.canvas.selection=!!t.prevSelection}catch{}}function Oe(e,t){const i=ye(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 Ee(e){const t=e.getCropSession();if(t){e.canvas.discardActiveObject(),xe(e,t),e.setCropSession(null);try{e.canvas.renderAll()}catch{}}}async function Be(e){var t,i;const n=e.getCropSession();if(!n||!n.cropRect)return;const{canvas:a}=e;a.discardActiveObject();const o=n.beforeJson,l=n.cropRect,c=!!e.options.crop.preserveMasksAfterCrop;try{l.setCoords();const u=Number(l.angle)||0;if(!e.options.crop.allowRotationOfCropRect&&Math.abs(u%360)>.01)throw new ae("applyCrop failed: rotated crop rectangles are disabled.");const h=function(e){const t=Number(e.angle)||0,i=Math.abs(t%360);return i>.01&&Math.abs(i-360)>.01?ye(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))}}(l);if(!pe(h,a.getWidth(),a.getHeight()))throw new ae("applyCrop failed: crop region is empty or outside the canvas.");const d=fe(h,a.getWidth(),a.getHeight(),{includePartialPixels:!1}),m=c?function(e,t,i=[]){var n;const a=[],o=i.length>0?new Map(i.map(e=>[e.object,e])):null,r=e.getObjects().filter(q);for(const i of r)try{if(i.setCoords(),Oe(i,t)){const e=null!==(n=null==o?void 0:o.get(i))&&void 0!==n?n:de(i);a.push({mask:i,left:Ie(i.left,0),top:Ie(i.top,0),angle:Ie(i.angle,0),scaleX:Ie(i.scaleX,1),scaleY:Ie(i.scaleY,1),styleBackup:e})}e.remove(i)}catch{}return a}(a,d,n.maskBackups):[];Se(n),we(e,n),a.selection=!!n.prevSelection;const g=function(e){var t,i;const n=e.cropExportFileType,a=null==n||"source"===n?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=r(String(n)))&&void 0!==i?i:"png",o=s(a);return"png"===a?{format:a,mimeType:o}:{format:a,mimeType:o,quality:ke(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}),p={format:g.format,multiplier:1,left:d.left,top:d.top,width:d.width,height:d.height};void 0!==g.quality&&(p.quality=g.quality);const f=a.toDataURL(p);await e.loadImage(f),m.length>0&&(!function(e,t,i){var n;if(0===i.length)return;const{canvas:a}=e;let o=0;for(const e of i)try{me(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(),a.add(e.mask),a.bringObjectToFront(e.mask),ue(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===(n=e.updateMaskList)||void 0===n||n.call(e)}catch{}}(e,d,m),a.renderAll());const b=e.saveState();e.setCropSession(null),o&&b&&o!==b&&e.historyManager.push(new V(()=>e.loadFromState(b),()=>e.loadFromState(o)))}catch(t){xe(e,n),e.setCropSession(null);try{await e.loadFromState(o)}catch(e){console.warn("[ImageEditor] applyCrop: rollback failed",e)}if(t instanceof ae)throw t;const i=t instanceof Error?`applyCrop failed: ${t.message}`:"applyCrop failed";throw new ae(i,t)}}function Ae(e,t,i,n){if(!(Le(e)&&Le(t)&&Le(i)&&Le(n)))return{width:Math.max(1,Math.round(e)||1),height:Math.max(1,Math.round(t)||1),needsResize:!1};if(!(e>i||t>n))return{width:e,height:t,needsResize:!1};const a=Math.min(i/e,n/t);return{width:Math.max(1,Math.round(e*a)),height:Math.max(1,Math.round(t*a)),needsResize:!0}}function Le(e){return Number.isFinite(e)&&e>0}function je(e){const t=/^data:(image\/[a-z0-9+\-.]+)\s*;/i.exec(e);return t?t[1].toLowerCase():null}function Fe(e,t,i){return new Promise((n,a)=>{const o=Date.now(),r=setTimeout(()=>{a(new te(i,Date.now()-o))},t);e.then(e=>{clearTimeout(r),n(e)},e=>{clearTimeout(r),a(e)})})}function Ne(e,t){const i=Math.hypot(e.a,e.b),n=Math.hypot(e.c,e.d),a=Math.min(i>1e-8?i:Number.POSITIVE_INFINITY,n>1e-8?n:Number.POSITIVE_INFINITY);return!Number.isFinite(a)||a<=0?t:t/a}function Te(e,t,i,n){const a=Number(t.width)||0,o=Number(t.height)||0,r=Number(n);if(a<=0||o<=0||!Number.isFinite(i.x)||!Number.isFinite(i.y)||!Number.isFinite(r)||r<=0)return null;const s=function(e){if(e.length<6)return null;const t=e[0],i=e[1],n=e[2],a=e[3],o=e[4],r=e[5];return Number.isFinite(t)&&Number.isFinite(i)&&Number.isFinite(n)&&Number.isFinite(a)&&Number.isFinite(o)&&Number.isFinite(r)?{a:t,b:i,c:n,d:a,e:o,f:r}:null}(t.calcTransformMatrix());if(!s)return null;const l=function(e){const t=e.a*e.d-e.b*e.c;return!Number.isFinite(t)||Math.abs(t)<1e-8?null:{a:e.d/t,b:-e.b/t,c:-e.c/t,d:e.a/t,e:(e.c*e.f-e.d*e.e)/t,f:(e.b*e.e-e.a*e.f)/t}}(s);if(!l)return null;const c=function(e,t){return{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}(i,l),u=c.x+a/2,h=c.y+o/2;return u<0||h<0||u>a||h>o?null:{sourceX:u,sourceY:h,sourceRadius:Ne(s,r/2)}}function De(e,t,i,n,a){const o=e-i,r=t-n;return o*o+r*r<=a}function Pe(e,t,i){return 4*(i*e+t)}function Re(e){var t,i,n,a;const{imageData:o}=e,{width:r,height:s,data:l}=o,c=Number(e.centerX),u=Number(e.centerY),h=Number(e.radius);if(!Number.isFinite(c)||!Number.isFinite(u)||!Number.isFinite(h)||h<=0||r<=0||s<=0)return!1;const d=(m=e.blockSize,Number.isFinite(m)&&m>0?Math.max(1,Math.floor(m)):1);var m;const g=Math.max(0,Math.floor(c-h)),p=Math.min(r-1,Math.ceil(c+h)),f=Math.max(0,Math.floor(u-h)),b=Math.min(s-1,Math.ceil(u+h));if(g>p||f>b)return!1;const v=h*h;let y=!1;for(let e=f;e<=b;e+=d)for(let o=g;o<=p;o+=d){const s=Math.min(p,o+d-1),h=Math.min(b,e+d-1);let m=-1;for(let t=e;t<=h&&m<0;t+=1)for(let e=o;e<=s;e+=1)if(De(e,t,c,u,v)){m=Pe(r,e,t);break}if(m<0)continue;const g=null!==(t=l[m])&&void 0!==t?t:0,f=null!==(i=l[m+1])&&void 0!==i?i:0,M=null!==(n=l[m+2])&&void 0!==n?n:0,C=null!==(a=l[m+3])&&void 0!==a?a:0;for(let t=e;t<=h;t+=1)for(let e=o;e<=s;e+=1){if(!De(e,t,c,u,v))continue;const i=Pe(r,e,t);l[i]=g,l[i+1]=f,l[i+2]=M,l[i+3]=C,y=!0}}return y}function ze(e){const t=e;return!!t&&"number"==typeof t.x&&Number.isFinite(t.x)&&"number"==typeof t.y&&Number.isFinite(t.y)}function We(e,t){const i=t;if(ze(i.scenePoint))return i.scenePoint;if(ze(i.pointer))return i.pointer;if(ze(i.absolutePointer))return i.absolutePointer;if(i.e&&"function"==typeof e.getPointer){const t=e.getPointer(i.e);if(ze(t))return t}return null}function Ue(e){try{e.requestRenderAll()}catch{try{e.renderAll()}catch{}}}function He(e,t){var i;const{canvas:n}=e,a=null!==(i=t.previewCircle)&&void 0!==i?i:function(e){var t;const i=e.getMosaicConfig(),n=new e.fabric.Circle({left:0,top:0,radius:i.brushSize/2,originX:"center",originY:"center",fill:i.previewFill,stroke:i.previewStroke,strokeWidth:i.previewStrokeWidth,strokeDashArray:null!==(t=i.previewStrokeDashArray)&&void 0!==t?t:void 0,selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!1});return n.isMosaicPreview=!0,n}(e);return t.previewCircle=a,n.getObjects().includes(a)||n.add(a),n.bringObjectToFront(a),st(e),a}function Qe(e,t){const i=t.previewCircle;if(i){try{e.canvas.remove(i)}catch{}t.previewCircle=null}}function $e(e,t,i){var n;const a=t.rasterCache;if(!a)return null;const o=null!==(n=t.previewImage)&&void 0!==n?n:function(e,t,i){const n=new e.fabric.FabricImage(i.offscreenCanvas,{selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!0});return Je(n,t),n.set({selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!0}),n.isMosaicPreview=!0,n}(e,i,a);t.previewImage=o,Je(o,i),o.set({selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!0}),o.dirty=!0,e.canvas.getObjects().includes(o)||e.canvas.add(o),function(e,t,i){var n,a;const o=e.canvas.getObjects().indexOf(i);if(!(o<0))try{null===(a=(n=e.canvas).moveObjectTo)||void 0===a||a.call(n,t,o+1)}catch{}}(e,o,i);const r=t.previewCircle;return r&&e.canvas.getObjects().includes(r)&&e.canvas.bringObjectToFront(r),o}function qe(e,t){const i=t.previewImage;if(i){try{e.canvas.remove(i)}catch{}t.previewImage=null}}function Ye(e){var t;const i=null===(t=e.getMosaicSession())||void 0===t?void 0:t.previewCircle;i&&(i.set({visible:!1}),Ue(e.canvas))}function Xe(e,t){const i=e.getMosaicSession();if(!i)return;He(e,i).set({left:t.x,top:t.y,visible:!0}),Ue(e.canvas)}function Ge(e,t,i,n){e.canvas.on(i,n),t.handlers.push({eventName:i,callback:n})}function _e(e){var t;const i=e;try{const e=null===(t=i.getSrc)||void 0===t?void 0:t.call(i);if("string"==typeof e&&e.length>0)return e}catch{}return"string"==typeof i.src&&i.src.length>0?i.src:null}function Ve(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.floor(t):0}function Je(e,t){e.set({left:t.left,top:t.top,scaleX:t.scaleX,scaleY:t.scaleY,angle:t.angle,skewX:t.skewX,skewY:t.skewY,flipX:t.flipX,flipY:t.flipY,originX:t.originX,originY:t.originY,selectable:t.selectable,evented:t.evented,hasControls:t.hasControls,hoverCursor:t.hoverCursor}),e.setCoords()}async function Ke(e,t,i){if(t.rasterCache)return t.rasterCache;const a=function(e){var t,i,n,a,o;const r=null===(i=(t=e.canvas).getElement)||void 0===i?void 0:i.call(t);return null!==(o=null!==(n=null==r?void 0:r.ownerDocument)&&void 0!==n?n:null===(a=e.canvas.lowerCanvasEl)||void 0===a?void 0:a.ownerDocument)&&void 0!==o?o:document}(e),o=await function(e,t){return new Promise((i,n)=>{const a=e.createElement("img"),o=()=>{"function"==typeof a.removeEventListener?(a.removeEventListener("load",r),a.removeEventListener("error",s)):(a.onload=null,a.onerror=null)},r=()=>{const e=Ve(a.naturalWidth||a.width),t=Ve(a.naturalHeight||a.height);o(),e<=0||t<=0?n(new Error("Mosaic image decode failed: source image has no dimensions.")):i({element:a,width:e,height:t})},s=e=>{o(),n(new Error("string"==typeof e?`Mosaic image decode failed: ${e}`:"Mosaic image decode failed."))};t.startsWith("data:")||(a.crossOrigin="anonymous"),"function"==typeof a.addEventListener?(a.addEventListener("load",r,{once:!0}),a.addEventListener("error",s,{once:!0})):(a.onload=r,a.onerror=s),a.src=t})}(a,i),r=a.createElement("canvas");r.width=o.width,r.height=o.height;const s=r.getContext("2d");if(!s)return n(e.options,new Error("Mosaic could not obtain a 2D canvas context."),"Mosaic apply failed."),null;let l;s.drawImage(o.element,0,0,o.width,o.height);try{l=s.getImageData(0,0,o.width,o.height)}catch(t){return n(e.options,t,"Mosaic apply failed because the source image pixels could not be read."),null}const c={offscreenCanvas:r,renderingContext:s,imageData:l,source:i,width:o.width,height:o.height};return t.rasterCache=c,c}function Ze(e,t,i,n){const a=t.rasterCache;if(!a)return!1;const o=e.getMosaicConfig(),r=t.lastImagePoint,s=r?function(e,t){const i=t.sourceX-e.sourceX,n=t.sourceY-e.sourceY,a=Math.hypot(i,n),o=Math.min(e.sourceRadius,t.sourceRadius),r=Math.max(1,o/2),s=Math.max(1,Math.ceil(a/r)),l=[];for(let a=1;a<=s;a+=1){const o=a/s;l.push({sourceX:e.sourceX+i*o,sourceY:e.sourceY+n*o,sourceRadius:e.sourceRadius+(t.sourceRadius-e.sourceRadius)*o})}return l}(r,n):[n];let l=!1;for(const e of s)l=Re({imageData:a.imageData,centerX:e.sourceX,centerY:e.sourceY,radius:e.sourceRadius,blockSize:o.blockSize})||l;return t.lastImagePoint=n,l&&(t.hasUncommittedChanges=!0,a.renderingContext.putImageData(a.imageData,0,0),$e(e,t,i),Ue(e.canvas)),l}async function et(e,t,n){const a=e.getMosaicSession();if(!a||a!==t)return;const o=e.getOriginalImage();if(!o||!e.isImageLoaded())return;const r=e.getMosaicConfig(),s=Te(e.fabric,o,n,r.brushSize);if(!s)return void(a.lastImagePoint=null);const l=_e(o);if(!l)return void i(e.options,new Error("Mosaic cannot read the current image source."),"Mosaic skipped because the image source is unavailable.");await Ke(e,a,l)&&Ze(e,a,o,s)}async function tt(e,t,i){var n;if(t.commitRequested=!1,t.lastImagePoint=null,!t.hasUncommittedChanges||!t.rasterCache)return;const a=e.getOriginalImage();if(!a||!e.isImageLoaded())return;const o=null!==(n=_e(a))&&void 0!==n?n:t.rasterCache.source,l=t.rasterCache;l.renderingContext.putImageData(l.imageData,0,0);const c=function(e,t){var i,n,a,o;const l=e.getMosaicConfig(),c=l.outputFileType,u="source"===c?function(e){return"image/jpeg"===e?"jpeg":"image/webp"===e?"webp":"png"}(null!==(n=null!==(i=e.getCurrentImageMimeType())&&void 0!==i?i:function(e){return"image/jpeg"===e||"image/png"===e||"image/webp"===e?e:null}(je(t)))&&void 0!==n?n:"image/png"):null!==(a=r(String(c)))&&void 0!==a?a:"png",h=s(u);return"png"===u?{mimeType:h}:{mimeType:h,quality:null!==(o=l.outputQuality)&&void 0!==o?o:e.options.downsampleQuality}}(e,o),u=void 0===c.quality?l.offscreenCanvas.toDataURL(c.mimeType):l.offscreenCanvas.toDataURL(c.mimeType,c.quality),h=await async function(e,t){return await Fe(e.fabric.FabricImage.fromURL(t,{crossOrigin:"anonymous"}),e.options.imageLoadTimeoutMs,"Mosaic FabricImage.fromURL")}(e,u);Qe(e,t),qe(e,t);try{!function(e,t,i,n){const{canvas:a}=e;let o=!1,r=!1;try{Je(i,t),a.remove(t),o=!0,a.add(i),r=!0,a.sendObjectToBack(i),e.setOriginalImage(i),e.setCurrentImageMimeType(n),a.renderAll()}catch(n){try{r&&a.remove(i),o&&!a.getObjects().includes(t)&&(a.add(t),a.sendObjectToBack(t)),e.setOriginalImage(t)}catch{}throw n}}(e,a,h,c.mimeType);const i=e.captureSnapshot();!function(e,t){var i;const n=null!==(i=e.getLastSnapshot())&&void 0!==i?i:t;n&&t&&n!==t&&(e.historyManager.push(new V(async()=>{await e.loadFromState(t)},async()=>{await e.loadFromState(n)})),e.setLastSnapshot(t))}(e,i),l.source=u,t.hasUncommittedChanges=!1}finally{e.getMosaicSession()===t&&He(e,t)}e.updateInputs(),e.updateUi(),e.emitImageChanged(i)}async function it(e,t){const i=e.getMosaicSession();if(!i||i!==t||i.isApplying)return;i.isApplying=!0;const a=e.buildCallbackContext("applyMosaic",!1);e.emitBusyChangeIfChanged(a),e.updateUi();try{for(;e.getMosaicSession()===i&&i.pendingCanvasPoints.length>0;){const t=i.pendingCanvasPoints.shift();t&&await et(e,i,t)}e.getMosaicSession()===i&&i.commitRequested&&await tt(e,i,a)}finally{e.getMosaicSession()===i&&(i.isApplying=!1),e.emitBusyChangeIfChanged(a),e.updateUi(),e.getMosaicSession()===i&&(i.pendingCanvasPoints.length>0||i.commitRequested)&&it(e,i).catch(t=>{n(e.options,t,"Mosaic apply failed.")})}}function nt(e,t){const i=e.getMosaicSession();i&&(i.pendingCanvasPoints.push(t),i.pendingCanvasPoints.length>4096&&i.pendingCanvasPoints.splice(0,i.pendingCanvasPoints.length-4096),it(e,i).catch(t=>{n(e.options,t,"Mosaic apply failed.")}))}function at(e,t){t.commitRequested=!0,it(e,t).catch(t=>{n(e.options,t,"Mosaic apply failed.")})}function ot(e){if(e.getMosaicSession())return;if(!e.isImageLoaded()||!e.getOriginalImage())return;const{canvas:t}=e;e.hideAllMaskLabels(),t.discardActiveObject();const i=!!t.selection,n=t.defaultCursor,a=t.getObjects().map(e=>{var t,i;return{object:e,evented:null===(t=e.evented)||void 0===t||t,selectable:null===(i=e.selectable)||void 0===i||i}});for(const e of a)try{e.object.set({evented:!1,selectable:!1})}catch{}t.selection=!1,t.defaultCursor="crosshair";const o={previewCircle:null,previewImage:null,prevSelection:i,prevDefaultCursor:n,prevObjectStates:a,handlers:[],rasterCache:null,pendingCanvasPoints:[],isPointerDown:!1,isApplying:!1,commitRequested:!1,hasUncommittedChanges:!1,lastImagePoint:null};e.setMosaicSession(o),He(e,o),function(e,t){Ge(e,t,"mouse:move",t=>{const i=We(e.canvas,t);if(!i)return void Ye(e);Xe(e,i);const n=e.getMosaicSession();(null==n?void 0:n.isPointerDown)&&nt(e,i)}),Ge(e,t,"mouse:out",()=>{Ye(e);const t=e.getMosaicSession();(null==t?void 0:t.isPointerDown)&&(t.isPointerDown=!1,at(e,t))}),Ge(e,t,"mouse:down",t=>{const i=We(e.canvas,t);if(!i)return;const n=e.getMosaicSession();n&&(n.isPointerDown=!0,n.lastImagePoint=null,nt(e,i))}),Ge(e,t,"mouse:up",t=>{const i=e.getMosaicSession();if(!i)return;const n=We(e.canvas,t);n&&(Xe(e,n),nt(e,n)),i.isPointerDown=!1,at(e,i)})}(e,o),t.renderAll()}function rt(e){var t;const i=e.getMosaicSession();i&&(!function(e,t){for(const i of t.handlers)try{e.canvas.off(i.eventName,i.callback)}catch{}t.handlers=[]}(e,i),Qe(e,i),qe(e,i),function(e){for(const t of e.prevObjectStates)try{t.object.set({evented:t.evented,selectable:t.selectable})}catch{}e.prevObjectStates=[]}(i),e.canvas.selection=!!i.prevSelection,e.canvas.defaultCursor=null!==(t=i.prevDefaultCursor)&&void 0!==t?t:"default",e.setMosaicSession(null),e.canvas.renderAll())}function st(e){var t;const i=e.getMosaicSession(),n=null==i?void 0:i.previewCircle;if(!i||!n)return;const a=e.getMosaicConfig();n.set({radius:a.brushSize/2,fill:a.previewFill,stroke:a.previewStroke,strokeWidth:a.previewStrokeWidth,strokeDashArray:null!==(t=a.previewStrokeDashArray)&&void 0!==t?t:void 0}),e.canvas.bringObjectToFront(n),Ue(e.canvas)}function lt(e,t){const i=Number(e);if(Number.isFinite(i)&&i>0)return i;const n=Number(t);return Number.isFinite(n)&&n>0?n:1}function ct(e,t,i){const n=e,a=n[t],o="function"==typeof a?a.call(n):n[i];return Math.max(1,Math.ceil(Number.isFinite(o)?Number(o):1))}async function ut(e,t,i){return t?async function(e,t,i){if(!e.canvas)return await i();const n=e.canvas.getObjects().filter(q),a=n.map(de);try{return n.forEach((e,i)=>t(e,i)),await i()}finally{for(const e of a)me(e)}}({canvas:e.canvas,options:e.options},mt,i):async function(e,t){const i=ht(e.canvas).filter(q).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 ht(e){try{return e.getObjects()}catch{return[]}}function dt(e,t){return ht(e).includes(t)}function mt(e){try{e.set({opacity:1,fill:"#000",strokeWidth:0,stroke:null,selectable:!1}),"function"==typeof e.setCoords&&e.setCoords()}catch{}}function gt(e){return{width:Math.max(1,e.naturalWidth||e.width||1),height:Math.max(1,e.naturalHeight||e.height||1)}}function pt(e){return new Promise((t,i)=>{const n=new Image;n.crossOrigin="anonymous";const a=()=>{"function"==typeof n.removeEventListener?(n.removeEventListener("load",o),n.removeEventListener("error",r)):(n.onload=null,n.onerror=null)},o=()=>{a(),t(n)},r=()=>{a(),i(new Error("Failed to decode export data URL"))};"function"==typeof n.addEventListener?(n.addEventListener("load",o,{once:!0}),n.addEventListener("error",r,{once:!0})):(n.onload=o,n.onerror=r),n.src=e})}function ft(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 n=t.match(/^(?:rgba|hsla)\((.*),\s*([^,/)]+)\)$/i);if(n&&bt(n[2]))return!0;const a=t.match(/^[a-z][a-z0-9-]*\([^/]+\/\s*([^)]+)\)$/i);return!(!a||!bt(a[1]))}(i))return"#ffffff";const n=function(){try{return"undefined"==typeof document||"function"!=typeof document.createElement?null:document.createElement("canvas").getContext("2d")}catch{return null}}();if(!n)return t;n.fillStyle="#000001";const a=n.fillStyle;n.fillStyle=i;const o=n.fillStyle;if(o!==a)return o;n.fillStyle="#000002";const r=n.fillStyle;n.fillStyle=i;const s=n.fillStyle;return s!==r?s:t}(e)}function bt(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 vt(e){console.warn(`[ImageEditor] ${e} skipped: no image is loaded on the canvas.`)}async function yt(e,t){if(!e.isImageLoaded())return vt("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),n=function(e){const t=[];for(const i of ht(e)){if(!q(i))continue;const n=i.labelObject;if(!n)continue;const a=dt(e,n);t.push({mask:i,label:n,wasOnCanvas:a,visible:n.visible});try{"function"==typeof n.set&&n.set({visible:!1}),a&&e.remove(n)}catch{}}return t}(e.canvas);try{e.canvas.discardActiveObject();const i=function(e,t){const i=null!=t?t:{};return{exportArea:(n=i.exportArea,a=e.options.exportAreaByDefault,"canvas"===n||"image"===n?n:"canvas"===a?"canvas":"image"),mergeMask:"boolean"==typeof i.mergeMask?i.mergeMask:e.options.mergeMaskByDefault,multiplier:lt(i.multiplier,e.options.exportMultiplier),format:c(i,e.options.downsampleQuality)};var n,a}(e,t),{region:n,partialEdges:a}=function(e,t){if("canvas"===t)return{region:null,partialEdges:null};const i=e.getOriginalImage();if(!i)return{region:null,partialEdges:null};const n=ye(i),a=e.canvas,o="function"==typeof a.getWidth?a.getWidth():a.width,r="function"==typeof a.getHeight?a.getHeight():a.height;if(!pe(n,o,r))throw new re("exportImageBase64 failed: image export region is empty.");return{region:fe(n,o,r,{includePartialPixels:!0}),partialEdges:ve(n,Number(i.angle)||0)}}(e,i.exportArea);!function(e,t,i){var n,a;const o=null!==(n=null==i?void 0:i.width)&&void 0!==n?n:ct(e.canvas,"getWidth","width"),r=null!==(a=null==i?void 0:i.height)&&void 0!==a?a:ct(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,n);const o=n&&"jpeg"===i.format.format?"png":i.format.format,r="png"===o?void 0:i.format.quality;let s=await ut(e,i.mergeMask,async()=>function(e,t,i,n,a){const o={format:t,multiplier:n};return void 0!==i&&(o.quality=i),a&&(o.left=a.left,o.top=a.top,o.width=a.width,o.height=a.height),e.toDataURL(o)}(e.canvas,o,r,i.multiplier,n));if(n){const t="jpeg"===i.format.format?{format:"png",mimeType:"image/png",quality:void 0}:i.format;s=await async function(e,t,i){if(!function(e){return!!e&&(e.left||e.top||e.right||e.bottom)}(t))return e;const n=await pt(e),{width:a,height:o}=gt(n),r=document.createElement("canvas");r.width=a,r.height=o;const s=r.getContext("2d");if(!s)throw new Error("2D canvas context is unavailable");s.drawImage(n,0,0,a,o);const l=s.getImageData(0,0,a,o),c=l.data,u=(e,t,i,n)=>{var o,r,s,l,u,h;const d=4*(t*a+e),m=4*(n*a+i),g=null!==(o=c[d+3])&&void 0!==o?o:0,p=null!==(r=c[m+3])&&void 0!==r?r:0;0===g&&p>0&&(c[d]=null!==(s=c[m])&&void 0!==s?s:0,c[d+1]=null!==(l=c[m+1])&&void 0!==l?l:0,c[d+2]=null!==(u=c[m+2])&&void 0!==u?u:0,c[d+3]=p);const f=null!==(h=c[d+3])&&void 0!==h?h:0;f>0&&f<255&&(c[d+3]=255)};if((null==t?void 0:t.left)&&a>1)for(let e=0;e<o;e+=1)u(0,e,1,e);if((null==t?void 0:t.right)&&a>1)for(let e=0;e<o;e+=1)u(a-1,e,a-2,e);if((null==t?void 0:t.top)&&o>1)for(let e=0;e<a;e+=1)u(e,0,e,1);if((null==t?void 0:t.bottom)&&o>1)for(let e=0;e<a;e+=1)u(e,o-1,e,o-2);return s.putImageData(l,0,0),void 0===i.quality?r.toDataURL(i.mimeType):r.toDataURL(i.mimeType,i.quality)}(s,a,t),"jpeg"===i.format.format&&(s=await async function(e,t,i){const n=await pt(e),{width:a,height:o}=gt(n),r=document.createElement("canvas");r.width=a,r.height=o;const s=r.getContext("2d");if(!s)throw new Error("2D canvas context is unavailable");return s.fillStyle=ft(t),s.fillRect(0,0,a,o),s.drawImage(n,0,0,a,o),r.toDataURL("image/jpeg",i)}(s,e.options.backgroundColor,i.format.quality))}return 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&&!dt(e,i.label)&&(e.add(i.label),e.bringObjectToFront(i.label))}catch{}}(e.canvas,n),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 Mt(e,t){var i;if(!e.isImageLoaded())throw vt("exportImageFile"),new oe("exportImageFile");const n=null!=t?t:{},a=null!==(i=n.fileName)&&void 0!==i?i:e.options.defaultDownloadFileName,o=c(n,e.options.downsampleQuality),r=await yt(e,{exportArea:n.exportArea,mergeMask:n.mergeMask,multiplier:n.multiplier,quality:n.quality,fileType:n.fileType});if(!r)throw new oe("exportImageFile");const s=await async function(e,t,i){if(e.startsWith(`data:${t.mimeType}`))return e;const n=await pt(e),{width:a,height:o}=gt(n),r=document.createElement("canvas");r.width=a,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=ft(i),s.fillRect(0,0,a,o)),s.drawImage(n,0,0,a,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+/=]+)$/i.exec(e),n=null!==(t=null==i?void 0:i[1])&&void 0!==t?t:"";if(!n)throw new Error("exportImageFile received a malformed or empty image data URL.");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 a=globalThis.Buffer;if(a&&"function"==typeof a.from){const e=a.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 re("exportImageFile failed to decode rendered data URL.",e)}return new File([l],a,{type:o.mimeType})}function Ct(e,t){if(!e.isImageLoaded())return void vt("downloadImage");const i=null!=t?t:e.options.defaultDownloadFileName;yt(e,{exportArea:e.options.exportAreaByDefault,mergeMask:e.options.mergeMaskByDefault,multiplier:e.options.exportMultiplier}).then(t=>{if(!t)return;const n=function(e){var t,i,n,a,o;const r=e;return null!==(o=null!==(n=null===(i=null===(t=r.getElement)||void 0===t?void 0:t.call(r))||void 0===i?void 0:i.ownerDocument)&&void 0!==n?n:null===(a=r.lowerCanvasEl)||void 0===a?void 0:a.ownerDocument)&&void 0!==o?o:document}(e.canvas),a=n.createElement("a");a.download=i,a.href=t;const o=n.body;o.appendChild(a);try{a.click()}finally{o.removeChild(a)}}).catch(t=>{n(e.options,t,"downloadImage failed."),console.error("[ImageEditor] downloadImage failed",t)})}class It{constructor(){Object.defineProperty(this,"lastVisible",{enumerable:!0,configurable:!0,writable:!0,value:null})}measure(e,t,i){var n;if(!e)return t;const a=Math.floor(e.clientWidth),o=Math.floor(e.clientHeight);return a>0&&o>0?(this.lastVisible=function(e,t,i){if(!e)return t;const n=Math.floor(e.clientWidth||0),a=Math.floor(e.clientHeight||0);if(n<=0||a<=0)return t;const o=function(e){var t,i;const n=e.style;let a="",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);a=t.overflow,o=t.overflowX,r=t.overflowY}const l=[wt(null==n?void 0:n.overflow),wt(null==n?void 0:n.overflowX),wt(a),wt(o)],c=[wt(null==n?void 0:n.overflow),wt(null==n?void 0:n.overflowY),wt(a),wt(r)];return{x:l,y:c,all:[...l,...c]}}(e);if(o.all.includes("scroll"))return{width:n,height:a};const r=Ot(i),s=o.x.some(St),l=o.y.some(St),c=Math.ceil(e.scrollWidth||0),u=Math.ceil(e.scrollHeight||0),h=s&&c>n+kt;return{width:n+(l&&u>a+kt?r.width:0),height:a+(h?r.height:0)}}(e,t,i),this.lastVisible):null!==(n=this.lastVisible)&&void 0!==n?n:t}peek(){return this.lastVisible}clear(){this.lastVisible=null}}const kt=.5;function wt(e){return String(null!=e?e:"").trim().toLowerCase()}function St(e){return"auto"===e||"overlay"===e}function xt(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 n=Math.max(0,i.offsetWidth-i.clientWidth),a=Math.max(0,i.offsetHeight-i.clientHeight);return i.remove(),{width:n,height:a}}function Ot(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 Et(e,t,i,n){const a=Math.max(1,i.width||1),o=Math.max(1,i.height||1),r=Ot(n);let s=!1,l=!1;for(let i=0;i<4;i+=1){const i=Math.max(1,a-(l?r.width:0)),n=Math.max(1,o-(s?r.height:0)),c=e>i+kt,u=t>n+kt;if(c===s&&u===l)break;s=c,l=u}const c=Math.max(1,a-(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 Bt(e,t,i,n){const a=Math.max(1,Math.round(Number(t)||1)),o=Math.max(1,Math.round(Number(i)||1));var r;e.setDimensions({width:a,height:o}),(r=n)&&r.offsetWidth}async function At(e,t,a={}){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,originalImage:e.getOriginalImage(),isImageLoadedToCanvas:e.getIsImageLoadedToCanvas(),lastSnapshot:e.getLastSnapshot(),canvasJson:Ft(e.canvas),maskCounter:e.getMaskCounter(),currentScale:e.getCurrentScale(),currentRotation:e.getCurrentRotation(),baseImageScale:e.getBaseImageScale(),currentImageMimeType:e.getCurrentImageMimeType()};try{e.setPlaceholderVisible(!1);const n=function(e){const t=new Image,i=(e=!1)=>{"function"==typeof t.removeEventListener?(t.removeEventListener("load",n),t.removeEventListener("error",a)):(t.onload=null,t.onerror=null),e&&(t.src="")},n=()=>{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 ee("Failed to decode image data URL: image has no natural dimensions.",null));i(!1),o(t)},a=e=>{i(!0),r(new ee("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",n,{once:!0}),t.addEventListener("error",a,{once:!0})):(t.onload=n,t.onerror=a),t.src=e});return{promise:s,cleanup:i}}(t);let r;try{r=await Fe(n.promise,e.options.imageLoadTimeoutMs,"image decode")}catch(e){throw n.cleanup(!0),e}const s=function(e,t,n,a){const o=jt(je(t));if(!n.downsampleOnLoad)return{dataUrl:t,mimeType:o};if(!Lt(n.downsampleMaxWidth)||!Lt(n.downsampleMaxHeight))return i(n,null,"loadImage skipped downsampling because downsample bounds are invalid."),{dataUrl:t,mimeType:o};const r=Ae(e.naturalWidth,e.naturalHeight,n.downsampleMaxWidth,n.downsampleMaxHeight);if(!r.needsResize)return{dataUrl:t,mimeType:o};const s=je(t),l=function(e,t,i,n,a,o,r,s){var l;const{width:c,height:u}=Ae(e.naturalWidth,e.naturalHeight,t,i),h=function(e,t,i){return i||(!t||"image/png"!==e&&"image/webp"!==e?"image/jpeg":e)}(n,a,o),d=null!==(l=null!=s?s:e.ownerDocument)&&void 0!==l?l:"undefined"!=typeof document?document:null;if(!d)throw new ie("Failed to obtain an owner document for downsampling.");const m=d.createElement("canvas");m.width=c,m.height=u;const g=m.getContext("2d");if(!g)throw new ie("Failed to obtain a 2D context for downsampling.");return g.drawImage(e,0,0,e.naturalWidth,e.naturalHeight,0,0,c,u),{dataUrl:"image/png"===h?m.toDataURL(h):m.toDataURL(h,r),width:c,height:u,mimeType:h}}(e,n.downsampleMaxWidth,n.downsampleMaxHeight,s,n.preserveSourceFormat,n.downsampleMimeType,n.downsampleQuality,a),c=jt(je(l.dataUrl));return{dataUrl:l.dataUrl,mimeType:null!=c?c:l.mimeType}}(r,t,e.options,function(e){var t,i,n,a,o;const r=e;return null!==(o=null!==(n=null===(i=null===(t=r.getElement)||void 0===t?void 0:t.call(r))||void 0===i?void 0:i.ownerDocument)&&void 0!==n?n:null===(a=r.lowerCanvasEl)||void 0===a?void 0:a.ownerDocument)&&void 0!==o?o:"undefined"!=typeof document?document:void 0}(e.canvas)),l=await Fe(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,n,a,o;const r=null!==(i=t.width)&&void 0!==i?i:0,s=null!==(n=t.height)&&void 0!==n?n:0,l=xt(null!==(o=null===(a=e.containerElement)||void 0===a?void 0:a.ownerDocument)&&void 0!==o?o:null),c=e.viewportCache.measure(e.containerElement,{width:e.options.canvasWidth,height:e.options.canvasHeight},l),u=e.options.layoutMode;if("fit"===u)return function(e,t,i,n,a){const o=Math.max(1,(a.width||i)-1),r=Math.max(1,(a.height||n)-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,n,a,o){const r=a.width||i,s=a.height||n,l=Ot(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)),n=Math.max(1,s-(c?l.height:0));h=Math.min(1,Math.max(i/e,n/t)),d=e*h,m=t*h;const a=d>i+kt,o=m>n+kt;if(a===c&&o===u)break;c=a,u=o}const g=Et(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,n,a){return{canvasWidth:Math.max(a.width,Math.floor(e)),canvasHeight:Math.max(a.height,Math.floor(t)),imageScale:1,imageLeft:0,imageTop:0,baseImageScale:1}}(r,s,e.options.canvasWidth,e.options.canvasHeight,c)}(e,l);if(Bt(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(X({canvas:e.canvas,currentScale:1,currentRotation:0,baseImageScale:c.baseImageScale,currentImageMimeType:s.mimeType})),!0===a.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){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 n(e.options,t,i),t}}function Lt(e){return Number.isFinite(e)&&e>0}function jt(e){return"image/jpeg"===e||"image/png"===e||"image/webp"===e?e:null}function Ft(e){e.discardActiveObject();const t=e.toJSON(Y);return JSON.stringify(t)}function Nt(e,t,i,n){return new Promise((a,o)=>{const r=Object.keys(t).length;if(0===r||n.isDisposed())return void a();let s=0,l=!1,c=[],u=null,h=null;const d=()=>{null!==u&&(clearTimeout(u),u=null),null==h||h(),h=null},m=()=>{l||(l=!0,d(),a())},g=()=>{for(const e of c)try{e()}catch{}m()},p=Number.isFinite(i.duration)?Math.max(0,i.duration):0;u=setTimeout(g,p+1e3),h=n.registerAnimationAborter(g);try{const a=e.animate(t,{duration:i.duration,onChange:()=>{var e;n.isDisposed()||null===(e=i.onChange)||void 0===e||e.call(i)},onComplete:()=>{++s>=r&&m()}});c=function(e){const t=Array.isArray(e)?e:e&&"object"==typeof e?Object.values(e):[e];return t.flatMap(e=>{const t=null==e?void 0:e.abort;return"function"==typeof t?[()=>t.call(e)]:[]})}(a)}catch(e){(e=>{l||(l=!0,d(),o(e))})(e)}})}class Tt{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 n=this.context.getBaseImageScale()*i;try{const e=Dt(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(()=>Nt(t,{scaleX:n,scaleY:n},{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:n,scaleY:n}),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(()=>Nt(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=Dt(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 Dt(e){e.setCoords();const t=e.getCoords()[0];if(t)return t;const i=e.getBoundingRect();return{x:i.left,y:i.top}}function Pt(e,t,i,n,a){if("number"==typeof e)return e;if("function"==typeof e)return e(n,a);if("string"==typeof e&&e.endsWith("%")){const a=parseFloat(e);if(!Number.isFinite(a))return i;const o="x"===t?n.getWidth():n.getHeight();return Math.floor(o*(a/100))}return i}function Rt(e){return Array.isArray(e)?{x:Number(e[0]),y:Number(e[1])}:{x:Number(e.x),y:Number(e.y)}}function zt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Wt(e,t){i(e,null,`createMask skipped: ${t}.`)}function Ut(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 Ht(e){return"number"==typeof e&&Number.isFinite(e)}function Qt(e,t,i){return!!Ht(i)||(Wt(e,`${t} must resolve to a finite number`),!1)}function $t(e,t,i){return!!(Ht(i)&&i>0)||(Wt(e,`${t} must resolve to a positive number`),!1)}function qt(e,t,i){return!!(Ht(i)&&i>=0)||(Wt(e,`${t} must resolve to a non-negative number`),!1)}function Yt(e,t){if(!Array.isArray(t)||t.length<3)return Wt(e,"polygon masks require at least three points"),null;const i=t.map(Rt);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 n=e[i],a=e[(i+1)%e.length];t+=n.x*a.y-a.x*n.y}return Math.abs(t)/2}(i)<=1e-6?(Wt(e,"polygon points must describe a non-zero area"),null):i:(Wt(e,"polygon points must contain finite x/y values"),null)}function Xt(e,t={}){var n,a,o,r,s,l,c,u,h,d,m,g,p,f,b,v;const{canvas:y,options:M,fabric:C}=e;if(!y)return null;const I=function(e,t){const i={...e},n=i.styles;delete i.onCreate,delete i.fabricGenerator,delete i.styles;const a=zt(t.styles)?t.styles:{},o=zt(n)?n:{};return{...i,...t,styles:{...o,...a}}}(M.defaultMaskConfig,t),k=null!==(n=I.shape)&&void 0!==n?n:"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,n]of i)if(!Ut(n))return Wt(e,`${t} is not a supported numeric value`),!1;return!0}(M,I))return null;const w={width:M.defaultMaskWidth,height:M.defaultMaskHeight,color:"rgba(0,0,0,0.5)",alpha:.5,gap:5,left:void 0,top:void 0,angle:0,selectable:!0,...I,shape:k};let S,x;const O=e.getLastMask();if(void 0===I.left&&O){const e=(null!==(a=O.left)&&void 0!==a?a:0)+("function"==typeof O.getScaledWidth?O.getScaledWidth():(null!==(o=O.width)&&void 0!==o?o:0)*(null!==(r=O.scaleX)&&void 0!==r?r:1));S=Math.round(e+(null!==(s=w.gap)&&void 0!==s?s:5)),x=null!==(l=O.top)&&void 0!==l?l:10}else S=Pt(I.left,"x",10,y,M),x=Pt(I.top,"y",10,y,M);w.width=Pt(I.width,"x",M.defaultMaskWidth,y,M),w.height=Pt(I.height,"y",M.defaultMaskHeight,y,M);const E=void 0!==I.rx?Pt(I.rx,"x",0,y,M):void 0,B=void 0!==I.ry?Pt(I.ry,"y",0,y,M):void 0,A="circle"===k?Pt(I.radius,"x",Math.min(w.width,w.height)/2,y,M):void 0,L="polygon"===k?Yt(M,I.points):null;if(!(Qt(M,"left",S)&&Qt(M,"top",x)&&$t(M,"width",w.width)&&$t(M,"height",w.height)&&Qt(M,"gap",w.gap)&&Qt(M,"angle",w.angle)&&Qt(M,"alpha",w.alpha)))return null;if(void 0!==E&&!qt(M,"rx",E)||void 0!==B&&!qt(M,"ry",B)||void 0!==A&&!$t(M,"radius",A)||"polygon"===k&&null===L)return null;if("expand"===M.layoutMode){const t=Math.ceil(S+w.width+10),i=Math.ceil(x+w.height+10),n=Math.max(y.getWidth(),t),a=Math.max(y.getHeight(),i);n===y.getWidth()&&a===y.getHeight()||(e.expandCanvasIfNeeded?e.expandCanvasIfNeeded(n,a):y.setDimensions({width:n,height:a}))}let j;if("function"==typeof t.fabricGenerator){const e=t.fabricGenerator(w,y,M);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(M,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:S,top:x,...e,radius:A,fill:w.color,opacity:w.alpha,angle:null!==(c=w.angle)&&void 0!==c?c:0,...w.styles});break;case"ellipse":j=new C.Ellipse({left:S,top:x,...e,rx:null!=E?E:w.width/2,ry:null!=B?B: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 t=new C.Polygon(L,{...e,fill:w.color,opacity:w.alpha,angle:null!==(h=w.angle)&&void 0!==h?h:0,...w.styles});t.setCoords();const i=t.getBoundingRect(),n=S-i.left,a=x-i.top;t.set({left:(null!==(d=t.left)&&void 0!==d?d:0)+n,top:(null!==(m=t.top)&&void 0!==m?m:0)+a}),t.setCoords(),j=t;break}default:j=new C.Rect({left:S,top:x,...e,width:w.width,height:w.height,fill:w.color,opacity:w.alpha,angle:null!==(g=w.angle)&&void 0!==g?g:0,...void 0!==E?{rx:E}:{},...void 0!==B?{ry:B}:{},...w.styles})}}const F=j;F.selectable=!("selectable"in I)||!!I.selectable,F.evented=!("evented"in I)||!!I.evented,F.hasControls=!("hasControls"in I)||!!I.hasControls,F.transparentCorners="transparentCorners"in I&&!!I.transparentCorners,F.strokeUniform=!("strokeUniform"in I)||!!I.strokeUniform,F.lockRotation=!M.maskRotatable,F.borderColor=null!==(p=I.borderColor)&&void 0!==p?p:"red",F.cornerColor=null!==(f=I.cornerColor)&&void 0!==f?f:"black",F.cornerSize=null!==(b=I.cornerSize)&&void 0!==b?b:8;const N=null!==(v=w.styles)&&void 0!==v?v:{};F.stroke="stroke"in N?N.stroke:"#ccc",F.strokeWidth="strokeWidth"in N?N.strokeWidth:1,"strokeDashArray"in N&&(F.strokeDashArray=N.strokeDashArray),F.originalAlpha=w.alpha,F.originalStroke=F.stroke,F.originalStrokeWidth=F.strokeWidth,ce(F);const T=e.getMaskCounter()+1;if(e.setMaskCounter(T),F.maskId=T,F.maskUid=`mask-${T}`,F.maskName=`${M.maskName}${T}`,e.setLastMask(F),y.add(F),y.bringObjectToFront(F),e.updateMaskList(),!1!==w.selectable&&y.setActiveObject(F),y.renderAll(),e.saveCanvasState(),"function"==typeof t.onCreate)try{t.onCreate(F,y)}catch(e){i(M,e,"createMask onCreate callback threw.")}return F}function Gt(e,t={}){const i=e.canvas.getObjects().filter(q);if(0!==i.length){for(const t of i)e.removeLabelForMask(t),he(t),e.canvas.remove(t);e.canvas.discardActiveObject(),e.setLastMask(null),e.updateMaskList(),e.canvas.renderAll(),!1!==t.saveHistory&&e.saveCanvasState()}}function _t(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 Vt(e,t){var n;const{canvas:a,options:o,fabric:r}=e;if(!a||!o.maskLabelOnSelect)return;_t(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 a=t.maskName;if("function"==typeof o.label.getText)try{a=o.label.getText(t,e)}catch(e){i(o,e,"label.getText callback threw."),a=t.maskName}const l={left:0,top:0,...null!==(n=o.label.textOptions)&&void 0!==n?n:{},originX:"left",originY:"top"};s=new r.FabricText(a,l)}s.maskLabel=!0,t.labelObject=s,a.add(s),a.bringObjectToFront(s),Jt(e,t)}function Jt(e,t){var i,n,a;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!==(n=r.maskLabelOffset)&&void 0!==n?n:3);t.labelObject.set({left:Math.round(l.x+u/d*m),top:Math.round(l.y+h/d*m),angle:null!==(a=t.angle)&&void 0!==a?a:0,originX:"left",originY:"top",visible:!0}),t.labelObject.setCoords(),o.renderAll()}function Kt(e){var t,i,n,a,o;const r=e.canvas;return null!==(o=null!==(n=null===(i=null===(t=null==r?void 0:r.getElement)||void 0===t?void 0:t.call(r))||void 0===i?void 0:i.ownerDocument)&&void 0!==n?n:null===(a=null==r?void 0:r.lowerCanvasEl)||void 0===a?void 0:a.ownerDocument)&&void 0!==o?o:document}class Zt{constructor(e,t,i=()=>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=e,this.isDisposed=t,this.resolveDocument=i}bindIfExists(e,t,i){const n=this.resolveElementId(e);if(!n)return!1;const a=this.resolveDocument().getElementById(n);if(!a)return!1;const o=e=>{this.isDisposed()||i(e)};return a.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=this.resolveDocument().getElementById(t);if(i)try{i.removeEventListener(e.eventType,e.handler)}catch{}}this.registry=[]}size(){return this.registry.length}}function ei(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 ti={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp"},ii=new Set(Object.values(ti));function ni(e){if(e)try{e.value=""}catch{}}const ai=.5,oi=Symbol("ImageEditorInternalOperation"),ri=Symbol("ImageEditorAllowDuringAnimationQueue"),si=["scalePercentageInput","rotateLeftDegreesInput","rotateRightDegreesInput","rotateLeftButton","rotateRightButton","createMaskButton","removeSelectedMaskButton","removeAllMasksButton","mergeMasksButton","downloadImageButton","zoomInButton","zoomOutButton","resetImageTransformButton","undoButton","redoButton","imageInput","enterCropModeButton","applyCropButton","cancelCropButton","enterMosaicModeButton","exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],li=["applyCropButton","cancelCropButton"],ci=new Set(["applyCrop","cancelCrop"]),ui=["scalePercentageInput","rotateLeftDegreesInput","rotateRightDegreesInput","rotateLeftButton","rotateRightButton","createMaskButton","removeSelectedMaskButton","removeAllMasksButton","mergeMasksButton","downloadImageButton","zoomInButton","zoomOutButton","resetImageTransformButton","undoButton","redoButton","imageInput","enterCropModeButton","applyCropButton","cancelCropButton","enterMosaicModeButton","exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],hi=["exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],di=new Set(["exitMosaicMode","applyMosaic","setMosaicConfig","resetMosaicConfig","setMosaicBrushSize","setMosaicBlockSize","saveState"]),mi=new Set(["init","loadImage","loadFromState","saveState","scaleImage","rotateImage","resetImageTransform","createMask","removeSelectedMask","removeAllMasks","mergeMasks","enterCropMode","applyCrop","cancelCrop","enterMosaicMode","exitMosaicMode","applyMosaic","setMosaicConfig","resetMosaicConfig","setMosaicBrushSize","setMosaicBlockSize","undo","redo","exportImageBase64","exportImageFile","downloadImage","dispose"]);class gi{constructor(e={},n={}){var a;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,"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 It}),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,"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 n;if(K(e))return{fabric:e,isFabricLoaded:!0,options:null!=t?t:{}};const a=null!==(n=e)&&void 0!==n?n:{},o=function(e){return e.fabric}(i);return K(o)?{fabric:o,isFabricLoaded:!0,options:a}:(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:a})}(e,n);this.fabricModule=null!==(a=o.fabric)&&void 0!==a?a:{},this.isFabricLoaded=o.isFabricLoaded,this.options=Q(o.options),this.currentLayoutMode=this.options.layoutMode,this.defaultMosaicConfig=this.options.defaultMosaicConfig,this.currentMosaicConfig=W(this.defaultMosaicConfig);const r=o.options.defaultLayoutMode;void 0===r||S(r)||i(this.options,new TypeError(`[ImageEditor] Unsupported defaultLayoutMode ${JSON.stringify(r)}. Expected "fit", "cover", or "expand".`),'Invalid defaultLayoutMode fell back to "expand".'),this.operationGuard=new $,this.animQueue=new t,this.historyManager=new J(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",enterMosaicModeButton:"enterMosaicModeButton",exitMosaicModeButton:"exitMosaicModeButton",mosaicBrushSizeInput:"mosaicBrushSizeInput",mosaicBlockSizeInput:"mosaicBlockSizeInput",uploadArea:"uploadArea",...e},this.domBindings=new Zt(e=>this.elements[e],()=>this.isDisposed,()=>{var e,t;return null!==(t=null===(e=this.canvasElement)||void 0===e?void 0:e.ownerDocument)&&void 0!==t?t:document}),this.initCanvas(),this.transformController=new Tt(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 n=this.elements.canvasContainer;this.containerElement=n&&null!==(e=document.getElementById(n))&&void 0!==e?e:i.parentElement;const a=this.elements.imagePlaceholder;this.placeholderElement=a?document.getElementById(a):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&&q(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&&q(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=>{n(this.options,e,"Crop apply failed.")})}),this.bindElementIfExists("cancelCropButton","click",()=>{this.cancelCrop()}),this.bindElementIfExists("enterMosaicModeButton","click",()=>{this.enterMosaicMode()}),this.bindElementIfExists("exitMosaicModeButton","click",()=>{this.exitMosaicMode()});const e=(e,t)=>{const i=e=>{const i=parseFloat(e.target.value);t(i)};this.bindElementIfExists(e,"input",i),this.bindElementIfExists(e,"change",i)};e("mosaicBrushSizeInput",e=>{this.setMosaicBrushSize(e)}),e("mosaicBlockSizeInput",e=>{this.setMosaicBlockSize(e)})}bindElementIfExists(e,t,i){var n;null===(n=this.domBindings)||void 0===n||n.bindIfExists(e,t,i)}async loadImageFile(e){const t=this.elements.imageInput,a=t?document.getElementById(t):null,o=function(e){var t,i;if(e.type&&ii.has(e.type))return e.type;if(e.type)return null;const n=/\.([a-z0-9]+)$/i.exec(e.name),a=null===(t=null==n?void 0:n[1])||void 0===t?void 0:t.toLowerCase();return a&&null!==(i=ti[a])&&void 0!==i?i:null}(e);if(!o)return i(this.options,null,`Unsupported image file type: ${e.type||e.name||"unknown"}.`),void ni(a);let r;try{r=await function(e){return new Promise((t,i)=>{const n=new FileReader;n.onload=()=>{const e=n.result;"string"==typeof e?t(e):i(new Error("FileReader returned a non-string result"))},n.onerror=()=>{var e;i(null!==(e=n.error)&&void 0!==e?e:new Error("FileReader error"))},n.onabort=()=>{i(new Error("FileReader read aborted"))},n.readAsDataURL(e)})}(e)}catch(e){return n(this.options,e,"Failed to read selected image file."),void ni(a)}try{await this.loadImage(r)}catch{}finally{ni(a)}}async loadImage(e,t={}){return this.loadImageInternal(e,t)}async loadImageInternal(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),n=this.originalImage,a=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.getRuntimeOptions(),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=>{ei(this.placeholderElement,this.containerElement,!!this.options.showPlaceholder&&e)}};try{await At(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(),n&&n!==this.originalImage&&this.emitOptionCallback("onImageCleared",[n,i]);const r=this.getImageInfo();r&&this.emitOptionCallback("onImageLoaded",[r,i]),a&&this.emitMasksChanged(i),this.emitImageChanged(i)}getInternalOperationToken(e){var t;return null!==(t=null==e?void 0:e[oi])&&void 0!==t?t:null}canRunDuringAnimationQueue(e){return!!(null==e?void 0:e[ri])}withInternalOperationOptions(e,t={}){return{...t,...e?{[oi]:e}:{}}}withAnimationQueueBypass(e={}){return{...e,[ri]:!0}}assertIdleForOperation(e,t){const i=this.getInternalOperationToken(t);if(this.operationGuard.assertIdleForOperation(e,i),this.cropSession&&!this.operationGuard.isOwnOperation(i)&&!ci.has(e))throw new Error(`[ImageEditor] Cannot run "${e}" while crop mode is active.`);if(this.mosaicSession&&!this.operationGuard.isOwnOperation(i)&&!di.has(e))throw new Error(`[ImageEditor] Cannot run "${e}" while mosaic 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(t){if(!this.isExpectedIdleGuardError(t,e))throw t;return!1}}isExpectedIdleGuardError(e,t){return e instanceof Error&&e.message.startsWith(`[ImageEditor] Cannot run "${t}" `)}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||null!==this.mosaicSession}setLayoutMode(e){S(e)?this.currentLayoutMode=e:i(this.options,new TypeError(`[ImageEditor] Unsupported layout mode ${JSON.stringify(e)}. 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(e,t=!1){return{operation:e,isInternalOperation:t}}getOperationContext(e,t){const i=this.getInternalOperationToken(t),n=this.operationGuard.activeOperationName();return i&&n?this.buildCallbackContext(null!==(a=n)&&mi.has(a)?n:e,!0):this.buildCallbackContext(e,!1);var a}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,n;try{this.originalImage.setCoords();const e=this.originalImage.getBoundingRect();i=Math.max(0,Number(e.width)||0),n=Math.max(0,Number(e.height)||0)}catch{i=Math.max(0,(Number(this.originalImage.width)||0)*Math.abs(Number(this.originalImage.scaleX)||1)),n=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:n,scale:this.currentScale,rotation:this.currentRotation,canvasWidth:e,canvasHeight:t}}getMasks(){return this.canvas?this.canvas.getObjects().filter(q).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,isMosaicMode:null!==this.mosaicSession,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(q);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?je(t):null;return this.isSupportedImageMimeType(i)?i:null}setCanvasSizePx(e,t){this.canvas&&Bt(this.canvas,e,t,this.containerElement)}alignObjectBoundingBoxToCanvasTopLeft(e){var t,i;e.setCoords();const n=e.getBoundingRect();e.set({left:(null!==(t=e.left)&&void 0!==t?t:0)-n.left,top:(null!==(i=e.top)&&void 0!==i?i:0)-n.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(),n=xt(null!==(t=null===(e=this.containerElement)||void 0===e?void 0:e.ownerDocument)&&void 0!==t?t:null),a=this.measureLayoutViewport(n);if("fit"===this.currentLayoutMode||"cover"===this.currentLayoutMode){const e=Et(i.width,i.height,a,n);return void this.setCanvasSizePx(e.width,e.height)}i.width<=a.width&&i.height<=a.height?this.setCanvasSizePx(a.width,a.height):this.setCanvasSizePx(Math.max(a.width,Math.ceil(i.width)),Math.max(a.height,Math.ceil(i.height)))}shouldNormalizeCanvasSizeAfterStateRestore(){var e,t;if(!this.canvas||!this.originalImage)return!1;this.originalImage.setCoords();const i=this.originalImage.getBoundingRect(),n=this.measureLayoutViewport(xt(null!==(t=null===(e=this.containerElement)||void 0===e?void 0:e.ownerDocument)&&void 0!==t?t:null)),a=Math.ceil(this.canvas.getWidth()),o=Math.ceil(this.canvas.getHeight()),r=i.width>a+ai||i.height>o+ai;if("fit"===this.currentLayoutMode||"cover"===this.currentLayoutMode){const e=a>n.width+ai&&i.width<=n.width+ai,t=o>n.height+ai&&i.height<=n.height+ai;return r||e||t}if("expand"===this.currentLayoutMode){const e=Math.max(n.width,Math.ceil(i.width)),t=Math.max(n.height,Math.ceil(i.height));return Math.abs(a-e)>ai||Math.abs(o-t)>ai}return r}settleFitCoverScrollbarsAfterStateRestore(){if(!this.canvas||!this.containerElement||"fit"!==this.currentLayoutMode&&"cover"!==this.currentLayoutMode)return;const e=Math.ceil(this.canvas.getWidth()),t=Math.ceil(this.canvas.getHeight());if(e<=1||t<=1)return;const i=Math.floor(this.containerElement.clientWidth||0),n=Math.floor(this.containerElement.clientHeight||0);if(i<=0||n<=0)return;const a=Math.ceil(this.containerElement.scrollWidth||0),o=Math.ceil(this.containerElement.scrollHeight||0),r=a>i+ai,s=o>n+ai;if(!r&&!s)return;const l=s&&Math.abs(e-i)<=1,c=r&&Math.abs(t-n)<=1;(l||c)&&(this.setCanvasSizePx(l?e-1:e,c?t-1:t),this.setCanvasSizePx(e,t))}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),n=Math.min(e.imageDisplayWidth/t,e.imageDisplayHeight/i);this.originalImage.set({left:0,top:0,angle:0,scaleX:n,scaleY:n,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=n,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.updateCanvasSizeToImageBounds(),this.alignObjectBoundingBoxToCanvasTopLeft(this.originalImage),this.canvas.getObjects().filter(q).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),n=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),n.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),n=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),n.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 a=this.activeStateRestoreOperation,o=this.buildCallbackContext(null!=a?a:"loadFromState","undo"===a||"redo"===a),r=this.originalImage,s=this.getMaskCollectionSignature();try{const t=await G({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 n=t.editorState;n&&(this.currentScale=n.currentScale,this.currentRotation=n.currentRotation,this.baseImageScale=n.baseImageScale),this.originalImage?this.currentImageMimeType=n&&"currentImageMimeType"in n?null!==(i=n.currentImageMimeType)&&void 0!==i?i:null:this.inferCurrentImageMimeType():this.currentImageMimeType=null,this.isImageLoadedToCanvas=!!this.originalImage,this.originalImage&&this.shouldNormalizeCanvasSizeAfterStateRestore()&&(this.updateCanvasSizeToImageBounds(),this.alignObjectBoundingBoxToCanvasTopLeft(this.originalImage)),this.originalImage&&this.settleFitCoverScrollbarsAfterStateRestore();const a=t.objects.filter(q);this.lastMask=a.reduce((e,t)=>!e||t.maskId>e.maskId?t:e,null),a.forEach(e=>{le(e),ue(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==n?void 0:n.activeMaskId;if("number"==typeof l){const e=a.find(e=>e.maskId===l);e&&this.withSelectionChangeContext(o,()=>{this.canvas.setActiveObject(e),this.handleSelectionChanged([e])})}}catch(e){throw n(this.options,e,"Failed to restore canvas state."),e}}saveState(){this.saveStateInternal()}saveStateInternal(e){var t,n;if(!this.canvas||this.shouldSuppressSaveState)return;if(!this.canRunIdleOperation("saveState",e))return;const a=this.canvas.getActiveObject(),o=this.getActiveMaskForSnapshot();this.hideAllMaskLabels();try{const e=X({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!==(n=this.lastSnapshot)&&void 0!==n?n:e;if(e===i)return;const a=new V(async()=>{await this.loadFromStateInternal(e,this.withAnimationQueueBypass())},async()=>{await this.loadFromStateInternal(i,this.withAnimationQueueBypass())});this.historyManager.push(a),this.lastSnapshot=e}catch(e){i(this.options,e,"Failed to capture canvas snapshot.")}finally{this.restoreActiveMaskAfterSnapshot(a,o),this.updateUi()}}restoreActiveMaskAfterSnapshot(e,t){if(!this.canvas)return;const i=e&&q(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(),n=this.withSelectionChangeContext(t,()=>Xt(i,e));return n&&(this.emitMasksChanged(t),this.emitImageChanged(t)),n}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&&q(t)&&(e.removeLabelForMask(t),he(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),n=this.buildRemoveMaskContext();this.withSelectionChangeContext(i,()=>Gt(n,e)),this.updateUi(),this.getMasks().length!==t&&(this.emitMasksChanged(i),this.emitImageChanged(i))}buildCreateMaskContext(){return{fabric:this.fabricModule,canvas:this.canvas,options:this.getRuntimeOptions(),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&&_t(t,e)}createLabelForMask(e){const t=this.buildMaskLabelContext();t&&Vt(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(q).forEach(e=>{try{delete e.labelObject}catch{}})}(e)}syncMaskLabel(e){const t=this.buildMaskLabelContext();t&&Jt(t,e)}showLabelForMask(e){const t=this.buildMaskLabelContext();t&&function(e,t){e.options.maskLabelOnSelect&&(t.labelObject||Vt(e,t),t.labelObject&&(t.labelObject.visible=!0,Jt(e,t)))}(t,e)}handleSelectionChanged(e){var t,i,n;if(!this.canvas)return;const a=null!==(t=e.find(q))&&void 0!==t?t:null;this.canvas.getObjects().filter(q).forEach(e=>{e!==a?(e.labelObject&&this.removeLabelForMask(e),le(e)):e.set({stroke:"#ff0000",strokeWidth:1})}),a&&this.showLabelForMask(a),this.updateMaskListSelection(a),this.canvas.requestRenderAll(),this.updateUi();const o=null!==(i=this.nextSelectionChangeContext)&&void 0!==i?i:this.buildCallbackContext(null!==(n=this.activeStateRestoreOperation)&&void 0!==n?n:"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=Kt(e),n=i.getElementById(t);if(!n||!e.canvas)return;n.innerHTML="";const a=e.canvas;a.getObjects().filter(q).forEach(t=>{const o=i.createElement("li");o.className="list-group-item mask-item",o.textContent=t.maskName,o.dataset.maskId=String(t.maskId),o.onclick=()=>{const t=Number(o.dataset.maskId);if(!Number.isFinite(t))return;const i=a.getObjects().find(e=>q(e)&&e.maskId===t);i&&(a.setActiveObject(i),e.onMaskSelected(i))},n.appendChild(o)})}(this.buildMaskListContext())}updateMaskListSelection(e){!function(e,t){const i=e.getListElementId();if(!i)return;const n=Kt(e).getElementById(i);if(!n)return;const a=t?String(t.maskId):null;n.querySelectorAll(".mask-item").forEach(e=>{const t=null!==a&&e.dataset.maskId===a;e.classList.toggle("active",t)})}(this.buildMaskListContext(),e)}async mergeMasks(){if(!this.canvas)return;if(!this.canRunIdleOperation("mergeMasks"))return;if(!this.canvas.getObjects().some(q))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,n=e.containerElement?e.containerElement.scrollLeft:null;try{const a=await yt(e,{exportArea:"image",mergeMask:!0,multiplier:e.options.exportMultiplier,fileType:"png"});if(!a)throw new ne("mergeMasks: exportImageBase64 returned an empty data URL.");e.removeAllMasksNoHistory(),await e.loadImage(a,{preserveScroll:!0});const o=e.saveState();if(e.containerElement)try{null!==i&&(e.containerElement.scrollTop=i),null!==n&&(e.containerElement.scrollLeft=n)}catch(e){console.warn("[ImageEditor] mergeMasks: scroll restore failed",e)}t&&o&&t!==o&&e.historyManager.push(new V(()=>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 ne)throw i;const n=i instanceof Error?`mergeMasks failed: ${i.message}`:"mergeMasks failed";throw new ne(n,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{Ct(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 n=this.buildExportServiceContext();try{return await yt(n,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 n=this.buildExportServiceContext();try{return await Mt(n,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 n=this.captureImageDisplayGeometry();await this.loadImageInternal(t,this.withInternalOperationOptions(e,null!=i?i:{})),this.restoreMergedImageDisplayGeometry(n)},saveState:()=>this.captureSnapshotInternal(),loadFromState:t=>this.loadFromStateInternal(t,this.withInternalOperationOptions(e,this.withAnimationQueueBypass())),removeAllMasksNoHistory:()=>{Gt(this.buildRemoveMaskContext(),{saveHistory:!1})}}}captureSnapshotInternal(){var e;if(!this.canvas)throw new Error("[ImageEditor] Cannot capture canvas snapshot before init or after dispose.");const t=this.getActiveMaskForSnapshot();return this.hideAllMaskLabels(),X({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();if(t&&q(t))return t;const i=this.canvas.getObjects().filter(e=>q(e)&&!!e.labelObject);return 1===i.length&&null!==(e=i[0])&&void 0!==e?e:null}enterMosaicMode(){if(!this.canvas||!this.originalImage)return;if(this.mosaicSession)return;if(!this.isImageLoaded())return;if(!this.canRunIdleOperation("enterMosaicMode"))return;ot(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi();const e=this.buildCallbackContext("enterMosaicMode",!1);this.emitBusyChangeIfChanged(e),this.emitImageChanged(e)}exitMosaicMode(){if(!this.canvas||!this.mosaicSession)return;if(!this.canRunIdleOperation("exitMosaicMode"))return;rt(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi();const e=this.buildCallbackContext("exitMosaicMode",!1);this.emitBusyChangeIfChanged(e),this.emitImageChanged(e)}isMosaicMode(){return null!==this.mosaicSession}getMosaicConfig(){return W(this.currentMosaicConfig)}setMosaicConfig(e){this.applyMosaicConfigPatch(e,"setMosaicConfig")}resetMosaicConfig(){if(this.isDisposed)return;const e=W(this.defaultMosaicConfig);H(this.currentMosaicConfig,e)||(this.currentMosaicConfig=e,this.mosaicSession&&this.canvas&&st(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi(),this.emitImageChanged(this.buildCallbackContext("resetMosaicConfig",!1)))}setMosaicBrushSize(e){this.applyMosaicConfigPatch({brushSize:e},"setMosaicBrushSize")}setMosaicBlockSize(e){this.applyMosaicConfigPatch({blockSize:e},"setMosaicBlockSize")}applyMosaicConfigPatch(e,t){if(this.isDisposed)return;if(null===e||"object"!=typeof e||Array.isArray(e))return void i(this.options,new TypeError("[ImageEditor] Invalid Mosaic config object."),"Ignored invalid Mosaic config.");const n=function(e){const t=O(e)?e:{},i=[];if(!R(t,"brushSize")||"number"==typeof t.brushSize&&Number.isFinite(t.brushSize)&&t.brushSize>0||i.push("brushSize"),!R(t,"blockSize")||"number"==typeof t.blockSize&&Number.isFinite(t.blockSize)&&t.blockSize>0||i.push("blockSize"),R(t,"previewStroke")&&"string"!=typeof t.previewStroke&&i.push("previewStroke"),!R(t,"previewStrokeWidth")||"number"==typeof t.previewStrokeWidth&&Number.isFinite(t.previewStrokeWidth)&&t.previewStrokeWidth>=0||i.push("previewStrokeWidth"),R(t,"previewStrokeDashArray")){const e=t.previewStrokeDashArray;null===e||Array.isArray(e)&&e.every(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0)||i.push("previewStrokeDashArray")}if(R(t,"previewFill")&&"string"!=typeof t.previewFill&&i.push("previewFill"),R(t,"outputFileType")){const e=t.outputFileType;"source"===e||"string"==typeof e&&r(e)||i.push("outputFileType")}return!R(t,"outputQuality")||void 0===t.outputQuality||null===t.outputQuality||"number"==typeof t.outputQuality&&Number.isFinite(t.outputQuality)||i.push("outputQuality"),i}(e);n.length>0&&i(this.options,new TypeError(`[ImageEditor] Ignored invalid Mosaic config field(s): ${n.join(", ")}.`),"Ignored invalid Mosaic config fields.");const a=U(this.currentMosaicConfig,e);H(this.currentMosaicConfig,a)||(this.currentMosaicConfig=a,this.mosaicSession&&this.canvas&&st(this.buildMosaicControllerContext()),this.updateInputs(),this.updateUi(),this.emitImageChanged(this.buildCallbackContext(t,!1)))}buildMosaicControllerContext(){return{fabric:this.fabricModule,canvas:this.canvas,options:this.options,historyManager:this.historyManager,getMosaicConfig:()=>W(this.currentMosaicConfig),isImageLoaded:()=>this.isImageLoaded(),getOriginalImage:()=>this.originalImage,setOriginalImage:e=>{this.originalImage=e},getCurrentImageMimeType:()=>this.currentImageMimeType,setCurrentImageMimeType:e=>{this.currentImageMimeType=e},getLastSnapshot:()=>this.lastSnapshot,setLastSnapshot:e=>{this.lastSnapshot=e},captureSnapshot:()=>this.captureSnapshotInternal(),loadFromState:e=>this.loadFromStateInternal(e,this.withAnimationQueueBypass()),updateUi:()=>{this.updateUi()},updateInputs:()=>{this.updateInputs()},hideAllMaskLabels:()=>{this.hideAllMaskLabels()},emitImageChanged:e=>{this.emitImageChanged(e)},emitBusyChangeIfChanged:e=>{this.emitBusyChangeIfChanged(e)},buildCallbackContext:(e,t)=>this.buildCallbackContext(e,t),getMosaicSession:()=>this.mosaicSession,setMosaicSession:e=>{this.mosaicSession=e}}}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 n=e.getOriginalImage();if(!n)return;if(!e.isImageLoaded())return;t.discardActiveObject();const a=e.saveState(),o=!!t.selection;t.selection=!1,n.setCoords();const r=n.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:Me,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 M=!!i.crop.hideMasksDuringCrop,C=[];M&&t.getObjects().forEach(e=>{e!==y&&q(e)&&C.push(de(e))});const I=[];if(t.getObjects().forEach(e=>{var t,i;if(e!==y){I.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{}}}),M)for(const e of C)ge(e.object);const k=()=>{try{const e=Math.max(1,Number(y.width)||1),i=Math.max(1,Number(y.height)||1),n=Math.min(u/e,Math.max(f/e,Number(y.scaleX)||1)),a=Math.min(h/i,Math.max(b/i,Number(y.scaleY)||1)),o=e*n,r=i*a,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:n,scaleY:a}),y.setCoords(),t.requestRenderAll()}catch{}};y.on("modified",k),y.on("moving",k),y.on("scaling",k);const w={beforeJson:a,prevSelection:o,prevEvented:I,maskBackups:C,cropRect:y,handlers:[{target:y,handlers:[{eventName:"modified",callback:k},{eventName:"moving",callback:k},{eventName:"scaling",callback:k}]}]};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;Ee(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 n=this.buildCropControllerContext(i);await Be(n),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.loadImageInternal(t,this.withInternalOperationOptions(e,null!=i?i:{})),getMaskCounter:()=>this.maskCounter,setMaskCounter:e=>{this.maskCounter=e},updateMaskList:()=>{this.updateMaskList()}}}updateInputs(){const e=this.elements.scalePercentageInput;if(e){const t=document.getElementById(e);t&&(t.value=String(Math.round(100*this.currentScale)))}const t=this.getMosaicConfig(),i=this.elements.mosaicBrushSizeInput;if(i){const e=document.getElementById(i);e&&(e.value=String(t.brushSize))}const n=this.elements.mosaicBlockSizeInput;if(n){const e=document.getElementById(n);e&&(e.value=String(t.blockSize))}}updateUi(){var e;if(!this.canvas)return;const t=!!this.originalImage,i=(t?this.canvas.getObjects().filter(q):[]).length>0,n=this.canvas.getActiveObject(),a=!(!n||!q(n)),o=1===this.currentScale&&0===this.currentRotation,r=this.historyManager.canUndo(),s=this.historyManager.canRedo(),l=null!==this.cropSession,c=null!==this.mosaicSession,u=this.operationGuard.isBusy()||this.animQueue.isBusy(),h=!0===(null===(e=this.mosaicSession)||void 0===e?void 0:e.isApplying);if(l)si.forEach(e=>{this.setControlEnabled(e,!u&&li.includes(e))});else{if(c)return ui.forEach(e=>{this.setControlEnabled(e,!u&&!h&&hi.includes(e))}),void this.setControlEnabled("imageInput",!1);this.setControlEnabled("scalePercentageInput",t&&!u),this.setControlEnabled("rotateLeftDegreesInput",t&&!u),this.setControlEnabled("rotateRightDegreesInput",t&&!u),this.setControlEnabled("zoomInButton",t&&!u&&this.currentScale<this.options.maxScale),this.setControlEnabled("zoomOutButton",t&&!u&&this.currentScale>this.options.minScale),this.setControlEnabled("rotateLeftButton",t&&!u),this.setControlEnabled("rotateRightButton",t&&!u),this.setControlEnabled("createMaskButton",t&&!u),this.setControlEnabled("removeSelectedMaskButton",a&&!u),this.setControlEnabled("removeAllMasksButton",i&&!u),this.setControlEnabled("mergeMasksButton",t&&i&&!u),this.setControlEnabled("downloadImageButton",t&&!u),this.setControlEnabled("resetImageTransformButton",t&&!o&&!u),this.setControlEnabled("undoButton",t&&!u&&r),this.setControlEnabled("redoButton",t&&!u&&s),this.setControlEnabled("enterCropModeButton",t&&!u),this.setControlEnabled("enterMosaicModeButton",t&&!u),this.setControlEnabled("exitMosaicModeButton",!1),this.setControlEnabled("mosaicBrushSizeInput",!this.isDisposed),this.setControlEnabled("mosaicBlockSizeInput",!this.isDisposed),this.setControlEnabled("imageInput",!u),this.setControlEnabled("applyCropButton",!1),this.setControlEnabled("cancelCropButton",!1)}}setControlEnabled(e,t){var i;const n=this.elements[e];if(!n)return;const a=document.getElementById(n);if(a)if(this.recordElementOriginalState(e,a),"disabled"in a)a.disabled=!t;else if(t){const t=this.elementOriginalAriaDisabledMap.get(e);null==t?a.removeAttribute("aria-disabled"):a.setAttribute("aria-disabled",t),a.style.pointerEvents=null!==(i=this.elementOriginalPointerEventsMap.get(e))&&void 0!==i?i:""}else a.setAttribute("aria-disabled","true"),a.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 n=this.elements[i];if(!n)continue;const a=document.getElementById(n);if(a){if("disabled"in a&&this.elementOriginalDisabledMap.has(i)&&(a.disabled=null!==(e=this.elementOriginalDisabledMap.get(i))&&void 0!==e&&e),this.elementOriginalAriaDisabledMap.has(i)){const e=this.elementOriginalAriaDisabledMap.get(i);null==e?a.removeAttribute("aria-disabled"):a.setAttribute("aria-disabled",e)}this.elementOriginalPointerEventsMap.has(i)&&(a.style.pointerEvents=null!==(t=this.elementOriginalPointerEventsMap.get(i))&&void 0!==t?t:"")}}this.elementOriginalDisabledMap.clear(),this.elementOriginalAriaDisabledMap.clear(),this.elementOriginalPointerEventsMap.clear()}updatePlaceholderStatus(){ei(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{Ee(this.buildCropControllerContext())}catch{}this.cropSession=null}if(this.mosaicSession&&this.canvas){try{rt(this.buildMosaicControllerContext())}catch{}this.mosaicSession=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=gi,e.default=gi,e.isMaskObject=q,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",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="free",p=100,b=100,v=10,y=!0,C=!1,S=!1,w="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({})}),x=Object.freeze({brushSize:8,color:"#ff0000",opacity:1,lineCap:"round",lineJoin:"round",selectable:!0,evented:!0,annotationHidden:!1,annotationLocked:!1}),k=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 O(t){return"function"==typeof t?t:null}function A(t){return"fit"===t||"cover"===t||"expand"===t}function E(t){return A(t)?t:d}function j(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function B(t){return Array.isArray(t)?[...t]:t}function T(t){if(!j(t))return u;const e={};for(const[n,i]of Object.entries(t))"onCreate"!==n&&"fabricGenerator"!==n&&"styles"!==n&&(e[n]=B(i));const n=t.styles;if(j(n)){const t={};for(const[e,i]of Object.entries(n))t[e]=B(i);Object.freeze(t),e.styles=t}return Object.freeze(e),e}function L(t,e){const n=Number(t);return!Number.isFinite(n)||n<=0?e:Math.max(1,Math.floor(n))}function D(t,e){const n=Number(t);return!Number.isFinite(n)||n<=0?e:n}function N(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 R(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 z(t){const e=Number(t);return!Number.isFinite(e)||e<=0?h.maxExportPixels:Math.max(1,Math.floor(e))}function P(t){return"canvas"===t||"image"===t?t:h.exportAreaByDefault}function H(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 U(t){return"number"==typeof t&&Number.isFinite(t)}function $(t){return{...t,previewStrokeDashArray:t.previewStrokeDashArray?[...t.previewStrokeDashArray]:null}}function Q(t,e,n=t){const i=j(e)?e:{},o=$(t);return W(i,"brushSize")&&(o.brushSize=function(t,e){return U(t)&&t>0?t:e}(i.brushSize,n.brushSize)),W(i,"blockSize")&&(o.blockSize=function(t,e){return U(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 U(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 U(t)?Math.max(0,Math.min(1,t)):e}(i.outputQuality,n.outputQuality)),o}function Y(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 X(t){return{...t,styles:{...t.styles}}}function q(t){return{...t}}function V(t,e){return"number"==typeof t&&Number.isFinite(t)&&t>0?t:e}function G(t,e){return"boolean"==typeof t?t:e}function _(t,e){return"string"==typeof t?t:e}function K(t){return"number"==typeof t&&Number.isFinite(t)?t:void 0}function J(t,e,n=t){const i=j(e)?e:{},o=X(t);var a;return W(i,"text")&&(o.text=_(i.text,n.text)),W(i,"left")&&(o.left=K(i.left)),W(i,"top")&&(o.top=K(i.top)),W(i,"width")&&(o.width=V(i.width,n.width)),W(i,"fontSize")&&(o.fontSize=V(i.fontSize,n.fontSize)),W(i,"fontFamily")&&(o.fontFamily=_(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=_(i.fill,n.fill)),W(i,"backgroundColor")&&(o.backgroundColor=_(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,j(a)?{...a}:{})}),o}function Z(t,e,n=t){const i=j(e)?e:{},o=q(t);return W(i,"brushSize")&&(o.brushSize=V(i.brushSize,n.brushSize)),W(i,"color")&&(o.color=_(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 tt(t){var e,n,i,o,a;const r=null!=t?t:{},s={...h};for(const t of Object.keys(r)){if(!k.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=r[t];if(void 0!==e)if("downsampleQuality"!==t)if("maxExportPixels"!==t)if("exportAreaByDefault"!==t){if("defaultLayoutMode"===t){const t=E(e);s.defaultLayoutMode=t,s.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?s[t]=e:s.maskLabelOffset=N(e,h.maskLabelOffset):s.defaultMaskConfig=T(e):s.defaultMaskHeight=D(e,h.defaultMaskHeight):s.defaultMaskWidth=D(e,h.defaultMaskWidth):s.exportMultiplier=D(e,h.exportMultiplier):s.imageLoadTimeoutMs=L(e,h.imageLoadTimeoutMs):s.downsampleMaxHeight=L(e,h.downsampleMaxHeight):s.downsampleMaxWidth=L(e,h.downsampleMaxWidth):s.rotationStep=F(e,h.rotationStep):s.scaleStep=D(e,h.scaleStep):s.maxScale=D(e,h.maxScale):s.minScale=D(e,h.minScale):s.animationDuration=N(e,h.animationDuration):s.canvasHeight=L(e,h.canvasHeight):s.canvasWidth=L(e,h.canvasWidth)}else s.exportAreaByDefault=P(e);else s.maxExportPixels=z(e);else s.downsampleQuality=R(e)}if(s.onImageLoadStart=O(r.onImageLoadStart),s.onImageLoaded=O(r.onImageLoaded),s.onImageCleared=O(r.onImageCleared),s.onImageChanged=O(r.onImageChanged),s.onBusyChange=O(r.onBusyChange),s.onEditorDisposed=O(r.onEditorDisposed),s.onMasksChanged=O(r.onMasksChanged),s.onAnnotationsChanged=O(r.onAnnotationsChanged),s.onSelectionChange=O(r.onSelectionChange),s.onError=O(r.onError),s.onWarning=O(r.onWarning),s.maxHistorySize=function(t){const e=Number(t);return Number.isFinite(e)?Math.max(1,Math.floor(e)):h.maxHistorySize}(s.maxHistorySize),s.maxExportPixels=z(s.maxExportPixels),s.minScale>s.maxScale){const t=s.minScale;s.minScale=s.maxScale,s.maxScale=t}const l=r.label&&"object"==typeof r.label?r.label:{},c={...g,...l.textOptions&&"object"==typeof l.textOptions?l.textOptions:{}},u={getText:"function"==typeof l.getText?l.getText:m.getText,textOptions:c};"function"==typeof l.create&&(u.create=l.create),Object.freeze(u.textOptions),Object.freeze(u);const d=r.crop&&"object"==typeof r.crop?r.crop:{},A={aspectRatio:null!==(e=d.aspectRatio)&&void 0!==e?e:f,minWidth:D(d.minWidth,p),minHeight:D(d.minHeight,b),padding:N(d.padding,v),hideMasksDuringCrop:null!==(n=d.hideMasksDuringCrop)&&void 0!==n?n:y,preserveMasksAfterCrop:null!==(i=d.preserveMasksAfterCrop)&&void 0!==i?i:C,allowRotationOfCropRect:null!==(o=d.allowRotationOfCropRect)&&void 0!==o?o:S,exportFileType:null!==(a=d.exportFileType)&&void 0!==a?a:w,exportQuality:H(d.exportQuality)};Object.freeze(A);const B=function(t,e){return j(t)?Q(e,t):$(e)}(r.defaultMosaicConfig,I);B.previewStrokeDashArray&&Object.freeze(B.previewStrokeDashArray),Object.freeze(B);const W=function(t,e){return j(t)?J(e,t):X(e)}(r.defaultTextConfig,M);Object.freeze(W.styles),Object.freeze(W);const U=function(t,e){return j(t)?Z(e,t):q(e)}(r.defaultDrawConfig,x);return Object.freeze(U),Object.freeze({...s,label:u,crop:A,defaultMosaicConfig:B,defaultTextConfig:W,defaultDrawConfig:U})}class et{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 nt(t){return!!t&&"object"==typeof t&&"baseImage"===t.editorObjectKind}function it(t){const e=t;return!!e&&"mask"===e.editorObjectKind&&"number"==typeof e.maskId&&"string"==typeof e.maskUid&&"string"==typeof e.maskName}function ot(t){const e=t;return!!e&&"annotation"===e.editorObjectKind&&"number"==typeof e.annotationId&&"string"==typeof e.annotationType&&"string"==typeof e.annotationName}function at(t){return ot(t)&&"text"===t.annotationType}function rt(t){return ot(t)&&"draw"===t.annotationType}function st(t){const e=t;return!!e&&"session"===e.editorObjectKind&&"string"==typeof e.sessionObjectType}function lt(t){return it(t)||ot(t)}function ct(t){const e=t;return e.editorObjectKind="baseImage",e}function ut(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 dt(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 ht(t,e){const n=t;return n.editorObjectKind="session",n.sessionObjectType=e,n}const gt=["editorObjectKind","sessionObjectType","maskId","maskUid","maskName","isCropRect","maskLabel","originalAlpha","originalStroke","originalStrokeWidth","hasControls","selectable","strokeUniform","lockRotation","transparentCorners","borderColor","cornerColor","cornerSize","flipX","flipY","isMosaicPreview","annotationId","annotationType","annotationName","annotationHidden","annotationLocked"];function mt(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&&it(l)?l.maskId:"number"==typeof t.activeMaskId?t.activeMaskId:null,u=l&&ot(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(gt);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),"boolean"==typeof i.flipX&&(o.flipX=i.flipX),"boolean"==typeof i.flipY&&(o.flipY=i.flipY),!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 ft(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):dt(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}):ct(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;ut(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(it).reduce((t,e)=>Math.max(t,e.maskId),0),d=l.filter(ot).reduce((t,e)=>Math.max(t,e.annotationId),0),h=l.filter(it),g=l.filter(ot);return{editorState:c,maxMaskId:u,maxAnnotationId:d,originalImage:null!==(n=l.find(nt))&&void 0!==n?n:null,objects:l,masks:h,annotations:g,jsonString:r}}class pt{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 bt{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 vt(t){if(null===t||"object"!=typeof t)return!1;return"function"==typeof t.Canvas}function yt(t){return!0===t.annotationLocked}function Ct(t){return!yt(t)}function St(t,e){try{t.set(e)}catch{Object.assign(t,e)}}function wt(t){var e;const n=!0===t.annotationHidden,i=yt(t);St(t,{visible:!n,selectable:!i,evented:!i,hasControls:!i,lockMovementX:i,lockMovementY:i,lockScalingX:i,lockScalingY:i,lockRotation:i}),i||St(t,{selectable:!0,evented:!0,hasControls:!0,lockMovementX:!1,lockMovementY:!1,lockScalingX:!1,lockScalingY:!1,lockRotation:!1}),at(t)&&function(t,e){t.editable=e}(t,!i),null===(e=t.setCoords)||void 0===e||e.call(t)}function It(t){t.forEach(wt)}function Mt(t){return t.getObjects().filter(ot).slice()}function xt(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(ot)}function kt(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 Ot(t,e){try{t.set(e)}catch{Object.assign(t,e)}}function At(t,e){const n=kt(t),i=e;"boolean"==typeof i.annotationHidden&&(t.annotationHidden=i.annotationHidden),"boolean"==typeof i.annotationLocked&&(t.annotationLocked=i.annotationLocked);return yt(t)||("boolean"==typeof i.selectable&&(t.selectable=i.selectable),"boolean"==typeof i.evented&&(t.evented=i.evented),at(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&&Ot(t,n)}(t,e),rt(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&&Ot(t,n)}(t,e)),wt(t),kt(t)!==n}function Et(t,e,n={}){const i=!0===n.force,o=e.filter(t=>i||Ct(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 jt(t,e={}){return Et(t,Mt(t.canvas),e)}function Bt(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 Lt(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 Dt(t,e){t.getObjects().includes(e)||t.add(e)}function Nt(t,e){return t.getObjects().filter(t=>t!==e)}function Ft(t){return t.findIndex(t=>st(t)||Tt(t))}function Rt(t){const e=function(t){const e=[],n=[],i=[],o=[];for(const a of t.getObjects())nt(a)?e.push(a):lt(a)?n.push(a):st(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)=>{Lt(t,e,n)})}function zt(t,e){Dt(t,e);const n=Nt(t,e),i=Ft(n);Lt(t,e,-1===i?n.length:i)}function Pt(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 Ht(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 Ut(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 $t(t){t.setCoords();const e=t.getBoundingRect();return{left:e.left,top:e.top,width:e.width,height:e.height}}function Qt(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 Yt(t){return Array.isArray(t)?{x:Number(t[0]),y:Number(t[1])}:{x:Number(t.x),y:Number(t.y)}}function Xt(t){const e=t;return!!e&&"number"==typeof e.x&&Number.isFinite(e.x)&&"number"==typeof e.y&&Number.isFinite(e.y)}function qt(t,e){const n=e&&"object"==typeof e?e:null;if(!n)return null;if(Xt(n.scenePoint))return{...n.scenePoint};if(Xt(n.pointer))return{...n.pointer};if(Xt(n.absolutePointer))return{...n.absolutePointer};if(n.e&&"function"==typeof t.getPointer){const e=t.getPointer(n.e);if(Xt(e))return{...e}}return null}function Vt(t,e){var n,i;const o=J(t.getTextConfig(),e),a=function(t){const e=t.getOriginalImage();if(e){const t=$t(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:Qt(r,"x",a.left,t.canvas,t.options),top:Qt(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 _t(t,e={}){var n,i;if(!t.isImageLoaded())return null;const o=Vt(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=dt(a,{annotationId:r.annotationId,annotationType:"text",annotationName:r.annotationName,annotationHidden:r.annotationHidden,annotationLocked:r.annotationLocked});wt(s),Gt(t,s),zt(t.canvas,s),!1!==o.selectable&&Ct(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&&Ct(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 Kt(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(at(o)&&Ct(o)?(t.canvas.setActiveObject(o),null===(i=(n=o).enterEditing)||void 0===i||i.call(n)):lt(o)&&t.canvas.setActiveObject(o));const a=qt(t.canvas,e);a&&_t(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"}};ht(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 Jt(t){const e=t.getTextSession();e&&(e.dispose(),t.setTextSession(null),t.canvas.requestRenderAll(),t.updateUi())}function Zt(t,e){var n;const i=t.canvas.getActiveObject();if(!i||!at(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 te(t,e){e.filter(at).forEach(e=>{Gt(t,e)})}function ee(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 ne(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=dt(e,{annotationId:i,annotationType:"draw",annotationName:`${t.options.drawAnnotationName}${i}`,annotationHidden:n.annotationHidden,annotationLocked:n.annotationLocked});return wt(o),o}(t,n);zt(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 ie(t){const e=t.getDrawSession();e&&(e.dispose(),t.setDrawSession(null),t.canvas.requestRenderAll(),t.updateUi())}function oe(t,e){Object.setPrototypeOf(t,e.prototype)}class ae 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,oe(this,ae)}}class re 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,oe(this,re)}}class se 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,oe(this,se)}}class le 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,oe(this,le)}}class ce 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,oe(this,ce)}}class ue 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,oe(this,ue)}}class de 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,oe(this,de)}}class he 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,oe(this,he)}}const ge="#ccc";function me(t){var e;const n=Number(t.originalStrokeWidth);t.set({stroke:null!==(e=t.originalStroke)&&void 0!==e?e:ge,strokeWidth:Number.isFinite(n)?n:1})}function fe(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:ge,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 pe(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:ge),!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),fe(n)}function be(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 ve(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 ye(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 Ce(t){try{t.set({opacity:0,evented:!1,selectable:!1})}catch{}}const Se=[6,4],we=.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,we);const i=Number(e);return Number.isFinite(i)?l(i,we):we}function xe(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 ke(t){for(const e of t.prevEvented)try{e.object.set({evented:e.evented,selectable:e.selectable})}catch{}t.prevEvented=[]}function Oe(t,e){xe(t,e),ke(e),function(t){for(const e of t.maskBackups)ye(e);t.maskBackups=[]}(e);try{t.canvas.selection=!!e.prevSelection}catch{}}function Ae(t,e){const n=$t(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}const Ee=Object.freeze({free:null,"1:1":1,"3:4":3/4,"4:3":4/3,"3:2":1.5,"2:3":2/3,"9:16":9/16,"16:9":16/9});function je(t){var e;if(null==t)return null;if("number"==typeof t)return Number.isFinite(t)&&t>0?t:null;if("string"==typeof t){const n=t.trim();if(Object.prototype.hasOwnProperty.call(Ee,n))return null!==(e=Ee[n])&&void 0!==e?e:null;const i=n.split(":");if(2!==i.length)return null;const o=Number(i[0]),a=Number(i[1]);return Number.isFinite(o)&&o>0&&Number.isFinite(a)&&a>0?o/a:null}if("object"==typeof t){const e=Number(t.width),n=Number(t.height);return Number.isFinite(e)&&e>0&&Number.isFinite(n)&&n>0?e/n:null}return null}function Be(t,e,n){const i=Math.max(1,t),o=Math.max(1,e);let a=i,r=a/n;return r>o&&(r=o,a=r*n),{width:Math.max(1,a),height:Math.max(1,r)}}function Te(t,e,n,i,o,a,r,s){var l;const c=Be(r,s,i),u=null!==(l=function(t,e,n,i,o){let a=Math.max(1,t),r=a/o;return r<e&&(r=Math.max(1,e),a=r*o),a<=n&&r<=i?{width:a,height:r}:null}(o,a,c.width,c.height,i))&&void 0!==l?l:c;let d="height"===n?e*i:t,h="height"===n?e:t/i;return(d>c.width||h>c.height)&&({width:d,height:h}=c),(d<u.width||h<u.height)&&({width:d,height:h}=u),{width:d,height:h}}function Le(t,e,n,i,o){const a=2*o<n?o:0,r=2*o<i?o:0;return{left:t+a,top:e+r,width:Math.max(1,n-2*a),height:Math.max(1,i-2*r)}}function De(t,e,n){const i=function(t){const e=t.getOriginalImage();if(!e)return null;e.setCoords();const{options:n}=t,i=e.getBoundingRect(),o=Number.isFinite(Number(n.crop.padding))?Number(n.crop.padding):10,a=Math.max(0,Math.floor(i.left)),r=Math.max(0,Math.floor(i.top)),s=Math.max(1,Math.floor(i.width)),l=Math.max(1,Math.floor(i.height)),c=Math.max(1,Number(n.crop.minWidth)||1),u=Math.max(1,Number(n.crop.minHeight)||1);return{boundsLeft:a,boundsTop:r,maxCropWidth:s,maxCropHeight:l,minCropWidth:Math.min(c,s),minCropHeight:Math.min(u,l),padding:o,imageBounds:i}}(t);if(!i)return;if(null===n)return function(t,e){const n=Math.min(e.maxCropWidth,Math.max(e.minCropWidth,(Number(t.width)||1)*(Number(t.scaleX)||1))),i=Math.min(e.maxCropHeight,Math.max(e.minCropHeight,(Number(t.height)||1)*(Number(t.scaleY)||1))),o=Math.min(e.boundsLeft+e.maxCropWidth-n,Math.max(e.boundsLeft,Number(t.left)||e.boundsLeft)),a=Math.min(e.boundsTop+e.maxCropHeight-i,Math.max(e.boundsTop,Number(t.top)||e.boundsTop));t.set({left:o,top:a,width:n,height:i,scaleX:1,scaleY:1})}(e,i),void e.setCoords();const o=Le(i.boundsLeft,i.boundsTop,i.maxCropWidth,i.maxCropHeight,i.padding),a=Be(o.width,o.height,n);e.set({left:o.left+(o.width-a.width)/2,top:o.top+(o.height-a.height)/2,width:a.width,height:a.height,scaleX:1,scaleY:1}),e.setCoords()}function Ne(t,e,n){const i=null!==e;t.setControlsVisibility({tl:!0,tr:!0,br:!0,bl:!0,mt:!i,mb:!i,ml:!i,mr:!i,mtr:n}),t.setCoords()}function Fe(t,e={}){var n;const{canvas:i,options:o}=t;if(t.getCropSession())return;const a=t.getOriginalImage();if(!a)return;if(!t.isImageLoaded())return;i.discardActiveObject();const r=t.saveState(),s=!!i.selection;i.selection=!1,a.setCoords();const l=a.getBoundingRect(),c=Number.isFinite(Number(o.crop.padding))?Number(o.crop.padding):10,u=Math.max(0,Math.floor(l.left)),d=Math.max(0,Math.floor(l.top)),h=Math.max(1,Math.floor(l.width)),g=Math.max(1,Math.floor(l.height)),m=Math.max(1,Number(o.crop.minWidth)||1),f=Math.max(1,Number(o.crop.minHeight)||1),p=Math.min(m,h),b=Math.min(f,g),v=!!o.crop.allowRotationOfCropRect,y=je(null!==(n=e.aspectRatio)&&void 0!==n?n:o.crop.aspectRatio);let C,S,w,I;if(null===y)C=Math.min(u+h-1,Math.max(u,Math.floor(l.left+c))),S=Math.min(d+g-1,Math.max(d,Math.floor(l.top+c))),w=p,I=b;else{const t=Le(u,d,h,g,c),e=Be(t.width,t.height,y);w=e.width,I=e.height,C=t.left+(t.width-w)/2,S=t.top+(t.height-I)/2}const M=new t.fabric.Rect({left:C,top:S,width:w,height:I,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});Ne(M,y,v),i.add(M),ht(M,"cropRect"),M.isCropRect=!0,i.bringObjectToFront(M),i.setActiveObject(M);const x=!!o.crop.hideMasksDuringCrop,k=[];x&&i.getObjects().forEach(t=>{t!==M&&it(t)&&k.push(ve(t))});const O=[];if(i.getObjects().forEach(t=>{var e,n;if(t!==M){O.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{}}}),x)for(const t of k)Ce(t.object);const A=()=>{try{const e=Math.max(1,Number(M.width)||1),n=Math.max(1,Number(M.height)||1);let o,a;const r=t.getCropSession(),s=r?r.aspectRatio:y;if(null===s)o=Math.min(h/e,Math.max(p/e,Number(M.scaleX)||1)),a=Math.min(g/n,Math.max(b/n,Number(M.scaleY)||1));else{const t=Math.max(1e-4,Number(M.scaleX)||1),r=Math.max(1e-4,Number(M.scaleY)||1),l=function(t,e,n,i){var o,a,r;const s=String(null!==(r=null!==(o=e.__corner)&&void 0!==o?o:null===(a=t._currentTransform)||void 0===a?void 0:a.corner)&&void 0!==r?r:"").toLowerCase();return"mt"===s||"mb"===s?"height":"ml"===s||"mr"===s?"width":Math.abs(i-1)>Math.abs(n-1)?"height":"width"}(i,M,t,r),c=Te(e*t,n*r,l,s,p,b,h,g);o=c.width/e,a=c.height/n}const l=e*o,c=n*a,m=Math.max(u,u+h-l),f=Math.max(d,d+g-c),v=Math.min(m,Math.max(u,Number(M.left)||u)),C=Math.min(f,Math.max(d,Number(M.top)||d));M.set({left:v,top:C,scaleX:o,scaleY:a}),M.setCoords(),i.requestRenderAll()}catch{}};M.on("modified",A),M.on("moving",A),M.on("scaling",A);const E={beforeJson:r,prevSelection:s,prevEvented:O,maskBackups:k,cropRect:M,aspectRatio:y,handlers:[{target:M,handlers:[{eventName:"modified",callback:A},{eventName:"moving",callback:A},{eventName:"scaling",callback:A}]}]};t.setCropSession(E),i.renderAll()}function Re(t){const e=t.getCropSession();if(e){t.canvas.discardActiveObject(),Oe(t,e),t.setCropSession(null);try{t.canvas.renderAll()}catch{}}}async function ze(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 ue("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?$t(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(!Pt(d,o.getWidth(),o.getHeight()))throw new ue("applyCrop failed: crop region is empty or outside the canvas.");const h=Ht(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(it);for(const n of r)try{if(n.setCoords(),Ae(n,e)){const t=null!==(i=null==a?void 0:a.get(n))&&void 0!==i?i:ve(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):[];ke(i),xe(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{ye(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),pe(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 pt(()=>t.loadFromState(b),()=>t.loadFromState(a)))}catch(e){Oe(t,i),t.setCropSession(null);try{await t.loadFromState(a)}catch(t){console.warn("[ImageEditor] applyCrop: rollback failed",t)}if(e instanceof ue)throw e;const n=e instanceof Error?`applyCrop failed: ${e.message}`:"applyCrop failed";throw new ue(n,e)}}function Pe(t,e,n,i){if(!(He(t)&&He(e)&&He(n)&&He(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 He(t){return Number.isFinite(t)&&t>0}function We(t){const e=/^data:(image\/[a-z0-9+\-.]+)\s*;/i.exec(t);return e?e[1].toLowerCase():null}function Ue(t,e,n){return new Promise((i,o)=>{const a=Date.now(),r=setTimeout(()=>{o(new re(n,Date.now()-a))},e);t.then(t=>{clearTimeout(r),i(t)},t=>{clearTimeout(r),o(t)})})}function $e(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 Qe(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:$e(s,r/2)}}function Ye(t,e,n,i,o){const a=t-n,r=e-i;return a*a+r*r<=o}function Xe(t,e,n){return 4*(n*t+e)}function qe(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(Ye(t,e,c,u,v)){g=Xe(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(!Ye(t,e,c,u,v))continue;const n=Xe(r,t,e);l[n]=m,l[n+1]=p,l[n+2]=C,l[n+3]=S,y=!0}}return y}function Ve(t){try{t.requestRenderAll()}catch{try{t.renderAll()}catch{}}}function Ge(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 ht(n,"mosaicPreviewCircle"),n.isMosaicPreview=!0,n}(t);return e.previewCircle=o,i.getObjects().includes(o)||i.add(o),i.bringObjectToFront(o),fn(t),o}function _e(t,e){const n=e.previewCircle;if(n){try{t.canvas.remove(n)}catch{}e.previewCircle=null}}function Ke(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 an(i,e),i.set({selectable:!1,evented:!1,excludeFromExport:!0,objectCaching:!1,visible:!0}),ht(i,"mosaicPreviewImage"),i.isMosaicPreview=!0,i}(t,n,o);e.previewImage=a,an(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 Je(t,e){const n=e.previewImage;if(n){try{t.canvas.remove(n)}catch{}e.previewImage=null}}function Ze(t){var e;const n=null===(e=t.getMosaicSession())||void 0===e?void 0:e.previewCircle;n&&(n.set({visible:!1}),Ve(t.canvas))}function tn(t,e){const n=t.getMosaicSession();if(!n)return;Ge(t,n).set({left:e.x,top:e.y,visible:!0}),Ve(t.canvas)}function en(t,e,n,i){t.canvas.on(n,i),e.handlers.push({eventName:n,callback:i})}function nn(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 on(t){const e=Number(t);return Number.isFinite(e)&&e>0?Math.floor(e):0}function an(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 rn(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=on(o.naturalWidth||o.width),e=on(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 sn(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=qe({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),Ke(t,e,n),Ve(t.canvas)),l}async function ln(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=Qe(t.fabric,a,i,r.brushSize);if(!s)return void(o.lastImagePoint=null);const l=nn(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 rn(t,o,l)&&sn(t,o,a,s)}async function cn(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=nn(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}(We(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 Ue(t.fabric.FabricImage.fromURL(e,{crossOrigin:"anonymous"}),t.options.imageLoadTimeoutMs,"Mosaic FabricImage.fromURL")}(t,u);_e(t,e),Je(t,e);try{!function(t,e,n,i){const{canvas:o}=t;let a=!1,r=!1;try{an(n,e),o.remove(e),a=!0,o.add(n),r=!0,o.sendObjectToBack(n),t.setOriginalImage(ct(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 pt(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&&Ge(t,e)}t.updateInputs(),t.updateUi(),t.emitImageChanged(n)}async function un(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 ln(t,n,e)}t.getMosaicSession()===n&&n.commitRequested&&await cn(t,n,o)}finally{t.getMosaicSession()===n&&(n.isApplying=!1),t.emitBusyChangeIfChanged(o),t.updateUi(),t.getMosaicSession()===n&&(n.pendingCanvasPoints.length>0||n.commitRequested)&&un(t,n).catch(e=>{i(t.options,e,"Mosaic apply failed.")})}}function dn(t,e){const n=t.getMosaicSession();n&&(n.pendingCanvasPoints.push(e),n.pendingCanvasPoints.length>4096&&n.pendingCanvasPoints.splice(0,n.pendingCanvasPoints.length-4096),un(t,n).catch(e=>{i(t.options,e,"Mosaic apply failed.")}))}function hn(t,e){e.commitRequested=!0,un(t,e).catch(e=>{i(t.options,e,"Mosaic apply failed.")})}function gn(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),Ge(t,a),function(t,e){en(t,e,"mouse:move",e=>{const n=qt(t.canvas,e);if(!n)return void Ze(t);tn(t,n);const i=t.getMosaicSession();(null==i?void 0:i.isPointerDown)&&dn(t,n)}),en(t,e,"mouse:out",()=>{Ze(t);const e=t.getMosaicSession();(null==e?void 0:e.isPointerDown)&&(e.isPointerDown=!1,hn(t,e))}),en(t,e,"mouse:down",e=>{const n=qt(t.canvas,e);if(!n)return;const i=t.getMosaicSession();i&&(i.isPointerDown=!0,i.lastImagePoint=null,dn(t,n))}),en(t,e,"mouse:up",e=>{const n=t.getMosaicSession();if(!n)return;const i=qt(t.canvas,e);i&&(tn(t,i),dn(t,i)),n.isPointerDown=!1,hn(t,n)})}(t,a),e.renderAll()}function mn(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),_e(t,n),Je(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 fn(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),Ve(t.canvas)}function pn(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 bn(t,e){if("mergeAnnotations"===t){if(e instanceof ce)return e;const t=e instanceof Error?`mergeAnnotations failed: ${e.message}`:"mergeAnnotations failed";return new ce(t,e)}if(e instanceof le)return e;const n=e instanceof Error?`mergeMasks failed: ${e.message}`:"mergeMasks failed";return new le(n,e)}async function vn(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 bn(e.operation,`${e.operation}: exportImageBase64 returned an empty data URL.`);if(e.removeTargetsNoHistory(),await t.loadImage(r,{preserveScroll:!0}),await e.restorePreservedObjects(i),Rt(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 pt(()=>t.loadFromState(s),()=>t.loadFromState(n)))}catch(i){try{await t.loadFromState(n)}catch(t){console.warn(`[ImageEditor] ${e.operation}: rollback failed`,t)}throw bn(e.operation,i)}}function yn(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 Cn(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:yn(n.multiplier,t.options.exportMultiplier),format:c(n,t.options.downsampleQuality)};var i,o}function Sn(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 wn(t,e,n){return e?async function(t,e,n){if(!t.canvas)return await n();const i=t.canvas.getObjects().filter(it),o=i.map(ve);try{return i.forEach((t,n)=>e(t,n)),await n()}finally{for(const t of o)ye(t)}}({canvas:t.canvas,options:t.options},On,n):In(t.canvas,it,n)}async function In(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{}kn(t)}}function Mn(t){try{return t.getObjects()}catch{return[]}}function xn(t,e){return Mn(t).includes(e)}function kn(t){try{"function"==typeof t.requestRenderAll?t.requestRenderAll():t.renderAll()}catch{}}function On(t){try{t.set({opacity:1,fill:"#000",strokeWidth:0,stroke:null,selectable:!1}),"function"==typeof t.setCoords&&t.setCoords()}catch{}}function An(t){return!!t&&(t.left||t.top||t.right||t.bottom)}function En(t){return{width:Math.max(1,t.naturalWidth||t.width||1),height:Math.max(1,t.naturalHeight||t.height||1)}}function jn(t){return pn(t,{crossOrigin:"anonymous",createError:()=>new Error("Failed to decode export data URL")}).promise}function Bn(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&&Ln(i[2]))return!0;const o=e.match(/^[a-z][a-z0-9-]*\([^/]+\/\s*([^)]+)\)$/i);return!(!o||!Ln(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 Tn(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 Ln(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 Dn(t){console.warn(`[ImageEditor] ${t} skipped: no image is loaded on the canvas.`)}async function Nn(t,e){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(!it(n))continue;const i=n.labelObject;if(!i)continue;const o=xn(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{region:n,partialEdges:i}=function(t,e){if("canvas"===e)return{region:null,partialEdges:null};const n=t.getOriginalImage();if(!n)return{region:null,partialEdges:null};const i=$t(n),o=t.canvas,a="function"==typeof o.getWidth?o.getWidth():o.width,r="function"==typeof o.getHeight?o.getHeight():o.height;if(!Pt(i,a,r))throw new he("exportImageBase64 failed: image export region is empty.");return{region:Ht(i,a,r,{includePartialPixels:!0}),partialEdges:Ut(i,Number(n.angle)||0)}}(t,e.exportArea);!function(t,e,n){var i,o;const a=null!==(i=null==n?void 0:n.width)&&void 0!==i?i:Sn(t.canvas,"getWidth","width"),r=null!==(o=null==n?void 0:n.height)&&void 0!==o?o:Sn(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,e.multiplier,n);const o=n&&"jpeg"===e.format.format?"png":e.format.format,a="png"===o?void 0:e.format.quality;let r=await async function(t,e){return In(t.canvas,t=>st(t)||!0===t.isCropRect||!0===t.maskLabel||!0===t.isMosaicPreview,e)}(t,async()=>wn(t,e.mergeMasks,async()=>async function(t,e,n){return In(t.canvas,e?t=>ot(t)&&!0===t.annotationHidden:ot,n)}(t,e.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,o,a,e.multiplier,n))));if(n){const n="jpeg"===e.format.format?{format:"png",mimeType:"image/png",quality:void 0}:e.format;An(i)&&(r=await async function(t,e,n,i){if(!An(e))return t;const o=await jn(t),{width:a,height:r}=En(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)}(r,i,n,Tn(t.canvas))),"jpeg"===e.format.format&&(r=await async function(t,e,n,i){const o=await jn(t),{width:a,height:r}=En(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=Bn(e,i),l.fillRect(0,0,a,r),l.drawImage(o,0,0,a,r),s.toDataURL("image/jpeg",n)}(r,t.options.backgroundColor,e.format.quality,Tn(t.canvas)))}return r}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&&!xn(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),kn(t.canvas)}}async function Fn(t,e){if(!t.isImageLoaded())return Dn("exportImageBase64"),"";return Nn(t,Cn(t,e))}async function Rn(t,e){var n;if(!t.isImageLoaded())throw Dn("exportImageFile"),new de("exportImageFile");const i=null!=e?e:{},o=Cn(t,i),a=await Nn(t,o),r=await async function(t,e,n,i){if(t.startsWith(`data:${e.mimeType}`))return t;const o=await jn(t),{width:a,height:r}=En(o),s=Tn(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=Bn(n,s),c.fillRect(0,0,a,r)),c.drawImage(o,0,0,a,r),l.toDataURL(e.mimeType,e.quality)}(a,o.format,t.options.backgroundColor,t.canvas);let s;try{s=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.")}(r)}catch(t){throw new he("exportImageFile failed to decode rendered data URL.",t)}const l=function(t,e){const n="edited_image",i=String(t||n).trim()||n,o=function(t){return"jpeg"===t?"jpg":t}(e.format);return/\.(jpe?g|png|webp)$/i.test(i)?i.replace(/\.(jpe?g|png|webp)$/i,`.${o}`):`${i}.${o}`}(null!==(n=i.fileName)&&void 0!==n?n:t.options.defaultDownloadFileName,o.format);return new File([s],l,{type:o.format.mimeType})}async function zn(t,e){if(t.isImageLoaded()){if(null!=e&&"object"!=typeof e)throw new TypeError("[ImageEditor] downloadImage(options) expects an ImageExportOptions object.");try{!function(t,e){const n=Tn(t.canvas),i=URL.createObjectURL(e),o=n.createElement("a");o.download=e.name,o.href=i;const a=n.body;a.appendChild(o);try{o.click()}finally{a.removeChild(o),"function"==typeof globalThis.setTimeout?globalThis.setTimeout(()=>URL.revokeObjectURL(i),0):URL.revokeObjectURL(i)}}(t,await Rn(t,e))}catch(e){throw i(t.options,e,"downloadImage failed."),console.error("[ImageEditor] downloadImage failed",e),e}}else Dn("downloadImage")}const Pn={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",bmp:"image/bmp"},Hn=new Set(Object.values(Pn));function Wn(t){if("string"!=typeof t)return!1;if(!t.startsWith("data:image/"))return!1;const e=/^data:(image\/[^;,]+)(?:[;,])/.exec(t);return!!e&&Hn.has(e[1].toLowerCase())}function Un(t){if(t)try{t.value=""}catch{}}class $n{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=[Yn(null==i?void 0:i.overflow),Yn(null==i?void 0:i.overflowX),Yn(o),Yn(a)],c=[Yn(null==i?void 0:i.overflow),Yn(null==i?void 0:i.overflowY),Yn(o),Yn(r)];return{x:l,y:c,all:[...l,...c]}}(t);if(a.all.includes("scroll"))return{width:i,height:o};const r=Vn(n),s=a.x.some(Xn),l=a.y.some(Xn),c=Math.ceil(t.scrollWidth||0),u=Math.ceil(t.scrollHeight||0),d=s&&c>i+Qn;return{width:i+(l&&u>o+Qn?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 Qn=.5;function Yn(t){return String(null!=t?t:"").trim().toLowerCase()}function Xn(t){return"auto"===t||"overlay"===t}function qn(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 Vn(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 Gn(t,e,n,i){const o=Math.max(1,n.width||1),a=Math.max(1,n.height||1),r=Vn(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+Qn,u=e>i+Qn;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 _n(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 Kn(t,e,o={}){if(!Wn(e))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:ti(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=pn(e,{validate:t=>function(t){return Number.isFinite(t.naturalWidth)&&Number.isFinite(t.naturalHeight)&&t.naturalWidth>0&&t.naturalHeight>0}(t)?null:new ae("Failed to decode image data URL: image has no natural dimensions.",null),createError:t=>new ae("Failed to decode image data URL.",t)});let r;try{r=await Ue(i.promise,t.options.imageLoadTimeoutMs,"image decode")}catch(t){throw i.cleanup(!0),t}const s=function(t,e,i,o){const a=Zn(We(e));if(!i.downsampleOnLoad)return{dataUrl:e,mimeType:a};if(!Jn(i.downsampleMaxWidth)||!Jn(i.downsampleMaxHeight))return n(i,null,"loadImage skipped downsampling because downsample bounds are invalid."),{dataUrl:e,mimeType:a};const r=Pe(t.naturalWidth,t.naturalHeight,i.downsampleMaxWidth,i.downsampleMaxHeight);if(!r.needsResize)return{dataUrl:e,mimeType:a};const s=We(e),l=function(t,e,n,i,o,a,r,s){var l;const{width:c,height:u}=Pe(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 se("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 se("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=Zn(We(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 Ue(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=ct(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=qn(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=Vn(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+Qn,a=g>i+Qn;if(o===c&&a===u)break;c=o,u=a}const m=Gn(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(_n(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(mt({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 Jn(t){return Number.isFinite(t)&&t>0}function Zn(t){return"image/jpeg"===t||"image/png"===t||"image/webp"===t?t:null}function ti(t){t.discardActiveObject();const e=t.toJSON(gt);return JSON.stringify(e)}function ei(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 ni{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=ii(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(()=>ei(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(()=>ei(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=ii(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 flipHorizontal(){await this.flipImage("flipX")}async flipVertical(){await this.flipImage("flipY")}async flipImage(t){const e=this.context.getOriginalImage();if(e&&!this.context.guard.isAnimating()&&!this.context.guard.isDisposed()){try{const n=e.getCenterPoint();e.set({originX:"center",originY:"center"}),e.setPositionByOrigin(n,"center","center"),e.set({[t]:!e[t]}),e.setCoords();const i=ii(e);e.set({originX:"left",originY:"top"}),e.setPositionByOrigin(i,"left","top"),e.setCoords()}catch(e){return void console.warn(`[ImageEditor] ${"flipX"===t?"flipHorizontal":"flipVertical"} failed`,e)}this.context.guard.isDisposed()||(this.context.afterTransformSnap&&this.context.afterTransformSnap(),this.context.saveCanvasState())}}async resetImageTransform(){if(this.context.getOriginalImage()){this.context.setSuppressSaveState(!0);try{await this.scaleImage(1),await this.rotateImage(0);const t=this.context.getOriginalImage();t&&!this.context.guard.isDisposed()&&(t.set({flipX:!1,flipY:!1}),t.setCoords(),this.context.afterTransformSnap&&this.context.afterTransformSnap())}finally{this.context.setSuppressSaveState(!1)}this.context.guard.isDisposed()||this.context.saveCanvasState()}}}function ii(t){t.setCoords();const e=t.getCoords()[0];if(e)return e;const n=t.getBoundingRect();return{x:n.left,y:n.top}}function oi(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}function ai(t,e){n(t,null,`createMask skipped: ${e}.`)}function ri(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 si(t){return"number"==typeof t&&Number.isFinite(t)}function li(t,e,n){return!!si(n)||(ai(t,`${e} must resolve to a finite number`),!1)}function ci(t,e,n){return!!(si(n)&&n>0)||(ai(t,`${e} must resolve to a positive number`),!1)}function ui(t,e,n){return!!(si(n)&&n>=0)||(ai(t,`${e} must resolve to a non-negative number`),!1)}function di(t,e){if(!Array.isArray(e)||e.length<3)return ai(t,"polygon masks require at least three points"),null;const n=e.map(Yt);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?(ai(t,"polygon points must describe a non-zero area"),null):n:(ai(t,"polygon points must contain finite x/y values"),null)}function hi(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 w=function(t,e){const n={...t},i=n.styles;delete n.onCreate,delete n.fabricGenerator,delete n.styles;const o=oi(e.styles)?e.styles:{},a=oi(i)?i:{};return{...n,...e,styles:{...a,...o}}}(C.defaultMaskConfig,e),I=null!==(i=w.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(!ri(i))return ai(t,`${e} is not a supported numeric value`),!1;return!0}(C,w))return null;const M={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,...w,shape:I};let x,k;const O=t.getLastMask();if(void 0===w.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=M.gap)&&void 0!==s?s:5)),k=null!==(l=O.top)&&void 0!==l?l:10}else x=Qt(w.left,"x",10,y,C),k=Qt(w.top,"y",10,y,C);M.width=Qt(w.width,"x",C.defaultMaskWidth,y,C),M.height=Qt(w.height,"y",C.defaultMaskHeight,y,C);const A=void 0!==w.rx?Qt(w.rx,"x",0,y,C):void 0,E=void 0!==w.ry?Qt(w.ry,"y",0,y,C):void 0,j="circle"===I?Qt(w.radius,"x",Math.min(M.width,M.height)/2,y,C):void 0,B="polygon"===I?di(C,w.points):null;if(!(li(C,"left",x)&&li(C,"top",k)&&ci(C,"width",M.width)&&ci(C,"height",M.height)&&li(C,"gap",M.gap)&&li(C,"angle",M.angle)&&li(C,"alpha",M.alpha)))return null;if(void 0!==A&&!ui(C,"rx",A)||void 0!==E&&!ui(C,"ry",E)||void 0!==j&&!ci(C,"radius",j)||"polygon"===I&&null===B)return null;if("expand"===C.layoutMode){const e=Math.ceil(x+M.width+10),n=Math.ceil(k+M.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 T;if("function"==typeof e.fabricGenerator){const t=e.fabricGenerator(M,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;T=t}else{const t={originX:"left",originY:"top"};switch(I){case"circle":T=new S.Circle({left:x,top:k,...t,radius:j,fill:M.color,opacity:M.alpha,angle:null!==(c=M.angle)&&void 0!==c?c:0,...M.styles});break;case"ellipse":T=new S.Ellipse({left:x,top:k,...t,rx:null!=A?A: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 e=new S.Polygon(B,{...t,fill:M.color,opacity:M.alpha,angle:null!==(d=M.angle)&&void 0!==d?d:0,...M.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(),T=e;break}default:T=new S.Rect({left:x,top:k,...t,width:M.width,height:M.height,fill:M.color,opacity:M.alpha,angle:null!==(m=M.angle)&&void 0!==m?m:0,...void 0!==A?{rx:A}:{},...void 0!==E?{ry:E}:{},...M.styles})}}const L=T;L.selectable=!("selectable"in w)||!!w.selectable,L.evented=!("evented"in w)||!!w.evented,L.hasControls=!("hasControls"in w)||!!w.hasControls,L.transparentCorners="transparentCorners"in w&&!!w.transparentCorners,L.strokeUniform=!("strokeUniform"in w)||!!w.strokeUniform,L.lockRotation=!C.maskRotatable,L.borderColor=null!==(f=w.borderColor)&&void 0!==f?f:"red",L.cornerColor=null!==(p=w.cornerColor)&&void 0!==p?p:"black",L.cornerSize=null!==(b=w.cornerSize)&&void 0!==b?b:8;const D=null!==(v=M.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 N=t.getMaskCounter()+1;var F;if(t.setMaskCounter(N),ut(L,{maskId:N,maskUid:(F=N,`mask-${F}`),maskName:`${C.maskName}${N}`,originalAlpha:M.alpha,originalStroke:L.stroke,originalStrokeWidth:L.strokeWidth}),fe(L),t.setLastMask(L),function(t,e){Dt(t,e);const n=Nt(t,e),i=Ft(n);Lt(t,e,-1===i?n.length:i)}(y,L),t.updateMaskList(),!1!==M.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 gi(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 it(e)?[e]:[];const n=e.getObjects;return("function"==typeof n?n.call(e):[]).filter(it)}(t.canvas);if(0!==e.length){for(const n of e)t.removeLabelForMask(n),be(n),t.canvas.remove(n);t.canvas.discardActiveObject(),t.updateMaskList(),t.canvas.renderAll(),t.saveCanvasState()}}function mi(t,e={}){const n=t.canvas.getObjects().filter(it);if(0!==n.length){for(const e of n)t.removeLabelForMask(e),be(e),t.canvas.remove(e);t.canvas.discardActiveObject(),t.setLastMask(null),t.updateMaskList(),t.canvas.renderAll(),!1!==e.saveHistory&&t.saveCanvasState()}}function fi(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 pi(t,e){var i;const{canvas:o,options:a,fabric:r}=t;if(!o||!a.maskLabelOnSelect)return;fi(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)}ht(s,"maskLabel"),s.maskLabel=!0,e.labelObject=s,o.add(s),o.bringObjectToFront(s),bi(t,e)}function bi(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 vi(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 yi{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 Ci(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 Si=.5,wi=Symbol("ImageEditorInternalOperation"),Ii=Symbol("ImageEditorAllowDuringAnimationQueue"),Mi=["scalePercentageInput","rotateLeftDegreesInput","rotateRightDegreesInput","rotateLeftButton","rotateRightButton","flipHorizontalButton","flipVerticalButton","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","cropAspectRatioSelect","applyCropButton","cancelCropButton","enterMosaicModeButton","exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],xi=["cropAspectRatioSelect","applyCropButton","cancelCropButton"],ki=new Set(["setCropAspectRatio","applyCrop","cancelCrop"]),Oi=["exitTextModeButton","textColorInput","textFontSizeInput"],Ai=["exitDrawModeButton","drawColorInput","drawBrushSizeInput"],Ei=["scalePercentageInput","rotateLeftDegreesInput","rotateRightDegreesInput","rotateLeftButton","rotateRightButton","flipHorizontalButton","flipVerticalButton","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","cropAspectRatioSelect","applyCropButton","cancelCropButton","enterMosaicModeButton","exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],ji=["exitMosaicModeButton","mosaicBrushSizeInput","mosaicBlockSizeInput"],Bi=new Set(["exitMosaicMode","applyMosaic","setMosaicConfig","resetMosaicConfig","setMosaicBrushSize","setMosaicBlockSize","saveState"]),Ti=new Set(["init","loadImage","loadFromState","saveState","scaleImage","rotateImage","flipHorizontal","flipVertical","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","setCropAspectRatio","applyCrop","cancelCrop","enterMosaicMode","exitMosaicMode","applyMosaic","setMosaicConfig","resetMosaicConfig","setMosaicBrushSize","setMosaicBlockSize","undo","redo","exportImageBase64","exportImageFile","downloadImage","dispose"]),Li={crop:ki,mosaic:Bi,text:new Set(["exitTextMode","createTextAnnotation","setTextConfig","resetTextConfig","setTextColor","setTextFontSize","saveState"]),draw:new Set(["exitDrawMode","setDrawConfig","resetDrawConfig","setDrawColor","setDrawBrushSize","saveState"])};class Di{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 $n}),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(vt(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 vt(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=tt(a.options),this.currentLayoutMode=this.options.layoutMode,this.defaultMosaicConfig=this.options.defaultMosaicConfig,this.currentMosaicConfig=$(this.defaultMosaicConfig),this.defaultTextConfig=this.options.defaultTextConfig,this.currentTextConfig=X(this.defaultTextConfig),this.defaultDrawConfig=this.options.defaultDrawConfig,this.currentDrawConfig=q(this.defaultDrawConfig);const r=a.options.defaultLayoutMode;void 0===r||A(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 et,this.animQueue=new e,this.historyManager=new bt(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",flipHorizontalButton:"flipHorizontalButton",flipVerticalButton:"flipVerticalButton",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",cropAspectRatioSelect:"cropAspectRatioSelect",applyCropButton:"applyCropButton",cancelCropButton:"cancelCropButton",enterMosaicModeButton:"enterMosaicModeButton",exitMosaicModeButton:"exitMosaicModeButton",mosaicBrushSizeInput:"mosaicBrushSizeInput",mosaicBlockSizeInput:"mosaicBlockSizeInput",uploadArea:"uploadArea",...t},this.initCanvas(),this.domBindings=new yi(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 ni(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("flipHorizontalButton","click",()=>{this.flipHorizontal()}),this.bindElementIfExists("flipVerticalButton","click",()=>{this.flipVertical()}),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({aspectRatio:this.getSelectedCropAspectRatio()})}),this.bindElementIfExists("cropAspectRatioSelect","change",()=>{this.cropSession&&this.setCropAspectRatio(this.getSelectedCropAspectRatio())}),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||!at(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?(Zt(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()&&Zt(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&&Hn.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=Pn[o])&&void 0!==n?n:null}(t);if(!a)return n(this.options,null,`Unsupported image file type: ${t.type||t.name||"unknown"}.`),void Un(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 Un(o)}try{await this.loadImage(r)}catch{}finally{Un(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(!Wn(t))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=>{Ci(this.placeholderElement,this.containerElement,!!this.options.showPlaceholder&&t)}};try{await Kn(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[wi])&&void 0!==e?e:null}canRunDuringAnimationQueue(t){return!!(null==t?void 0:t[Ii])}withInternalOperationOptions(t,e={}){return{...e,...t?{[wi]:t}:{}}}withAnimationQueueBypass(t={}){return{...t,[Ii]:!0}}assertIdleForOperation(t,e){const n=this.getInternalOperationToken(e);this.operationGuard.assertIdleForOperation(t,n);const i=this.getActiveToolMode();if(i&&!this.operationGuard.isOwnOperation(n)&&!Li[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}}getSelectedCropAspectRatio(){const t=this.elements.cropAspectRatioSelect,e=t?document.getElementById(t):null;return(e&&"value"in e?String(e.value).trim():"")||"free"}isExpectedIdleGuardError(t,e){return t instanceof Error&&t.message.startsWith(`[ImageEditor] Cannot run "${e}" `)}assertCanQueueAnimation(t,e){const n=this.getInternalOperationToken(e);this.operationGuard.assertCanQueueAnimation(t,n);const i=this.getActiveToolMode();if(i&&!this.operationGuard.isOwnOperation(n)&&!Li[i].has(t))throw new Error(`[ImageEditor] Cannot run "${t}" while ${i} mode is active.`)}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){A(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)&&Ti.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(it).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(){var t,e;const n=this.canvas?this.canvas.getWidth():0,i=this.canvas?this.canvas.getHeight():0,o=this.getImageInfo();return{hasImage:null!==o,image:o,maskCount:this.getMasks().length,annotationCount:this.getAnnotations().length,currentScale:this.currentScale,currentRotation:this.currentRotation,isFlippedHorizontally:!!(null===(t=this.originalImage)||void 0===t?void 0:t.flipX),isFlippedVertically:!!(null===(e=this.originalImage)||void 0===e?void 0:e.flipY),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:n,canvasHeight:i}}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(it),o=t.filter(ot),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?We(e):null;return this.isSupportedImageMimeType(n)?n:null}setCanvasSizePx(t,e){this.canvas&&_n(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=qn(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+Si&&i.height<=a.height+Si;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=Gn(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(qn(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+Si||n.height>a+Si;if("fit"===this.currentLayoutMode||"cover"===this.currentLayoutMode){const t=o>i.width+Si&&n.width<=i.width+Si,e=a>i.height+Si&&n.height<=i.height+Si;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)>Si||Math.abs(a-e)>Si}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+Si,s=a>i+Si;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(it).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)})}flipHorizontal(){if(this.isDisposed||!this.transformController)return Promise.resolve();try{this.assertCanQueueAnimation("flipHorizontal")}catch(t){return Promise.reject(t)}const t=this.transformController,e=this.buildCallbackContext("flipHorizontal",!1),n=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await t.flipHorizontal(),this.isDisposed||this.emitImageChanged(e)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(e),n.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(e)})}flipVertical(){if(this.isDisposed||!this.transformController)return Promise.resolve();try{this.assertCanQueueAnimation("flipVertical")}catch(t){return Promise.reject(t)}const t=this.transformController,e=this.buildCallbackContext("flipVertical",!1),n=this.animQueue.add(async()=>{if(!this.isDisposed){this.updateUi();try{await t.flipVertical(),this.isDisposed||this.emitImageChanged(e)}finally{this.isDisposed||this.updateInputs()}}});return this.emitBusyChangeIfChanged(e),n.finally(()=>{this.refreshUiAfterQueuedAnimation(),this.emitBusyChangeIfChanged(e)})}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 ft({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=>{me(t),pe(t)}),It(e.annotations),te(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=mt({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 pt(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&&it(t)?t:e,o=t&&ot(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,()=>hi(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,()=>gi(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,()=>mi(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&&fi(e,t)}createLabelForMask(t){const e=this.buildMaskLabelContext();e&&pi(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(it).forEach(t=>{try{delete t.labelObject}catch{}})}(t)}syncMaskLabel(t){const e=this.buildMaskLabelContext();e&&bi(e,t)}showLabelForMask(t){const e=this.buildMaskLabelContext();e&&function(t,e){t.options.maskLabelOnSelect&&(e.labelObject||pi(t,e),e.labelObject&&(e.labelObject.visible=!0,bi(t,e)))}(e,t)}handleObjectMovingScalingRotating(t){it(t)&&this.syncMaskLabel(t)}handleObjectModified(t){if(it(t)){this.syncMaskLabel(t);const e=this.buildCallbackContext("saveState",!1);return this.saveState(),this.emitMasksChanged(e),void this.emitImageChanged(e)}if(ot(t)){if(yt(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(it))&&void 0!==e?e:null,r=null!==(n=t.find(ot))&&void 0!==n?n:null;this.canvas.getObjects().filter(it).forEach(t=>{t!==a?(t.labelObject&&this.removeLabelForMask(t),me(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=vi(t),i=n.getElementById(e);if(!i||!t.canvas)return;i.innerHTML="";const o=t.canvas;o.getObjects().filter(it).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=>it(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=vi(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;Kt(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;Jt(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")?_t(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,ee(t);const s=e=>ne(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;ie(this.buildDrawControllerContext());const t=this.buildCallbackContext("exitDrawMode",!1);this.emitBusyChangeIfChanged(t),this.emitImageChanged(t)}isDrawMode(){return null!==this.drawSession}getTextConfig(){return X(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 q(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;Et(t=this.buildAnnotationManagerContext(),xt(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,()=>{jt(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&&(!!At(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=xt(t.canvas);return 0!==n.length&&(!!n.map(t=>At(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(it),n=t.filter(t=>ot(t)&&Ct(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);Et(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=Bt(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=Bt(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=j(t)?t:{},n=[];return W(e,"text")&&"string"!=typeof e.text&&n.push("text"),W(e,"width")&&!U(e.width)&&n.push("width"),W(e,"fontSize")&&!U(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=J(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=j(t)?t:{},n=[];return W(e,"brushSize")&&!U(e.brushSize)&&n.push("brushSize"),W(e,"color")&&"string"!=typeof e.color&&n.push("color"),W(e,"opacity")&&!U(e.opacity)&&n.push("opacity"),n}(t);i.length>0&&n(this.options,null,`${e} ignored invalid Draw config fields: ${i.join(", ")}.`);const o=Z(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()&&ee(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&&at(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&&at(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&&rt(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&&rt(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(lt);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})=>lt(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)}),Rt(this.canvas),this.canvas.setActiveObject(i),this.canvas.renderAll(),this.saveState(),this.updateMaskList(),this.updateAnnotationList(),this.updateUi();const c=this.buildCallbackContext(t,!1);it(i)&&this.emitMasksChanged(c),ot(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(it))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 vn(t,{operation:"mergeMasks",exportOptions:{exportArea:"image",mergeMasks:!0,mergeAnnotations:!1,multiplier:t.options.exportMultiplier,fileType:"png"},getTargets:()=>t.canvas.getObjects().filter(it),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()}}async 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 i=this.buildExportServiceContext();try{await zn(i,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 Fn(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 Rn(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=>Fn(this.buildExportServiceContext(),t),updateUi:()=>this.updateUi(),updateInputs:()=>this.updateInputs(),removeAllMasksNoHistory:()=>{mi(this.buildRemoveMaskContext(),{saveHistory:!1})},getAnnotations:()=>this.getAnnotations(),restoreAnnotations:t=>{const e=this.getLiveCanvasOrThrow("restoreAnnotations");t.forEach(t=>{e.add(t)}),It(t),te(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=>Fn(this.buildExportServiceContext(),t),updateUi:()=>this.updateUi(),updateInputs:()=>this.updateInputs(),removeAllAnnotationsNoHistory:()=>{jt(this.buildAnnotationManagerContext(),{saveHistory:!1,force:!0})},getMasks:()=>this.getMasks(),restoreMasks:t=>{const e=this.getLiveCanvasOrThrow("restoreMasks");t.forEach(t=>{e.add(t),pe(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(),mt({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&&it(e))return e;const n=this.canvas.getObjects().filter(t=>it(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&&ot(t)?t:null}enterMosaicMode(){if(!this.canvas||!this.originalImage)return;if(this.mosaicSession)return;if(!this.isImageLoaded())return;if(!this.canRunIdleOperation("enterMosaicMode"))return;gn(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;mn(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 $(this.currentMosaicConfig)}setMosaicConfig(t){this.applyMosaicConfigPatch(t,"setMosaicConfig")}resetMosaicConfig(){if(this.isDisposed)return;const t=$(this.defaultMosaicConfig);Y(this.currentMosaicConfig,t)||(this.currentMosaicConfig=t,this.mosaicSession&&this.canvas&&fn(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=j(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=Q(this.currentMosaicConfig,t);Y(this.currentMosaicConfig,o)||(this.currentMosaicConfig=o,this.mosaicSession&&this.canvas&&fn(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:()=>$(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(t={}){if(!this.canvas||!this.originalImage)return;if(this.cropSession)return;if(!this.isImageLoaded())return;if(!this.canRunIdleOperation("enterCropMode"))return;Fe(this.buildCropControllerContext(),t),this.updateUi();const e=this.buildCallbackContext("enterCropMode",!1);this.emitBusyChangeIfChanged(e),this.emitImageChanged(e)}setCropAspectRatio(t){if(!this.canvas||!this.cropSession)return;if(!this.canRunIdleOperation("setCropAspectRatio"))return;!function(t,e){const n=t.getCropSession();if(!(null==n?void 0:n.cropRect))return;const i=je(e);n.aspectRatio=i,De(t,n.cropRect,i),Ne(n.cropRect,i,!!t.options.crop.allowRotationOfCropRect),t.canvas.setActiveObject(n.cropRect),t.canvas.requestRenderAll()}(this.buildCropControllerContext(),t),this.updateUi();const e=this.buildCallbackContext("setCropAspectRatio",!1);this.emitImageChanged(e)}cancelCrop(){if(!this.canvas||!this.cropSession)return;if(!this.canRunIdleOperation("cancelCrop"))return;Re(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 ze(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(ot))return;const t=this.buildCallbackContext("mergeAnnotations",!1),e=this.operationGuard.beginBusyOperation("mergeAnnotations");this.emitBusyChangeIfChanged(t),this.updateUi();try{await async function(t){await vn(t,{operation:"mergeAnnotations",exportOptions:{exportArea:"image",mergeMasks:!1,mergeAnnotations:!0,multiplier:t.options.exportMultiplier,fileType:"png"},getTargets:()=>t.canvas.getObjects().filter(ot),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,e,n;if(!this.canvas)return;const i=!!this.originalImage,o=i?this.canvas.getObjects().filter(it):[],a=i?this.canvas.getObjects().filter(ot):[],r=o.length>0,s=a.length>0,l=this.canvas.getActiveObject(),c=!(!l||!it(l)),u=!(!l||!ot(l)),d=!!l&&lt(l),h=1===this.currentScale&&0===this.currentRotation&&!(null===(t=this.originalImage)||void 0===t?void 0:t.flipX)&&!(null===(e=this.originalImage)||void 0===e?void 0:e.flipY),g=this.historyManager.canUndo(),m=this.historyManager.canRedo(),f=null!==this.cropSession,p=null!==this.mosaicSession,b=null!==this.textSession,v=null!==this.drawSession,y=this.operationGuard.isBusy()||this.animQueue.isBusy(),C=!0===(null===(n=this.mosaicSession)||void 0===n?void 0:n.isApplying);if(f)Mi.forEach(t=>{this.setControlEnabled(t,!y&&xi.includes(t))});else if(b)Mi.forEach(t=>{this.setControlEnabled(t,!y&&Oi.includes(t))});else if(v)Mi.forEach(t=>{this.setControlEnabled(t,!y&&Ai.includes(t))});else{if(p)return Ei.forEach(t=>{this.setControlEnabled(t,!y&&!C&&ji.includes(t))}),void this.setControlEnabled("imageInput",!1);this.setControlEnabled("scalePercentageInput",i&&!y),this.setControlEnabled("rotateLeftDegreesInput",i&&!y),this.setControlEnabled("rotateRightDegreesInput",i&&!y),this.setControlEnabled("zoomInButton",i&&!y&&this.currentScale<this.options.maxScale),this.setControlEnabled("zoomOutButton",i&&!y&&this.currentScale>this.options.minScale),this.setControlEnabled("rotateLeftButton",i&&!y),this.setControlEnabled("rotateRightButton",i&&!y),this.setControlEnabled("flipHorizontalButton",i&&!y),this.setControlEnabled("flipVerticalButton",i&&!y),this.setControlEnabled("createMaskButton",i&&!y),this.setControlEnabled("removeSelectedMaskButton",c&&!y),this.setControlEnabled("removeAllMasksButton",r&&!y),this.setControlEnabled("mergeMasksButton",i&&r&&!y),this.setControlEnabled("removeSelectedAnnotationButton",u&&!y),this.setControlEnabled("removeAllAnnotationsButton",s&&!y),this.setControlEnabled("deleteSelectedObjectButton",d&&!y),this.setControlEnabled("mergeAnnotationsButton",i&&s&&!y),this.setControlEnabled("bringSelectedObjectForwardButton",d&&!y),this.setControlEnabled("sendSelectedObjectBackwardButton",d&&!y),this.setControlEnabled("bringSelectedObjectToFrontButton",d&&!y),this.setControlEnabled("sendSelectedObjectToBackButton",d&&!y),this.setControlEnabled("downloadImageButton",i&&!y),this.setControlEnabled("resetImageTransformButton",i&&!h&&!y),this.setControlEnabled("undoButton",i&&!y&&g),this.setControlEnabled("redoButton",i&&!y&&m),this.setControlEnabled("enterCropModeButton",i&&!y),this.setControlEnabled("cropAspectRatioSelect",i&&!y),this.setControlEnabled("enterMosaicModeButton",i&&!y),this.setControlEnabled("enterTextModeButton",i&&!y),this.setControlEnabled("enterDrawModeButton",i&&!y),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",!y),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(){Ci(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{Re(this.buildCropControllerContext())}catch{}this.cropSession=null}if(this.mosaicSession&&this.canvas){try{mn(this.buildMosaicControllerContext())}catch{}this.mosaicSession=null}if(this.textSession&&this.canvas){try{Jt(this.buildTextControllerContext())}catch{}this.textSession=null}if(this.drawSession&&this.canvas){try{ie(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=Di,t.default=Di,t.isAnnotationObject=ot,t.isBaseImageObject=nt,t.isDrawAnnotationObject=rt,t.isEditableOverlayObject=lt,t.isMaskObject=it,t.isSessionObject=st,t.isTextAnnotationObject=at,Object.defineProperty(t,"__esModule",{value:!0})});
2
2
  //# sourceMappingURL=image-editor.umd.js.map