@bensitu/image-editor 1.5.1 → 2.0.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 (154) hide show
  1. package/README.md +370 -466
  2. package/dist/cjs/index.cjs +5422 -0
  3. package/dist/cjs/index.cjs.map +1 -0
  4. package/dist/esm/animation/animation-queue.js +67 -0
  5. package/dist/esm/animation/animation-queue.js.map +1 -0
  6. package/dist/esm/core/callback-reporter.js +23 -0
  7. package/dist/esm/core/callback-reporter.js.map +1 -0
  8. package/dist/esm/core/default-options.js +322 -0
  9. package/dist/esm/core/default-options.js.map +1 -0
  10. package/dist/esm/core/errors.js +156 -0
  11. package/dist/esm/core/errors.js.map +1 -0
  12. package/dist/esm/core/operation-guard.js +129 -0
  13. package/dist/esm/core/operation-guard.js.map +1 -0
  14. package/dist/esm/core/public-types.js +4 -0
  15. package/dist/esm/core/public-types.js.map +1 -0
  16. package/dist/esm/core/state-serializer.js +251 -0
  17. package/dist/esm/core/state-serializer.js.map +1 -0
  18. package/dist/esm/crop/crop-controller.js +403 -0
  19. package/dist/esm/crop/crop-controller.js.map +1 -0
  20. package/dist/esm/export/export-format.js +53 -0
  21. package/dist/esm/export/export-format.js.map +1 -0
  22. package/dist/esm/export/export-service.js +596 -0
  23. package/dist/esm/export/export-service.js.map +1 -0
  24. package/dist/esm/fabric/fabric-adapter.js +37 -0
  25. package/dist/esm/fabric/fabric-adapter.js.map +1 -0
  26. package/dist/esm/fabric/fabric-animation.js +37 -0
  27. package/dist/esm/fabric/fabric-animation.js.map +1 -0
  28. package/dist/esm/history/command.js +2 -0
  29. package/dist/esm/history/command.js.map +1 -0
  30. package/dist/esm/history/history-manager.js +103 -0
  31. package/dist/esm/history/history-manager.js.map +1 -0
  32. package/dist/esm/image/image-loader.js +245 -0
  33. package/dist/esm/image/image-loader.js.map +1 -0
  34. package/dist/esm/image/image-resampler.js +55 -0
  35. package/dist/esm/image/image-resampler.js.map +1 -0
  36. package/dist/esm/image/layout-manager.js +224 -0
  37. package/dist/esm/image/layout-manager.js.map +1 -0
  38. package/dist/esm/image/transform-controller.js +132 -0
  39. package/dist/esm/image/transform-controller.js.map +1 -0
  40. package/dist/esm/image-editor.js +1740 -0
  41. package/dist/esm/image-editor.js.map +1 -0
  42. package/dist/esm/index.js +5 -0
  43. package/dist/esm/index.js.map +1 -0
  44. package/dist/esm/mask/mask-factory.js +332 -0
  45. package/dist/esm/mask/mask-factory.js.map +1 -0
  46. package/dist/esm/mask/mask-label-manager.js +120 -0
  47. package/dist/esm/mask/mask-label-manager.js.map +1 -0
  48. package/dist/esm/mask/mask-list.js +47 -0
  49. package/dist/esm/mask/mask-list.js.map +1 -0
  50. package/dist/esm/mask/mask-style.js +182 -0
  51. package/dist/esm/mask/mask-style.js.map +1 -0
  52. package/dist/esm/ui/dom-bindings.js +60 -0
  53. package/dist/esm/ui/dom-bindings.js.map +1 -0
  54. package/dist/esm/ui/ui-state.js +25 -0
  55. package/dist/esm/ui/ui-state.js.map +1 -0
  56. package/dist/esm/ui/visibility-state.js +11 -0
  57. package/dist/esm/ui/visibility-state.js.map +1 -0
  58. package/dist/esm/utils/canvas-region.js +100 -0
  59. package/dist/esm/utils/canvas-region.js.map +1 -0
  60. package/dist/esm/utils/dom.js +6 -0
  61. package/dist/esm/utils/dom.js.map +1 -0
  62. package/dist/esm/utils/file.js +53 -0
  63. package/dist/esm/utils/file.js.map +1 -0
  64. package/dist/esm/utils/number.js +24 -0
  65. package/dist/esm/utils/number.js.map +1 -0
  66. package/dist/esm/utils/timeout.js +17 -0
  67. package/dist/esm/utils/timeout.js.map +1 -0
  68. package/dist/types/animation/animation-queue.d.ts +111 -0
  69. package/dist/types/animation/animation-queue.d.ts.map +1 -0
  70. package/dist/types/core/callback-reporter.d.ts +125 -0
  71. package/dist/types/core/callback-reporter.d.ts.map +1 -0
  72. package/dist/types/core/default-options.d.ts +56 -0
  73. package/dist/types/core/default-options.d.ts.map +1 -0
  74. package/dist/types/core/errors.d.ts +142 -0
  75. package/dist/types/core/errors.d.ts.map +1 -0
  76. package/dist/types/core/operation-guard.d.ts +192 -0
  77. package/dist/types/core/operation-guard.d.ts.map +1 -0
  78. package/dist/types/core/public-types.d.ts +678 -0
  79. package/dist/types/core/public-types.d.ts.map +1 -0
  80. package/dist/types/core/state-serializer.d.ts +301 -0
  81. package/dist/types/core/state-serializer.d.ts.map +1 -0
  82. package/dist/types/crop/crop-controller.d.ts +407 -0
  83. package/dist/types/crop/crop-controller.d.ts.map +1 -0
  84. package/dist/types/export/export-format.d.ts +136 -0
  85. package/dist/types/export/export-format.d.ts.map +1 -0
  86. package/dist/types/export/export-service.d.ts +333 -0
  87. package/dist/types/export/export-service.d.ts.map +1 -0
  88. package/dist/types/fabric/fabric-adapter.d.ts +74 -0
  89. package/dist/types/fabric/fabric-adapter.d.ts.map +1 -0
  90. package/dist/types/fabric/fabric-animation.d.ts +141 -0
  91. package/dist/types/fabric/fabric-animation.d.ts.map +1 -0
  92. package/dist/types/history/command.d.ts +16 -0
  93. package/dist/types/history/command.d.ts.map +1 -0
  94. package/dist/types/history/history-manager.d.ts +129 -0
  95. package/dist/types/history/history-manager.d.ts.map +1 -0
  96. package/dist/types/image/image-loader.d.ts +265 -0
  97. package/dist/types/image/image-loader.d.ts.map +1 -0
  98. package/dist/types/image/image-resampler.d.ts +139 -0
  99. package/dist/types/image/image-resampler.d.ts.map +1 -0
  100. package/dist/types/image/layout-manager.d.ts +255 -0
  101. package/dist/types/image/layout-manager.d.ts.map +1 -0
  102. package/dist/types/image/transform-controller.d.ts +287 -0
  103. package/dist/types/image/transform-controller.d.ts.map +1 -0
  104. package/dist/types/image-editor.d.ts +650 -0
  105. package/dist/types/image-editor.d.ts.map +1 -0
  106. package/dist/types/index.d.cts +31 -0
  107. package/dist/types/index.d.cts.map +1 -0
  108. package/dist/types/index.d.ts +31 -0
  109. package/dist/types/index.d.ts.map +1 -0
  110. package/dist/types/mask/mask-factory.d.ts +209 -0
  111. package/dist/types/mask/mask-factory.d.ts.map +1 -0
  112. package/dist/types/mask/mask-label-manager.d.ts +171 -0
  113. package/dist/types/mask/mask-label-manager.d.ts.map +1 -0
  114. package/dist/types/mask/mask-list.d.ts +144 -0
  115. package/dist/types/mask/mask-list.d.ts.map +1 -0
  116. package/dist/types/mask/mask-style.d.ts +338 -0
  117. package/dist/types/mask/mask-style.d.ts.map +1 -0
  118. package/dist/types/ui/dom-bindings.d.ts +103 -0
  119. package/dist/types/ui/dom-bindings.d.ts.map +1 -0
  120. package/dist/types/ui/ui-state.d.ts +112 -0
  121. package/dist/types/ui/ui-state.d.ts.map +1 -0
  122. package/dist/types/ui/visibility-state.d.ts +77 -0
  123. package/dist/types/ui/visibility-state.d.ts.map +1 -0
  124. package/dist/types/utils/canvas-region.d.ts +177 -0
  125. package/dist/types/utils/canvas-region.d.ts.map +1 -0
  126. package/dist/types/utils/dom.d.ts +26 -0
  127. package/dist/types/utils/dom.d.ts.map +1 -0
  128. package/dist/types/utils/file.d.ts +80 -0
  129. package/dist/types/utils/file.d.ts.map +1 -0
  130. package/dist/types/utils/number.d.ts +132 -0
  131. package/dist/types/utils/number.d.ts.map +1 -0
  132. package/dist/types/utils/timeout.d.ts +84 -0
  133. package/dist/types/utils/timeout.d.ts.map +1 -0
  134. package/dist/umd/image-editor.umd.js +2 -0
  135. package/dist/umd/image-editor.umd.js.map +1 -0
  136. package/package.json +72 -66
  137. package/dist/image-editor.cjs +0 -4185
  138. package/dist/image-editor.cjs.map +0 -7
  139. package/dist/image-editor.esm.js +0 -4154
  140. package/dist/image-editor.esm.js.map +0 -7
  141. package/dist/image-editor.esm.min.js +0 -9
  142. package/dist/image-editor.esm.min.js.map +0 -7
  143. package/dist/image-editor.esm.min.mjs +0 -9
  144. package/dist/image-editor.esm.min.mjs.map +0 -7
  145. package/dist/image-editor.esm.mjs +0 -4154
  146. package/dist/image-editor.esm.mjs.map +0 -7
  147. package/dist/image-editor.js +0 -4151
  148. package/dist/image-editor.js.map +0 -7
  149. package/dist/image-editor.min.js +0 -9
  150. package/dist/image-editor.min.js.map +0 -7
  151. package/image-editor.d.ts +0 -269
  152. package/src/browser.js +0 -11
  153. package/src/esm.js +0 -9
  154. package/src/image-editor.js +0 -4775
@@ -1,4151 +0,0 @@
1
- (() => {
2
- // src/image-editor.js
3
- /**
4
- * @file image-editor.js
5
- * @module image-editor
6
- * @version 1.5.1
7
- * @author Ben Situ
8
- * @license MIT
9
- * @description Lightweight canvas-based image editor with masking/transform/export support.
10
- */
11
- var fabric = null;
12
- var INTERNAL_OPERATION_TOKEN = /* @__PURE__ */ Symbol.for("ImageEditorInternalOperation");
13
- function getGlobalScope() {
14
- if (typeof globalThis !== "undefined") return globalThis;
15
- if (typeof self !== "undefined") return self;
16
- if (typeof window !== "undefined") return window;
17
- return null;
18
- }
19
- function getGlobalFabric() {
20
- const scope2 = getGlobalScope();
21
- return scope2 && scope2.fabric ? scope2.fabric : null;
22
- }
23
- function setFabric(fabricInstance) {
24
- fabric = fabricInstance || getGlobalFabric();
25
- return fabric;
26
- }
27
- function ensureFabric() {
28
- if (!fabric) setFabric();
29
- return fabric;
30
- }
31
- var ImageEditor = class {
32
- constructor(options = {}) {
33
- const defaultLabel = {
34
- getText: (mask) => mask.maskName,
35
- textOptions: {
36
- fontSize: 12,
37
- fill: "#fff",
38
- backgroundColor: "rgba(0,0,0,0.7)",
39
- padding: 2,
40
- fontFamily: "monospace",
41
- fontWeight: "bold",
42
- selectable: false,
43
- evented: false,
44
- originX: "left",
45
- originY: "top"
46
- }
47
- };
48
- const defaultCrop = {
49
- minWidth: 100,
50
- minHeight: 100,
51
- padding: 10,
52
- hideMasksDuringCrop: true,
53
- preserveMasksAfterCrop: false,
54
- allowRotationOfCropRect: false
55
- };
56
- const userLabel = options.label || {};
57
- const userCrop = options.crop || {};
58
- this.options = {
59
- canvasWidth: 800,
60
- canvasHeight: 600,
61
- backgroundColor: "transparent",
62
- animationDuration: 300,
63
- minScale: 0.1,
64
- maxScale: 5,
65
- scaleStep: 0.05,
66
- rotationStep: 90,
67
- expandCanvasToImage: true,
68
- fitImageToCanvas: false,
69
- coverImageToCanvas: false,
70
- downsampleOnLoad: true,
71
- downsampleMaxWidth: 4e3,
72
- downsampleMaxHeight: 3e3,
73
- downsampleQuality: 0.92,
74
- preserveSourceFormat: true,
75
- downsampleMimeType: null,
76
- imageLoadTimeoutMs: 3e4,
77
- exportMultiplier: 1,
78
- maxExportPixels: 5e7,
79
- exportImageAreaByDefault: true,
80
- defaultMaskWidth: 50,
81
- defaultMaskHeight: 80,
82
- maskRotatable: false,
83
- maskLabelOnSelect: true,
84
- maskLabelOffset: 3,
85
- maskName: "mask",
86
- groupSelection: false,
87
- showPlaceholder: true,
88
- initialImageBase64: null,
89
- // Provide a base64 'data:image/...' string here if you want auto-load
90
- defaultDownloadFileName: "edited_image.jpg",
91
- onError: null,
92
- onWarning: null,
93
- ...options,
94
- label: {
95
- ...defaultLabel,
96
- ...userLabel,
97
- textOptions: {
98
- ...defaultLabel.textOptions,
99
- ...userLabel.textOptions || {}
100
- }
101
- },
102
- crop: {
103
- ...defaultCrop,
104
- ...userCrop
105
- }
106
- };
107
- this._fabricLoaded = !!ensureFabric();
108
- if (!this._fabricLoaded) {
109
- this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted.");
110
- }
111
- this.canvas = null;
112
- this.canvasElement = null;
113
- this.containerElement = null;
114
- this.placeholderElement = null;
115
- this.originalImage = null;
116
- this.baseImageScale = 1;
117
- this.currentScale = 1;
118
- this.currentRotation = 0;
119
- this.maskCounter = 0;
120
- this.isAnimating = false;
121
- this._isLoading = false;
122
- this._activeOperationName = null;
123
- this._activeOperationToken = null;
124
- this.elements = {};
125
- this.isImageLoadedToCanvas = false;
126
- this.maxHistorySize = 50;
127
- this._handlersByElementKey = {};
128
- this._elementCache = {};
129
- this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
130
- this._lastMask = null;
131
- this._lastMaskInitialLeft = null;
132
- this._lastMaskInitialTop = null;
133
- this._lastMaskInitialWidth = null;
134
- this._lastSnapshot = null;
135
- this._cropMode = false;
136
- this._cropRect = null;
137
- this._cropHandlers = [];
138
- this._cropPrevEvented = null;
139
- this._prevSelectionSetting = void 0;
140
- this._containerOriginalOverflow = null;
141
- this._lastContainerViewportSize = null;
142
- this._canvasElementOriginalStyle = null;
143
- this._visibilityStateByElement = /* @__PURE__ */ new WeakMap();
144
- this._scrollbarSizeCache = null;
145
- this._activeAnimationRejectors = /* @__PURE__ */ new Set();
146
- this._disposed = false;
147
- this._initialized = false;
148
- this._deprecatedElementKeyWarnings = /* @__PURE__ */ new Set();
149
- this._cropRotationWarningEmitted = false;
150
- this.onImageLoaded = typeof this.options.onImageLoaded === "function" ? this.options.onImageLoaded : null;
151
- this.animationQueue = new AnimationQueue();
152
- this.historyManager = new HistoryManager(this.maxHistorySize);
153
- }
154
- /**
155
- * Backward-compatible alias for {@link ImageEditor#canvasElement}.
156
- *
157
- * @deprecated Use canvasElement instead. This alias will be removed in v2.0.0.
158
- * @returns {HTMLCanvasElement|null} The canvas element currently owned by the editor.
159
- */
160
- get canvasEl() {
161
- return this.canvasElement;
162
- }
163
- set canvasEl(value) {
164
- this.canvasElement = value;
165
- }
166
- /**
167
- * Backward-compatible alias for {@link ImageEditor#containerElement}.
168
- *
169
- * @deprecated Use containerElement instead. This alias will be removed in v2.0.0.
170
- * @returns {HTMLElement|null} The canvas viewport/container element.
171
- */
172
- get containerEl() {
173
- return this.containerElement;
174
- }
175
- set containerEl(value) {
176
- this.containerElement = value;
177
- }
178
- /**
179
- * Backward-compatible alias for {@link ImageEditor#placeholderElement}.
180
- *
181
- * @deprecated Use placeholderElement instead. This alias will be removed in v2.0.0.
182
- * @returns {HTMLElement|null} The placeholder element shown before an image loads.
183
- */
184
- get placeholderEl() {
185
- return this.placeholderElement;
186
- }
187
- set placeholderEl(value) {
188
- this.placeholderElement = value;
189
- }
190
- /**
191
- * Initializes the editor, binds to DOM elements, sets up event handlers,
192
- * and (optionally) loads an initial image.
193
- * Use this method to set up the editor UI before interacting with it.
194
- *
195
- * @param {Object} [idMap={}] - Optional mapping from logical element names to actual DOM element IDs.
196
- * Supported keys include: canvas, canvasContainer, imagePlaceholder, scalePercentageInput,
197
- * rotateLeftDegreesInput, rotateRightDegreesInput, rotateLeftButton, rotateRightButton,
198
- * createMaskButton, removeSelectedMaskButton, removeAllMasksButton, mergeMasksButton,
199
- * downloadImageButton, maskList, zoomInButton, zoomOutButton, resetImageTransformButton,
200
- * undoButton, redoButton, imageInput, uploadArea, enterCropModeButton, applyCropButton,
201
- * and cancelCropButton. Deprecated 1.x names remain supported as aliases.
202
- *
203
- * @returns {void}
204
- *
205
- * @public
206
- *
207
- * @example
208
- * editor.init({
209
- * canvas: 'myFabricCanvasId',
210
- * downloadImageButton: 'myDownloadButtonId'
211
- * });
212
- */
213
- init(idMap = {}) {
214
- if (!this._fabricLoaded) {
215
- this._fabricLoaded = !!ensureFabric();
216
- if (!this._fabricLoaded) {
217
- this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted.");
218
- return;
219
- }
220
- }
221
- if (this._initialized || this.canvas) this.dispose();
222
- this._disposed = false;
223
- this._initialized = true;
224
- this.animationQueue = new AnimationQueue();
225
- this.historyManager = new HistoryManager(this.maxHistorySize);
226
- this._visibilityStateByElement = /* @__PURE__ */ new WeakMap();
227
- this._activeAnimationRejectors = /* @__PURE__ */ new Set();
228
- this._isLoading = false;
229
- this._activeOperationName = null;
230
- this._activeOperationToken = null;
231
- this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
232
- this._containerOriginalOverflow = null;
233
- this._lastContainerViewportSize = null;
234
- this._canvasElementOriginalStyle = null;
235
- const defaults = {
236
- canvas: "fabricCanvas",
237
- canvasContainer: null,
238
- // Pass an ID here if you have a scrollable viewport container
239
- imagePlaceholder: "imagePlaceholder",
240
- imgPlaceholder: null,
241
- scalePercentageInput: "scalePercentageInput",
242
- scaleRate: null,
243
- rotateLeftDegreesInput: "rotateLeftDegreesInput",
244
- rotationLeftInput: null,
245
- rotateRightDegreesInput: "rotateRightDegreesInput",
246
- rotationRightInput: null,
247
- rotateLeftButton: "rotateLeftButton",
248
- rotateLeftBtn: null,
249
- rotateRightButton: "rotateRightButton",
250
- rotateRightBtn: null,
251
- createMaskButton: "createMaskButton",
252
- addMaskBtn: null,
253
- removeSelectedMaskButton: "removeSelectedMaskButton",
254
- removeMaskBtn: null,
255
- removeAllMasksButton: "removeAllMasksButton",
256
- removeAllMasksBtn: null,
257
- mergeMasksButton: "mergeMasksButton",
258
- mergeBtn: null,
259
- downloadImageButton: "downloadImageButton",
260
- downloadBtn: null,
261
- maskList: "maskList",
262
- zoomInButton: "zoomInButton",
263
- zoomInBtn: null,
264
- zoomOutButton: "zoomOutButton",
265
- zoomOutBtn: null,
266
- resetImageTransformButton: "resetImageTransformButton",
267
- resetBtn: null,
268
- undoButton: "undoButton",
269
- undoBtn: null,
270
- redoButton: "redoButton",
271
- redoBtn: null,
272
- imageInput: "imageInput",
273
- uploadArea: null,
274
- enterCropModeButton: "enterCropModeButton",
275
- cropBtn: null,
276
- applyCropButton: "applyCropButton",
277
- applyCropBtn: null,
278
- cancelCropButton: "cancelCropButton",
279
- cancelCropBtn: null
280
- };
281
- this.elements = this._resolveElementIdMap(idMap || {}, defaults);
282
- this._elementCache = {};
283
- this._initCanvas();
284
- this._bindEvents();
285
- this._updateInputs();
286
- this._updateMaskList();
287
- this._updateUI();
288
- if (this.options.initialImageBase64) {
289
- this.loadImage(this.options.initialImageBase64).catch((error) => this._reportError("initialImageBase64 could not be loaded", error));
290
- } else {
291
- this._updatePlaceholderStatus();
292
- }
293
- }
294
- _resolveElementIdMap(idMap, defaults) {
295
- const resolved = { ...defaults, ...idMap };
296
- this._resolveElementAliases(resolved, idMap, defaults, "imagePlaceholder", ["imgPlaceholder"]);
297
- this._resolveElementAliases(resolved, idMap, defaults, "scalePercentageInput", ["scaleRate"]);
298
- this._resolveElementAliases(resolved, idMap, defaults, "rotateLeftDegreesInput", ["rotationLeftInput"]);
299
- this._resolveElementAliases(resolved, idMap, defaults, "rotateRightDegreesInput", ["rotationRightInput"]);
300
- this._resolveElementAlias(resolved, idMap, defaults, "rotateLeftButton", "rotateLeftBtn");
301
- this._resolveElementAlias(resolved, idMap, defaults, "rotateRightButton", "rotateRightBtn");
302
- this._resolveElementAlias(resolved, idMap, defaults, "createMaskButton", "addMaskBtn");
303
- this._resolveElementAliases(resolved, idMap, defaults, "removeSelectedMaskButton", ["removeMaskBtn"]);
304
- this._resolveElementAlias(resolved, idMap, defaults, "removeAllMasksButton", "removeAllMasksBtn");
305
- this._resolveElementAlias(resolved, idMap, defaults, "mergeMasksButton", "mergeBtn");
306
- this._resolveElementAliases(resolved, idMap, defaults, "downloadImageButton", ["downloadBtn"]);
307
- this._resolveElementAlias(resolved, idMap, defaults, "zoomInButton", "zoomInBtn");
308
- this._resolveElementAlias(resolved, idMap, defaults, "zoomOutButton", "zoomOutBtn");
309
- this._resolveElementAlias(resolved, idMap, defaults, "resetImageTransformButton", "resetBtn");
310
- this._resolveElementAlias(resolved, idMap, defaults, "undoButton", "undoBtn");
311
- this._resolveElementAlias(resolved, idMap, defaults, "redoButton", "redoBtn");
312
- this._resolveElementAliases(resolved, idMap, defaults, "enterCropModeButton", ["cropBtn"]);
313
- this._resolveElementAlias(resolved, idMap, defaults, "applyCropButton", "applyCropBtn");
314
- this._resolveElementAlias(resolved, idMap, defaults, "cancelCropButton", "cancelCropBtn");
315
- return resolved;
316
- }
317
- _resolveElementAlias(resolved, idMap, defaults, canonicalKey, deprecatedKey) {
318
- this._resolveElementAliases(resolved, idMap, defaults, canonicalKey, [deprecatedKey]);
319
- }
320
- _resolveElementAliases(resolved, idMap, defaults, canonicalKey, deprecatedKeys) {
321
- const hasCanonicalKey = Object.prototype.hasOwnProperty.call(idMap, canonicalKey);
322
- if (hasCanonicalKey) {
323
- resolved[canonicalKey] = idMap[canonicalKey];
324
- return;
325
- }
326
- let deprecatedValue;
327
- let hasDeprecatedValue = false;
328
- for (const deprecatedKey of deprecatedKeys) {
329
- if (Object.prototype.hasOwnProperty.call(idMap, deprecatedKey)) {
330
- if (!hasDeprecatedValue) {
331
- deprecatedValue = idMap[deprecatedKey];
332
- hasDeprecatedValue = true;
333
- }
334
- this._warnDeprecatedElementIdKey(deprecatedKey, canonicalKey);
335
- }
336
- }
337
- if (hasDeprecatedValue) {
338
- resolved[canonicalKey] = deprecatedValue;
339
- return;
340
- }
341
- resolved[canonicalKey] = defaults[canonicalKey];
342
- }
343
- _warnDeprecatedElementIdKey(deprecatedKey, canonicalKey) {
344
- if (!this._deprecatedElementKeyWarnings) this._deprecatedElementKeyWarnings = /* @__PURE__ */ new Set();
345
- if (this._deprecatedElementKeyWarnings.has(deprecatedKey)) return;
346
- this._deprecatedElementKeyWarnings.add(deprecatedKey);
347
- this._reportWarning(
348
- `ElementIdMap.${deprecatedKey} is deprecated. Use ${canonicalKey} instead. This alias will be removed in v2.0.0.`
349
- );
350
- }
351
- _reportError(message, error = null) {
352
- const handler = this.options && this.options.onError;
353
- if (typeof handler !== "function") return;
354
- try {
355
- handler(error, message);
356
- } catch {
357
- }
358
- }
359
- _reportWarning(message, error = null) {
360
- const handler = this.options && this.options.onWarning;
361
- if (typeof handler !== "function") return;
362
- try {
363
- handler(error, message);
364
- } catch {
365
- }
366
- }
367
- _notifyImageLoaded() {
368
- const optionsCallback = this.options && this.options.onImageLoaded;
369
- const callback = typeof optionsCallback === "function" ? optionsCallback : this.onImageLoaded;
370
- if (typeof callback === "function") callback();
371
- }
372
- /**
373
- * Initializes the Fabric canvas, viewport elements, and selection event handlers.
374
- *
375
- * @returns {void}
376
- * @private
377
- */
378
- _initCanvas() {
379
- const canvasElement = this._getElement("canvas");
380
- if (!canvasElement) throw new Error("Canvas is not found: " + this.elements.canvas);
381
- this.canvasElement = canvasElement;
382
- this._canvasElementOriginalStyle = {
383
- display: canvasElement.style.display || "",
384
- width: canvasElement.style.width || "",
385
- height: canvasElement.style.height || "",
386
- maxWidth: canvasElement.style.maxWidth || ""
387
- };
388
- if (this.elements.canvasContainer) {
389
- const containerElement = this._getElement("canvasContainer");
390
- this.containerElement = containerElement || canvasElement.parentElement;
391
- } else {
392
- this.containerElement = canvasElement.parentElement;
393
- }
394
- this.placeholderElement = this._getElement("imagePlaceholder") || null;
395
- let initialWidth = this.options.canvasWidth;
396
- let initialHeight = this.options.canvasHeight;
397
- if (this.containerElement) {
398
- const containerWidth = Math.floor(this.containerElement.clientWidth);
399
- const containerHeight = Math.floor(this.containerElement.clientHeight);
400
- if (containerWidth > 0 && containerHeight > 0) {
401
- initialWidth = containerWidth;
402
- initialHeight = containerHeight;
403
- this._lastContainerViewportSize = {
404
- width: containerWidth,
405
- height: containerHeight
406
- };
407
- }
408
- }
409
- this.canvas = new fabric.Canvas(canvasElement, {
410
- width: initialWidth,
411
- height: initialHeight,
412
- backgroundColor: this.options.backgroundColor,
413
- selection: this.options.groupSelection,
414
- preserveObjectStacking: true
415
- });
416
- this.canvas.on("selection:created", (event) => this._handleSelectionChanged(event.selected));
417
- this.canvas.on("selection:updated", (event) => this._handleSelectionChanged(event.selected));
418
- this.canvas.on("selection:cleared", () => this._handleSelectionChanged([]));
419
- this.canvas.on("object:moving", (event) => {
420
- if (event.target && event.target.maskId) this._syncMaskLabel(event.target);
421
- });
422
- this.canvas.on("object:scaling", (event) => {
423
- if (event.target && event.target.maskId) this._syncMaskLabel(event.target);
424
- });
425
- this.canvas.on("object:rotating", (event) => {
426
- if (event.target && event.target.maskId) this._syncMaskLabel(event.target);
427
- });
428
- this.canvas.on("object:modified", (event) => this._handleObjectModified(event.target));
429
- this.canvasElement.style.display = "block";
430
- }
431
- /**
432
- * Returns a configured DOM element and caches lookups for hot UI paths.
433
- *
434
- * @param {string} key - Key in the configured element map.
435
- * @returns {HTMLElement|null} The configured element, or null when missing.
436
- * @private
437
- */
438
- _getElement(key) {
439
- const id = this.elements && this.elements[key];
440
- if (!id) return null;
441
- if (this._elementCache && Object.prototype.hasOwnProperty.call(this._elementCache, key)) {
442
- return this._elementCache[key];
443
- }
444
- const element = document.getElementById(id);
445
- if (this._elementCache) this._elementCache[key] = element || null;
446
- return element || null;
447
- }
448
- /**
449
- * Records a history entry after Fabric finishes modifying one or more masks.
450
- *
451
- * @param {fabric.Object|fabric.ActiveSelection|null} target - Modified Fabric object or selection.
452
- * @returns {void}
453
- * @private
454
- */
455
- _handleObjectModified(target) {
456
- const masks = this._getModifiedMasks(target);
457
- if (!masks.length) return;
458
- masks.forEach((mask) => {
459
- if (typeof mask.setCoords === "function") mask.setCoords();
460
- this._syncMaskLabel(mask);
461
- });
462
- this._expandCanvasToFitObjects(masks);
463
- this.saveState();
464
- }
465
- /**
466
- * Extracts editable mask objects from a Fabric modification target.
467
- *
468
- * @param {fabric.Object|fabric.ActiveSelection|null} target - Fabric object or active selection.
469
- * @returns {Array<fabric.Object>} Modified mask objects.
470
- * @private
471
- */
472
- _getModifiedMasks(target) {
473
- if (!target) return [];
474
- if (target.maskId) return [target];
475
- const objects = typeof target.getObjects === "function" ? target.getObjects() : [];
476
- return Array.isArray(objects) ? objects.filter((object) => object && object.maskId) : [];
477
- }
478
- /**
479
- * Updates container overflow behavior for fit and cover image modes.
480
- *
481
- * @param {Object} [options={}] - Overflow update options.
482
- * @param {boolean} [options.preserveScroll=false] - If true, keeps the current scroll offsets.
483
- * @returns {void}
484
- * @private
485
- */
486
- _syncContainerOverflow(options = {}) {
487
- if (!this.containerElement || !this.containerElement.style) return;
488
- this._captureContainerOverflowState();
489
- const shouldPreserveScroll = options.preserveScroll === true;
490
- const layoutMode = this._getImageLayoutMode();
491
- if (layoutMode === "cover") {
492
- this.containerElement.style.overflow = "scroll";
493
- if (!shouldPreserveScroll) {
494
- this.containerElement.scrollLeft = 0;
495
- this.containerElement.scrollTop = 0;
496
- }
497
- } else if (layoutMode === "fit") {
498
- this.containerElement.style.overflow = "auto";
499
- if (!shouldPreserveScroll) {
500
- this.containerElement.scrollLeft = 0;
501
- this.containerElement.scrollTop = 0;
502
- }
503
- } else {
504
- this._restoreContainerOverflowState();
505
- }
506
- }
507
- _captureContainerOverflowState() {
508
- if (!this.containerElement || !this.containerElement.style || this._containerOriginalOverflow) return;
509
- this._containerOriginalOverflow = {
510
- overflow: this.containerElement.style.overflow || "",
511
- overflowX: this.containerElement.style.overflowX || "",
512
- overflowY: this.containerElement.style.overflowY || ""
513
- };
514
- }
515
- _restoreContainerOverflowState() {
516
- if (!this.containerElement || !this.containerElement.style || !this._containerOriginalOverflow) return;
517
- this.containerElement.style.overflow = this._containerOriginalOverflow.overflow;
518
- this.containerElement.style.overflowX = this._containerOriginalOverflow.overflowX;
519
- this.containerElement.style.overflowY = this._containerOriginalOverflow.overflowY;
520
- }
521
- _restoreContainerOverflowSnapshot(snapshot) {
522
- if (!this.containerElement || !this.containerElement.style || !snapshot) return;
523
- this.containerElement.style.overflow = snapshot.overflow || "";
524
- this.containerElement.style.overflowX = snapshot.overflowX || "";
525
- this.containerElement.style.overflowY = snapshot.overflowY || "";
526
- }
527
- /**
528
- * DOM / UI bindings
529
- * @private
530
- */
531
- _bindEvents() {
532
- this._bindIfExists("uploadArea", "click", () => {
533
- const uploadAreaElement = this._getElement("uploadArea");
534
- if (this._isElementDisabled(uploadAreaElement)) return;
535
- this._getElement("imageInput")?.click();
536
- });
537
- this._bindIfExists("imageInput", "change", (event) => {
538
- const file = event.target.files && event.target.files[0];
539
- if (file) {
540
- this._loadImageFile(file).catch((error) => this._reportError("Image file could not be loaded", error)).finally(() => {
541
- event.target.value = "";
542
- });
543
- }
544
- });
545
- this._bindIfExists("zoomInButton", "click", () => this.scaleImage(this.currentScale + this.options.scaleStep).catch((error) => this._reportError("scaleImage failed", error)));
546
- this._bindIfExists("zoomOutButton", "click", () => this.scaleImage(this.currentScale - this.options.scaleStep).catch((error) => this._reportError("scaleImage failed", error)));
547
- this._bindIfExists("resetImageTransformButton", "click", () => {
548
- this.resetImageTransform().catch((error) => this._reportError("resetImageTransform failed", error));
549
- });
550
- this._bindIfExists("createMaskButton", "click", () => this.createMask());
551
- this._bindIfExists("removeSelectedMaskButton", "click", () => this.removeSelectedMask());
552
- this._bindIfExists("removeAllMasksButton", "click", () => this.removeAllMasks());
553
- this._bindIfExists("mergeMasksButton", "click", () => this.mergeMasks().catch((error) => this._reportError("merge error", error)));
554
- this._bindIfExists("downloadImageButton", "click", () => this.downloadImage());
555
- this._bindIfExists("undoButton", "click", () => this.undo().catch((error) => this._reportError("undo failed", error)));
556
- this._bindIfExists("redoButton", "click", () => this.redo().catch((error) => this._reportError("redo failed", error)));
557
- this._bindIfExists("rotateLeftButton", "click", () => {
558
- const rotationInputElement = this._getElement("rotateLeftDegreesInput");
559
- let step = this.options.rotationStep;
560
- if (rotationInputElement) {
561
- const parsedStep = parseFloat(rotationInputElement.value);
562
- if (!isNaN(parsedStep)) step = parsedStep;
563
- }
564
- this.rotateImage(this.currentRotation - step).catch((error) => this._reportError("rotateImage failed", error));
565
- });
566
- this._bindIfExists("rotateRightButton", "click", () => {
567
- const rotationInputElement = this._getElement("rotateRightDegreesInput");
568
- let step = this.options.rotationStep;
569
- if (rotationInputElement) {
570
- const parsedStep = parseFloat(rotationInputElement.value);
571
- if (!isNaN(parsedStep)) step = parsedStep;
572
- }
573
- this.rotateImage(this.currentRotation + step).catch((error) => this._reportError("rotateImage failed", error));
574
- });
575
- this._bindIfExists("enterCropModeButton", "click", () => this.enterCropMode());
576
- this._bindIfExists("applyCropButton", "click", () => {
577
- this.applyCrop().catch((error) => this._reportError("applyCrop failed", error));
578
- });
579
- this._bindIfExists("cancelCropButton", "click", () => this.cancelCrop());
580
- this._bindIfExists("maskList", "click", (event) => this._handleMaskListClick(event));
581
- }
582
- /**
583
- * Binds a DOM event listener when the configured element exists and records it for disposal.
584
- *
585
- * @param {string} key - Key in this.elements for the target DOM element.
586
- * @param {string} eventName - DOM event name to listen for.
587
- * @param {EventListener} handler - Event listener callback.
588
- * @private
589
- */
590
- _bindIfExists(key, eventName, handler) {
591
- const element = this._getElement(key);
592
- if (element) {
593
- element.addEventListener(eventName, handler);
594
- this._handlersByElementKey = this._handlersByElementKey || {};
595
- if (!this._handlersByElementKey[key]) this._handlersByElementKey[key] = [];
596
- this._handlersByElementKey[key].push({ eventName, handler });
597
- }
598
- }
599
- /**
600
- * Reads an image File as a data URL and loads it into the Fabric canvas.
601
- *
602
- * @param {File} file - Image file selected by the user.
603
- * @returns {Promise<void>} Resolves after the selected file is loaded.
604
- * @private
605
- */
606
- _loadImageFile(file) {
607
- if (!this._isSupportedImageFile(file)) {
608
- const error = new Error("Selected file is not a supported image");
609
- this._reportError("Selected file is not a supported image", error);
610
- return Promise.reject(error);
611
- }
612
- return new Promise((resolve, reject) => {
613
- const reader = new FileReader();
614
- reader.onload = (event) => {
615
- this.loadImage(event.target.result).then(resolve).catch(reject);
616
- };
617
- reader.onerror = (event) => {
618
- const error = new Error("Image file could not be read");
619
- this._reportError("Image file could not be read", event);
620
- reject(error);
621
- };
622
- reader.readAsDataURL(file);
623
- });
624
- }
625
- _isSupportedImageFile(file) {
626
- if (!file) return false;
627
- if (typeof file.type === "string" && file.type.startsWith("image/")) return true;
628
- const fileName = String(file.name || "");
629
- return /\.(avif|bmp|gif|jpe?g|png|webp)$/i.test(fileName);
630
- }
631
- /**
632
- * Warns when more than one mutually exclusive image layout mode is enabled.
633
- *
634
- * @returns {void}
635
- * @private
636
- */
637
- _warnOnImageLayoutOptionConflict() {
638
- const activeModes = [
639
- ["fitImageToCanvas", this.options.fitImageToCanvas],
640
- ["coverImageToCanvas", this.options.coverImageToCanvas],
641
- ["expandCanvasToImage", this.options.expandCanvasToImage]
642
- ].filter(([, isEnabled]) => !!isEnabled).map(([name]) => name);
643
- if (activeModes.length <= 1) return;
644
- this._reportWarning(
645
- `Only one image layout mode should be enabled. Active modes: ${activeModes.join(", ")}.`
646
- );
647
- }
648
- _getImageLayoutMode() {
649
- if (this.options.fitImageToCanvas) return "fit";
650
- if (this.options.coverImageToCanvas) return "cover";
651
- if (this.options.expandCanvasToImage) return "expand";
652
- return "contain";
653
- }
654
- /**
655
- * Loads a base64 data URL into the Fabric canvas as the base image.
656
- *
657
- * @async
658
- * @param {string} imageBase64 - Image data URL beginning with `data:image/`.
659
- * @param {LoadImageOptions} [options={}] - Optional load behavior.
660
- * @returns {Promise<void>} Resolves after the Fabric image is added to the canvas.
661
- * @public
662
- */
663
- async loadImage(imageBase64, options = {}) {
664
- if (!this._fabricLoaded) return;
665
- if (!this.canvas || this._disposed) return;
666
- if (!imageBase64 || typeof imageBase64 !== "string" || !imageBase64.startsWith("data:image/")) return;
667
- options = options || {};
668
- this._assertIdleForOperation("loadImage", options);
669
- const isNestedOperation = this._isOwnInternalOperation(options);
670
- const operationToken = isNestedOperation ? this._getInternalOperationToken(options) : this._beginBusyOperation("loadImage");
671
- let transaction = null;
672
- try {
673
- this._isLoading = true;
674
- this._updateUI();
675
- this._warnOnImageLayoutOptionConflict();
676
- transaction = this._captureLoadImageTransaction();
677
- const imageElement = await this._createImageElement(imageBase64);
678
- if (this._disposed || !this.canvas) throw new Error("Editor was disposed while loading image");
679
- let loadSource = imageBase64;
680
- const downsampleMaxWidth = Number(this.options.downsampleMaxWidth);
681
- const downsampleMaxHeight = Number(this.options.downsampleMaxHeight);
682
- if (this.options.downsampleOnLoad && downsampleMaxWidth > 0 && downsampleMaxHeight > 0) {
683
- const shouldResize = imageElement.naturalWidth > downsampleMaxWidth || imageElement.naturalHeight > downsampleMaxHeight;
684
- if (shouldResize) {
685
- const ratio = Math.min(
686
- downsampleMaxWidth / imageElement.naturalWidth,
687
- downsampleMaxHeight / imageElement.naturalHeight
688
- );
689
- const targetWidth = Math.round(imageElement.naturalWidth * ratio);
690
- const targetHeight = Math.round(imageElement.naturalHeight * ratio);
691
- loadSource = this._resampleImageToDataURL(
692
- imageElement,
693
- targetWidth,
694
- targetHeight,
695
- this._normalizeQuality(this.options.downsampleQuality),
696
- imageBase64
697
- );
698
- }
699
- } else if (this.options.downsampleOnLoad) {
700
- this._reportWarning("loadImage: downsample limits must be positive numbers; using the original image");
701
- }
702
- const fabricImage = await this._createFabricImageFromURL(loadSource);
703
- if (this._disposed || !this.canvas) throw new Error("Editor was disposed while loading image");
704
- this.canvas.discardActiveObject();
705
- this._hideAllMaskLabels();
706
- this.canvas.clear();
707
- this.canvas.setBackgroundColor(this.options.backgroundColor, this.canvas.renderAll.bind(this.canvas));
708
- fabricImage.set({ originX: "left", originY: "top", selectable: false, evented: false });
709
- this._setPlaceholderVisible(false);
710
- this._syncContainerOverflow({ preserveScroll: options.preserveScroll === true });
711
- const imageWidth = fabricImage.width;
712
- const imageHeight = fabricImage.height;
713
- const viewport = this._getContainerViewportSize();
714
- const minWidth = viewport.width;
715
- const minHeight = viewport.height;
716
- const layoutMode = this._getImageLayoutMode();
717
- if (layoutMode === "fit") {
718
- const canvasWidth = Math.max(1, minWidth - 1);
719
- const canvasHeight = Math.max(1, minHeight - 1);
720
- this._setCanvasSizeInt(canvasWidth, canvasHeight);
721
- const fitScale = Math.min(canvasWidth / imageWidth, canvasHeight / imageHeight, 1);
722
- fabricImage.set({ left: 0, top: 0 });
723
- fabricImage.scale(fitScale);
724
- this.baseImageScale = fabricImage.scaleX || 1;
725
- } else if (layoutMode === "cover") {
726
- const layout = this._calculateCoverCanvasLayout(imageWidth, imageHeight);
727
- this._setCanvasSizeInt(layout.canvasWidth, layout.canvasHeight);
728
- fabricImage.set({ left: 0, top: 0 });
729
- fabricImage.scale(layout.scale);
730
- this.baseImageScale = fabricImage.scaleX || 1;
731
- } else if (layoutMode === "expand") {
732
- const canvasWidth = Math.max(minWidth, Math.floor(imageWidth));
733
- const canvasHeight = Math.max(minHeight, Math.floor(imageHeight));
734
- this._setCanvasSizeInt(canvasWidth, canvasHeight);
735
- fabricImage.set({ left: 0, top: 0 });
736
- fabricImage.scale(1);
737
- this.baseImageScale = 1;
738
- } else {
739
- const canvasWidth = Math.max(this.options.canvasWidth, minWidth);
740
- const canvasHeight = Math.max(this.options.canvasHeight, minHeight);
741
- this._setCanvasSizeInt(canvasWidth, canvasHeight);
742
- const fitScale = Math.min(canvasWidth / imageWidth, canvasHeight / imageHeight, 1);
743
- fabricImage.set({ left: 0, top: 0 });
744
- fabricImage.scale(fitScale);
745
- this.baseImageScale = fabricImage.scaleX || 1;
746
- }
747
- this.originalImage = fabricImage;
748
- this.canvas.add(fabricImage);
749
- this.canvas.sendToBack(fabricImage);
750
- this._clearMaskPlacementMemory();
751
- if (options.resetMaskCounter !== false) this.maskCounter = 0;
752
- this.currentScale = 1;
753
- this.currentRotation = 0;
754
- this._updateInputs();
755
- this._updateMaskList();
756
- this.isImageLoadedToCanvas = true;
757
- this._updateUI();
758
- this.canvas.renderAll();
759
- this._lastSnapshot = this._captureCanvasStateOrThrow("loadImage");
760
- this._notifyImageLoaded();
761
- } catch (error) {
762
- await this._rollbackLoadImageTransaction(
763
- transaction,
764
- this._withInternalOperationOptions(operationToken)
765
- );
766
- throw error;
767
- } finally {
768
- this._isLoading = false;
769
- if (!isNestedOperation) this._endBusyOperation(operationToken);
770
- if (!this._disposed && this.canvas) this._updateUI();
771
- }
772
- }
773
- /**
774
- * Checks whether there is a loaded image on the current canvas.
775
- * @returns {boolean} true if loaded, false if not
776
- */
777
- isImageLoaded() {
778
- const fabricInstance = ensureFabric();
779
- return !!(this.originalImage && fabricInstance && this.originalImage instanceof fabricInstance.Image && this.originalImage.width > 0 && this.originalImage.height > 0);
780
- }
781
- /**
782
- * Checks whether the editor is in a temporary non-mutating state.
783
- *
784
- * @returns {boolean} True while loading, animating, cropping, or running a compound operation.
785
- * @public
786
- */
787
- isBusy() {
788
- return !!(this.isAnimating || this._cropMode || this._isLoading || this._activeOperationToken || this.animationQueue && this.animationQueue.isBusy());
789
- }
790
- /**
791
- * Creates an HTMLImageElement from a given data URL.
792
- *
793
- * @param {string} dataUrl - A data URL representing the image (e.g., "data:image/png;base64,...").
794
- * @param {number} [timeoutMs=this.options.imageLoadTimeoutMs] - Maximum decode time before rejecting.
795
- * @returns {Promise<HTMLImageElement>} A promise that resolves to the created image element when loaded, or rejects on error.
796
- * @private
797
- */
798
- _createImageElement(dataUrl, timeoutMs = this.options.imageLoadTimeoutMs) {
799
- return new Promise((resolve, reject) => {
800
- const imageElement = new Image();
801
- let isSettled = false;
802
- const safeTimeoutMs = Number.isFinite(Number(timeoutMs)) && Number(timeoutMs) > 0 ? Number(timeoutMs) : 3e4;
803
- let timerId;
804
- const settle = (callback) => {
805
- if (isSettled) return;
806
- isSettled = true;
807
- clearTimeout(timerId);
808
- imageElement.onload = null;
809
- imageElement.onerror = null;
810
- callback();
811
- };
812
- timerId = setTimeout(() => {
813
- settle(() => reject(new Error("Image load timed out")));
814
- try {
815
- imageElement.src = "";
816
- } catch (error) {
817
- this._reportWarning("Image timeout cleanup failed", error);
818
- }
819
- }, safeTimeoutMs);
820
- imageElement.onload = () => settle(() => resolve(imageElement));
821
- imageElement.onerror = (error) => settle(() => reject(error));
822
- imageElement.src = dataUrl;
823
- });
824
- }
825
- _createFabricImageFromURL(dataUrl, timeoutMs = this.options.imageLoadTimeoutMs) {
826
- return new Promise((resolve, reject) => {
827
- const safeTimeoutMs = this._getSafeTimeoutMs(timeoutMs);
828
- let isSettled = false;
829
- let timerId;
830
- const settle = (callback) => {
831
- if (isSettled) return;
832
- isSettled = true;
833
- clearTimeout(timerId);
834
- callback();
835
- };
836
- timerId = setTimeout(() => {
837
- settle(() => reject(new Error("Fabric image load timed out")));
838
- }, safeTimeoutMs);
839
- try {
840
- fabric.Image.fromURL(dataUrl, (fabricImage) => {
841
- settle(() => {
842
- if (!fabricImage) {
843
- reject(new Error("Image could not be loaded"));
844
- return;
845
- }
846
- resolve(fabricImage);
847
- });
848
- }, { crossOrigin: "anonymous" });
849
- } catch (error) {
850
- settle(() => reject(error));
851
- }
852
- });
853
- }
854
- _getSafeTimeoutMs(timeoutMs) {
855
- const safeTimeoutMs = Number(timeoutMs);
856
- return Number.isFinite(safeTimeoutMs) && safeTimeoutMs > 0 ? safeTimeoutMs : 3e4;
857
- }
858
- _captureLoadImageTransaction() {
859
- return {
860
- canvasState: this._serializeCanvasState(),
861
- baseImageScale: this.baseImageScale,
862
- currentScale: this.currentScale,
863
- currentRotation: this.currentRotation,
864
- maskCounter: this.maskCounter,
865
- isImageLoadedToCanvas: this.isImageLoadedToCanvas,
866
- lastSnapshot: this._lastSnapshot,
867
- lastMask: this._lastMask,
868
- lastMaskInitialLeft: this._lastMaskInitialLeft,
869
- lastMaskInitialTop: this._lastMaskInitialTop,
870
- lastMaskInitialWidth: this._lastMaskInitialWidth,
871
- containerOverflow: this.containerElement && this.containerElement.style ? {
872
- overflow: this.containerElement.style.overflow || "",
873
- overflowX: this.containerElement.style.overflowX || "",
874
- overflowY: this.containerElement.style.overflowY || ""
875
- } : null,
876
- scrollLeft: this.containerElement ? this.containerElement.scrollLeft : 0,
877
- scrollTop: this.containerElement ? this.containerElement.scrollTop : 0,
878
- placeholderVisibility: this._captureElementVisibility(this.placeholderElement),
879
- canvasVisibility: this._captureElementVisibility(this._getCanvasVisibilityElement())
880
- };
881
- }
882
- async _rollbackLoadImageTransaction(transaction, options = {}) {
883
- if (!transaction || !this.canvas || this._disposed) return;
884
- let didRestoreCanvasState = false;
885
- let didFailCanvasRestore = false;
886
- try {
887
- if (transaction.canvasState) {
888
- await this.loadFromState(transaction.canvasState, options);
889
- didRestoreCanvasState = true;
890
- }
891
- } catch (error) {
892
- this._lastMask = null;
893
- didFailCanvasRestore = true;
894
- this._reportError("loadImage rollback failed", error);
895
- }
896
- if (didFailCanvasRestore) {
897
- this._reconcileEditorStateFromCanvas();
898
- } else {
899
- this.baseImageScale = transaction.baseImageScale;
900
- this.currentScale = transaction.currentScale;
901
- this.currentRotation = transaction.currentRotation;
902
- this.maskCounter = transaction.maskCounter;
903
- this.isImageLoadedToCanvas = transaction.isImageLoadedToCanvas;
904
- this._lastSnapshot = transaction.lastSnapshot;
905
- if (didRestoreCanvasState) {
906
- this._restoreLastMaskReference(transaction.lastMask);
907
- } else {
908
- this._lastMask = null;
909
- }
910
- this._lastMaskInitialLeft = transaction.lastMaskInitialLeft;
911
- this._lastMaskInitialTop = transaction.lastMaskInitialTop;
912
- this._lastMaskInitialWidth = transaction.lastMaskInitialWidth;
913
- }
914
- this._restoreElementVisibility(this.placeholderElement, transaction.placeholderVisibility);
915
- this._restoreElementVisibility(this._getCanvasVisibilityElement(), transaction.canvasVisibility);
916
- if (this.containerElement) {
917
- this.containerElement.scrollLeft = transaction.scrollLeft;
918
- this.containerElement.scrollTop = transaction.scrollTop;
919
- this._restoreContainerOverflowSnapshot(transaction.containerOverflow);
920
- }
921
- this._updateInputs();
922
- this._updateMaskList();
923
- this._updateUI();
924
- if (this.canvas) this.canvas.renderAll();
925
- }
926
- _reconcileEditorStateFromCanvas() {
927
- if (!this.canvas) {
928
- this.originalImage = null;
929
- this.baseImageScale = 1;
930
- this.currentScale = 1;
931
- this.currentRotation = 0;
932
- this.maskCounter = 0;
933
- this.isImageLoadedToCanvas = false;
934
- this._lastSnapshot = null;
935
- this._clearMaskPlacementMemory();
936
- return;
937
- }
938
- const canvasObjects = this.canvas.getObjects();
939
- this.originalImage = canvasObjects.find((object) => object.type === "image" && !object.maskId) || null;
940
- if (this.originalImage) {
941
- const imageScale = Number(this.originalImage.scaleX) || 1;
942
- this.baseImageScale = imageScale;
943
- this.currentScale = 1;
944
- this.currentRotation = Number(this.originalImage.angle) || 0;
945
- } else {
946
- this.baseImageScale = 1;
947
- this.currentScale = 1;
948
- this.currentRotation = 0;
949
- }
950
- const masks = canvasObjects.filter((object) => object.maskId);
951
- this.maskCounter = masks.reduce((max, mask) => Math.max(max, Number(mask.maskId) || 0), 0);
952
- this._lastMask = masks[masks.length - 1] || null;
953
- if (!this._lastMask) {
954
- this._lastMaskInitialLeft = null;
955
- this._lastMaskInitialTop = null;
956
- this._lastMaskInitialWidth = null;
957
- }
958
- this.isImageLoadedToCanvas = !!this.originalImage;
959
- try {
960
- this._lastSnapshot = this._serializeCanvasState();
961
- } catch (error) {
962
- this._lastSnapshot = null;
963
- this._reportWarning("loadImage rollback: failed to reconcile canvas snapshot", error);
964
- }
965
- }
966
- _restoreLastMaskReference(previousLastMask) {
967
- if (!this.canvas) {
968
- this._lastMask = null;
969
- return;
970
- }
971
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
972
- const previousMaskId = previousLastMask && previousLastMask.maskId;
973
- this._lastMask = masks.find((mask) => mask.maskId === previousMaskId) || masks[masks.length - 1] || null;
974
- if (!this._lastMask) {
975
- this._lastMaskInitialLeft = null;
976
- this._lastMaskInitialTop = null;
977
- this._lastMaskInitialWidth = null;
978
- }
979
- }
980
- /**
981
- * Resamples the given image element to a new width and height and returns the result as a data URL.
982
- *
983
- * @param {HTMLImageElement} imageElement - The image element to resample.
984
- * @param {number} targetWidth - Target width (in pixels) for the resampled image.
985
- * @param {number} targetHeight - Target height (in pixels) for the resampled image.
986
- * @param {number} [quality=0.92] - Image quality between 0 and 1 for lossy formats.
987
- * @param {string|null} [sourceDataUrl=null] - Source data URL used to preserve alpha-capable formats.
988
- * @returns {string} A data URL representing the resampled image.
989
- * @private
990
- */
991
- _resampleImageToDataURL(imageElement, targetWidth, targetHeight, quality = 0.92, sourceDataUrl = null) {
992
- const sourceWidth = Math.max(1, Number(imageElement && (imageElement.naturalWidth || imageElement.width)) || 0);
993
- const sourceHeight = Math.max(1, Number(imageElement && (imageElement.naturalHeight || imageElement.height)) || 0);
994
- const safeTargetWidth = Math.round(Number(targetWidth));
995
- const safeTargetHeight = Math.round(Number(targetHeight));
996
- if (!Number.isFinite(safeTargetWidth) || !Number.isFinite(safeTargetHeight) || safeTargetWidth <= 0 || safeTargetHeight <= 0) {
997
- throw new Error("Invalid image resample target dimensions");
998
- }
999
- const offscreenCanvas = document.createElement("canvas");
1000
- offscreenCanvas.width = safeTargetWidth;
1001
- offscreenCanvas.height = safeTargetHeight;
1002
- const context = offscreenCanvas.getContext("2d");
1003
- if (!context) throw new Error("2D canvas context is unavailable");
1004
- context.drawImage(imageElement, 0, 0, sourceWidth, sourceHeight, 0, 0, safeTargetWidth, safeTargetHeight);
1005
- return offscreenCanvas.toDataURL(this._getDownsampleMimeType(sourceDataUrl), quality);
1006
- }
1007
- _getDataUrlMimeType(dataUrl) {
1008
- const match = String(dataUrl || "").match(/^data:([^;,]+)[;,]/i);
1009
- return match ? match[1].toLowerCase() : "";
1010
- }
1011
- _getDownsampleMimeType(sourceDataUrl) {
1012
- if (this.options.downsampleMimeType) {
1013
- const requestedFormat = this._normalizeImageFormat(this.options.downsampleMimeType);
1014
- return `image/${requestedFormat}`;
1015
- }
1016
- const sourceMimeType = this._getDataUrlMimeType(sourceDataUrl);
1017
- if (this.options.preserveSourceFormat !== false && (sourceMimeType === "image/png" || sourceMimeType === "image/webp")) {
1018
- return sourceMimeType;
1019
- }
1020
- return "image/jpeg";
1021
- }
1022
- _captureCanvasStateOrThrow(context) {
1023
- const snapshot = this._serializeCanvasState();
1024
- if (!snapshot) throw new Error(`${context}: canvas state is unavailable`);
1025
- return snapshot;
1026
- }
1027
- /**
1028
- * Sets canvas size to integer width and height values to prevent scrollbars due to sub-pixel rendering.
1029
- * Also updates the corresponding style attributes.
1030
- *
1031
- * @param {number} width - Canvas width in pixels.
1032
- * @param {number} height - Canvas height in pixels.
1033
- * @private
1034
- */
1035
- _setCanvasSizeInt(width, height) {
1036
- if (!this.canvas) return;
1037
- const integerWidth = Math.max(1, Math.round(Number(width) || 1));
1038
- const integerHeight = Math.max(1, Math.round(Number(height) || 1));
1039
- this.canvas.setWidth(integerWidth);
1040
- this.canvas.setHeight(integerHeight);
1041
- if (typeof this.canvas.calcOffset === "function") this.canvas.calcOffset();
1042
- if (this.canvasElement) {
1043
- this.canvasElement.style.width = integerWidth + "px";
1044
- this.canvasElement.style.height = integerHeight + "px";
1045
- }
1046
- }
1047
- _ceilCanvasDimension(value) {
1048
- const numericValue = Number(value) || 0;
1049
- const roundedValue = Math.round(numericValue);
1050
- if (Math.abs(numericValue - roundedValue) < 0.01) return roundedValue;
1051
- return Math.ceil(numericValue);
1052
- }
1053
- _getContainerViewportSize() {
1054
- if (!this.containerElement) {
1055
- return {
1056
- width: Math.max(1, Math.floor(this.options.canvasWidth || 1)),
1057
- height: Math.max(1, Math.floor(this.options.canvasHeight || 1))
1058
- };
1059
- }
1060
- const measuredWidth = Math.floor(this.containerElement.clientWidth || 0);
1061
- const measuredHeight = Math.floor(this.containerElement.clientHeight || 0);
1062
- let width = Math.max(1, measuredWidth || this._lastContainerViewportSize?.width || this.options.canvasWidth || 1);
1063
- let height = Math.max(1, measuredHeight || this._lastContainerViewportSize?.height || this.options.canvasHeight || 1);
1064
- if (measuredWidth > 0 && measuredHeight > 0) {
1065
- this._lastContainerViewportSize = { width: measuredWidth, height: measuredHeight };
1066
- }
1067
- if (this._hasFixedContainerScrollbars()) {
1068
- return { width, height };
1069
- }
1070
- const overflow = this._getContainerOverflowValues();
1071
- const canScrollX = overflow.x.some((value) => value === "auto" || value === "scroll");
1072
- const canScrollY = overflow.y.some((value) => value === "auto" || value === "scroll");
1073
- const hasHorizontalScrollbar = canScrollX && this.containerElement.scrollWidth > this.containerElement.clientWidth;
1074
- const hasVerticalScrollbar = canScrollY && this.containerElement.scrollHeight > this.containerElement.clientHeight;
1075
- if (hasHorizontalScrollbar || hasVerticalScrollbar) {
1076
- const scrollbar = this._getScrollbarSize();
1077
- if (hasVerticalScrollbar) width += scrollbar.width;
1078
- if (hasHorizontalScrollbar) height += scrollbar.height;
1079
- }
1080
- return { width, height };
1081
- }
1082
- /**
1083
- * Reads inline and computed overflow values for both scroll axes.
1084
- *
1085
- * @returns {{x:string[], y:string[]}} Overflow values grouped by axis.
1086
- * @private
1087
- */
1088
- _getContainerOverflowValues() {
1089
- if (!this.containerElement) return { x: [], y: [] };
1090
- const inlineOverflow = this.containerElement.style.overflow;
1091
- const inlineOverflowX = this.containerElement.style.overflowX;
1092
- const inlineOverflowY = this.containerElement.style.overflowY;
1093
- let computedOverflow = "";
1094
- let computedOverflowX = "";
1095
- let computedOverflowY = "";
1096
- if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
1097
- const style = window.getComputedStyle(this.containerElement);
1098
- computedOverflow = style.overflow;
1099
- computedOverflowX = style.overflowX;
1100
- computedOverflowY = style.overflowY;
1101
- }
1102
- return {
1103
- x: [inlineOverflow, inlineOverflowX, computedOverflow, computedOverflowX],
1104
- y: [inlineOverflow, inlineOverflowY, computedOverflow, computedOverflowY]
1105
- };
1106
- }
1107
- _hasFixedContainerScrollbars() {
1108
- if (!this.containerElement) return false;
1109
- const overflow = this._getContainerOverflowValues();
1110
- return [...overflow.x, ...overflow.y].some((value) => value === "scroll");
1111
- }
1112
- _getScrollbarSize() {
1113
- if (this._scrollbarSizeCache) {
1114
- return { ...this._scrollbarSizeCache };
1115
- }
1116
- if (typeof document === "undefined" || !document.createElement || !document.body) {
1117
- return { width: 0, height: 0 };
1118
- }
1119
- const probe = document.createElement("div");
1120
- probe.style.position = "absolute";
1121
- probe.style.visibility = "hidden";
1122
- probe.style.overflow = "scroll";
1123
- probe.style.width = "100px";
1124
- probe.style.height = "100px";
1125
- probe.style.top = "-9999px";
1126
- document.body.appendChild(probe);
1127
- const width = Math.max(0, probe.offsetWidth - probe.clientWidth);
1128
- const height = Math.max(0, probe.offsetHeight - probe.clientHeight);
1129
- document.body.removeChild(probe);
1130
- this._scrollbarSizeCache = { width, height };
1131
- return { ...this._scrollbarSizeCache };
1132
- }
1133
- _getScrollSafetyMargin() {
1134
- return 2;
1135
- }
1136
- _getScrollableCanvasSize(contentWidth, contentHeight, viewport = this._getContainerViewportSize()) {
1137
- if (this._hasFixedContainerScrollbars()) {
1138
- const safetyMargin2 = this._getScrollSafetyMargin();
1139
- const safeWidth = Math.max(1, viewport.width - safetyMargin2);
1140
- const safeHeight = Math.max(1, viewport.height - safetyMargin2);
1141
- return {
1142
- width: contentWidth > viewport.width + 0.5 ? this._ceilCanvasDimension(contentWidth) : safeWidth,
1143
- height: contentHeight > viewport.height + 0.5 ? this._ceilCanvasDimension(contentHeight) : safeHeight,
1144
- viewportWidth: viewport.width,
1145
- viewportHeight: viewport.height,
1146
- hasHorizontal: true,
1147
- hasVertical: true
1148
- };
1149
- }
1150
- const scrollbar = this._getScrollbarSize();
1151
- let hasVertical = false;
1152
- let hasHorizontal = false;
1153
- let effectiveWidth;
1154
- let effectiveHeight;
1155
- for (let i = 0; i < 4; i += 1) {
1156
- effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
1157
- effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
1158
- const nextHasVertical = contentHeight > effectiveHeight + 0.5;
1159
- const nextHasHorizontal = contentWidth > effectiveWidth + 0.5;
1160
- if (nextHasVertical === hasVertical && nextHasHorizontal === hasHorizontal) break;
1161
- hasVertical = nextHasVertical;
1162
- hasHorizontal = nextHasHorizontal;
1163
- }
1164
- effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
1165
- effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
1166
- const safetyMargin = this._getScrollSafetyMargin();
1167
- const layoutMode = this._getImageLayoutMode();
1168
- const shouldReserveNoScrollbarMargin = layoutMode === "fit" || layoutMode === "cover";
1169
- const getNonOverflowAxisSize = (contentSize, effectiveSize, hasOppositeScrollbar) => {
1170
- const margin = hasOppositeScrollbar ? safetyMargin : shouldReserveNoScrollbarMargin ? 1 : 0;
1171
- const safeEffectiveSize = Math.max(1, effectiveSize - margin);
1172
- return contentSize <= safeEffectiveSize + 0.5 ? safeEffectiveSize : effectiveSize;
1173
- };
1174
- return {
1175
- width: hasHorizontal ? this._ceilCanvasDimension(contentWidth) : getNonOverflowAxisSize(contentWidth, effectiveWidth, hasVertical),
1176
- height: hasVertical ? this._ceilCanvasDimension(contentHeight) : getNonOverflowAxisSize(contentHeight, effectiveHeight, hasHorizontal),
1177
- viewportWidth: effectiveWidth,
1178
- viewportHeight: effectiveHeight,
1179
- hasHorizontal,
1180
- hasVertical
1181
- };
1182
- }
1183
- _calculateCoverCanvasLayout(imageWidth, imageHeight) {
1184
- const viewport = this._getContainerViewportSize();
1185
- if (this._hasFixedContainerScrollbars()) {
1186
- const safetyMargin = this._getScrollSafetyMargin();
1187
- const targetWidth = Math.max(1, viewport.width - safetyMargin);
1188
- const targetHeight = Math.max(1, viewport.height - safetyMargin);
1189
- const scale2 = Math.min(1, Math.max(targetWidth / imageWidth, targetHeight / imageHeight));
1190
- const contentWidth2 = imageWidth * scale2;
1191
- const contentHeight2 = imageHeight * scale2;
1192
- const canvasSize2 = this._getScrollableCanvasSize(contentWidth2, contentHeight2, viewport);
1193
- return {
1194
- scale: scale2,
1195
- canvasWidth: canvasSize2.width,
1196
- canvasHeight: canvasSize2.height
1197
- };
1198
- }
1199
- const scrollbar = this._getScrollbarSize();
1200
- let hasVertical = false;
1201
- let hasHorizontal = false;
1202
- let scale = 1;
1203
- let contentWidth = imageWidth;
1204
- let contentHeight = imageHeight;
1205
- let effectiveWidth;
1206
- let effectiveHeight;
1207
- for (let i = 0; i < 4; i += 1) {
1208
- effectiveWidth = Math.max(1, viewport.width - (hasVertical ? scrollbar.width : 0));
1209
- effectiveHeight = Math.max(1, viewport.height - (hasHorizontal ? scrollbar.height : 0));
1210
- scale = Math.min(1, Math.max(effectiveWidth / imageWidth, effectiveHeight / imageHeight));
1211
- contentWidth = imageWidth * scale;
1212
- contentHeight = imageHeight * scale;
1213
- const nextHasVertical = contentHeight > effectiveHeight + 0.5;
1214
- const nextHasHorizontal = contentWidth > effectiveWidth + 0.5;
1215
- if (nextHasVertical === hasVertical && nextHasHorizontal === hasHorizontal) break;
1216
- hasVertical = nextHasVertical;
1217
- hasHorizontal = nextHasHorizontal;
1218
- }
1219
- const canvasSize = this._getScrollableCanvasSize(contentWidth, contentHeight, viewport);
1220
- return {
1221
- scale,
1222
- canvasWidth: canvasSize.width,
1223
- canvasHeight: canvasSize.height
1224
- };
1225
- }
1226
- _getStateProperties() {
1227
- return [
1228
- "maskId",
1229
- "maskName",
1230
- "maskLabel",
1231
- "isCropRect",
1232
- "originalAlpha",
1233
- "originalStroke",
1234
- "originalStrokeWidth",
1235
- "selectable",
1236
- "evented",
1237
- "hasControls",
1238
- "lockRotation",
1239
- "borderColor",
1240
- "cornerColor",
1241
- "cornerSize",
1242
- "transparentCorners",
1243
- "strokeUniform",
1244
- "strokeDashArray"
1245
- ];
1246
- }
1247
- _getMaskNormalStyle(mask) {
1248
- const strokeWidth = Number(mask && mask.originalStrokeWidth);
1249
- const opacity = Number(mask && mask.originalAlpha);
1250
- const style = {
1251
- stroke: mask && mask.originalStroke || "#ccc",
1252
- strokeWidth: Number.isFinite(strokeWidth) ? strokeWidth : 1
1253
- };
1254
- if (Number.isFinite(opacity)) style.opacity = opacity;
1255
- return style;
1256
- }
1257
- _withNormalizedMaskStyles(callback) {
1258
- if (!this.canvas) return callback();
1259
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
1260
- const maskStyleBackups = [];
1261
- try {
1262
- masks.forEach((mask) => {
1263
- const normalStyle = this._getMaskNormalStyle(mask);
1264
- const stylePatch = {};
1265
- Object.keys(normalStyle).forEach((property) => {
1266
- if (mask[property] !== normalStyle[property]) {
1267
- stylePatch[property] = normalStyle[property];
1268
- }
1269
- });
1270
- const changedProperties = Object.keys(stylePatch);
1271
- if (!changedProperties.length) return;
1272
- const backup = { object: mask };
1273
- changedProperties.forEach((property) => {
1274
- backup[property] = mask[property];
1275
- });
1276
- maskStyleBackups.push(backup);
1277
- mask.set(stylePatch);
1278
- });
1279
- const result = callback();
1280
- if (result && typeof result.then === "function") {
1281
- throw new Error("_withNormalizedMaskStyles callback must be synchronous");
1282
- }
1283
- return result;
1284
- } finally {
1285
- maskStyleBackups.forEach((backup) => {
1286
- try {
1287
- const restorePatch = {};
1288
- Object.keys(backup).forEach((property) => {
1289
- if (property !== "object") restorePatch[property] = backup[property];
1290
- });
1291
- backup.object.set(restorePatch);
1292
- } catch (error) {
1293
- void error;
1294
- }
1295
- });
1296
- }
1297
- }
1298
- _getSerializableStateObjects() {
1299
- if (!this.canvas) return [];
1300
- return this.canvas.getObjects().filter((object) => !object.isCropRect && !object.maskLabel);
1301
- }
1302
- _restoreHighPrecisionSerializedGeometry(serializedObjects) {
1303
- if (!Array.isArray(serializedObjects)) return;
1304
- const fabricObjects = this._getSerializableStateObjects();
1305
- const numericProperties = [
1306
- "left",
1307
- "top",
1308
- "width",
1309
- "height",
1310
- "scaleX",
1311
- "scaleY",
1312
- "angle",
1313
- "skewX",
1314
- "skewY",
1315
- "cropX",
1316
- "cropY",
1317
- "radius",
1318
- "rx",
1319
- "ry",
1320
- "strokeWidth"
1321
- ];
1322
- serializedObjects.forEach((serializedObject, index) => {
1323
- const fabricObject = fabricObjects[index];
1324
- if (!serializedObject || !fabricObject) return;
1325
- numericProperties.forEach((property) => {
1326
- const numericValue = Number(fabricObject[property]);
1327
- if (Number.isFinite(numericValue)) serializedObject[property] = numericValue;
1328
- });
1329
- if (Array.isArray(serializedObject.points) && Array.isArray(fabricObject.points)) {
1330
- serializedObject.points = fabricObject.points.map((point) => ({
1331
- x: Number.isFinite(Number(point && point.x)) ? Number(point.x) : 0,
1332
- y: Number.isFinite(Number(point && point.y)) ? Number(point.y) : 0
1333
- }));
1334
- }
1335
- });
1336
- }
1337
- _restoreMaskControls(mask) {
1338
- if (!mask) return;
1339
- const cornerSize = Number(mask.cornerSize);
1340
- mask.set({
1341
- selectable: mask.selectable !== false,
1342
- evented: mask.evented !== false,
1343
- hasControls: mask.hasControls !== false,
1344
- lockRotation: typeof mask.lockRotation === "boolean" ? mask.lockRotation : !this.options.maskRotatable,
1345
- borderColor: mask.borderColor || "red",
1346
- cornerColor: mask.cornerColor || "black",
1347
- cornerSize: Number.isFinite(cornerSize) ? cornerSize : 8,
1348
- transparentCorners: mask.transparentCorners === true,
1349
- strokeUniform: mask.strokeUniform !== false
1350
- });
1351
- if (typeof mask.setCoords === "function") mask.setCoords();
1352
- }
1353
- /**
1354
- * Captures editor-owned runtime state that Fabric does not include in canvas JSON.
1355
- *
1356
- * @returns {{version:number, baseImageScale:number, currentScale:number, currentRotation:number, maskCounter:number, canvasWidth:number, canvasHeight:number}} Serializable editor metadata.
1357
- * @private
1358
- */
1359
- _serializeEditorMetadata() {
1360
- const baseImageScale = Number(this.baseImageScale);
1361
- const currentScale = Number(this.currentScale);
1362
- const currentRotation = Number(this.currentRotation);
1363
- const maskCounter = Number(this.maskCounter);
1364
- const canvasWidth = this.canvas ? Number(this.canvas.getWidth()) : NaN;
1365
- const canvasHeight = this.canvas ? Number(this.canvas.getHeight()) : NaN;
1366
- return {
1367
- version: 1,
1368
- baseImageScale: Number.isFinite(baseImageScale) && baseImageScale > 0 ? baseImageScale : 1,
1369
- currentScale: Number.isFinite(currentScale) && currentScale > 0 ? currentScale : 1,
1370
- currentRotation: Number.isFinite(currentRotation) ? currentRotation : 0,
1371
- maskCounter: Number.isFinite(maskCounter) && maskCounter > 0 ? Math.floor(maskCounter) : 0,
1372
- canvasWidth: Number.isFinite(canvasWidth) && canvasWidth > 0 ? Math.round(canvasWidth) : 1,
1373
- canvasHeight: Number.isFinite(canvasHeight) && canvasHeight > 0 ? Math.round(canvasHeight) : 1
1374
- };
1375
- }
1376
- _serializeCanvasState() {
1377
- if (!this.canvas) return null;
1378
- return this._withNormalizedMaskStyles(() => {
1379
- const jsonObject = this.canvas.toJSON(this._getStateProperties());
1380
- if (Array.isArray(jsonObject.objects)) {
1381
- jsonObject.objects = jsonObject.objects.filter((object) => !object.isCropRect && !object.maskLabel);
1382
- this._restoreHighPrecisionSerializedGeometry(jsonObject.objects);
1383
- }
1384
- jsonObject.imageEditorMetadata = this._serializeEditorMetadata();
1385
- return JSON.stringify(jsonObject);
1386
- });
1387
- }
1388
- /**
1389
- * Normalizes a lossy image quality value to Fabric/canvas's 0..1 range.
1390
- *
1391
- * @param {number} quality - Requested image quality.
1392
- * @returns {number} A finite quality value between 0 and 1.
1393
- * @private
1394
- */
1395
- _normalizeQuality(quality, fallback = void 0) {
1396
- const fallbackQuality = fallback == null ? this.options.downsampleQuality : fallback;
1397
- const numericFallback = fallbackQuality == null ? NaN : Number(fallbackQuality);
1398
- const safeFallback = Number.isFinite(numericFallback) ? Math.max(0, Math.min(1, numericFallback)) : 0.92;
1399
- if (quality == null) return safeFallback;
1400
- const numericQuality = Number(quality);
1401
- if (!Number.isFinite(numericQuality)) return safeFallback;
1402
- return Math.max(0, Math.min(1, numericQuality));
1403
- }
1404
- /**
1405
- * Normalizes public image format aliases to canvas export format names.
1406
- *
1407
- * @param {string} format - Requested image format or MIME type.
1408
- * @returns {'jpeg'|'png'|'webp'} Canvas-compatible image format.
1409
- * @private
1410
- */
1411
- _normalizeImageFormat(format) {
1412
- const typeMapping = {
1413
- "jpeg": "jpeg",
1414
- "jpg": "jpeg",
1415
- "image/jpeg": "jpeg",
1416
- "png": "png",
1417
- "image/png": "png",
1418
- "webp": "webp",
1419
- "image/webp": "webp"
1420
- };
1421
- return typeMapping[String(format || "jpeg").toLowerCase()] || "jpeg";
1422
- }
1423
- /**
1424
- * Converts a bounding rectangle into a canvas-safe integer source region.
1425
- *
1426
- * @param {{left:number, top:number, width:number, height:number}} bounds - Bounds in canvas coordinates.
1427
- * @param {Object} [options={}] - Region rounding options.
1428
- * @param {boolean} [options.includePartialPixels=true] - If false, excludes partially covered trailing pixels.
1429
- * @returns {{sourceX:number, sourceY:number, sourceWidth:number, sourceHeight:number}} Clamped source region.
1430
- * @private
1431
- */
1432
- _getClampedCanvasRegion(bounds, options = {}) {
1433
- const canvasWidth = Math.max(1, Math.round(this.canvas.getWidth()));
1434
- const canvasHeight = Math.max(1, Math.round(this.canvas.getHeight()));
1435
- const left = Number(bounds.left) || 0;
1436
- const top = Number(bounds.top) || 0;
1437
- const width = Math.max(0, Number(bounds.width) || 0);
1438
- const height = Math.max(0, Number(bounds.height) || 0);
1439
- const includePartialPixels = options.includePartialPixels !== false;
1440
- const roundEnd = includePartialPixels ? Math.ceil : Math.floor;
1441
- const sourceX = Math.min(canvasWidth - 1, Math.max(0, Math.floor(left)));
1442
- const sourceY = Math.min(canvasHeight - 1, Math.max(0, Math.floor(top)));
1443
- const endX = Math.min(canvasWidth, Math.max(sourceX + 1, roundEnd(left + width)));
1444
- const endY = Math.min(canvasHeight, Math.max(sourceY + 1, roundEnd(top + height)));
1445
- return {
1446
- sourceX,
1447
- sourceY,
1448
- sourceWidth: Math.max(1, endX - sourceX),
1449
- sourceHeight: Math.max(1, endY - sourceY)
1450
- };
1451
- }
1452
- _hasFractionalCanvasEdge(value) {
1453
- const numericValue = Number(value);
1454
- if (!Number.isFinite(numericValue)) return false;
1455
- return Math.abs(numericValue - Math.round(numericValue)) > 0.01;
1456
- }
1457
- _hasScaledImageEdge(axis) {
1458
- if (!this.originalImage) return false;
1459
- const scale = Number(axis === "y" ? this.originalImage.scaleY : this.originalImage.scaleX);
1460
- if (!Number.isFinite(scale)) return false;
1461
- return Math.abs(scale - 1) > 0.01;
1462
- }
1463
- _getPartialExportEdges(bounds) {
1464
- if (!bounds) return null;
1465
- const angle = Math.abs((Number(this.originalImage && this.originalImage.angle) || 0) % 90);
1466
- const isAxisAligned = angle < 0.01 || Math.abs(angle - 90) < 0.01;
1467
- if (!isAxisAligned) return null;
1468
- return {
1469
- left: this._hasFractionalCanvasEdge(bounds.left),
1470
- top: this._hasFractionalCanvasEdge(bounds.top),
1471
- right: this._hasFractionalCanvasEdge((Number(bounds.left) || 0) + (Number(bounds.width) || 0)) || this._hasScaledImageEdge("x"),
1472
- bottom: this._hasFractionalCanvasEdge((Number(bounds.top) || 0) + (Number(bounds.height) || 0)) || this._hasScaledImageEdge("y")
1473
- };
1474
- }
1475
- async _sealPartialTransparentEdges(dataUrl, edges) {
1476
- if (!edges || !Object.values(edges).some(Boolean)) return dataUrl;
1477
- const imageElement = await this._createImageElement(dataUrl);
1478
- const width = Math.max(1, imageElement.naturalWidth || imageElement.width || 1);
1479
- const height = Math.max(1, imageElement.naturalHeight || imageElement.height || 1);
1480
- const offscreenCanvas = document.createElement("canvas");
1481
- offscreenCanvas.width = width;
1482
- offscreenCanvas.height = height;
1483
- const context = offscreenCanvas.getContext("2d");
1484
- if (!context) throw new Error("2D canvas context is unavailable");
1485
- context.drawImage(imageElement, 0, 0, width, height);
1486
- const imageData = context.getImageData(0, 0, width, height);
1487
- const pixels = imageData.data;
1488
- const sealPixel = (x, y, fallbackX, fallbackY) => {
1489
- const index = (y * width + x) * 4;
1490
- const fallbackIndex = (fallbackY * width + fallbackX) * 4;
1491
- if (pixels[index + 3] === 0 && pixels[fallbackIndex + 3] > 0) {
1492
- pixels[index] = pixels[fallbackIndex];
1493
- pixels[index + 1] = pixels[fallbackIndex + 1];
1494
- pixels[index + 2] = pixels[fallbackIndex + 2];
1495
- pixels[index + 3] = pixels[fallbackIndex + 3];
1496
- }
1497
- if (pixels[index + 3] > 0 && pixels[index + 3] < 255) {
1498
- pixels[index + 3] = 255;
1499
- }
1500
- };
1501
- if (edges.left && width > 1) {
1502
- for (let y = 0; y < height; y += 1) sealPixel(0, y, 1, y);
1503
- }
1504
- if (edges.right && width > 1) {
1505
- for (let y = 0; y < height; y += 1) sealPixel(width - 1, y, width - 2, y);
1506
- }
1507
- if (edges.top && height > 1) {
1508
- for (let x = 0; x < width; x += 1) sealPixel(x, 0, x, 1);
1509
- }
1510
- if (edges.bottom && height > 1) {
1511
- for (let x = 0; x < width; x += 1) sealPixel(x, height - 1, x, height - 2);
1512
- }
1513
- context.putImageData(imageData, 0, 0);
1514
- return offscreenCanvas.toDataURL("image/png");
1515
- }
1516
- /**
1517
- * Exports a source region directly through Fabric's region export options.
1518
- *
1519
- * @param {Object} region - Canvas source region and export options.
1520
- * @param {number} region.sourceX - Source region x coordinate.
1521
- * @param {number} region.sourceY - Source region y coordinate.
1522
- * @param {number} region.sourceWidth - Source region width.
1523
- * @param {number} region.sourceHeight - Source region height.
1524
- * @param {number} [region.multiplier=1] - Export multiplier.
1525
- * @param {number} [region.quality=0.92] - Output image quality for lossy formats.
1526
- * @param {'jpeg'|'png'|'webp'} [region.format='jpeg'] - Output image format.
1527
- * @param {Object|null} [region.sealPartialEdges=null] - Fractional canvas edges whose alpha should be sealed.
1528
- * @returns {Promise<string>} Resolves with an image data URL for the cropped region.
1529
- * @private
1530
- */
1531
- async _exportCanvasRegionToDataURL({ sourceX, sourceY, sourceWidth, sourceHeight, multiplier = 1, quality = 0.92, format = "jpeg", sealPartialEdges = null }) {
1532
- const safeMultiplier = this._getSafeExportMultiplier(multiplier);
1533
- this._assertExportPixelBudget(sourceWidth, sourceHeight, safeMultiplier);
1534
- const safeFormat = this._normalizeImageFormat(format);
1535
- const exportFormat = safeFormat === "jpeg" ? "png" : safeFormat;
1536
- let regionDataUrl = this.canvas.toDataURL({
1537
- format: exportFormat,
1538
- quality,
1539
- multiplier: safeMultiplier,
1540
- left: sourceX,
1541
- top: sourceY,
1542
- width: sourceWidth,
1543
- height: sourceHeight
1544
- });
1545
- regionDataUrl = await this._sealPartialTransparentEdges(regionDataUrl, sealPartialEdges);
1546
- if (safeFormat !== "jpeg") return regionDataUrl;
1547
- return this._convertDataUrlToOpaqueJpeg(regionDataUrl, quality);
1548
- }
1549
- _getSafeExportMultiplier(multiplier) {
1550
- const numericMultiplier = Number(multiplier);
1551
- if (!Number.isFinite(numericMultiplier) || numericMultiplier <= 0) {
1552
- throw new Error("Export multiplier must be a finite positive number");
1553
- }
1554
- return Math.max(1, numericMultiplier);
1555
- }
1556
- _assertExportPixelBudget(sourceWidth, sourceHeight, safeMultiplier) {
1557
- const width = Math.max(1, Math.ceil(Number(sourceWidth) || 1));
1558
- const height = Math.max(1, Math.ceil(Number(sourceHeight) || 1));
1559
- const outputWidth = Math.ceil(width * safeMultiplier);
1560
- const outputHeight = Math.ceil(height * safeMultiplier);
1561
- const outputPixels = outputWidth * outputHeight;
1562
- const configuredMaxPixels = Number(this.options.maxExportPixels);
1563
- const maxPixels = Number.isFinite(configuredMaxPixels) && configuredMaxPixels > 0 ? Math.floor(configuredMaxPixels) : 5e7;
1564
- if (outputPixels > maxPixels) {
1565
- throw new Error(`Export would create ${outputPixels} pixels, exceeding the configured maxExportPixels limit of ${maxPixels}`);
1566
- }
1567
- }
1568
- async _convertDataUrlToOpaqueJpeg(dataUrl, quality = 0.92) {
1569
- const imageElement = await this._createImageElement(dataUrl);
1570
- const width = Math.max(1, imageElement.naturalWidth || imageElement.width || 1);
1571
- const height = Math.max(1, imageElement.naturalHeight || imageElement.height || 1);
1572
- const offscreenCanvas = document.createElement("canvas");
1573
- offscreenCanvas.width = width;
1574
- offscreenCanvas.height = height;
1575
- const context = offscreenCanvas.getContext("2d");
1576
- if (!context) throw new Error("2D canvas context is unavailable");
1577
- context.fillStyle = this._getJpegBackgroundColor();
1578
- context.fillRect(0, 0, width, height);
1579
- context.drawImage(imageElement, 0, 0, width, height);
1580
- return offscreenCanvas.toDataURL("image/jpeg", this._normalizeQuality(quality));
1581
- }
1582
- _getJpegBackgroundColor() {
1583
- const backgroundColor = String(this.options.backgroundColor || "").trim();
1584
- if (!backgroundColor || this._isTransparentCssColor(backgroundColor)) return "#ffffff";
1585
- return backgroundColor;
1586
- }
1587
- _isTransparentCssColor(color) {
1588
- const normalizedColor = String(color || "").trim().toLowerCase();
1589
- if (!normalizedColor || normalizedColor === "transparent") return true;
1590
- const hexAlphaMatch = normalizedColor.match(/^#(?:[0-9a-f]{3}([0-9a-f])|[0-9a-f]{6}([0-9a-f]{2}))$/i);
1591
- if (hexAlphaMatch) {
1592
- const alpha = hexAlphaMatch[1] || hexAlphaMatch[2];
1593
- return alpha === "0" || alpha === "00";
1594
- }
1595
- const slashAlphaMatch = normalizedColor.match(/^(?:rgba?|hsla?)\([^)]*\/\s*([^)]+)\)$/i);
1596
- if (slashAlphaMatch) return this._isZeroCssAlpha(slashAlphaMatch[1]);
1597
- const commaAlphaMatch = normalizedColor.match(/^(?:rgba|hsla)\((.*)\)$/i);
1598
- if (commaAlphaMatch) {
1599
- const parts = commaAlphaMatch[1].split(",");
1600
- if (parts.length >= 4) return this._isZeroCssAlpha(parts[parts.length - 1]);
1601
- }
1602
- return false;
1603
- }
1604
- _isZeroCssAlpha(alphaValue) {
1605
- const normalizedAlpha = String(alphaValue || "").trim();
1606
- if (!normalizedAlpha) return false;
1607
- if (normalizedAlpha.endsWith("%")) return Number.parseFloat(normalizedAlpha) === 0;
1608
- return Number(normalizedAlpha) === 0;
1609
- }
1610
- _decodeBase64Payload(base64Payload) {
1611
- const payload = String(base64Payload || "");
1612
- if (!payload) throw new Error("Data URL base64 payload is empty");
1613
- if (typeof atob === "function") {
1614
- return Uint8Array.from(atob(payload), (char) => char.charCodeAt(0));
1615
- }
1616
- if (typeof Buffer !== "undefined" && typeof Buffer.from === "function") {
1617
- return new Uint8Array(Buffer.from(payload, "base64"));
1618
- }
1619
- throw new Error("Base64 decoding is unavailable");
1620
- }
1621
- _decodeDataUrlPayload(dataUrl) {
1622
- const match = String(dataUrl || "").match(/^data:([^;,]+);base64,([A-Za-z0-9+/=]+)$/i);
1623
- if (!match || !match[2]) {
1624
- throw new Error("Export produced an invalid or empty base64 data URL");
1625
- }
1626
- return this._decodeBase64Payload(match[2]);
1627
- }
1628
- /**
1629
- * Gets the top-left corner coordinates of the given object.
1630
- * Used for geometry calculations (e.g., scale, rotate).
1631
- *
1632
- * @param {Object} fabricObject - The object for which to get the top-left coordinates. Should support setCoords and getCoords/getBoundingRect methods.
1633
- * @returns {{x: number, y: number}} The top-left corner point as an object with x and y properties.
1634
- * @private
1635
- */
1636
- _getObjectTopLeftPoint(fabricObject) {
1637
- if (!fabricObject) return { x: 0, y: 0 };
1638
- fabricObject.setCoords();
1639
- const boundingRect = fabricObject.getBoundingRect(true, true);
1640
- return { x: boundingRect.left, y: boundingRect.top };
1641
- }
1642
- _getObjectCoordinateTopLeftPoint(fabricObject) {
1643
- if (!fabricObject) return { x: 0, y: 0 };
1644
- fabricObject.setCoords();
1645
- const coords = typeof fabricObject.getCoords === "function" ? fabricObject.getCoords() : null;
1646
- if (coords && coords.length) return coords[0];
1647
- return this._getObjectTopLeftPoint(fabricObject);
1648
- }
1649
- _getObjectOriginPoint(fabricObject, originX, originY) {
1650
- if (!fabricObject) return { x: 0, y: 0 };
1651
- if (typeof fabricObject.getPointByOrigin === "function") {
1652
- return fabricObject.getPointByOrigin(originX, originY);
1653
- }
1654
- return this._getObjectTopLeftPoint(fabricObject);
1655
- }
1656
- _translateObjectByCanvasOffset(fabricObject, deltaX, deltaY) {
1657
- if (!fabricObject) return;
1658
- if (typeof fabricObject.getCenterPoint === "function" && typeof fabricObject.setPositionByOrigin === "function") {
1659
- const center = fabricObject.getCenterPoint();
1660
- const nextCenter = new fabric.Point(center.x + deltaX, center.y + deltaY);
1661
- fabricObject.setPositionByOrigin(nextCenter, "center", "center");
1662
- } else {
1663
- fabricObject.set({
1664
- left: (fabricObject.left || 0) + deltaX,
1665
- top: (fabricObject.top || 0) + deltaY
1666
- });
1667
- }
1668
- fabricObject.setCoords();
1669
- }
1670
- /**
1671
- * Sets the object's origin at the specified origin point, keeping a reference point fixed in position.
1672
- *
1673
- * @param {Object} fabricObject - The object to modify. Should support set, setPositionByOrigin, and setCoords.
1674
- * @param {string} originX - The new originX ("left", "center", "right", etc.).
1675
- * @param {string} originY - The new originY ("top", "center", "bottom", etc.).
1676
- * @param {{x: number, y: number}} refPoint - The point to keep fixed while setting the new origins.
1677
- * @private
1678
- */
1679
- _setObjectOriginKeepingPosition(fabricObject, originX, originY, refPoint) {
1680
- if (!fabricObject || !refPoint || !fabricObject.setPositionByOrigin) return;
1681
- fabricObject.set({ originX, originY });
1682
- fabricObject.setPositionByOrigin(refPoint, originX, originY);
1683
- fabricObject.setCoords();
1684
- }
1685
- /**
1686
- * Moves the object so its bounding box aligns with the canvas's top-left corner (0, 0).
1687
- *
1688
- * @param {Object} fabricObject - The object to align.
1689
- * @private
1690
- */
1691
- _alignObjectBoundingBoxToCanvasTopLeft(fabricObject) {
1692
- if (!fabricObject) return;
1693
- fabricObject.setCoords();
1694
- const boundingRect = fabricObject.getBoundingRect(true, true);
1695
- const deltaX = boundingRect.left;
1696
- const deltaY = boundingRect.top;
1697
- fabricObject.set({ left: (fabricObject.left || 0) - deltaX, top: (fabricObject.top || 0) - deltaY });
1698
- fabricObject.setCoords();
1699
- this.canvas.renderAll();
1700
- }
1701
- /**
1702
- * Updates the canvas size to match the bounding box of the original image,
1703
- * ensuring that the canvas is always at least as large as its container.
1704
- * @private
1705
- */
1706
- _updateCanvasSizeToImageBounds() {
1707
- if (!this.originalImage) return;
1708
- this.originalImage.setCoords();
1709
- const imageBounds = this.originalImage.getBoundingRect(true, true);
1710
- const size = this._getScrollableCanvasSize(imageBounds.width, imageBounds.height);
1711
- this._setCanvasSizeInt(size.width, size.height);
1712
- }
1713
- /**
1714
- * Whether post-load edits should resize the canvas to keep transformed content visible.
1715
- *
1716
- * @returns {boolean} True when canvas bounds should follow edited image or mask bounds.
1717
- * @private
1718
- */
1719
- _shouldResizeCanvasToContentBounds() {
1720
- return !!(this.options.expandCanvasToImage || this.options.coverImageToCanvas || this.options.fitImageToCanvas);
1721
- }
1722
- /**
1723
- * Expands the canvas once so all provided objects remain visible after an edit.
1724
- *
1725
- * @param {Array<fabric.Object>} fabricObjects - Objects whose bounds should fit inside the canvas.
1726
- * @param {number} [padding=10] - Extra canvas space after the farthest object edge.
1727
- * @returns {void}
1728
- * @private
1729
- */
1730
- _expandCanvasToFitObjects(fabricObjects, padding = 10) {
1731
- if (!this.canvas || !Array.isArray(fabricObjects) || !fabricObjects.length || !this._shouldResizeCanvasToContentBounds()) return;
1732
- try {
1733
- const currentWidth = this.canvas.getWidth();
1734
- const currentHeight = this.canvas.getHeight();
1735
- let requiredWidth = currentWidth;
1736
- let requiredHeight = currentHeight;
1737
- const layoutMode = this._getImageLayoutMode();
1738
- const usesScrollableFitBounds = layoutMode === "fit" || layoutMode === "cover";
1739
- let contentWidth = 0;
1740
- let contentHeight = 0;
1741
- const includeObjectBounds = (fabricObject, objectPadding = 0) => {
1742
- if (!fabricObject) return;
1743
- if (typeof fabricObject.setCoords === "function") fabricObject.setCoords();
1744
- const boundingRect = fabricObject.getBoundingRect(true, true);
1745
- const right = Math.ceil(boundingRect.left + boundingRect.width + objectPadding);
1746
- const bottom = Math.ceil(boundingRect.top + boundingRect.height + objectPadding);
1747
- contentWidth = Math.max(contentWidth, right);
1748
- contentHeight = Math.max(contentHeight, bottom);
1749
- return { right, bottom };
1750
- };
1751
- fabricObjects.forEach((fabricObject) => {
1752
- const bounds = includeObjectBounds(fabricObject, padding);
1753
- if (!bounds) return;
1754
- requiredWidth = Math.max(requiredWidth, bounds.right);
1755
- requiredHeight = Math.max(requiredHeight, bounds.bottom);
1756
- });
1757
- if (usesScrollableFitBounds) {
1758
- if (this.originalImage) includeObjectBounds(this.originalImage, 0);
1759
- this.canvas.getObjects().forEach((object) => {
1760
- if (object && object.maskId) includeObjectBounds(object, padding);
1761
- });
1762
- const contentSize = this._getScrollableCanvasSize(
1763
- Math.max(1, contentWidth),
1764
- Math.max(1, contentHeight)
1765
- );
1766
- const newWidth2 = contentSize.hasHorizontal ? Math.max(currentWidth, contentSize.width) : contentSize.width;
1767
- const newHeight2 = contentSize.hasVertical ? Math.max(currentHeight, contentSize.height) : contentSize.height;
1768
- if (newWidth2 !== currentWidth || newHeight2 !== currentHeight) {
1769
- this._setCanvasSizeInt(newWidth2, newHeight2);
1770
- }
1771
- return;
1772
- }
1773
- let minWidth = 0;
1774
- let minHeight = 0;
1775
- if (this.containerElement) {
1776
- const viewport = this._getContainerViewportSize();
1777
- const safetyMargin = this._getScrollSafetyMargin();
1778
- minWidth = Math.max(1, viewport.width - safetyMargin);
1779
- minHeight = Math.max(1, viewport.height - safetyMargin);
1780
- }
1781
- const newWidth = Math.max(currentWidth, minWidth, requiredWidth);
1782
- const newHeight = Math.max(currentHeight, minHeight, requiredHeight);
1783
- if (newWidth !== currentWidth || newHeight !== currentHeight) {
1784
- this._setCanvasSizeInt(newWidth, newHeight);
1785
- }
1786
- } catch (error) {
1787
- this._reportWarning("expandCanvasToFitObjects: failed to expand canvas", error);
1788
- }
1789
- }
1790
- _captureImageDisplayBounds() {
1791
- if (!this.originalImage || !this.canvas) return null;
1792
- this.originalImage.setCoords();
1793
- const bounds = this.originalImage.getBoundingRect(true, true);
1794
- const width = Number(bounds && bounds.width);
1795
- const height = Number(bounds && bounds.height);
1796
- if (!Number.isFinite(width) || width <= 0 || !Number.isFinite(height) || height <= 0) return null;
1797
- return {
1798
- left: Number.isFinite(Number(bounds.left)) ? Number(bounds.left) : 0,
1799
- top: Number.isFinite(Number(bounds.top)) ? Number(bounds.top) : 0,
1800
- width,
1801
- height
1802
- };
1803
- }
1804
- _restoreImageDisplayBounds(displayBounds) {
1805
- if (!displayBounds || !this.originalImage || !this.canvas) return;
1806
- const imageWidth = Number(this.originalImage.width);
1807
- const imageHeight = Number(this.originalImage.height);
1808
- if (!Number.isFinite(imageWidth) || imageWidth <= 0 || !Number.isFinite(imageHeight) || imageHeight <= 0) return;
1809
- const scaleX = Number(displayBounds.width) / imageWidth;
1810
- const scaleY = Number(displayBounds.height) / imageHeight;
1811
- if (!Number.isFinite(scaleX) || scaleX <= 0 || !Number.isFinite(scaleY) || scaleY <= 0) return;
1812
- const left = Number(displayBounds.left) || 0;
1813
- const top = Number(displayBounds.top) || 0;
1814
- const requiredCanvasWidth = Math.max(1, Math.ceil(left + Number(displayBounds.width)));
1815
- const requiredCanvasHeight = Math.max(1, Math.ceil(top + Number(displayBounds.height)));
1816
- const currentCanvasWidth = Math.max(1, Math.round(Number(this.canvas.getWidth()) || 1));
1817
- const currentCanvasHeight = Math.max(1, Math.round(Number(this.canvas.getHeight()) || 1));
1818
- const layoutMode = this._getImageLayoutMode();
1819
- if (layoutMode === "fit" || layoutMode === "cover") {
1820
- const contentSize = this._getScrollableCanvasSize(requiredCanvasWidth, requiredCanvasHeight);
1821
- if (contentSize.width !== currentCanvasWidth || contentSize.height !== currentCanvasHeight) {
1822
- this._setCanvasSizeInt(contentSize.width, contentSize.height);
1823
- }
1824
- } else if (requiredCanvasWidth > currentCanvasWidth || requiredCanvasHeight > currentCanvasHeight) {
1825
- this._setCanvasSizeInt(
1826
- Math.max(currentCanvasWidth, requiredCanvasWidth),
1827
- Math.max(currentCanvasHeight, requiredCanvasHeight)
1828
- );
1829
- }
1830
- this.originalImage.set({
1831
- originX: "left",
1832
- originY: "top",
1833
- left,
1834
- top,
1835
- scaleX,
1836
- scaleY
1837
- });
1838
- this.originalImage.setCoords();
1839
- this.baseImageScale = scaleX;
1840
- this.currentScale = 1;
1841
- this.currentRotation = Number(this.originalImage.angle) || 0;
1842
- this._updateInputs();
1843
- this.canvas.renderAll();
1844
- }
1845
- /**
1846
- * Scales the original image by a given factor, with animation.
1847
- * Returns a promise that resolves when the scale animation is complete.
1848
- * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
1849
- * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
1850
- * @public
1851
- */
1852
- scaleImage(factor, options = {}) {
1853
- try {
1854
- this._assertCanQueueAnimation("scaleImage", options);
1855
- } catch (error) {
1856
- return Promise.reject(error);
1857
- }
1858
- return this.animationQueue.add(async () => {
1859
- const operationToken = this._beginBusyOperation("scaleImage");
1860
- try {
1861
- await this._scaleImageImpl(factor, this._withInternalOperationOptions(operationToken, options));
1862
- } finally {
1863
- this._endBusyOperation(operationToken);
1864
- }
1865
- }).finally(() => {
1866
- if (!this._disposed && this.canvas) this._updateUI();
1867
- });
1868
- }
1869
- _getInternalOperationToken(options) {
1870
- return options && options[INTERNAL_OPERATION_TOKEN];
1871
- }
1872
- _isOwnInternalOperation(options) {
1873
- const token = this._getInternalOperationToken(options);
1874
- return !!token && token === this._activeOperationToken;
1875
- }
1876
- _beginBusyOperation(operationName) {
1877
- const token = Symbol(operationName);
1878
- this._activeOperationName = operationName;
1879
- this._activeOperationToken = token;
1880
- this._updateUI();
1881
- return token;
1882
- }
1883
- _endBusyOperation(token) {
1884
- if (token && token === this._activeOperationToken) {
1885
- this._activeOperationName = null;
1886
- this._activeOperationToken = null;
1887
- this._updateUI();
1888
- }
1889
- }
1890
- _withInternalOperationOptions(token, options = {}) {
1891
- return {
1892
- ...options,
1893
- [INTERNAL_OPERATION_TOKEN]: token
1894
- };
1895
- }
1896
- _assertEditorAvailable(operationName) {
1897
- if (this._disposed || !this.canvas) throw new Error(`${operationName} cannot run after the editor has been disposed`);
1898
- }
1899
- _isCropModeAllowedOperation(operationName) {
1900
- return operationName === "applyCrop" || operationName === "cancelCrop";
1901
- }
1902
- _assertIdleForOperation(operationName, options = {}) {
1903
- this._assertEditorAvailable(operationName);
1904
- const isOwnInternalOperation = this._isOwnInternalOperation(options);
1905
- if (this._cropMode && !this._isCropModeAllowedOperation(operationName) && !isOwnInternalOperation) {
1906
- throw new Error(`${operationName} cannot run while crop mode is active`);
1907
- }
1908
- if ((this.isAnimating || this.animationQueue && this.animationQueue.isBusy()) && !isOwnInternalOperation) {
1909
- throw new Error(`${operationName} cannot run while an animation is running`);
1910
- }
1911
- if (this._isLoading && !isOwnInternalOperation) {
1912
- throw new Error(`${operationName} cannot run while an image is loading`);
1913
- }
1914
- if (this._activeOperationToken && !isOwnInternalOperation) {
1915
- throw new Error(`${operationName} cannot run while ${this._activeOperationName || "another operation"} is running`);
1916
- }
1917
- }
1918
- _assertCanQueueAnimation(operationName, options = {}) {
1919
- this._assertEditorAvailable(operationName);
1920
- const isOwnInternalOperation = this._isOwnInternalOperation(options);
1921
- if (this._cropMode && !this._isCropModeAllowedOperation(operationName) && !isOwnInternalOperation) {
1922
- throw new Error(`${operationName} cannot run while crop mode is active`);
1923
- }
1924
- if (this._isLoading && !isOwnInternalOperation) {
1925
- throw new Error(`${operationName} cannot run while an image is loading`);
1926
- }
1927
- if (this._activeOperationToken && !isOwnInternalOperation) {
1928
- throw new Error(`${operationName} cannot run while ${this._activeOperationName || "another operation"} is running`);
1929
- }
1930
- }
1931
- _canMutateNow(operationName, options = {}) {
1932
- try {
1933
- this._assertIdleForOperation(operationName, options);
1934
- return true;
1935
- } catch (error) {
1936
- this._reportError(`${operationName} blocked`, error);
1937
- return false;
1938
- }
1939
- }
1940
- _rejectActiveAnimations(reason) {
1941
- const error = reason instanceof Error ? reason : new Error(String(reason || "Animation cancelled"));
1942
- this._activeAnimationRejectors.forEach((reject) => {
1943
- try {
1944
- reject(error);
1945
- } catch (rejectError) {
1946
- void rejectError;
1947
- }
1948
- });
1949
- this._activeAnimationRejectors.clear();
1950
- }
1951
- _animateFabricProperty(fabricObject, property, value) {
1952
- return new Promise((resolve, reject) => {
1953
- if (this._disposed || !this.canvas || !fabricObject) {
1954
- reject(new Error("Animation cannot start after editor disposal"));
1955
- return;
1956
- }
1957
- let isSettled = false;
1958
- const duration = Math.max(0, Number(this.options.animationDuration) || 0);
1959
- const timeoutMs = Math.max(1e3, duration + 1e3);
1960
- let timerId;
1961
- const settle = (callback) => {
1962
- if (isSettled) return;
1963
- isSettled = true;
1964
- clearTimeout(timerId);
1965
- this._activeAnimationRejectors.delete(reject);
1966
- callback();
1967
- };
1968
- this._activeAnimationRejectors.add(reject);
1969
- timerId = setTimeout(() => {
1970
- settle(() => reject(new Error(`Animation timed out while changing ${property}`)));
1971
- }, timeoutMs);
1972
- try {
1973
- fabricObject.animate(property, value, {
1974
- duration,
1975
- onChange: () => {
1976
- if (!this._disposed && this.canvas) this.canvas.renderAll();
1977
- },
1978
- onComplete: () => settle(resolve)
1979
- });
1980
- } catch (error) {
1981
- settle(() => reject(error));
1982
- }
1983
- });
1984
- }
1985
- /**
1986
- * Scales the original image by a given factor, with animation.
1987
- * Returns a promise that resolves when the scale animation is complete.
1988
- * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
1989
- * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
1990
- * @private
1991
- */
1992
- async _scaleImageImpl(factor, options = {}) {
1993
- if (!this.originalImage || this._disposed) return;
1994
- if (this.isAnimating) return;
1995
- const saveHistory = options.saveHistory !== false;
1996
- let didStartAnimation = false;
1997
- try {
1998
- factor = Math.max(this.options.minScale, Math.min(this.options.maxScale, factor));
1999
- this.currentScale = factor;
2000
- this.isAnimating = true;
2001
- didStartAnimation = true;
2002
- this._updateUI();
2003
- const targetScale = this.baseImageScale * factor;
2004
- const topLeft = this._getObjectTopLeftPoint(this.originalImage);
2005
- this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", topLeft);
2006
- await Promise.all([
2007
- this._animateFabricProperty(this.originalImage, "scaleX", targetScale),
2008
- this._animateFabricProperty(this.originalImage, "scaleY", targetScale)
2009
- ]);
2010
- if (this._disposed || !this.canvas || !this.originalImage) throw new Error("Editor was disposed during scale animation");
2011
- this.originalImage.set({ scaleX: targetScale, scaleY: targetScale });
2012
- this.originalImage.setCoords();
2013
- if (this._shouldResizeCanvasToContentBounds()) {
2014
- this._updateCanvasSizeToImageBounds();
2015
- }
2016
- this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
2017
- this.canvas.getObjects().forEach((object) => {
2018
- if (object.maskId) this._syncMaskLabel(object);
2019
- });
2020
- this._updateInputs();
2021
- if (saveHistory) this.saveState(options);
2022
- } finally {
2023
- if (didStartAnimation) {
2024
- this.isAnimating = false;
2025
- this._updateInputs();
2026
- this._updateUI();
2027
- }
2028
- }
2029
- }
2030
- /**
2031
- * Rotates the original image by a given number of degrees, with animation.
2032
- * Returns a promise that resolves when the rotation animation is complete.
2033
- * @param {number} degrees - The angle in degrees to rotate the image.
2034
- * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
2035
- * @public
2036
- */
2037
- rotateImage(degrees, options = {}) {
2038
- try {
2039
- this._assertCanQueueAnimation("rotateImage", options);
2040
- } catch (error) {
2041
- return Promise.reject(error);
2042
- }
2043
- return this.animationQueue.add(async () => {
2044
- const operationToken = this._beginBusyOperation("rotateImage");
2045
- try {
2046
- await this._rotateImageImpl(degrees, this._withInternalOperationOptions(operationToken, options));
2047
- } finally {
2048
- this._endBusyOperation(operationToken);
2049
- }
2050
- }).finally(() => {
2051
- if (!this._disposed && this.canvas) this._updateUI();
2052
- });
2053
- }
2054
- /**
2055
- * Rotates the original image by a given number of degrees, with animation.
2056
- * Returns a promise that resolves when the rotation animation is complete.
2057
- * @param {number} degrees - The angle in degrees to rotate the image.
2058
- * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
2059
- * @private
2060
- */
2061
- async _rotateImageImpl(degrees, options = {}) {
2062
- if (!this.originalImage || this._disposed) return;
2063
- if (this.isAnimating) return;
2064
- if (isNaN(degrees)) return;
2065
- const saveHistory = options.saveHistory !== false;
2066
- const image = this.originalImage;
2067
- const previousOriginX = image.originX || "left";
2068
- const previousOriginY = image.originY || "top";
2069
- const previousOriginPoint = this._getObjectOriginPoint(image, previousOriginX, previousOriginY);
2070
- let didStartAnimation = false;
2071
- let didCompleteRotation = false;
2072
- try {
2073
- this.currentRotation = degrees;
2074
- this.isAnimating = true;
2075
- didStartAnimation = true;
2076
- this._updateUI();
2077
- const center = image.getCenterPoint();
2078
- this._setObjectOriginKeepingPosition(image, "center", "center", center);
2079
- await this._animateFabricProperty(image, "angle", degrees);
2080
- if (this._disposed || !this.canvas || !this.originalImage) throw new Error("Editor was disposed during rotation animation");
2081
- this.originalImage.set("angle", degrees);
2082
- this.originalImage.setCoords();
2083
- if (this._shouldResizeCanvasToContentBounds()) {
2084
- this._updateCanvasSizeToImageBounds();
2085
- }
2086
- this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
2087
- const newTopLeft = this._getObjectCoordinateTopLeftPoint(this.originalImage);
2088
- this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", newTopLeft);
2089
- this.canvas.getObjects().forEach((object) => {
2090
- if (object.maskId) this._syncMaskLabel(object);
2091
- });
2092
- this._updateInputs();
2093
- if (saveHistory) this.saveState(options);
2094
- didCompleteRotation = true;
2095
- } finally {
2096
- if (!didCompleteRotation && !this._disposed && image) {
2097
- this._setObjectOriginKeepingPosition(image, previousOriginX, previousOriginY, previousOriginPoint);
2098
- }
2099
- if (didStartAnimation) {
2100
- this.isAnimating = false;
2101
- this._updateInputs();
2102
- this._updateUI();
2103
- }
2104
- }
2105
- }
2106
- /**
2107
- * Resets the image transform: scales to 1 and rotates to 0 degrees.
2108
- *
2109
- * @returns {Promise<void>} Resolves when the reset history transition has been recorded.
2110
- * @public
2111
- */
2112
- resetImageTransform() {
2113
- if (!this.originalImage) return Promise.resolve();
2114
- try {
2115
- this._assertCanQueueAnimation("resetImageTransform");
2116
- } catch (error) {
2117
- return Promise.reject(error);
2118
- }
2119
- return this.animationQueue.add(async () => {
2120
- const operationToken = this._beginBusyOperation("resetImageTransform");
2121
- const before = this._lastSnapshot || this._captureCanvasStateOrThrow("resetImageTransform");
2122
- try {
2123
- await this._scaleImageImpl(1, this._withInternalOperationOptions(operationToken, { saveHistory: false }));
2124
- await this._rotateImageImpl(0, this._withInternalOperationOptions(operationToken, { saveHistory: false }));
2125
- const after = this._captureCanvasStateOrThrow("resetImageTransform");
2126
- this._pushStateTransition(before, after);
2127
- } catch (error) {
2128
- try {
2129
- await this.loadFromState(before, this._withInternalOperationOptions(operationToken));
2130
- } catch (restoreError) {
2131
- this._reportError("resetImageTransform rollback failed", restoreError);
2132
- }
2133
- throw error;
2134
- } finally {
2135
- this._endBusyOperation(operationToken);
2136
- }
2137
- }).finally(() => {
2138
- if (!this._disposed && this.canvas) this._updateUI();
2139
- }).catch((error) => {
2140
- this._reportError("resetImageTransform() failed", error);
2141
- throw error;
2142
- });
2143
- }
2144
- /**
2145
- * Backward-compatible alias for {@link ImageEditor#resetImageTransform}.
2146
- *
2147
- * @deprecated Use resetImageTransform() instead. This alias will be removed in v2.0.0.
2148
- * @returns {Promise<void>} Resolves when the image transform reset is complete.
2149
- */
2150
- reset() {
2151
- return this.resetImageTransform();
2152
- }
2153
- /**
2154
- * Restores a serialized canvas state and rebinds editor-specific mask/image metadata.
2155
- *
2156
- * @param {string|Object} serializedState - State returned by `_serializeCanvasState()` as a JSON string or object.
2157
- * @returns {Promise<void>} Resolves after Fabric has loaded the state and UI state has been refreshed.
2158
- * @public
2159
- */
2160
- loadFromState(serializedState, options = {}) {
2161
- if (!serializedState || !this.canvas || this._disposed) return Promise.resolve();
2162
- try {
2163
- this._assertIdleForOperation("loadFromState", options);
2164
- } catch (error) {
2165
- return Promise.reject(error);
2166
- }
2167
- if (this._cropMode || this._cropRect) {
2168
- this._removeCropRect();
2169
- this._restoreCropObjectState();
2170
- this._cropMode = false;
2171
- if (this._prevSelectionSetting !== void 0 && this.canvas) {
2172
- this.canvas.selection = !!this._prevSelectionSetting;
2173
- }
2174
- this._prevSelectionSetting = void 0;
2175
- }
2176
- return new Promise((resolve, reject) => {
2177
- try {
2178
- const state = typeof serializedState === "string" ? JSON.parse(serializedState) : serializedState;
2179
- const editorMetadata = state && state.imageEditorMetadata ? state.imageEditorMetadata : null;
2180
- const restoredCanvasWidth = Number(editorMetadata && editorMetadata.canvasWidth);
2181
- const restoredCanvasHeight = Number(editorMetadata && editorMetadata.canvasHeight);
2182
- const hasRestoredCanvasSize = Number.isFinite(restoredCanvasWidth) && restoredCanvasWidth > 0 && Number.isFinite(restoredCanvasHeight) && restoredCanvasHeight > 0;
2183
- if (editorMetadata && Object.prototype.hasOwnProperty.call(editorMetadata, "version") && Number(editorMetadata.version) !== 1) {
2184
- this._reportWarning(`loadFromState: unsupported editor metadata version ${editorMetadata.version}`);
2185
- }
2186
- const finishLoad = async () => {
2187
- try {
2188
- if (this._disposed || !this.canvas) {
2189
- reject(new Error("Editor was disposed while loading state"));
2190
- return;
2191
- }
2192
- await this._waitForFabricImagesReady(this.canvas.getObjects());
2193
- if (this._disposed || !this.canvas) {
2194
- reject(new Error("Editor was disposed while loading state"));
2195
- return;
2196
- }
2197
- this._hideAllMaskLabels();
2198
- const canvasObjects = this.canvas.getObjects();
2199
- this.originalImage = canvasObjects.find((object) => object.type === "image" && !object.maskId) || null;
2200
- if (this.originalImage) {
2201
- this.originalImage.set({ originX: "left", originY: "top", selectable: false, evented: false, hasControls: false, hoverCursor: "default" });
2202
- this.canvas.sendToBack(this.originalImage);
2203
- const restoredBaseScale = Number(editorMetadata && editorMetadata.baseImageScale);
2204
- const restoredCurrentScale = Number(editorMetadata && editorMetadata.currentScale);
2205
- const restoredCurrentRotation = Number(editorMetadata && editorMetadata.currentRotation);
2206
- if (Number.isFinite(restoredBaseScale) && restoredBaseScale > 0) {
2207
- this.baseImageScale = restoredBaseScale;
2208
- }
2209
- if (Number.isFinite(restoredCurrentScale) && restoredCurrentScale > 0) {
2210
- this.currentScale = restoredCurrentScale;
2211
- } else {
2212
- const baseScale = Number(this.baseImageScale) || 1;
2213
- const imageScale = Number(this.originalImage.scaleX) || baseScale;
2214
- this.currentScale = imageScale / baseScale;
2215
- }
2216
- this.currentRotation = Number.isFinite(restoredCurrentRotation) ? restoredCurrentRotation : Number(this.originalImage.angle) || 0;
2217
- } else {
2218
- this.baseImageScale = 1;
2219
- this.currentScale = 1;
2220
- this.currentRotation = 0;
2221
- }
2222
- if (hasRestoredCanvasSize) {
2223
- this._setCanvasSizeInt(restoredCanvasWidth, restoredCanvasHeight);
2224
- } else if (this.originalImage && this._shouldResizeCanvasToContentBounds()) {
2225
- this._updateCanvasSizeToImageBounds();
2226
- }
2227
- const masks = canvasObjects.filter((object) => object.maskId);
2228
- masks.forEach((mask) => {
2229
- this._restoreMaskControls(mask);
2230
- this._rebindMaskEvents(mask);
2231
- mask.set(this._getMaskNormalStyle(mask));
2232
- });
2233
- const restoredMaskCounter = Number(editorMetadata && editorMetadata.maskCounter);
2234
- const maxMaskId = masks.reduce((max, mask) => Math.max(max, mask.maskId), 0);
2235
- this.maskCounter = Number.isFinite(restoredMaskCounter) && restoredMaskCounter >= maxMaskId ? Math.floor(restoredMaskCounter) : maxMaskId;
2236
- this._lastMask = masks.length ? masks[masks.length - 1] : null;
2237
- if (!this._lastMask) {
2238
- this._lastMaskInitialLeft = null;
2239
- this._lastMaskInitialTop = null;
2240
- this._lastMaskInitialWidth = null;
2241
- }
2242
- this.isImageLoadedToCanvas = !!this.originalImage;
2243
- this.canvas.renderAll();
2244
- this._updateInputs();
2245
- this._updateMaskList();
2246
- this._updatePlaceholderStatus();
2247
- this._lastSnapshot = this._serializeCanvasState();
2248
- this._updateUI();
2249
- resolve();
2250
- } catch (callbackError) {
2251
- this._reportError("loadFromState() failed", callbackError);
2252
- reject(callbackError);
2253
- }
2254
- };
2255
- this.canvas.loadFromJSON(state, () => {
2256
- void finishLoad();
2257
- });
2258
- } catch (error) {
2259
- this._reportError("loadFromState() failed", error);
2260
- reject(error);
2261
- }
2262
- });
2263
- }
2264
- async _waitForFabricImagesReady(canvasObjects) {
2265
- const imageObjects = (canvasObjects || []).filter((object) => object && object.type === "image");
2266
- await Promise.all(imageObjects.map((object) => this._waitForImageElementReady(
2267
- typeof object.getElement === "function" ? object.getElement() : object._element
2268
- )));
2269
- }
2270
- _waitForImageElementReady(imageElement) {
2271
- if (!imageElement) return Promise.resolve();
2272
- const hasLoadedDimensions = (Number(imageElement.naturalWidth) > 0 || Number(imageElement.width) > 0) && (Number(imageElement.naturalHeight) > 0 || Number(imageElement.height) > 0);
2273
- if (hasLoadedDimensions) return Promise.resolve();
2274
- if (imageElement.complete) return Promise.reject(new Error("Image could not be loaded while restoring state"));
2275
- return new Promise((resolve, reject) => {
2276
- let isSettled = false;
2277
- let timerId;
2278
- const settle = (callback) => {
2279
- if (isSettled) return;
2280
- isSettled = true;
2281
- clearTimeout(timerId);
2282
- if (typeof imageElement.removeEventListener === "function") {
2283
- imageElement.removeEventListener("load", handleLoad);
2284
- imageElement.removeEventListener("error", handleError);
2285
- } else {
2286
- imageElement.onload = null;
2287
- imageElement.onerror = null;
2288
- }
2289
- callback();
2290
- };
2291
- const handleLoad = () => {
2292
- const didLoad = (Number(imageElement.naturalWidth) > 0 || Number(imageElement.width) > 0) && (Number(imageElement.naturalHeight) > 0 || Number(imageElement.height) > 0);
2293
- settle(() => {
2294
- if (didLoad) {
2295
- resolve();
2296
- } else {
2297
- reject(new Error("Image could not be loaded while restoring state"));
2298
- }
2299
- });
2300
- };
2301
- const handleError = (error) => settle(() => reject(error instanceof Error ? error : new Error("Image could not be loaded while restoring state")));
2302
- timerId = setTimeout(() => {
2303
- settle(() => reject(new Error("Image load timed out while restoring state")));
2304
- }, this._getSafeTimeoutMs(this.options.imageLoadTimeoutMs));
2305
- if (typeof imageElement.addEventListener === "function") {
2306
- imageElement.addEventListener("load", handleLoad, { once: true });
2307
- imageElement.addEventListener("error", handleError, { once: true });
2308
- } else {
2309
- imageElement.onload = handleLoad;
2310
- imageElement.onerror = handleError;
2311
- }
2312
- });
2313
- }
2314
- /**
2315
- * Saves the current editable canvas state as an undoable history transition.
2316
- *
2317
- * Labels are hidden before serialization because labels are UI overlays, while mask metadata is kept on
2318
- * mask objects and restored by `loadFromState()`.
2319
- *
2320
- * @returns {void}
2321
- * @public
2322
- */
2323
- saveState(options = {}) {
2324
- if (!this.canvas) return;
2325
- try {
2326
- this._assertIdleForOperation("saveState", options);
2327
- } catch (error) {
2328
- this._reportError("saveState blocked", error);
2329
- this._updateUI();
2330
- return;
2331
- }
2332
- try {
2333
- const after = this._captureCanvasStateOrThrow("saveState");
2334
- const before = this._lastSnapshot || after;
2335
- if (after === before) return;
2336
- let executedOnce = false;
2337
- const command = new Command(
2338
- (commandOptions = {}) => {
2339
- if (executedOnce) {
2340
- return this.loadFromState(after, commandOptions);
2341
- }
2342
- executedOnce = true;
2343
- return void 0;
2344
- },
2345
- (commandOptions = {}) => this.loadFromState(before, commandOptions)
2346
- );
2347
- this.historyManager.execute(command);
2348
- this._lastSnapshot = after;
2349
- } catch (error) {
2350
- this._reportWarning("saveState: failed to save canvas snapshot", error);
2351
- } finally {
2352
- this._updateUI();
2353
- }
2354
- }
2355
- /**
2356
- * Pushes a precomputed before/after state transition into history.
2357
- *
2358
- * Use this for operations such as crop and merge that build their snapshots around asynchronous image
2359
- * loading, where the "after" state is already applied before the history command is recorded.
2360
- *
2361
- * @param {string} before - Serialized state before the operation.
2362
- * @param {string} after - Serialized state after the operation.
2363
- * @returns {void}
2364
- * @private
2365
- */
2366
- _pushStateTransition(before, after) {
2367
- if (!before || !after) {
2368
- this._reportWarning("History transition skipped because a canvas snapshot is unavailable");
2369
- return;
2370
- }
2371
- if (before === after) return;
2372
- if (!this.historyManager) this.historyManager = new HistoryManager(this.maxHistorySize || 50);
2373
- const command = new Command(
2374
- (commandOptions = {}) => this.loadFromState(after, commandOptions),
2375
- (commandOptions = {}) => this.loadFromState(before, commandOptions)
2376
- );
2377
- this.historyManager.push(command);
2378
- this._lastSnapshot = after;
2379
- this._updateUI();
2380
- }
2381
- /**
2382
- * Undo the last state change, if possible.
2383
- *
2384
- * @returns {Promise<void>} Resolves after the history manager finishes the queued undo.
2385
- * @public
2386
- */
2387
- undo() {
2388
- try {
2389
- this._assertIdleForOperation("undo");
2390
- } catch (error) {
2391
- return Promise.reject(error);
2392
- }
2393
- const operationToken = this._beginBusyOperation("undo");
2394
- return this.historyManager.undo(this._withInternalOperationOptions(operationToken)).then(() => {
2395
- this._updateUI();
2396
- }).finally(() => {
2397
- this._endBusyOperation(operationToken);
2398
- }).catch((error) => {
2399
- this._reportError("undo failed", error);
2400
- throw error;
2401
- });
2402
- }
2403
- /**
2404
- * Redo the next state change, if possible.
2405
- *
2406
- * @returns {Promise<void>} Resolves after the history manager finishes the queued redo.
2407
- * @public
2408
- */
2409
- redo() {
2410
- try {
2411
- this._assertIdleForOperation("redo");
2412
- } catch (error) {
2413
- return Promise.reject(error);
2414
- }
2415
- const operationToken = this._beginBusyOperation("redo");
2416
- return this.historyManager.redo(this._withInternalOperationOptions(operationToken)).then(() => {
2417
- this._updateUI();
2418
- }).finally(() => {
2419
- this._endBusyOperation(operationToken);
2420
- }).catch((error) => {
2421
- this._reportError("redo failed", error);
2422
- throw error;
2423
- });
2424
- }
2425
- _rebindMaskEvents(mask) {
2426
- if (!mask) return;
2427
- this._cleanupMaskEvents(mask);
2428
- const metadata = {};
2429
- if (!Number.isFinite(Number(mask.originalAlpha))) {
2430
- metadata.originalAlpha = Number.isFinite(Number(mask.opacity)) ? Number(mask.opacity) : 0.5;
2431
- }
2432
- if (!mask.originalStroke) metadata.originalStroke = mask.stroke || "#ccc";
2433
- if (!Number.isFinite(Number(mask.originalStrokeWidth))) {
2434
- metadata.originalStrokeWidth = Number.isFinite(Number(mask.strokeWidth)) ? Number(mask.strokeWidth) : 1;
2435
- }
2436
- if (Object.keys(metadata).length) mask.set(metadata);
2437
- const mouseover = () => {
2438
- const opacity = Number(mask.originalAlpha);
2439
- mask.set({
2440
- stroke: "#ff5500",
2441
- strokeWidth: 2,
2442
- opacity: Math.min((Number.isFinite(opacity) ? opacity : 0.5) + 0.2, 1)
2443
- });
2444
- if (mask.canvas) mask.canvas.requestRenderAll();
2445
- };
2446
- const mouseout = () => {
2447
- mask.set(this._getMaskNormalStyle(mask));
2448
- if (mask.canvas) mask.canvas.requestRenderAll();
2449
- };
2450
- mask.on("mouseover", mouseover);
2451
- mask.on("mouseout", mouseout);
2452
- mask.__imageEditorMaskHandlers = { mouseover, mouseout };
2453
- }
2454
- _cleanupMaskEvents(mask) {
2455
- if (!mask || !mask.__imageEditorMaskHandlers) return;
2456
- try {
2457
- if (typeof mask.off === "function") {
2458
- mask.off("mouseover", mask.__imageEditorMaskHandlers.mouseover);
2459
- mask.off("mouseout", mask.__imageEditorMaskHandlers.mouseout);
2460
- }
2461
- } catch (error) {
2462
- this._reportWarning("Mask event cleanup failed", error);
2463
- }
2464
- try {
2465
- delete mask.__imageEditorMaskHandlers;
2466
- } catch (error) {
2467
- this._reportWarning("Mask event metadata cleanup failed", error);
2468
- }
2469
- }
2470
- /**
2471
- * Creates a mask and adds it to the canvas.
2472
- *
2473
- * Placement is based on explicit `left`/`top` values when provided; otherwise each new mask is placed
2474
- * after the previously created mask. Fabric object properties are applied through `set()` and `setCoords()`
2475
- * so controls and hit testing stay in sync with Fabric 5.x behavior.
2476
- *
2477
- * @param {Object} [config={}] - Optional mask configuration overrides.
2478
- * @param {string} [config.shape='rect'] - Mask shape: `rect`, `circle`, `ellipse`, `polygon`, or a custom shape handled by `fabricGenerator`.
2479
- * @param {Array<{x:number,y:number}>|Array<Array<number>>} [config.points] - Polygon points.
2480
- * @param {number|string|MaskValueResolver} [config.width] - Width in pixels, percentage string, or resolver callback.
2481
- * @param {number|string|MaskValueResolver} [config.height] - Height in pixels, percentage string, or resolver callback.
2482
- * @param {number|string|MaskValueResolver} [config.radius] - Circle radius in pixels, percentage string, or resolver callback.
2483
- * @param {number|string|MaskValueResolver} [config.rx] - Ellipse horizontal radius or rectangle corner radius.
2484
- * @param {number|string|MaskValueResolver} [config.ry] - Ellipse vertical radius or rectangle corner radius.
2485
- * @param {number|string|MaskValueResolver} [config.left] - Left position in pixels, percentage string, or resolver callback.
2486
- * @param {number|string|MaskValueResolver} [config.top] - Top position in pixels, percentage string, or resolver callback.
2487
- * @param {number} [config.angle=0] - Rotation angle in degrees.
2488
- * @param {string} [config.color='rgba(0,0,0,0.5)'] - Fill color.
2489
- * @param {number} [config.alpha=0.5] - Opacity from 0 to 1.
2490
- * @param {boolean} [config.selectable=true] - Whether the mask can be selected.
2491
- * @param {boolean} [config.hasControls=true] - Whether Fabric transform controls are shown.
2492
- * @param {Object} [config.styles] - Additional Fabric style properties, such as `stroke` or `strokeDashArray`.
2493
- * @param {MaskFabricGenerator} [config.fabricGenerator] - Factory callback that returns a custom Fabric object.
2494
- * @param {MaskCreateCallback} [config.onCreate] - Callback invoked after the mask is added to the canvas.
2495
- * @returns {fabric.Object|null} The created mask object, or null if the canvas is not initialized.
2496
- * @public
2497
- */
2498
- createMask(config = {}) {
2499
- if (!this.canvas) return null;
2500
- if (!this._canMutateNow("createMask")) return null;
2501
- const shapeType = config.shape || "rect";
2502
- const maskConfig = {
2503
- shape: shapeType,
2504
- width: this.options.defaultMaskWidth,
2505
- height: this.options.defaultMaskHeight,
2506
- color: "rgba(0,0,0,0.5)",
2507
- alpha: 0.5,
2508
- gap: 5,
2509
- left: void 0,
2510
- top: void 0,
2511
- angle: 0,
2512
- selectable: true,
2513
- ...config
2514
- };
2515
- const firstOffset = 10;
2516
- let left;
2517
- let top;
2518
- const getCanvasBasis = (axis) => {
2519
- const canvasWidth = this.canvas ? this.canvas.getWidth() : 0;
2520
- const canvasHeight = this.canvas ? this.canvas.getHeight() : 0;
2521
- if (axis === "height") return canvasHeight;
2522
- if (axis === "min") return Math.min(canvasWidth, canvasHeight);
2523
- return canvasWidth;
2524
- };
2525
- const resolveValue = (value, fallback, axis = "width") => {
2526
- if (typeof value === "function")
2527
- return value(this.canvas, this.options);
2528
- if (typeof value === "string" && value.endsWith("%")) {
2529
- const percent = Number.parseFloat(value) / 100;
2530
- if (!Number.isFinite(percent)) return fallback;
2531
- return Math.floor(getCanvasBasis(axis) * percent);
2532
- }
2533
- return value != null ? value : fallback;
2534
- };
2535
- const rejectInvalidMask = (message, error = null) => {
2536
- this._reportWarning(`createMask: ${message}`, error);
2537
- return null;
2538
- };
2539
- const resolveNumber = (value, fallback, axis, fieldName, constraints = {}) => {
2540
- const resolvedValue = resolveValue(value, fallback, axis);
2541
- const numericValue = Number(resolvedValue);
2542
- if (!Number.isFinite(numericValue)) {
2543
- throw new Error(`${fieldName} must be a finite number`);
2544
- }
2545
- if (constraints.positive && numericValue <= 0) {
2546
- throw new Error(`${fieldName} must be greater than 0`);
2547
- }
2548
- if (constraints.nonNegative && numericValue < 0) {
2549
- throw new Error(`${fieldName} must be 0 or greater`);
2550
- }
2551
- return numericValue;
2552
- };
2553
- try {
2554
- maskConfig.gap = resolveNumber(maskConfig.gap, 5, "width", "gap", { nonNegative: true });
2555
- maskConfig.width = resolveNumber(maskConfig.width, this.options.defaultMaskWidth, "width", "width", { positive: true });
2556
- maskConfig.height = resolveNumber(maskConfig.height, this.options.defaultMaskHeight, "height", "height", { positive: true });
2557
- maskConfig.angle = resolveNumber(maskConfig.angle, 0, "width", "angle");
2558
- maskConfig.alpha = Math.max(0, Math.min(1, resolveNumber(maskConfig.alpha, 0.5, "width", "alpha")));
2559
- if (maskConfig.left === void 0 && this._lastMask) {
2560
- const previousMask = this._lastMask;
2561
- if (typeof previousMask.setCoords === "function") previousMask.setCoords();
2562
- const previousBounds = typeof previousMask.getBoundingRect === "function" ? previousMask.getBoundingRect(true, true) : { left: previousMask.left || firstOffset, top: previousMask.top || firstOffset, width: previousMask.width || 0 };
2563
- left = Math.round(previousBounds.left + previousBounds.width + maskConfig.gap);
2564
- top = Math.round(previousBounds.top ?? firstOffset);
2565
- } else {
2566
- left = resolveNumber(maskConfig.left, firstOffset, "width", "left");
2567
- top = resolveNumber(maskConfig.top, firstOffset, "height", "top");
2568
- }
2569
- } catch (error) {
2570
- return rejectInvalidMask("invalid numeric configuration", error);
2571
- }
2572
- maskConfig.left = left;
2573
- maskConfig.top = top;
2574
- let mask;
2575
- if (typeof maskConfig.fabricGenerator === "function") {
2576
- mask = maskConfig.fabricGenerator(maskConfig, this.canvas, this.options);
2577
- } else {
2578
- switch (shapeType) {
2579
- case "circle":
2580
- try {
2581
- maskConfig.radius = resolveNumber(maskConfig.radius, Math.min(maskConfig.width, maskConfig.height) / 2, "min", "radius", { positive: true });
2582
- } catch (error) {
2583
- return rejectInvalidMask("invalid circle radius", error);
2584
- }
2585
- mask = new fabric.Circle({
2586
- left,
2587
- top,
2588
- radius: maskConfig.radius,
2589
- fill: maskConfig.color,
2590
- opacity: maskConfig.alpha,
2591
- angle: maskConfig.angle,
2592
- ...maskConfig.styles
2593
- });
2594
- break;
2595
- case "ellipse":
2596
- try {
2597
- maskConfig.rx = resolveNumber(maskConfig.rx, maskConfig.width / 2, "width", "rx", { positive: true });
2598
- maskConfig.ry = resolveNumber(maskConfig.ry, maskConfig.height / 2, "height", "ry", { positive: true });
2599
- } catch (error) {
2600
- return rejectInvalidMask("invalid ellipse radius", error);
2601
- }
2602
- mask = new fabric.Ellipse({
2603
- left,
2604
- top,
2605
- rx: maskConfig.rx,
2606
- ry: maskConfig.ry,
2607
- fill: maskConfig.color,
2608
- opacity: maskConfig.alpha,
2609
- angle: maskConfig.angle,
2610
- ...maskConfig.styles
2611
- });
2612
- break;
2613
- case "polygon": {
2614
- let polygonPoints = maskConfig.points || [];
2615
- if (!Array.isArray(polygonPoints) || polygonPoints.length < 3) {
2616
- return rejectInvalidMask("polygon masks require at least three points");
2617
- }
2618
- try {
2619
- polygonPoints = polygonPoints.map((point) => {
2620
- const x = Number(Array.isArray(point) ? point[0] : point.x);
2621
- const y = Number(Array.isArray(point) ? point[1] : point.y);
2622
- if (!Number.isFinite(x) || !Number.isFinite(y)) {
2623
- throw new Error("polygon point coordinates must be finite numbers");
2624
- }
2625
- return { x, y };
2626
- });
2627
- } catch (error) {
2628
- return rejectInvalidMask("invalid polygon points", error);
2629
- }
2630
- mask = new fabric.Polygon(polygonPoints, {
2631
- left,
2632
- top,
2633
- fill: maskConfig.color,
2634
- opacity: maskConfig.alpha,
2635
- angle: maskConfig.angle,
2636
- ...maskConfig.styles
2637
- });
2638
- break;
2639
- }
2640
- case "rect":
2641
- default:
2642
- try {
2643
- if (maskConfig.rx != null) maskConfig.rx = resolveNumber(maskConfig.rx, 0, "width", "rx", { nonNegative: true });
2644
- if (maskConfig.ry != null) maskConfig.ry = resolveNumber(maskConfig.ry, 0, "height", "ry", { nonNegative: true });
2645
- } catch (error) {
2646
- return rejectInvalidMask("invalid rectangle corner radius", error);
2647
- }
2648
- mask = new fabric.Rect({
2649
- left,
2650
- top,
2651
- width: maskConfig.width,
2652
- height: maskConfig.height,
2653
- fill: maskConfig.color,
2654
- opacity: maskConfig.alpha,
2655
- angle: maskConfig.angle,
2656
- rx: maskConfig.rx,
2657
- ry: maskConfig.ry,
2658
- ...maskConfig.styles
2659
- });
2660
- }
2661
- }
2662
- if (!mask || typeof mask.set !== "function" || typeof mask.setCoords !== "function") {
2663
- this._reportWarning("fabricGenerator returned an invalid Fabric object");
2664
- return null;
2665
- }
2666
- const styles = maskConfig.styles || {};
2667
- const hasStyle = (property) => Object.prototype.hasOwnProperty.call(styles, property);
2668
- const maskSettings = {
2669
- selectable: maskConfig.selectable !== false,
2670
- hasControls: "hasControls" in maskConfig ? maskConfig.hasControls : true,
2671
- lockRotation: !this.options.maskRotatable,
2672
- borderColor: "borderColor" in maskConfig ? maskConfig.borderColor : "red",
2673
- cornerColor: "cornerColor" in maskConfig ? maskConfig.cornerColor : "black",
2674
- cornerSize: "cornerSize" in maskConfig ? maskConfig.cornerSize : 8,
2675
- transparentCorners: "transparentCorners" in maskConfig ? maskConfig.transparentCorners : false,
2676
- stroke: hasStyle("stroke") ? styles.stroke : "#ccc",
2677
- strokeWidth: hasStyle("strokeWidth") ? styles.strokeWidth : 1,
2678
- opacity: hasStyle("opacity") ? styles.opacity : maskConfig.alpha,
2679
- strokeUniform: "strokeUniform" in maskConfig ? maskConfig.strokeUniform : hasStyle("strokeUniform") ? styles.strokeUniform : true
2680
- };
2681
- if (hasStyle("strokeDashArray")) maskSettings.strokeDashArray = styles.strokeDashArray;
2682
- mask.set(maskSettings);
2683
- mask.setCoords();
2684
- mask.set({
2685
- originalAlpha: Number.isFinite(Number(mask.opacity)) ? Number(mask.opacity) : maskConfig.alpha,
2686
- originalStroke: mask.stroke || "#ccc",
2687
- originalStrokeWidth: Number.isFinite(Number(mask.strokeWidth)) ? Number(mask.strokeWidth) : 1
2688
- });
2689
- this._rebindMaskEvents(mask);
2690
- this._expandCanvasToFitObjects([mask]);
2691
- this._lastMaskInitialLeft = left;
2692
- this._lastMaskInitialTop = top;
2693
- this._lastMaskInitialWidth = maskConfig.width;
2694
- const maskId = ++this.maskCounter;
2695
- mask.set({
2696
- maskId,
2697
- maskName: `${this.options.maskName}${maskId}`
2698
- });
2699
- this._lastMask = mask;
2700
- this.canvas.add(mask);
2701
- this.canvas.bringToFront(mask);
2702
- if (maskConfig.selectable) this.canvas.setActiveObject(mask);
2703
- this._handleSelectionChanged([mask]);
2704
- this._updateMaskList();
2705
- this._updateUI();
2706
- this.canvas.renderAll();
2707
- this.saveState();
2708
- if (typeof maskConfig.onCreate === "function") maskConfig.onCreate(mask, this.canvas);
2709
- return mask;
2710
- }
2711
- /**
2712
- * Backward-compatible alias for {@link ImageEditor#createMask}.
2713
- *
2714
- * @deprecated Use createMask() instead. This alias will be removed in v2.0.0.
2715
- * @param {Object} [config={}] - Mask configuration passed to createMask().
2716
- * @returns {fabric.Object|null} The created mask object, or null if the canvas is not initialized.
2717
- */
2718
- addMask(config = {}) {
2719
- return this.createMask(config);
2720
- }
2721
- /**
2722
- * Removes the currently selected mask from the canvas, if any.
2723
- * The associated label is also removed. UI and mask list are updated.
2724
- */
2725
- removeSelectedMask() {
2726
- if (!this.canvas) return;
2727
- if (!this._canMutateNow("removeSelectedMask")) return;
2728
- const activeObject = this.canvas.getActiveObject();
2729
- const selectedMasks = this._getModifiedMasks(activeObject);
2730
- if (!selectedMasks.length) return;
2731
- this.canvas.discardActiveObject();
2732
- selectedMasks.forEach((mask) => {
2733
- this._removeLabelForMask(mask);
2734
- this._cleanupMaskEvents(mask);
2735
- this.canvas.remove(mask);
2736
- });
2737
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
2738
- this._lastMask = masks.length ? masks[masks.length - 1] : null;
2739
- if (!this._lastMask) {
2740
- this._lastMaskInitialLeft = null;
2741
- this._lastMaskInitialTop = null;
2742
- this._lastMaskInitialWidth = null;
2743
- }
2744
- this._updateMaskList();
2745
- this._updateUI();
2746
- this.canvas.renderAll();
2747
- this.saveState();
2748
- }
2749
- /**
2750
- * Removes all masks from the canvas, including their labels.
2751
- * UI and internal mask placement memory are reset.
2752
- */
2753
- removeAllMasks(options = {}) {
2754
- if (!this.canvas) return;
2755
- if (!this._canMutateNow("removeAllMasks", options)) return;
2756
- const saveHistory = options.saveHistory !== false;
2757
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
2758
- masks.forEach((mask) => this._removeLabelForMask(mask));
2759
- masks.forEach((mask) => {
2760
- this._cleanupMaskEvents(mask);
2761
- this.canvas.remove(mask);
2762
- });
2763
- this.canvas.discardActiveObject();
2764
- this._lastMask = null;
2765
- this._lastMaskInitialLeft = null;
2766
- this._lastMaskInitialTop = null;
2767
- this._lastMaskInitialWidth = null;
2768
- this._updateMaskList();
2769
- this._updateUI();
2770
- this.canvas.renderAll();
2771
- if (saveHistory) this.saveState();
2772
- }
2773
- /**
2774
- * Removes the label associated with the specified mask object, if it exists.
2775
- *
2776
- * @param {fabric.Object} mask - The mask object whose label should be removed.
2777
- * @private
2778
- */
2779
- _removeLabelForMask(mask) {
2780
- if (!mask || !this.canvas) return;
2781
- if (mask.__label) {
2782
- try {
2783
- const canvasObjects = this.canvas.getObjects();
2784
- if (canvasObjects.includes(mask.__label)) {
2785
- this.canvas.remove(mask.__label);
2786
- }
2787
- } catch (error) {
2788
- void error;
2789
- }
2790
- try {
2791
- delete mask.__label;
2792
- } catch (error) {
2793
- void error;
2794
- }
2795
- }
2796
- }
2797
- _captureMaskLabelBackups(masks) {
2798
- if (!this.canvas) return [];
2799
- const canvasObjects = new Set(this.canvas.getObjects());
2800
- return (masks || []).map((mask) => {
2801
- const label = mask && mask.__label ? mask.__label : null;
2802
- return {
2803
- mask,
2804
- label,
2805
- hadLabel: !!label,
2806
- labelInCanvas: !!label && canvasObjects.has(label),
2807
- visible: label ? label.visible : void 0
2808
- };
2809
- });
2810
- }
2811
- _restoreMaskLabelBackups(labelBackups) {
2812
- if (!this.canvas || !Array.isArray(labelBackups)) return;
2813
- const canvasObjects = new Set(this.canvas.getObjects());
2814
- labelBackups.forEach((backup) => {
2815
- if (!backup || !backup.mask) return;
2816
- try {
2817
- if (!backup.hadLabel) {
2818
- if (backup.mask.__label) this._removeLabelForMask(backup.mask);
2819
- return;
2820
- }
2821
- backup.mask.__label = backup.label;
2822
- if (!backup.label) return;
2823
- if (backup.labelInCanvas && !canvasObjects.has(backup.label)) {
2824
- this.canvas.add(backup.label);
2825
- canvasObjects.add(backup.label);
2826
- }
2827
- if (backup.visible !== void 0) backup.label.set({ visible: backup.visible });
2828
- if (backup.labelInCanvas) this.canvas.bringToFront(backup.label);
2829
- this._syncMaskLabel(backup.mask);
2830
- } catch (error) {
2831
- this._reportWarning("restoreMaskLabelBackups: failed to restore mask label", error);
2832
- }
2833
- });
2834
- }
2835
- _captureActiveObjectBackup() {
2836
- if (!this.canvas) return null;
2837
- const activeObject = this.canvas.getActiveObject();
2838
- if (!activeObject) return null;
2839
- const selectedObjects = typeof activeObject.getObjects === "function" ? activeObject.getObjects() : [activeObject];
2840
- return { activeObject, selectedObjects };
2841
- }
2842
- _restoreActiveObjectBackup(activeObjectBackup) {
2843
- if (!this.canvas || !activeObjectBackup || !activeObjectBackup.activeObject) return;
2844
- const canvasObjects = this.canvas.getObjects();
2845
- const selectedObjects = Array.isArray(activeObjectBackup.selectedObjects) ? activeObjectBackup.selectedObjects : [];
2846
- const canRestore = selectedObjects.length ? selectedObjects.every((object) => canvasObjects.includes(object)) : canvasObjects.includes(activeObjectBackup.activeObject);
2847
- if (!canRestore) return;
2848
- try {
2849
- this.canvas.setActiveObject(activeObjectBackup.activeObject);
2850
- } catch (error) {
2851
- void error;
2852
- }
2853
- }
2854
- _captureMaskExportBackups(masks) {
2855
- return (masks || []).map((mask) => ({
2856
- object: mask,
2857
- visible: mask.visible,
2858
- opacity: mask.opacity,
2859
- fill: mask.fill,
2860
- strokeWidth: mask.strokeWidth,
2861
- stroke: mask.stroke,
2862
- selectable: mask.selectable,
2863
- lockRotation: mask.lockRotation
2864
- }));
2865
- }
2866
- _restoreMaskExportBackups(maskBackups) {
2867
- (maskBackups || []).forEach((backup) => {
2868
- try {
2869
- backup.object.set({
2870
- visible: backup.visible,
2871
- opacity: backup.opacity,
2872
- fill: backup.fill,
2873
- strokeWidth: backup.strokeWidth,
2874
- stroke: backup.stroke,
2875
- selectable: backup.selectable,
2876
- lockRotation: backup.lockRotation
2877
- });
2878
- backup.object.setCoords();
2879
- } catch (error) {
2880
- void error;
2881
- }
2882
- });
2883
- }
2884
- /**
2885
- * Returns a stable zero-based creation index for label callbacks.
2886
- *
2887
- * Mask ids are one-based and are not renumbered after deletion, so this value remains stable for the
2888
- * lifetime of a mask.
2889
- *
2890
- * @param {fabric.Object} mask - Mask object.
2891
- * @returns {number} Stable zero-based creation index.
2892
- * @private
2893
- */
2894
- _getMaskCreationIndex(mask) {
2895
- const maskId = Number(mask && mask.maskId);
2896
- if (Number.isFinite(maskId) && maskId > 0) return Math.floor(maskId) - 1;
2897
- const masks = this.canvas ? this.canvas.getObjects().filter((object) => object.maskId) : [];
2898
- return Math.max(0, masks.indexOf(mask));
2899
- }
2900
- /**
2901
- * Creates and adds a custom label (fabric.Text or fabric.IText) for the mask.
2902
- * The label is default bound to the top-left of the mask and managed as a non-interactive overlay.
2903
- *
2904
- * @param {fabric.Object} mask - The mask to create a label for.
2905
- * @private
2906
- */
2907
- _createLabelForMask(mask) {
2908
- if (!mask || !this.options.maskLabelOnSelect) return;
2909
- this._removeLabelForMask(mask);
2910
- let textObject = null;
2911
- if (this.options.label && typeof this.options.label.create === "function") {
2912
- textObject = this.options.label.create(mask, fabric);
2913
- if (!textObject || typeof textObject.set !== "function") {
2914
- this._reportWarning("label.create() returned an invalid Fabric object; using the default label");
2915
- textObject = null;
2916
- }
2917
- }
2918
- if (!textObject) {
2919
- let labelText = mask.maskName;
2920
- let textOptions = {
2921
- left: 0,
2922
- top: 0,
2923
- fontSize: 12,
2924
- fill: "#fff",
2925
- backgroundColor: "rgba(0,0,0,0.7)",
2926
- selectable: false,
2927
- evented: false,
2928
- padding: 2,
2929
- originX: "left",
2930
- originY: "top"
2931
- };
2932
- if (this.options.label) {
2933
- if (typeof this.options.label.getText === "function") {
2934
- labelText = this.options.label.getText(mask, this._getMaskCreationIndex(mask));
2935
- }
2936
- if (this.options.label.textOptions) {
2937
- Object.assign(textOptions, this.options.label.textOptions);
2938
- }
2939
- }
2940
- textObject = new fabric.Text(labelText, textOptions);
2941
- }
2942
- textObject.maskLabel = true;
2943
- mask.__label = textObject;
2944
- this.canvas.add(textObject);
2945
- this.canvas.bringToFront(textObject);
2946
- this._syncMaskLabel(mask);
2947
- }
2948
- /**
2949
- * Hides (removes) all mask labels from the canvas.
2950
- * Internal label references on mask objects are also deleted.
2951
- * @private
2952
- */
2953
- _hideAllMaskLabels() {
2954
- if (!this.canvas) return;
2955
- const canvasObjects = this.canvas.getObjects();
2956
- const canvasObjectSet = new Set(canvasObjects);
2957
- const labels = canvasObjects.filter((object) => object.maskLabel);
2958
- labels.forEach((label) => {
2959
- try {
2960
- if (canvasObjectSet.has(label)) {
2961
- this.canvas.remove(label);
2962
- }
2963
- } catch (error) {
2964
- void error;
2965
- }
2966
- });
2967
- canvasObjects.forEach((object) => {
2968
- if (object.maskId && object.__label) {
2969
- try {
2970
- delete object.__label;
2971
- } catch (error) {
2972
- void error;
2973
- }
2974
- }
2975
- });
2976
- }
2977
- /**
2978
- * Synchronizes the position, angle, and visibility of the mask's label so that it appears properly above the mask.
2979
- *
2980
- * @param {fabric.Object} mask - The mask whose label should be repositioned.
2981
- * @private
2982
- */
2983
- _syncMaskLabel(mask) {
2984
- if (!mask) return;
2985
- if (!this.options.maskLabelOnSelect) return;
2986
- if (!mask.__label) return;
2987
- if (typeof mask.setCoords === "function") mask.setCoords();
2988
- const bounds = mask.getBoundingRect ? mask.getBoundingRect(true, true) : null;
2989
- if (!bounds) return;
2990
- const tl = { x: bounds.left, y: bounds.top };
2991
- const center = mask.getCenterPoint();
2992
- const vx = center.x - tl.x;
2993
- const vy = center.y - tl.y;
2994
- const dist = Math.sqrt(vx * vx + vy * vy) || 1;
2995
- const ux = vx / dist;
2996
- const uy = vy / dist;
2997
- const offset = Math.max(0, this.options.maskLabelOffset ?? 3);
2998
- const px = tl.x + ux * offset;
2999
- const py = tl.y + uy * offset;
3000
- mask.__label.set({
3001
- left: Math.round(px),
3002
- top: Math.round(py),
3003
- angle: mask.angle || 0,
3004
- originX: "left",
3005
- originY: "top",
3006
- visible: true
3007
- });
3008
- mask.__label.setCoords();
3009
- if (typeof this.canvas.requestRenderAll === "function") {
3010
- this.canvas.requestRenderAll();
3011
- } else {
3012
- this.canvas.renderAll();
3013
- }
3014
- }
3015
- /**
3016
- * Shows the label for the given mask, creating it if necessary and synchronizing its position.
3017
- *
3018
- * @param {fabric.Object} mask - The mask whose label should be shown.
3019
- * @private
3020
- */
3021
- _showLabelForMask(mask) {
3022
- if (!mask) return;
3023
- if (!this.options.maskLabelOnSelect) return;
3024
- if (!mask.__label) this._createLabelForMask(mask);
3025
- mask.__label.set({ visible: true });
3026
- this._syncMaskLabel(mask);
3027
- }
3028
- /**
3029
- * Handles changes to the selection of canvas objects (masks),
3030
- * updates mask stroke and label display, and syncs mask list selection.
3031
- *
3032
- * @param {Array<Object>} selected - The currently selected objects (e.g. [mask] or []).
3033
- * @private
3034
- */
3035
- _handleSelectionChanged(selected) {
3036
- const selectedMask = (selected || []).find((object) => object.maskId);
3037
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3038
- masks.forEach((mask) => {
3039
- if (mask !== selectedMask) {
3040
- if (mask.__label) {
3041
- try {
3042
- this.canvas.remove(mask.__label);
3043
- } catch (error) {
3044
- void error;
3045
- }
3046
- delete mask.__label;
3047
- }
3048
- const originalStrokeWidth = Number(mask.originalStrokeWidth);
3049
- mask.set({
3050
- stroke: mask.originalStroke || "#ccc",
3051
- strokeWidth: Number.isFinite(originalStrokeWidth) ? originalStrokeWidth : 1
3052
- });
3053
- } else {
3054
- mask.set({ stroke: "#ff0000", strokeWidth: 1 });
3055
- }
3056
- });
3057
- if (selectedMask) this._showLabelForMask(selectedMask);
3058
- this._updateMaskListSelection(selectedMask);
3059
- this.canvas.renderAll();
3060
- this._updateUI();
3061
- }
3062
- /**
3063
- * Updates the mask list in the DOM to reflect the current masks on the canvas.
3064
- * Each list entry becomes a clickable element for mask selection.
3065
- * @private
3066
- */
3067
- _updateMaskList() {
3068
- const maskListElement = this._getElement("maskList");
3069
- if (!maskListElement) return;
3070
- maskListElement.innerHTML = "";
3071
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3072
- masks.forEach((mask) => {
3073
- const listItemElement = document.createElement("li");
3074
- listItemElement.className = "list-group-item mask-item";
3075
- listItemElement.textContent = mask.maskName;
3076
- listItemElement.dataset.maskId = String(mask.maskId);
3077
- maskListElement.appendChild(listItemElement);
3078
- });
3079
- }
3080
- _handleMaskListClick(event) {
3081
- if (!this.canvas) return;
3082
- const itemElement = event.target && event.target.closest ? event.target.closest(".mask-item") : null;
3083
- if (!itemElement || !itemElement.dataset) return;
3084
- const maskId = Number(itemElement.dataset.maskId);
3085
- const mask = this.canvas.getObjects().find((object) => Number(object.maskId) === maskId);
3086
- if (!mask) return;
3087
- this.canvas.setActiveObject(mask);
3088
- this._handleSelectionChanged([mask]);
3089
- }
3090
- /**
3091
- * Updates the visual selection (CSS 'active') state for the mask list in the DOM.
3092
- *
3093
- * @param {Object|null} selectedMask - The currently selected mask, or null if none selected.
3094
- * @private
3095
- */
3096
- _updateMaskListSelection(selectedMask) {
3097
- const maskListElement = this._getElement("maskList");
3098
- if (!maskListElement) return;
3099
- const maskItems = maskListElement.querySelectorAll(".mask-item");
3100
- maskItems.forEach((item) => {
3101
- const isSelected = !!selectedMask && Number(item.dataset.maskId) === Number(selectedMask.maskId);
3102
- item.classList.toggle("active", isSelected);
3103
- item.classList.toggle("selected", isSelected);
3104
- });
3105
- }
3106
- /**
3107
- * Flattens the current masks into the base image and reloads the flattened image.
3108
- *
3109
- * This removes editable mask objects after export and records the operation as one undoable history transition.
3110
- * It does nothing when no base image or no masks exist.
3111
- *
3112
- * @async
3113
- * @returns {Promise<void>} Resolves when the flattened image has been loaded.
3114
- * @public
3115
- */
3116
- async mergeMasks() {
3117
- if (!this.originalImage) return;
3118
- this._assertIdleForOperation("mergeMasks");
3119
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3120
- if (!masks.length) return;
3121
- const beforeImageDisplayBounds = this._captureImageDisplayBounds();
3122
- const beforeJson = this._serializeCanvasState();
3123
- const operationToken = this._beginBusyOperation("mergeMasks");
3124
- this.canvas.discardActiveObject();
3125
- this.canvas.renderAll();
3126
- try {
3127
- const merged = await this.exportImageBase64(this._withInternalOperationOptions(operationToken, {
3128
- exportImageArea: true,
3129
- multiplier: this.options.exportMultiplier,
3130
- fileType: "png"
3131
- }));
3132
- this.removeAllMasks(this._withInternalOperationOptions(operationToken, { saveHistory: false }));
3133
- if (this.canvas.getObjects().some((object) => object.maskId)) {
3134
- throw new Error("Masks could not be removed during merge");
3135
- }
3136
- await this.loadImage(merged, this._withInternalOperationOptions(operationToken, {
3137
- preserveScroll: true,
3138
- resetMaskCounter: false
3139
- }));
3140
- this._restoreImageDisplayBounds(beforeImageDisplayBounds);
3141
- const afterJson = this._serializeCanvasState();
3142
- this._pushStateTransition(beforeJson, afterJson);
3143
- } catch (error) {
3144
- this._reportError("merge error", error);
3145
- try {
3146
- await this.loadFromState(beforeJson, this._withInternalOperationOptions(operationToken));
3147
- } catch (restoreError) {
3148
- this._reportError("mergeMasks rollback failed", restoreError);
3149
- }
3150
- throw error;
3151
- } finally {
3152
- this._endBusyOperation(operationToken);
3153
- }
3154
- }
3155
- /**
3156
- * Backward-compatible alias for {@link ImageEditor#mergeMasks}.
3157
- *
3158
- * @deprecated Use mergeMasks() instead. This alias will be removed in v2.0.0.
3159
- * @returns {Promise<void>} Resolves when mask flattening is complete.
3160
- */
3161
- async merge() {
3162
- return this.mergeMasks();
3163
- }
3164
- /**
3165
- * Triggers a JPEG image download of the current canvas.
3166
- *
3167
- * The image area and multiplier are controlled by options.
3168
- * @param {string} [fileName=this.options.defaultDownloadFileName] - Desired download file name.
3169
- * @returns {void}
3170
- * @public
3171
- */
3172
- downloadImage(fileName = this.options.defaultDownloadFileName) {
3173
- if (!this.originalImage) return;
3174
- if (!this._canMutateNow("downloadImage")) return;
3175
- const exportImageArea = this.options.exportImageAreaByDefault;
3176
- this.exportImageBase64({ exportImageArea, multiplier: this.options.exportMultiplier }).then((imageBase64) => {
3177
- const link = document.createElement("a");
3178
- link.download = fileName;
3179
- link.href = imageBase64;
3180
- document.body.appendChild(link);
3181
- link.click();
3182
- document.body.removeChild(link);
3183
- }).catch((error) => this._reportError("download error", error));
3184
- }
3185
- /**
3186
- * Exports the current image as a Base64-encoded data URL.
3187
- *
3188
- * When `exportImageArea` is false, the export omits masks and labels. When it is true, masks are
3189
- * temporarily rendered as opaque export shapes and then restored, so editable mask state is not mutated.
3190
- *
3191
- * @async
3192
- * @param {Object} [options={}] - Export options.
3193
- * @param {boolean} [options.exportImageArea] - If true, exports only the image bounding area with masks cropped and blended.
3194
- * @param {number} [options.multiplier=1] - Scaling multiplier for output (resolution).
3195
- * @param {number} [options.quality=0.92] - Image quality between 0 and 1 for lossy formats.
3196
- * @param {string} [options.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp').
3197
- * @returns {Promise<string>} Resolves with an image data URL.
3198
- * @throws {Error} If there is no image loaded.
3199
- * @public
3200
- */
3201
- async exportImageBase64(options = {}) {
3202
- if (!this.originalImage) throw new Error("No image loaded");
3203
- options = options || {};
3204
- this._assertIdleForOperation("exportImageBase64", options);
3205
- const isNestedOperation = this._isOwnInternalOperation(options);
3206
- const operationToken = isNestedOperation ? this._getInternalOperationToken(options) : this._beginBusyOperation("exportImageBase64");
3207
- const exportImageArea = typeof options.exportImageArea === "boolean" ? options.exportImageArea : this.options.exportImageAreaByDefault;
3208
- const multiplier = options.multiplier || this.options.exportMultiplier || 1;
3209
- const quality = this._normalizeQuality(options.quality ?? this.options.downsampleQuality);
3210
- const format = this._normalizeImageFormat(options.fileType || options.format);
3211
- try {
3212
- if (!exportImageArea) {
3213
- const masks2 = this.canvas.getObjects().filter((object) => object.maskId || object.maskLabel);
3214
- const editableMasks = this.canvas.getObjects().filter((object) => object.maskId);
3215
- const maskVisibilityBackups = masks2.map((mask) => ({ object: mask, visible: mask.visible }));
3216
- const maskStyleBackups2 = this._captureMaskExportBackups(editableMasks);
3217
- const labelBackups2 = this._captureMaskLabelBackups(editableMasks);
3218
- const activeObjectBackup2 = this._captureActiveObjectBackup();
3219
- try {
3220
- masks2.forEach((mask) => {
3221
- mask.set({ visible: false });
3222
- });
3223
- this.canvas.discardActiveObject();
3224
- this.canvas.renderAll();
3225
- this.originalImage.setCoords();
3226
- const imageBounds = this.originalImage.getBoundingRect(true, true);
3227
- const exportRegion = this._getClampedCanvasRegion(imageBounds);
3228
- return await this._exportCanvasRegionToDataURL({
3229
- ...exportRegion,
3230
- multiplier,
3231
- quality,
3232
- format,
3233
- sealPartialEdges: this._getPartialExportEdges(imageBounds)
3234
- });
3235
- } finally {
3236
- maskVisibilityBackups.forEach((backup) => {
3237
- try {
3238
- backup.object.set({ visible: backup.visible });
3239
- } catch (error) {
3240
- void error;
3241
- }
3242
- });
3243
- this._restoreMaskExportBackups(maskStyleBackups2);
3244
- this._restoreMaskLabelBackups(labelBackups2);
3245
- this._restoreActiveObjectBackup(activeObjectBackup2);
3246
- this.canvas.renderAll();
3247
- }
3248
- }
3249
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3250
- const maskStyleBackups = this._captureMaskExportBackups(masks);
3251
- const labelBackups = this._captureMaskLabelBackups(masks);
3252
- const activeObjectBackup = this._captureActiveObjectBackup();
3253
- try {
3254
- masks.forEach((mask) => this._removeLabelForMask(mask));
3255
- this.canvas.discardActiveObject();
3256
- this.canvas.renderAll();
3257
- masks.forEach((mask) => {
3258
- mask.set({ opacity: 1, fill: "#000000", strokeWidth: 0, stroke: null, selectable: false });
3259
- mask.setCoords();
3260
- });
3261
- this.canvas.renderAll();
3262
- this.originalImage.setCoords();
3263
- const imageBounds = this.originalImage.getBoundingRect(true, true);
3264
- const exportRegion = this._getClampedCanvasRegion(imageBounds);
3265
- return await this._exportCanvasRegionToDataURL({
3266
- ...exportRegion,
3267
- multiplier,
3268
- quality,
3269
- format,
3270
- sealPartialEdges: this._getPartialExportEdges(imageBounds)
3271
- });
3272
- } finally {
3273
- this._restoreMaskExportBackups(maskStyleBackups);
3274
- this._restoreMaskLabelBackups(labelBackups);
3275
- this._restoreActiveObjectBackup(activeObjectBackup);
3276
- this.canvas.renderAll();
3277
- }
3278
- } finally {
3279
- if (!isNestedOperation) this._endBusyOperation(operationToken);
3280
- }
3281
- }
3282
- /**
3283
- * Backward-compatible alias for {@link ImageEditor#exportImageBase64}.
3284
- *
3285
- * @deprecated Use exportImageBase64() instead. This alias will be removed in v2.0.0.
3286
- * @param {Object} [options={}] - Export options passed to exportImageBase64().
3287
- * @returns {Promise<string>} Resolves with an image data URL.
3288
- */
3289
- async getImageBase64(options = {}) {
3290
- return this.exportImageBase64(options);
3291
- }
3292
- /**
3293
- * Exports the current image as a File object.
3294
- *
3295
- * The export can include flattened masks (`mergeMask: true`) or only the plain base image (`mergeMask: false`).
3296
- * Supported output formats are JPEG, PNG, and WebP.
3297
- *
3298
- * @async
3299
- * @param {Object} [options={}] - Export options.
3300
- * @param {boolean} [options.mergeMask=true] - If true, export image area with masks merged; if false, export the plain image without masks.
3301
- * @param {string} [options.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp'). Defaults to 'jpeg' on invalid input.
3302
- * @param {number} [options.quality=0.92] - Image quality for lossy types (0-1, default based on options.downsampleQuality).
3303
- * @param {number} [options.multiplier=1] - Output resolution multiplier.
3304
- * @param {string} [options.fileName] - Optional file name (only used for download).
3305
- * @returns {Promise<File>} Resolves with the exported image as a File object.
3306
- *
3307
- * @example
3308
- * const file = await this.exportImageFile({ mergeMask: false, fileType: 'png' });
3309
- */
3310
- async exportImageFile(options = {}) {
3311
- if (!this.originalImage) throw new Error("No image loaded");
3312
- options = options || {};
3313
- this._assertIdleForOperation("exportImageFile", options);
3314
- const isNestedOperation = this._isOwnInternalOperation(options);
3315
- const operationToken = isNestedOperation ? this._getInternalOperationToken(options) : this._beginBusyOperation("exportImageFile");
3316
- const {
3317
- mergeMask = true,
3318
- fileType = "jpeg",
3319
- quality = this.options.downsampleQuality ?? 0.92,
3320
- multiplier = this.options.exportMultiplier ?? 1,
3321
- fileName = this.options.defaultDownloadFileName ?? "exported_image.jpg"
3322
- } = options;
3323
- const safeFileType = this._normalizeImageFormat(fileType);
3324
- const normalizedQuality = this._normalizeQuality(quality);
3325
- try {
3326
- let imageBase64;
3327
- if (mergeMask) {
3328
- imageBase64 = await this.exportImageBase64(this._withInternalOperationOptions(operationToken, {
3329
- exportImageArea: true,
3330
- multiplier,
3331
- quality: normalizedQuality,
3332
- fileType: safeFileType
3333
- }));
3334
- } else {
3335
- imageBase64 = await this.exportImageBase64(this._withInternalOperationOptions(operationToken, {
3336
- exportImageArea: false,
3337
- multiplier,
3338
- quality: normalizedQuality,
3339
- fileType: safeFileType
3340
- }));
3341
- }
3342
- let imageDataUrl = imageBase64;
3343
- if (!imageDataUrl.startsWith(`data:image/${safeFileType}`)) {
3344
- imageDataUrl = await new Promise((resolve, reject) => {
3345
- const imageElement = new window.Image();
3346
- imageElement.crossOrigin = "Anonymous";
3347
- imageElement.onload = () => {
3348
- try {
3349
- const offscreenCanvas = document.createElement("canvas");
3350
- offscreenCanvas.width = imageElement.width;
3351
- offscreenCanvas.height = imageElement.height;
3352
- const context = offscreenCanvas.getContext("2d");
3353
- if (!context) throw new Error("Unable to create 2D canvas context for export conversion");
3354
- context.drawImage(imageElement, 0, 0);
3355
- const convertedDataUrl = offscreenCanvas.toDataURL(`image/${safeFileType}`, normalizedQuality);
3356
- resolve(convertedDataUrl);
3357
- } catch (error) {
3358
- reject(error);
3359
- }
3360
- };
3361
- imageElement.onerror = reject;
3362
- imageElement.src = imageBase64;
3363
- });
3364
- }
3365
- const bytes = this._decodeDataUrlPayload(imageDataUrl);
3366
- const mime = `image/${safeFileType}`;
3367
- return new File([bytes], fileName, { type: mime });
3368
- } finally {
3369
- if (!isNestedOperation) this._endBusyOperation(operationToken);
3370
- }
3371
- }
3372
- _clearMaskPlacementMemory() {
3373
- this._lastMask = null;
3374
- this._lastMaskInitialLeft = null;
3375
- this._lastMaskInitialTop = null;
3376
- this._lastMaskInitialWidth = null;
3377
- }
3378
- async _restoreStateAfterCropFailure(beforeJson, message, error, options = {}) {
3379
- this._reportError(message, error);
3380
- if (this._cropRect && this.canvas) this._removeCropRect();
3381
- this._cropRect = null;
3382
- this._cropMode = false;
3383
- if (this.canvas && this._prevSelectionSetting !== void 0) {
3384
- this.canvas.selection = !!this._prevSelectionSetting;
3385
- }
3386
- this._prevSelectionSetting = void 0;
3387
- if (beforeJson) {
3388
- try {
3389
- await this.loadFromState(beforeJson, options);
3390
- } catch (restoreError) {
3391
- this._reportError("applyCrop: rollback failed", restoreError);
3392
- }
3393
- }
3394
- this._updateUI();
3395
- if (this.canvas) this.canvas.renderAll();
3396
- }
3397
- _restoreCropObjectState() {
3398
- if (Array.isArray(this._cropPrevEvented)) {
3399
- this._cropPrevEvented.forEach((state) => {
3400
- try {
3401
- state.object.set({
3402
- evented: state.evented,
3403
- selectable: state.selectable,
3404
- visible: state.visible
3405
- });
3406
- } catch (error) {
3407
- void error;
3408
- }
3409
- });
3410
- }
3411
- this._cropPrevEvented = null;
3412
- }
3413
- _removeCropRect() {
3414
- if (this._cropHandlers && this._cropHandlers.length) {
3415
- this._cropHandlers.forEach((targetHandlers) => {
3416
- (targetHandlers.handlers || []).forEach((handlerRecord) => {
3417
- try {
3418
- if (targetHandlers.target && typeof targetHandlers.target.off === "function") {
3419
- targetHandlers.target.off(handlerRecord.eventName, handlerRecord.handler);
3420
- }
3421
- } catch (error) {
3422
- this._reportWarning("Crop handler cleanup failed", error);
3423
- }
3424
- });
3425
- });
3426
- }
3427
- try {
3428
- if (this.canvas && this._cropRect) this.canvas.remove(this._cropRect);
3429
- } catch (error) {
3430
- void error;
3431
- }
3432
- this._cropRect = null;
3433
- this._cropHandlers = [];
3434
- }
3435
- _getCropRectContentBounds(cropRect) {
3436
- if (!cropRect) return { left: 0, top: 0, width: 1, height: 1 };
3437
- const width = Math.max(1, (Number(cropRect.width) || 1) * Math.abs(Number(cropRect.scaleX) || 1));
3438
- const height = Math.max(1, (Number(cropRect.height) || 1) * Math.abs(Number(cropRect.scaleY) || 1));
3439
- return {
3440
- left: Number(cropRect.left) || 0,
3441
- top: Number(cropRect.top) || 0,
3442
- width,
3443
- height
3444
- };
3445
- }
3446
- /**
3447
- * Enters crop mode by creating a resizable crop rectangle above the base image.
3448
- *
3449
- * Other canvas objects are made non-interactive while crop mode is active. Masks can be hidden during
3450
- * cropping when `crop.hideMasksDuringCrop` is enabled.
3451
- *
3452
- * @returns {void}
3453
- * @public
3454
- */
3455
- enterCropMode() {
3456
- if (!this.canvas || !this.originalImage || this._cropMode) return;
3457
- if (!this._canMutateNow("enterCropMode")) return;
3458
- if (!this.isImageLoaded()) return;
3459
- this._removeCropRect();
3460
- this._cropMode = true;
3461
- this._prevSelectionSetting = this.canvas.selection;
3462
- this.canvas.selection = false;
3463
- this.canvas.discardActiveObject();
3464
- this.originalImage.setCoords();
3465
- const imageBounds = this.originalImage.getBoundingRect(true, true);
3466
- const padding = this.options.crop && this.options.crop.padding ? this.options.crop.padding : 10;
3467
- const left = Math.max(0, Math.floor(imageBounds.left + padding));
3468
- const top = Math.max(0, Math.floor(imageBounds.top + padding));
3469
- const maxCropWidth = Math.max(1, Math.floor(imageBounds.width));
3470
- const maxCropHeight = Math.max(1, Math.floor(imageBounds.height));
3471
- const configuredMinWidth = Math.max(1, Number(this.options.crop.minWidth) || 50);
3472
- const configuredMinHeight = Math.max(1, Number(this.options.crop.minHeight) || 50);
3473
- const minCropWidth = Math.min(configuredMinWidth, maxCropWidth);
3474
- const minCropHeight = Math.min(configuredMinHeight, maxCropHeight);
3475
- const width = minCropWidth;
3476
- const height = minCropHeight;
3477
- const requestedCropRotation = !!(this.options.crop && this.options.crop.allowRotationOfCropRect);
3478
- if (requestedCropRotation && !this._cropRotationWarningEmitted) {
3479
- this._cropRotationWarningEmitted = true;
3480
- this._reportWarning("crop.allowRotationOfCropRect is disabled in v1.x because rotated crop export is not supported");
3481
- }
3482
- const cropRect = new fabric.Rect({
3483
- left,
3484
- top,
3485
- width,
3486
- height,
3487
- fill: "rgba(0,0,0,0.12)",
3488
- stroke: "#00aaff",
3489
- strokeDashArray: [6, 4],
3490
- strokeWidth: 1,
3491
- strokeUniform: true,
3492
- selectable: true,
3493
- hasRotatingPoint: false,
3494
- lockRotation: true,
3495
- cornerSize: 8,
3496
- objectCaching: false,
3497
- originX: "left",
3498
- originY: "top",
3499
- lockScalingFlip: true
3500
- });
3501
- this.canvas.add(cropRect);
3502
- cropRect.isCropRect = true;
3503
- this.canvas.bringToFront(cropRect);
3504
- this.canvas.setActiveObject(cropRect);
3505
- this._cropRect = cropRect;
3506
- this._cropPrevEvented = [];
3507
- const shouldHideMasks = !!(this.options.crop && this.options.crop.hideMasksDuringCrop);
3508
- this.canvas.getObjects().forEach((object) => {
3509
- if (object !== cropRect) {
3510
- this._cropPrevEvented.push({ object, evented: object.evented, selectable: object.selectable, visible: object.visible });
3511
- try {
3512
- const updates = {
3513
- evented: false,
3514
- selectable: false
3515
- };
3516
- if (shouldHideMasks && (object.maskId || object.maskLabel)) updates.visible = false;
3517
- object.set(updates);
3518
- } catch (error) {
3519
- void error;
3520
- }
3521
- }
3522
- });
3523
- const handleCropRectModified = () => {
3524
- try {
3525
- const cropWidth = Math.max(1, Number(cropRect.width) || 1);
3526
- const cropHeight = Math.max(1, Number(cropRect.height) || 1);
3527
- const nextScaleX = Math.min(maxCropWidth / cropWidth, Math.max(minCropWidth / cropWidth, Number(cropRect.scaleX) || 1));
3528
- const nextScaleY = Math.min(maxCropHeight / cropHeight, Math.max(minCropHeight / cropHeight, Number(cropRect.scaleY) || 1));
3529
- cropRect.set({ scaleX: nextScaleX, scaleY: nextScaleY });
3530
- cropRect.setCoords();
3531
- const cropBounds = this._getCropRectContentBounds(cropRect);
3532
- const imageLeft = Number(imageBounds.left) || 0;
3533
- const imageTop = Number(imageBounds.top) || 0;
3534
- const imageRight = imageLeft + (Number(imageBounds.width) || 0);
3535
- const imageBottom = imageTop + (Number(imageBounds.height) || 0);
3536
- let deltaX = 0;
3537
- let deltaY = 0;
3538
- if (cropBounds.left < imageLeft) {
3539
- deltaX = imageLeft - cropBounds.left;
3540
- } else if (cropBounds.left + cropBounds.width > imageRight) {
3541
- deltaX = imageRight - (cropBounds.left + cropBounds.width);
3542
- }
3543
- if (cropBounds.top < imageTop) {
3544
- deltaY = imageTop - cropBounds.top;
3545
- } else if (cropBounds.top + cropBounds.height > imageBottom) {
3546
- deltaY = imageBottom - (cropBounds.top + cropBounds.height);
3547
- }
3548
- if (deltaX || deltaY) {
3549
- cropRect.set({
3550
- left: (Number(cropRect.left) || 0) + deltaX,
3551
- top: (Number(cropRect.top) || 0) + deltaY
3552
- });
3553
- cropRect.setCoords();
3554
- }
3555
- this.canvas.requestRenderAll();
3556
- } catch (error) {
3557
- void error;
3558
- }
3559
- };
3560
- cropRect.on("modified", handleCropRectModified);
3561
- cropRect.on("moving", handleCropRectModified);
3562
- cropRect.on("scaling", handleCropRectModified);
3563
- this._cropHandlers.push({
3564
- target: cropRect,
3565
- handlers: [
3566
- { eventName: "modified", handler: handleCropRectModified },
3567
- { eventName: "moving", handler: handleCropRectModified },
3568
- { eventName: "scaling", handler: handleCropRectModified }
3569
- ]
3570
- });
3571
- this._updateUI();
3572
- this.canvas.renderAll();
3573
- }
3574
- /**
3575
- * Cancels crop mode and removes the temporary crop rectangle.
3576
- *
3577
- * @returns {void}
3578
- * @public
3579
- */
3580
- cancelCrop() {
3581
- if (!this.canvas || !this._cropMode) return;
3582
- this._removeCropRect();
3583
- this._restoreCropObjectState();
3584
- this._cropMode = false;
3585
- this.canvas.selection = !!this._prevSelectionSetting;
3586
- this._prevSelectionSetting = void 0;
3587
- this.canvas.discardActiveObject();
3588
- this._updateUI();
3589
- this.canvas.renderAll();
3590
- }
3591
- /**
3592
- * Applies the current crop rectangle to the base image.
3593
- *
3594
- * Masks are removed by default. When `crop.preserveMasksAfterCrop` is true, masks that intersect the crop
3595
- * region are shifted into the cropped coordinate space and remain editable. The operation is recorded as a
3596
- * single undoable history transition.
3597
- *
3598
- * @async
3599
- * @returns {Promise<void>} Resolves after the cropped image has been loaded and history is updated.
3600
- * @public
3601
- */
3602
- async applyCrop() {
3603
- if (!this.canvas || !this._cropMode || !this._cropRect) return;
3604
- this._assertIdleForOperation("applyCrop");
3605
- const operationToken = this._beginBusyOperation("applyCrop");
3606
- const internalOptions = this._withInternalOperationOptions(operationToken);
3607
- try {
3608
- this._cropRect.setCoords();
3609
- const rectBounds = this._getCropRectContentBounds(this._cropRect);
3610
- const cropRegion = this._getClampedCanvasRegion(rectBounds, { includePartialPixels: false });
3611
- const shouldPreserveMasks = !!(this.options.crop && this.options.crop.preserveMasksAfterCrop);
3612
- this._restoreCropObjectState();
3613
- let beforeJson;
3614
- try {
3615
- beforeJson = this._serializeCanvasState();
3616
- } catch (error) {
3617
- this._reportError("applyCrop: failed to capture rollback state", error);
3618
- beforeJson = null;
3619
- }
3620
- if (!beforeJson) {
3621
- this.cancelCrop();
3622
- return;
3623
- }
3624
- const preservedMasks = [];
3625
- try {
3626
- const masks = this.canvas.getObjects().filter((object) => object.maskId);
3627
- if (masks && masks.length) {
3628
- masks.forEach((mask) => {
3629
- mask.setCoords();
3630
- const maskBounds = mask.getBoundingRect(true, true);
3631
- const intersectsCrop = maskBounds.left < cropRegion.sourceX + cropRegion.sourceWidth && maskBounds.left + maskBounds.width > cropRegion.sourceX && maskBounds.top < cropRegion.sourceY + cropRegion.sourceHeight && maskBounds.top + maskBounds.height > cropRegion.sourceY;
3632
- this._removeLabelForMask(mask);
3633
- this._cleanupMaskEvents(mask);
3634
- this.canvas.remove(mask);
3635
- if (shouldPreserveMasks && intersectsCrop) {
3636
- this._translateObjectByCanvasOffset(mask, -cropRegion.sourceX, -cropRegion.sourceY);
3637
- mask.set({ visible: true });
3638
- preservedMasks.push(mask);
3639
- }
3640
- });
3641
- this._clearMaskPlacementMemory();
3642
- this.canvas.discardActiveObject();
3643
- this.canvas.renderAll();
3644
- }
3645
- } catch (error) {
3646
- await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: failed to prepare masks", error, internalOptions);
3647
- return;
3648
- }
3649
- this._removeCropRect();
3650
- this._cropMode = false;
3651
- this.canvas.selection = !!this._prevSelectionSetting;
3652
- this._prevSelectionSetting = void 0;
3653
- let croppedBase64;
3654
- try {
3655
- croppedBase64 = await this._exportCanvasRegionToDataURL({
3656
- ...cropRegion,
3657
- multiplier: 1,
3658
- quality: this._normalizeQuality(this.options.downsampleQuality),
3659
- format: "jpeg"
3660
- });
3661
- } catch (error) {
3662
- await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: failed to create cropped image", error, internalOptions);
3663
- return;
3664
- }
3665
- try {
3666
- await this.loadImage(croppedBase64, this._withInternalOperationOptions(operationToken, { resetMaskCounter: false }));
3667
- if (preservedMasks.length) {
3668
- preservedMasks.forEach((mask) => {
3669
- this._rebindMaskEvents(mask);
3670
- this.canvas.add(mask);
3671
- this.canvas.bringToFront(mask);
3672
- });
3673
- this._lastMask = preservedMasks[preservedMasks.length - 1];
3674
- this.maskCounter = preservedMasks.reduce((max, mask) => Math.max(max, mask.maskId || 0), this.maskCounter);
3675
- this._updateMaskList();
3676
- this.canvas.renderAll();
3677
- }
3678
- } catch (error) {
3679
- await this._restoreStateAfterCropFailure(beforeJson, "applyCrop: loadImage(croppedBase64) failed", error, internalOptions);
3680
- return;
3681
- }
3682
- let afterJson;
3683
- try {
3684
- afterJson = preservedMasks.length ? this._serializeCanvasState() : this._lastSnapshot;
3685
- } catch (error) {
3686
- this._reportWarning("applyCrop: failed to serialize after state", error);
3687
- afterJson = null;
3688
- }
3689
- try {
3690
- this._pushStateTransition(beforeJson, afterJson);
3691
- } catch (error) {
3692
- this._reportWarning("applyCrop: failed to push history command", error);
3693
- }
3694
- this._updateUI();
3695
- this.canvas.renderAll();
3696
- } finally {
3697
- this._endBusyOperation(operationToken);
3698
- }
3699
- }
3700
- /* ---------- Misc / UI ---------- */
3701
- /**
3702
- * Updates the scale input field in the UI to reflect the current scale.
3703
- * Sets the value (as percentage) if the element is present.
3704
- * @private
3705
- */
3706
- _updateInputs() {
3707
- const scaleInputElement = this._getElement("scalePercentageInput");
3708
- if (scaleInputElement) scaleInputElement.value = Math.round(this.currentScale * 100);
3709
- }
3710
- /**
3711
- * Updates the enabled/disabled state of various UI controls (buttons)
3712
- * based on the current application state (image/mask presence, animation, etc).
3713
- * @private
3714
- */
3715
- _updateUI() {
3716
- if (!this.canvas) return;
3717
- const hasImage = !!this.originalImage;
3718
- const masks = hasImage ? this.canvas.getObjects().filter((object) => object.maskId) : [];
3719
- const hasMasks = masks.length > 0;
3720
- const activeObject = this.canvas.getActiveObject();
3721
- const hasSelectedMask = activeObject && activeObject.maskId;
3722
- const isDefaultTransform = this.currentScale === 1 && this.currentRotation === 0;
3723
- const canUndo = this.historyManager?.canUndo();
3724
- const canRedo = this.historyManager?.canRedo();
3725
- const isInCropMode = !!this._cropMode;
3726
- const isBusy = this.isBusy();
3727
- if (isInCropMode) {
3728
- for (const key of Object.keys(this.elements || {})) {
3729
- const element = this._getElement(key);
3730
- if (!element) continue;
3731
- if (key === "applyCropButton" || key === "cancelCropButton" || key === "applyCropBtn" || key === "cancelCropBtn") {
3732
- this._setDisabled(key, false);
3733
- } else {
3734
- this._setDisabled(key, true);
3735
- }
3736
- }
3737
- return;
3738
- }
3739
- this._setDisabled("zoomInButton", !hasImage || isBusy || this.currentScale >= this.options.maxScale);
3740
- this._setDisabled("zoomOutButton", !hasImage || isBusy || this.currentScale <= this.options.minScale);
3741
- this._setDisabled("rotateLeftButton", !hasImage || isBusy);
3742
- this._setDisabled("rotateRightButton", !hasImage || isBusy);
3743
- this._setDisabled("createMaskButton", !hasImage || isBusy);
3744
- this._setDisabled("removeSelectedMaskButton", !hasSelectedMask || isBusy);
3745
- this._setDisabled("removeAllMasksButton", !hasMasks || isBusy);
3746
- this._setDisabled("mergeMasksButton", !hasImage || !hasMasks || isBusy);
3747
- this._setDisabled("downloadImageButton", !hasImage || isBusy);
3748
- this._setDisabled("resetImageTransformButton", !hasImage || isDefaultTransform || isBusy);
3749
- this._setDisabled("undoButton", !hasImage || isBusy || !canUndo);
3750
- this._setDisabled("redoButton", !hasImage || isBusy || !canRedo);
3751
- this._setDisabled("enterCropModeButton", !hasImage || isBusy);
3752
- this._setDisabled("applyCropButton", true);
3753
- this._setDisabled("cancelCropButton", true);
3754
- this._setDisabled("scalePercentageInput", !hasImage || isBusy);
3755
- this._setDisabled("rotateLeftDegreesInput", !hasImage || isBusy);
3756
- this._setDisabled("rotateRightDegreesInput", !hasImage || isBusy);
3757
- this._setDisabled("maskList", !hasImage || isBusy);
3758
- this._setDisabled("imageInput", isBusy);
3759
- this._setDisabled("uploadArea", isBusy);
3760
- }
3761
- /**
3762
- * Enables or disables a specific UI element (typically a button) by its key.
3763
- *
3764
- * @param {string} key - Key of the element in this.elements (e.g. 'zoomInButton').
3765
- * @param {boolean} disabled - If true, disables the element; otherwise enables.
3766
- * @private
3767
- */
3768
- _setDisabled(key, disabled) {
3769
- const element = this._getElement(key);
3770
- if (!element) return;
3771
- if ("disabled" in element) {
3772
- element.disabled = !!disabled;
3773
- return;
3774
- }
3775
- if (!this._elementOriginalPointerEvents) this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
3776
- if (!this._elementOriginalPointerEvents.has(key)) {
3777
- this._elementOriginalPointerEvents.set(key, element.style.pointerEvents || "");
3778
- }
3779
- if (disabled) {
3780
- element.setAttribute("aria-disabled", "true");
3781
- element.style.pointerEvents = "none";
3782
- } else {
3783
- element.removeAttribute("aria-disabled");
3784
- element.style.pointerEvents = this._elementOriginalPointerEvents.get(key) ?? "";
3785
- }
3786
- }
3787
- _isElementDisabled(element) {
3788
- if (!element) return false;
3789
- if ("disabled" in element) return !!element.disabled;
3790
- return element.getAttribute("aria-disabled") === "true";
3791
- }
3792
- /**
3793
- * Updates placeholder and canvas container visibility based on whether an image is loaded.
3794
- * @private
3795
- */
3796
- _updatePlaceholderStatus() {
3797
- if (!this.options.showPlaceholder) return;
3798
- this._setPlaceholderVisible(!this.originalImage);
3799
- }
3800
- /**
3801
- * Shows or hides the placeholder and canvas container.
3802
- *
3803
- * @param {boolean} show - If true, displays the placeholder; otherwise displays the canvas container.
3804
- * @private
3805
- */
3806
- _setPlaceholderVisible(show) {
3807
- if (this.placeholderElement) this._setElementVisible(this.placeholderElement, show);
3808
- const canvasVisibilityElement = this._getCanvasVisibilityElement();
3809
- if (canvasVisibilityElement && canvasVisibilityElement !== this.placeholderElement) {
3810
- this._setElementVisible(canvasVisibilityElement, !show);
3811
- }
3812
- }
3813
- _getCanvasVisibilityElement() {
3814
- const wrapperElement = this.canvas && this.canvas.wrapperEl ? this.canvas.wrapperEl : null;
3815
- if (this.containerElement && this.placeholderElement && (this.containerElement === this.placeholderElement || this.containerElement.contains(this.placeholderElement))) {
3816
- return wrapperElement || this.canvasElement;
3817
- }
3818
- return this.containerElement || wrapperElement || this.canvasElement;
3819
- }
3820
- /**
3821
- * Updates element visibility.
3822
- *
3823
- * @param {HTMLElement} element - Element whose visibility should be updated.
3824
- * @param {boolean} isVisible - If true, removes the hidden state.
3825
- * @returns {void}
3826
- * @private
3827
- */
3828
- _setElementVisible(element, isVisible) {
3829
- if (!element) return;
3830
- this._rememberElementVisibility(element);
3831
- element.hidden = !isVisible;
3832
- element.setAttribute("aria-hidden", isVisible ? "false" : "true");
3833
- if (element.classList) {
3834
- element.classList.toggle("d-none", !isVisible);
3835
- }
3836
- }
3837
- _rememberElementVisibility(element) {
3838
- if (!element || this._visibilityStateByElement.has(element)) return;
3839
- this._visibilityStateByElement.set(element, this._captureElementVisibility(element));
3840
- }
3841
- _captureElementVisibility(element) {
3842
- if (!element) return null;
3843
- return {
3844
- hidden: element.hidden,
3845
- ariaHidden: element.getAttribute("aria-hidden"),
3846
- className: element.className
3847
- };
3848
- }
3849
- _restoreElementVisibility(element, state) {
3850
- if (!element || !state) return;
3851
- element.hidden = !!state.hidden;
3852
- if (state.ariaHidden === null) {
3853
- element.removeAttribute("aria-hidden");
3854
- } else {
3855
- element.setAttribute("aria-hidden", state.ariaHidden);
3856
- }
3857
- element.className = state.className || "";
3858
- }
3859
- /**
3860
- * Cleans up and disposes of the canvas and related references.
3861
- * Call this method to free memory and remove canvas listeners when the editor is no longer needed.
3862
- * @public
3863
- */
3864
- dispose() {
3865
- this._disposed = true;
3866
- this._rejectActiveAnimations(new Error("Editor disposed during animation"));
3867
- if (this.animationQueue) {
3868
- this.animationQueue.cancelAll(new Error("Editor disposed"));
3869
- }
3870
- this._isLoading = false;
3871
- this._activeOperationName = null;
3872
- this._activeOperationToken = null;
3873
- try {
3874
- for (const [key, handlers] of Object.entries(this._handlersByElementKey || {})) {
3875
- const element = this._getElement(key);
3876
- if (!element) continue;
3877
- handlers.forEach((handlerRecord) => {
3878
- try {
3879
- element.removeEventListener(handlerRecord.eventName, handlerRecord.handler);
3880
- } catch (error) {
3881
- void error;
3882
- }
3883
- });
3884
- }
3885
- } catch (error) {
3886
- void error;
3887
- }
3888
- if (this._cropRect) this._removeCropRect();
3889
- if (this.containerElement && this._containerOriginalOverflow) {
3890
- try {
3891
- this._restoreContainerOverflowState();
3892
- } catch (error) {
3893
- void error;
3894
- }
3895
- }
3896
- if (this._visibilityStateByElement) {
3897
- try {
3898
- [this.placeholderElement, this._getCanvasVisibilityElement()].forEach((element) => {
3899
- const state = element ? this._visibilityStateByElement.get(element) : null;
3900
- if (state) this._restoreElementVisibility(element, state);
3901
- });
3902
- } catch (error) {
3903
- void error;
3904
- }
3905
- }
3906
- if (this.canvasElement && this._canvasElementOriginalStyle) {
3907
- try {
3908
- this.canvasElement.style.display = this._canvasElementOriginalStyle.display;
3909
- this.canvasElement.style.width = this._canvasElementOriginalStyle.width;
3910
- this.canvasElement.style.height = this._canvasElementOriginalStyle.height;
3911
- this.canvasElement.style.maxWidth = this._canvasElementOriginalStyle.maxWidth;
3912
- } catch (error) {
3913
- void error;
3914
- }
3915
- }
3916
- if (this.canvas) {
3917
- try {
3918
- this.canvas.getObjects().forEach((object) => {
3919
- if (object && object.maskId) this._cleanupMaskEvents(object);
3920
- });
3921
- } catch (error) {
3922
- void error;
3923
- }
3924
- try {
3925
- this.canvas.dispose();
3926
- } catch (error) {
3927
- void error;
3928
- }
3929
- this.canvas = null;
3930
- this.canvasElement = null;
3931
- this.isImageLoadedToCanvas = false;
3932
- }
3933
- this._handlersByElementKey = {};
3934
- this._elementCache = {};
3935
- this._elementOriginalPointerEvents = /* @__PURE__ */ new Map();
3936
- this._clearMaskPlacementMemory();
3937
- this.originalImage = null;
3938
- this.baseImageScale = 1;
3939
- this.currentScale = 1;
3940
- this.currentRotation = 0;
3941
- this.isAnimating = false;
3942
- this._isLoading = false;
3943
- this._cropMode = false;
3944
- this._cropRect = null;
3945
- this._cropHandlers = [];
3946
- this._cropPrevEvented = null;
3947
- this._prevSelectionSetting = void 0;
3948
- this._lastContainerViewportSize = null;
3949
- this._initialized = false;
3950
- }
3951
- };
3952
- var AnimationQueue = class {
3953
- /**
3954
- * Creates an empty animation queue.
3955
- */
3956
- constructor() {
3957
- this.animationTasks = [];
3958
- this.isRunning = false;
3959
- this.currentTask = null;
3960
- this._generation = 0;
3961
- }
3962
- /**
3963
- * Adds an animation function to the queue.
3964
- *
3965
- * @param {AnimationTaskCallback} animationFn - Function that returns a value, Promise, or awaitable animation result.
3966
- * @returns {Promise<unknown>} Resolves or rejects with the queued animation result.
3967
- */
3968
- async add(animationFn) {
3969
- return new Promise((resolve, reject) => {
3970
- this.animationTasks.push({ animationFn, resolve, reject, isSettled: false });
3971
- if (!this.isRunning) {
3972
- this._drainQueue();
3973
- }
3974
- });
3975
- }
3976
- isBusy() {
3977
- return this.isRunning || this.animationTasks.length > 0;
3978
- }
3979
- cancelAll(reason = new Error("Animation queue cancelled")) {
3980
- this._generation += 1;
3981
- const cancellationError = reason instanceof Error ? reason : new Error(String(reason));
3982
- const tasks = [
3983
- ...this.currentTask ? [this.currentTask] : [],
3984
- ...this.animationTasks.splice(0)
3985
- ];
3986
- tasks.forEach((task) => {
3987
- if (!task || task.isSettled) return;
3988
- task.isSettled = true;
3989
- task.reject(cancellationError);
3990
- });
3991
- this.isRunning = false;
3992
- this.currentTask = null;
3993
- }
3994
- /**
3995
- * Runs queued animation tasks sequentially until the queue is empty.
3996
- *
3997
- * @private
3998
- * @returns {Promise<void>}
3999
- */
4000
- async _drainQueue() {
4001
- if (this.isRunning) return;
4002
- const generation = this._generation;
4003
- this.isRunning = true;
4004
- try {
4005
- while (this.animationTasks.length > 0 && generation === this._generation) {
4006
- const task = this.animationTasks.shift();
4007
- this.currentTask = task;
4008
- try {
4009
- const result = await task.animationFn();
4010
- if (generation === this._generation && !task.isSettled) {
4011
- task.isSettled = true;
4012
- task.resolve(result);
4013
- }
4014
- } catch (error) {
4015
- if (generation === this._generation && !task.isSettled) {
4016
- task.isSettled = true;
4017
- task.reject(error);
4018
- }
4019
- } finally {
4020
- if (this.currentTask === task) this.currentTask = null;
4021
- }
4022
- }
4023
- } finally {
4024
- if (generation === this._generation) {
4025
- this.isRunning = false;
4026
- this.currentTask = null;
4027
- }
4028
- }
4029
- }
4030
- };
4031
- var Command = class {
4032
- /**
4033
- * @param {HistoryTaskCallback} execute - Function that performs the action.
4034
- * @param {HistoryTaskCallback} undo - Function that reverts the action.
4035
- */
4036
- constructor(execute, undo) {
4037
- this.execute = execute;
4038
- this.undo = undo;
4039
- }
4040
- };
4041
- var HistoryManager = class {
4042
- /**
4043
- * @param {number} [maxSize=50] - Maximum number of commands to keep in history.
4044
- */
4045
- constructor(maxSize = 50) {
4046
- this.history = [];
4047
- this.currentIndex = -1;
4048
- this.maxSize = maxSize;
4049
- this.pending = Promise.resolve();
4050
- }
4051
- /**
4052
- * Queues a history task after the previously queued undo/redo task completes.
4053
- *
4054
- * @param {HistoryTaskCallback} task - Task to run after earlier history work settles.
4055
- * @returns {Promise<void>} Resolves or rejects with the queued task result.
4056
- * @private
4057
- */
4058
- enqueue(task) {
4059
- const nextTask = this.pending.then(() => Promise.resolve().then(task));
4060
- this.pending = nextTask.catch(() => void 0);
4061
- return nextTask;
4062
- }
4063
- /**
4064
- * Executes a new command and pushes it onto the history stack.
4065
- * Truncates any "future" history when branching.
4066
- *
4067
- * @param {Command} command The command to execute.
4068
- * @returns {void}
4069
- */
4070
- execute(command) {
4071
- const result = command.execute();
4072
- if (result && typeof result.then === "function") {
4073
- return this.enqueue(() => Promise.resolve(result).then(() => {
4074
- this.push(command);
4075
- }));
4076
- }
4077
- this.push(command);
4078
- return result;
4079
- }
4080
- /**
4081
- * Pushes an already-applied command onto the history stack.
4082
- * Truncates any "future" history when branching.
4083
- *
4084
- * @param {Command} command The command to push.
4085
- * @returns {void}
4086
- */
4087
- push(command) {
4088
- if (this.currentIndex < this.history.length - 1) {
4089
- this.history = this.history.slice(0, this.currentIndex + 1);
4090
- }
4091
- this.history.push(command);
4092
- if (this.history.length > this.maxSize) {
4093
- this.history.shift();
4094
- }
4095
- this.currentIndex = this.history.length - 1;
4096
- }
4097
- /**
4098
- * Checks whether an undo operation is possible.
4099
- *
4100
- * @returns {boolean} True if undo can be performed.
4101
- */
4102
- canUndo() {
4103
- return this.currentIndex >= 0;
4104
- }
4105
- /**
4106
- * Checks whether a redo operation is possible.
4107
- *
4108
- * @returns {boolean} True if redo can be performed.
4109
- */
4110
- canRedo() {
4111
- return this.currentIndex < this.history.length - 1;
4112
- }
4113
- /**
4114
- * Undoes the last executed command if possible.
4115
- *
4116
- * @returns {Promise<void>} Resolves after the undo task completes.
4117
- */
4118
- undo(options = {}) {
4119
- return this.enqueue(async () => {
4120
- if (this.currentIndex >= 0) {
4121
- const index = this.currentIndex;
4122
- await this.history[index].undo(options);
4123
- this.currentIndex = index - 1;
4124
- }
4125
- });
4126
- }
4127
- /**
4128
- * Redoes the next command in history if possible.
4129
- *
4130
- * @returns {Promise<void>} Resolves after the redo task completes.
4131
- */
4132
- redo(options = {}) {
4133
- return this.enqueue(async () => {
4134
- if (this.currentIndex < this.history.length - 1) {
4135
- const index = this.currentIndex + 1;
4136
- await this.history[index].execute(options);
4137
- this.currentIndex = index;
4138
- }
4139
- });
4140
- }
4141
- };
4142
- var image_editor_default = ImageEditor;
4143
-
4144
- // src/browser.js
4145
- var scope = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : null;
4146
- setFabric(scope && scope.fabric);
4147
- if (scope) {
4148
- scope.ImageEditor = image_editor_default;
4149
- }
4150
- })();
4151
- //# sourceMappingURL=image-editor.js.map