@bensitu/image-editor 1.1.2 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2001 @@
1
+ (() => {
2
+ // src/image-editor.js
3
+ /**
4
+ * @file image-editor.js
5
+ * @module image-editor
6
+ * @version 1.2.1
7
+ * @author Ben Situ
8
+ * @license MIT
9
+ * @description Lightweight canvas-based image editor with masking/transform/export support.
10
+ *
11
+ * This source file is free software, available under the MIT license.
12
+ * It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
13
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
+ * See the license files for details.
15
+ */
16
+ var fabric = null;
17
+ function getGlobalScope() {
18
+ if (typeof globalThis !== "undefined")
19
+ return globalThis;
20
+ if (typeof self !== "undefined")
21
+ return self;
22
+ if (typeof window !== "undefined")
23
+ return window;
24
+ return null;
25
+ }
26
+ function getGlobalFabric() {
27
+ const scope2 = getGlobalScope();
28
+ return scope2 && scope2.fabric ? scope2.fabric : null;
29
+ }
30
+ function setFabric(fabricInstance) {
31
+ fabric = fabricInstance || getGlobalFabric();
32
+ return fabric;
33
+ }
34
+ function ensureFabric() {
35
+ if (!fabric)
36
+ setFabric();
37
+ return fabric;
38
+ }
39
+ var ImageEditor = class {
40
+ constructor(options = {}) {
41
+ const defaultLabel = {
42
+ getText: (mask) => mask.maskName,
43
+ textOptions: {
44
+ fontSize: 12,
45
+ fill: "#fff",
46
+ backgroundColor: "rgba(0,0,0,0.7)",
47
+ padding: 2,
48
+ fontFamily: "monospace",
49
+ fontWeight: "bold",
50
+ selectable: false,
51
+ evented: false,
52
+ originX: "left",
53
+ originY: "top"
54
+ }
55
+ };
56
+ const defaultCrop = {
57
+ minWidth: 100,
58
+ minHeight: 100,
59
+ padding: 10,
60
+ hideMasksDuringCrop: true,
61
+ preserveMasksAfterCrop: false,
62
+ allowRotationOfCropRect: false
63
+ };
64
+ const userLabel = options.label || {};
65
+ const userCrop = options.crop || {};
66
+ this.options = {
67
+ canvasWidth: 800,
68
+ canvasHeight: 600,
69
+ backgroundColor: "transparent",
70
+ animationDuration: 300,
71
+ minScale: 0.1,
72
+ maxScale: 5,
73
+ scaleStep: 0.05,
74
+ rotationStep: 90,
75
+ expandCanvasToImage: true,
76
+ fitImageToCanvas: false,
77
+ coverImageToCanvas: false,
78
+ downsampleOnLoad: true,
79
+ downsampleMaxWidth: 4e3,
80
+ downsampleMaxHeight: 3e3,
81
+ downsampleQuality: 0.92,
82
+ exportMultiplier: 1,
83
+ exportImageAreaByDefault: true,
84
+ defaultMaskWidth: 50,
85
+ defaultMaskHeight: 80,
86
+ maskRotatable: false,
87
+ maskLabelOnSelect: true,
88
+ maskLabelOffset: 3,
89
+ maskName: "mask",
90
+ groupSelection: false,
91
+ showPlaceholder: true,
92
+ initialImageBase64: null,
93
+ // Provide a base64 'data:image/...' string here if you want auto-load
94
+ defaultDownloadFileName: "edited_image.jpg",
95
+ onError: null,
96
+ onWarning: null,
97
+ ...options,
98
+ label: {
99
+ ...defaultLabel,
100
+ ...userLabel,
101
+ textOptions: {
102
+ ...defaultLabel.textOptions,
103
+ ...userLabel.textOptions || {}
104
+ }
105
+ },
106
+ crop: {
107
+ ...defaultCrop,
108
+ ...userCrop
109
+ }
110
+ };
111
+ this._fabricLoaded = !!ensureFabric();
112
+ if (!this._fabricLoaded) {
113
+ this._reportError("fabric.js is not loaded. Please include fabric.js first. Initialization will be aborted.");
114
+ }
115
+ this.canvas = null;
116
+ this.canvasEl = null;
117
+ this.containerEl = null;
118
+ this.placeholderEl = null;
119
+ this.originalImage = null;
120
+ this.baseImageScale = 1;
121
+ this.currentScale = 1;
122
+ this.currentRotation = 0;
123
+ this.maskCounter = 0;
124
+ this.isAnimating = false;
125
+ this.elements = {};
126
+ this.isImageLoadedToCanvas = false;
127
+ this.maxHistorySize = 50;
128
+ this._boundHandlers = {};
129
+ this._lastMask = null;
130
+ this._lastMaskInitialLeft = null;
131
+ this._lastMaskInitialTop = null;
132
+ this._lastMaskInitialWidth = null;
133
+ this._cropMode = false;
134
+ this._cropRect = null;
135
+ this._cropHandlers = [];
136
+ this.onImageLoaded = typeof options.onImageLoaded === "function" ? options.onImageLoaded : null;
137
+ this.animQueue = new AnimationQueue();
138
+ this.historyManager = new HistoryManager(this.maxHistorySize);
139
+ }
140
+ /**
141
+ * Initializes the editor, binds to DOM elements, sets up event handlers,
142
+ * and (optionally) loads an initial image.
143
+ * Use this method to set up the editor UI before interacting with it.
144
+ *
145
+ * @param {Object} [idMap={}] - Optional mapping from logical element names to actual DOM element IDs.
146
+ * Supported keys include: canvas, canvasContainer, imgPlaceholder, scaleRate, rotationLeftInput, rotationRightInput,
147
+ * rotateLeftBtn, rotateRightBtn, addMaskBtn, removeMaskBtn, removeAllMasksBtn, mergeBtn, downloadBtn, maskList,
148
+ * zoomInBtn, zoomOutBtn, resetBtn, imageInput. Unknown keys are ignored.
149
+ *
150
+ * @returns {void}
151
+ *
152
+ * @public
153
+ *
154
+ * @example
155
+ * editor.init({
156
+ * canvas: 'myFabricCanvasId',
157
+ * downloadBtn: 'myDownloadButtonId'
158
+ * });
159
+ */
160
+ init(idMap = {}) {
161
+ if (!this._fabricLoaded)
162
+ return;
163
+ const defaults = {
164
+ canvas: "fabricCanvas",
165
+ canvasContainer: null,
166
+ // Pass an ID here if you have a scrollable viewport container
167
+ imgPlaceholder: "imgPlaceholder",
168
+ scaleRate: "scaleRate",
169
+ rotationLeftInput: "rotationLeftInput",
170
+ rotationRightInput: "rotationRightInput",
171
+ rotateLeftBtn: "rotateLeftBtn",
172
+ rotateRightBtn: "rotateRightBtn",
173
+ addMaskBtn: "addMaskBtn",
174
+ removeMaskBtn: "removeMaskBtn",
175
+ removeAllMasksBtn: "removeAllMasksBtn",
176
+ mergeBtn: "mergeBtn",
177
+ downloadBtn: "downloadBtn",
178
+ maskList: "maskList",
179
+ zoomInBtn: "zoomInBtn",
180
+ zoomOutBtn: "zoomOutBtn",
181
+ resetBtn: "resetBtn",
182
+ undoBtn: "undoBtn",
183
+ redoBtn: "redoBtn",
184
+ imageInput: "imageInput",
185
+ cropBtn: "cropBtn",
186
+ applyCropBtn: "applyCropBtn",
187
+ cancelCropBtn: "cancelCropBtn"
188
+ };
189
+ this.elements = { ...defaults, ...idMap };
190
+ this._initCanvas();
191
+ this._bindEvents();
192
+ this._updateInputs();
193
+ this._updateMaskList();
194
+ this._updateUI();
195
+ if (this.options.initialImageBase64) {
196
+ this.loadImage(this.options.initialImageBase64);
197
+ } else {
198
+ this._updatePlaceholderStatus();
199
+ }
200
+ }
201
+ _reportError(message, error = null) {
202
+ const handler = this.options && this.options.onError;
203
+ if (typeof handler !== "function")
204
+ return;
205
+ try {
206
+ handler(error, message);
207
+ } catch {
208
+ }
209
+ }
210
+ _reportWarning(message, error = null) {
211
+ const handler = this.options && this.options.onWarning;
212
+ if (typeof handler !== "function")
213
+ return;
214
+ try {
215
+ handler(error, message);
216
+ } catch {
217
+ }
218
+ }
219
+ /**
220
+ * Canvas setup helpers
221
+ * @private
222
+ */
223
+ _initCanvas() {
224
+ const canvasEl = document.getElementById(this.elements.canvas);
225
+ if (!canvasEl)
226
+ throw new Error("Canvas is not found: " + this.elements.canvas);
227
+ this.canvasEl = canvasEl;
228
+ if (this.elements.canvasContainer) {
229
+ const ce = document.getElementById(this.elements.canvasContainer);
230
+ this.containerEl = ce || canvasEl.parentElement;
231
+ } else {
232
+ this.containerEl = canvasEl.parentElement;
233
+ }
234
+ this.placeholderEl = document.getElementById(this.elements.imgPlaceholder) || null;
235
+ let initialW = this.options.canvasWidth;
236
+ let initialH = this.options.canvasHeight;
237
+ if (this.containerEl) {
238
+ const cw = Math.floor(this.containerEl.clientWidth);
239
+ const ch = Math.floor(this.containerEl.clientHeight);
240
+ if (cw > 0 && ch > 0) {
241
+ initialW = cw;
242
+ initialH = ch;
243
+ }
244
+ }
245
+ this.canvas = new fabric.Canvas(canvasEl, {
246
+ width: initialW,
247
+ height: initialH,
248
+ backgroundColor: this.options.backgroundColor,
249
+ selection: this.options.groupSelection,
250
+ preserveObjectStacking: true
251
+ });
252
+ this.canvas.on("selection:created", (e) => this._onSelectionChanged(e.selected));
253
+ this.canvas.on("selection:updated", (e) => this._onSelectionChanged(e.selected));
254
+ this.canvas.on("selection:cleared", () => this._onSelectionChanged([]));
255
+ this.canvas.on("object:moving", (e) => {
256
+ if (e.target && e.target.maskId)
257
+ this._syncMaskLabel(e.target);
258
+ });
259
+ this.canvas.on("object:scaling", (e) => {
260
+ if (e.target && e.target.maskId)
261
+ this._syncMaskLabel(e.target);
262
+ });
263
+ this.canvas.on("object:rotating", (e) => {
264
+ if (e.target && e.target.maskId)
265
+ this._syncMaskLabel(e.target);
266
+ });
267
+ this.canvas.on("object:modified", (e) => {
268
+ if (e.target && e.target.maskId)
269
+ this._syncMaskLabel(e.target);
270
+ });
271
+ this.canvasEl.style.display = "block";
272
+ }
273
+ /**
274
+ * DOM / UI bindings
275
+ * @private
276
+ */
277
+ _bindEvents() {
278
+ this._bindIfExists("uploadArea", "click", () => document.getElementById(this.elements.imageInput)?.click());
279
+ const inputEl = document.getElementById(this.elements.imageInput);
280
+ if (inputEl) {
281
+ inputEl.addEventListener("change", (e) => {
282
+ const f = e.target.files && e.target.files[0];
283
+ if (f)
284
+ this._loadImageFile(f);
285
+ });
286
+ }
287
+ this._bindIfExists("zoomInBtn", "click", () => this.scaleImage(this.currentScale + this.options.scaleStep));
288
+ this._bindIfExists("zoomOutBtn", "click", () => this.scaleImage(this.currentScale - this.options.scaleStep));
289
+ this._bindIfExists("resetBtn", "click", () => {
290
+ this.reset();
291
+ });
292
+ this._bindIfExists("addMaskBtn", "click", () => this.addMask());
293
+ this._bindIfExists("removeMaskBtn", "click", () => this.removeSelectedMask());
294
+ this._bindIfExists("removeAllMasksBtn", "click", () => this.removeAllMasks());
295
+ this._bindIfExists("mergeBtn", "click", () => this.merge());
296
+ this._bindIfExists("downloadBtn", "click", () => this.downloadImage());
297
+ this._bindIfExists("undoBtn", "click", () => this.undo());
298
+ this._bindIfExists("redoBtn", "click", () => this.redo());
299
+ const rotLeftBtn = document.getElementById(this.elements.rotateLeftBtn);
300
+ const rotRightBtn = document.getElementById(this.elements.rotateRightBtn);
301
+ if (rotLeftBtn)
302
+ rotLeftBtn.addEventListener("click", () => {
303
+ const el = document.getElementById(this.elements.rotationLeftInput);
304
+ let step = this.options.rotationStep;
305
+ if (el) {
306
+ const p = parseFloat(el.value);
307
+ if (!isNaN(p))
308
+ step = p;
309
+ }
310
+ this.rotateImage(this.currentRotation - step);
311
+ });
312
+ if (rotRightBtn)
313
+ rotRightBtn.addEventListener("click", () => {
314
+ const el = document.getElementById(this.elements.rotationRightInput);
315
+ let step = this.options.rotationStep;
316
+ if (el) {
317
+ const p = parseFloat(el.value);
318
+ if (!isNaN(p))
319
+ step = p;
320
+ }
321
+ this.rotateImage(this.currentRotation + step);
322
+ });
323
+ this._bindIfExists("cropBtn", "click", () => this.enterCropMode());
324
+ this._bindIfExists("applyCropBtn", "click", () => {
325
+ this.applyCrop().catch((e) => this._reportError("applyCrop failed", e));
326
+ });
327
+ this._bindIfExists("cancelCropBtn", "click", () => this.cancelCrop());
328
+ }
329
+ /**
330
+ * Event binding element check
331
+ *
332
+ * @param {*} event
333
+ * @param {*} handler
334
+ * @param {*} key
335
+ * @private
336
+ */
337
+ _bindIfExists(key, event, handler) {
338
+ const el = document.getElementById(this.elements[key]);
339
+ if (el) {
340
+ el.addEventListener(event, handler);
341
+ this._boundHandlers = this._boundHandlers || {};
342
+ if (!this._boundHandlers[key])
343
+ this._boundHandlers[key] = [];
344
+ this._boundHandlers[key].push({ event, handler });
345
+ }
346
+ }
347
+ /**
348
+ * Image loading helpers
349
+ *
350
+ * @param {File} file
351
+ * @private
352
+ */
353
+ _loadImageFile(file) {
354
+ if (!file || !file.type.startsWith("image/"))
355
+ return;
356
+ const reader = new FileReader();
357
+ reader.onload = (e) => this.loadImage(e.target.result);
358
+ reader.onerror = (e) => {
359
+ this._reportError("Image file could not be read", e);
360
+ };
361
+ reader.readAsDataURL(file);
362
+ }
363
+ /**
364
+ * Load a base64 encoded image string into fabric.
365
+ * @async
366
+ * @param {String} base64
367
+ */
368
+ async loadImage(base64) {
369
+ if (!this._fabricLoaded)
370
+ return;
371
+ if (!this.canvas)
372
+ return;
373
+ if (!base64 || typeof base64 !== "string" || !base64.startsWith("data:image/"))
374
+ return;
375
+ this._setPlaceholderVisible(false);
376
+ const imgEl = await this._createImageElement(base64);
377
+ let loadSrc = base64;
378
+ if (this.options.downsampleOnLoad) {
379
+ const needResize = imgEl.naturalWidth > this.options.downsampleMaxWidth || imgEl.naturalHeight > this.options.downsampleMaxHeight;
380
+ if (needResize) {
381
+ const ratio = Math.min(
382
+ this.options.downsampleMaxWidth / imgEl.naturalWidth,
383
+ this.options.downsampleMaxHeight / imgEl.naturalHeight
384
+ );
385
+ const tw = Math.round(imgEl.naturalWidth * ratio);
386
+ const th = Math.round(imgEl.naturalHeight * ratio);
387
+ loadSrc = this._resampleImageToDataURL(imgEl, tw, th, this.options.downsampleQuality);
388
+ }
389
+ }
390
+ return new Promise((resolve, reject) => {
391
+ fabric.Image.fromURL(loadSrc, (fimg) => {
392
+ try {
393
+ if (!fimg)
394
+ throw new Error("Image could not be loaded");
395
+ this.canvas.discardActiveObject();
396
+ this._hideAllMaskLabels();
397
+ this.canvas.clear();
398
+ this.canvas.setBackgroundColor(this.options.backgroundColor, this.canvas.renderAll.bind(this.canvas));
399
+ fimg.set({ originX: "left", originY: "top", selectable: false, evented: false });
400
+ const imgW = fimg.width;
401
+ const imgH = fimg.height;
402
+ const minW = this.containerEl ? Math.floor(this.containerEl.clientWidth || this.options.canvasWidth) : this.options.canvasWidth;
403
+ const minH = this.containerEl ? Math.floor(this.containerEl.clientHeight || this.options.canvasHeight) : this.options.canvasHeight;
404
+ if (this.options.fitImageToCanvas) {
405
+ const cw = Math.max(1, Math.min(this.options.canvasWidth, minW) - 1);
406
+ const ch = Math.max(1, Math.min(this.options.canvasHeight, minH) - 1);
407
+ this._setCanvasSizeInt(cw, ch);
408
+ const fitScale = Math.min(cw / imgW, ch / imgH, 1);
409
+ fimg.set({ left: 0, top: 0 });
410
+ fimg.scale(fitScale);
411
+ this.baseImageScale = fimg.scaleX || 1;
412
+ } else if (this.options.coverImageToCanvas) {
413
+ const cw = Math.max(this.options.canvasWidth, minW);
414
+ const ch = Math.max(this.options.canvasHeight, minH);
415
+ this._setCanvasSizeInt(cw, ch);
416
+ const coverScale = Math.min(1, Math.max(cw / imgW, ch / imgH));
417
+ fimg.set({ left: 0, top: 0 });
418
+ fimg.scale(coverScale);
419
+ this.baseImageScale = fimg.scaleX || 1;
420
+ } else if (this.options.expandCanvasToImage) {
421
+ const cw = Math.max(minW, Math.floor(imgW));
422
+ const ch = Math.max(minH, Math.floor(imgH));
423
+ this._setCanvasSizeInt(cw, ch);
424
+ fimg.set({ left: 0, top: 0 });
425
+ fimg.scale(1);
426
+ this.baseImageScale = 1;
427
+ } else {
428
+ const cw = Math.max(this.options.canvasWidth, minW);
429
+ const ch = Math.max(this.options.canvasHeight, minH);
430
+ this._setCanvasSizeInt(cw, ch);
431
+ const fitScale = Math.min(cw / imgW, ch / imgH, 1);
432
+ fimg.set({ left: 0, top: 0 });
433
+ fimg.scale(fitScale);
434
+ this.baseImageScale = fimg.scaleX || 1;
435
+ }
436
+ this.originalImage = fimg;
437
+ this.canvas.add(fimg);
438
+ this.canvas.sendToBack(fimg);
439
+ this._lastMask = null;
440
+ this._lastMaskInitialLeft = null;
441
+ this._lastMaskInitialTop = null;
442
+ this._lastMaskInitialWidth = null;
443
+ this.maskCounter = 0;
444
+ this.currentScale = 1;
445
+ this.currentRotation = 0;
446
+ this._updateInputs();
447
+ this._updateMaskList();
448
+ this.isImageLoadedToCanvas = true;
449
+ this._updateUI();
450
+ this.canvas.renderAll();
451
+ if (typeof this.onImageLoaded === "function") {
452
+ this.onImageLoaded();
453
+ }
454
+ resolve();
455
+ } catch (err) {
456
+ reject(err);
457
+ }
458
+ }, { crossOrigin: "anonymous" });
459
+ });
460
+ }
461
+ /**
462
+ * Checks whether there is a loaded image on the current canvas.
463
+ * @returns {boolean} true if loaded, false if not
464
+ */
465
+ isImageLoaded() {
466
+ const fabricInstance = ensureFabric();
467
+ return !!(this.originalImage && fabricInstance && this.originalImage instanceof fabricInstance.Image && this.originalImage.width > 0 && this.originalImage.height > 0);
468
+ }
469
+ /**
470
+ * Creates an HTMLImageElement from a given data URL.
471
+ *
472
+ * @param {string} dataURL - A data URL representing the image (e.g., "data:image/png;base64,...").
473
+ * @returns {Promise<HTMLImageElement>} A promise that resolves to the created image element when loaded, or rejects on error.
474
+ * @private
475
+ */
476
+ _createImageElement(dataURL) {
477
+ return new Promise((res, rej) => {
478
+ const img = new Image();
479
+ img.onload = () => {
480
+ img.onload = null;
481
+ img.onerror = null;
482
+ res(img);
483
+ };
484
+ img.onerror = (e) => {
485
+ img.onload = null;
486
+ img.onerror = null;
487
+ rej(e);
488
+ };
489
+ img.src = dataURL;
490
+ });
491
+ }
492
+ /**
493
+ * Resamples the given image element to a new width and height and returns the result as a JPEG data URL.
494
+ *
495
+ * @param {HTMLImageElement} imgEl - The image element to resample.
496
+ * @param {number} w - Target width (in pixels) for the resampled image.
497
+ * @param {number} h - Target height (in pixels) for the resampled image.
498
+ * @param {number} [quality=0.92] - JPEG image quality between 0 and 1 (optional, default 0.92).
499
+ * @returns {string} A data URL representing the resampled image as JPEG.
500
+ * @private
501
+ */
502
+ _resampleImageToDataURL(imgEl, w, h, quality = 0.92) {
503
+ const oc = document.createElement("canvas");
504
+ oc.width = w;
505
+ oc.height = h;
506
+ const ctx = oc.getContext("2d");
507
+ ctx.drawImage(imgEl, 0, 0, imgEl.naturalWidth, imgEl.naturalHeight, 0, 0, w, h);
508
+ return oc.toDataURL("image/jpeg", quality);
509
+ }
510
+ /**
511
+ * Sets canvas size to integer width and height values to prevent scrollbars due to sub-pixel rendering.
512
+ * Also updates the corresponding style attributes.
513
+ *
514
+ * @param {number} w - Canvas width (in pixels).
515
+ * @param {number} h - Canvas height (in pixels).
516
+ * @private
517
+ */
518
+ _setCanvasSizeInt(w, h) {
519
+ const iw = Math.max(1, Math.round(Number(w) || 1));
520
+ const ih = Math.max(1, Math.round(Number(h) || 1));
521
+ this.canvas.setWidth(iw);
522
+ this.canvas.setHeight(ih);
523
+ if (typeof this.canvas.calcOffset === "function")
524
+ this.canvas.calcOffset();
525
+ if (this.canvasEl) {
526
+ this.canvasEl.style.width = iw + "px";
527
+ this.canvasEl.style.height = ih + "px";
528
+ this.canvasEl.style.maxWidth = "none";
529
+ }
530
+ }
531
+ /**
532
+ * Gets the top-left corner coordinates of the given object.
533
+ * Used for geometry calculations (e.g., scale, rotate).
534
+ *
535
+ * @param {Object} obj - The object for which to get the top-left coordinates. Should support setCoords and getCoords/getBoundingRect methods.
536
+ * @returns {{x: number, y: number}} The top-left corner point as an object with x and y properties.
537
+ * @private
538
+ */
539
+ _getObjectTopLeftPoint(obj) {
540
+ if (!obj)
541
+ return { x: 0, y: 0 };
542
+ obj.setCoords();
543
+ const coords = typeof obj.getCoords === "function" ? obj.getCoords() : null;
544
+ if (coords && coords.length)
545
+ return coords[0];
546
+ const br = obj.getBoundingRect(true, true);
547
+ return { x: br.left, y: br.top };
548
+ }
549
+ /**
550
+ * Sets the object's origin at the specified origin point, keeping a reference point fixed in position.
551
+ *
552
+ * @param {Object} obj - The object to modify. Should support set, setPositionByOrigin, and setCoords.
553
+ * @param {string} originX - The new originX ("left", "center", "right", etc.).
554
+ * @param {string} originY - The new originY ("top", "center", "bottom", etc.).
555
+ * @param {{x: number, y: number}} refPoint - The point to keep fixed while setting the new origins.
556
+ * @private
557
+ */
558
+ _setObjectOriginKeepingPosition(obj, originX, originY, refPoint) {
559
+ if (!obj || !refPoint || !obj.setPositionByOrigin)
560
+ return;
561
+ obj.set({ originX, originY });
562
+ obj.setPositionByOrigin(refPoint, originX, originY);
563
+ obj.setCoords();
564
+ }
565
+ /**
566
+ * Moves the object so its bounding box aligns with the canvas's top-left corner (0, 0).
567
+ *
568
+ * @param {Object} obj - The object to align.
569
+ * @private
570
+ */
571
+ _alignObjectBoundingBoxToCanvasTopLeft(obj) {
572
+ if (!obj)
573
+ return;
574
+ obj.setCoords();
575
+ const br = obj.getBoundingRect(true, true);
576
+ const dx = br.left;
577
+ const dy = br.top;
578
+ obj.set({ left: (obj.left || 0) - dx, top: (obj.top || 0) - dy });
579
+ obj.setCoords();
580
+ this.canvas.renderAll();
581
+ }
582
+ /**
583
+ * Updates the canvas size to match the bounding box of the original image,
584
+ * ensuring that the canvas is always at least as large as its container.
585
+ * @private
586
+ */
587
+ _updateCanvasSizeToImageBounds() {
588
+ if (!this.originalImage)
589
+ return;
590
+ this.originalImage.setCoords();
591
+ const br = this.originalImage.getBoundingRect(true, true);
592
+ const containerW = this.containerEl ? Math.ceil(this.containerEl.clientWidth || 0) : 0;
593
+ const containerH = this.containerEl ? Math.ceil(this.containerEl.clientHeight || 0) : 0;
594
+ if (containerW > 0 && containerH > 0 && br.width <= containerW && br.height <= containerH) {
595
+ this._setCanvasSizeInt(containerW, containerH);
596
+ return;
597
+ }
598
+ const newW = Math.max(containerW || 0, Math.floor(br.width));
599
+ const newH = Math.max(containerH || 0, Math.floor(br.height));
600
+ this._setCanvasSizeInt(newW, newH);
601
+ }
602
+ /**
603
+ * Scales the original image by a given factor, with animation.
604
+ * Returns a promise that resolves when the scale animation is complete.
605
+ * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
606
+ * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
607
+ * @public
608
+ */
609
+ scaleImage(factor) {
610
+ return this.animQueue.add(() => this._scaleImageImpl(factor));
611
+ }
612
+ /**
613
+ * Scales the original image by a given factor, with animation.
614
+ * Returns a promise that resolves when the scale animation is complete.
615
+ * @param {number} factor - The scaling factor (will be clamped between `options.minScale` and `options.maxScale`).
616
+ * @returns {Promise<void>} Promise that resolves once the scaling animation finishes.
617
+ * @private
618
+ */
619
+ _scaleImageImpl(factor) {
620
+ if (!this.originalImage)
621
+ return Promise.resolve();
622
+ if (this.isAnimating)
623
+ return Promise.resolve();
624
+ factor = Math.max(this.options.minScale, Math.min(this.options.maxScale, factor));
625
+ this.currentScale = factor;
626
+ this.isAnimating = true;
627
+ this._updateUI();
628
+ const targetAbs = this.baseImageScale * factor;
629
+ const topLeft = this._getObjectTopLeftPoint(this.originalImage);
630
+ this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", topLeft);
631
+ const p1 = new Promise((res) => {
632
+ this.originalImage.animate("scaleX", targetAbs, {
633
+ duration: this.options.animationDuration,
634
+ onChange: this.canvas.renderAll.bind(this.canvas),
635
+ onComplete: res
636
+ });
637
+ });
638
+ const p2 = new Promise((res) => {
639
+ this.originalImage.animate("scaleY", targetAbs, {
640
+ duration: this.options.animationDuration,
641
+ onChange: this.canvas.renderAll.bind(this.canvas),
642
+ onComplete: res
643
+ });
644
+ });
645
+ return Promise.all([p1, p2]).then(() => {
646
+ this.originalImage.set({ scaleX: targetAbs, scaleY: targetAbs });
647
+ this.originalImage.setCoords();
648
+ if (this.options.expandCanvasToImage)
649
+ this._updateCanvasSizeToImageBounds();
650
+ this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
651
+ this.canvas.getObjects().forEach((o) => {
652
+ if (o.maskId)
653
+ this._syncMaskLabel(o);
654
+ });
655
+ this.isAnimating = false;
656
+ this._updateInputs();
657
+ this._updateUI();
658
+ this.saveState();
659
+ }).catch(() => {
660
+ this.isAnimating = false;
661
+ this._updateUI();
662
+ });
663
+ }
664
+ /**
665
+ * Rotates the original image by a given number of degrees, with animation.
666
+ * Returns a promise that resolves when the rotation animation is complete.
667
+ * @param {number} degrees - The angle in degrees to rotate the image.
668
+ * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
669
+ * @public
670
+ */
671
+ rotateImage(deg) {
672
+ return this.animQueue.add(() => this._rotateImageImpl(deg));
673
+ }
674
+ /**
675
+ * Rotates the original image by a given number of degrees, with animation.
676
+ * Returns a promise that resolves when the rotation animation is complete.
677
+ * @param {number} degrees - The angle in degrees to rotate the image.
678
+ * @returns {Promise<void>} Promise that resolves once the rotation animation finishes.
679
+ * @private
680
+ */
681
+ _rotateImageImpl(degrees) {
682
+ if (!this.originalImage)
683
+ return Promise.resolve();
684
+ if (this.isAnimating)
685
+ return Promise.resolve();
686
+ if (isNaN(degrees))
687
+ return Promise.resolve();
688
+ this.currentRotation = degrees;
689
+ this.isAnimating = true;
690
+ this._updateUI();
691
+ const center = this.originalImage.getCenterPoint();
692
+ this._setObjectOriginKeepingPosition(this.originalImage, "center", "center", center);
693
+ const p = new Promise((res) => {
694
+ this.originalImage.animate("angle", degrees, {
695
+ duration: this.options.animationDuration,
696
+ onChange: this.canvas.renderAll.bind(this.canvas),
697
+ onComplete: res
698
+ });
699
+ });
700
+ return p.then(() => {
701
+ this.originalImage.set("angle", degrees);
702
+ this.originalImage.setCoords();
703
+ if (this.options.expandCanvasToImage)
704
+ this._updateCanvasSizeToImageBounds();
705
+ this._alignObjectBoundingBoxToCanvasTopLeft(this.originalImage);
706
+ const newTopLeft = this._getObjectTopLeftPoint(this.originalImage);
707
+ this._setObjectOriginKeepingPosition(this.originalImage, "left", "top", newTopLeft);
708
+ this.canvas.getObjects().forEach((o) => {
709
+ if (o.maskId)
710
+ this._syncMaskLabel(o);
711
+ });
712
+ this.isAnimating = false;
713
+ this._updateInputs();
714
+ this._updateUI();
715
+ this.saveState();
716
+ }).catch(() => {
717
+ this.isAnimating = false;
718
+ this._updateUI();
719
+ });
720
+ }
721
+ /**
722
+ * Resets the image: scales to 1 and rotates to 0 degrees.
723
+ * @returns {Promise<void>} Promise that resolves when reset is complete.
724
+ */
725
+ reset() {
726
+ if (!this.originalImage)
727
+ return Promise.resolve();
728
+ return this.scaleImage(1).then(() => this.rotateImage(0)).then(() => {
729
+ this.saveState();
730
+ }).catch((err) => {
731
+ this._reportError("reset() failed", err);
732
+ });
733
+ }
734
+ /**
735
+ * Restores a canvas state that was previously stored by saveState().
736
+ * @param {string} jsonString - the JSON string returned by fabric.toJSON().
737
+ */
738
+ loadFromState(jsonString) {
739
+ if (!jsonString || !this.canvas)
740
+ return;
741
+ try {
742
+ const json = typeof jsonString === "string" ? JSON.parse(jsonString) : jsonString;
743
+ this.canvas.loadFromJSON(json, () => {
744
+ try {
745
+ this._hideAllMaskLabels();
746
+ const objs = this.canvas.getObjects();
747
+ this.originalImage = objs.find((o) => o.type === "image" && !o.maskId) || null;
748
+ if (this.originalImage) {
749
+ this.originalImage.set({ originX: "left", originY: "top", selectable: false, evented: false, hasControls: false, hoverCursor: "default" });
750
+ this.canvas.sendToBack(this.originalImage);
751
+ }
752
+ const masks = objs.filter((o) => o.maskId);
753
+ this.maskCounter = masks.reduce((max, m) => Math.max(max, m.maskId), 0);
754
+ this._lastMask = masks.length ? masks[masks.length - 1] : null;
755
+ if (!this._lastMask) {
756
+ this._lastMaskInitialLeft = null;
757
+ this._lastMaskInitialTop = null;
758
+ this._lastMaskInitialWidth = null;
759
+ }
760
+ this.isImageLoadedToCanvas = !!this.originalImage;
761
+ this.canvas.renderAll();
762
+ this._updateMaskList();
763
+ this._updatePlaceholderStatus();
764
+ this._updateUI();
765
+ } catch (callbackError) {
766
+ this._reportError("loadFromState() failed", callbackError);
767
+ }
768
+ });
769
+ } catch (e) {
770
+ this._reportError("loadFromState() failed", e);
771
+ }
772
+ }
773
+ /**
774
+ * Saves the current state of the canvas to history, storing any mask/raster label information.
775
+ */
776
+ saveState() {
777
+ if (!this.canvas)
778
+ return;
779
+ const activeObj = this.canvas.getActiveObject();
780
+ this._hideAllMaskLabels();
781
+ try {
782
+ const jsonObj = this.canvas.toJSON(["maskId", "maskName", "isCropRect"]);
783
+ if (Array.isArray(jsonObj.objects)) {
784
+ jsonObj.objects = jsonObj.objects.filter((o) => !o.isCropRect);
785
+ }
786
+ const after = JSON.stringify(jsonObj);
787
+ const before = this._lastSnapshot || after;
788
+ let executedOnce = false;
789
+ const cmd = new Command(
790
+ () => {
791
+ if (executedOnce) {
792
+ this.loadFromState(after);
793
+ }
794
+ executedOnce = true;
795
+ },
796
+ () => {
797
+ this.loadFromState(before);
798
+ }
799
+ );
800
+ this.historyManager.execute(cmd);
801
+ this._lastSnapshot = after;
802
+ if (activeObj && activeObj.maskId) {
803
+ this._showLabelForMask(activeObj);
804
+ }
805
+ this._updateUI();
806
+ } catch (err) {
807
+ this._reportWarning("saveState: failed to save canvas snapshot", err);
808
+ }
809
+ }
810
+ /**
811
+ * Undo the last state change, if possible.
812
+ */
813
+ undo() {
814
+ this.historyManager.undo();
815
+ }
816
+ /**
817
+ * Redo the next state change, if possible.
818
+ */
819
+ redo() {
820
+ this.historyManager.redo();
821
+ }
822
+ /**
823
+ * Adds a rectangular mask to the canvas.
824
+ * Mask placement and properties are determined by the provided config and instance options.
825
+ * Canvas and list UI are updated accordingly.
826
+ * @param {Object} [config={}] - Optional mask configuration overrides:
827
+ * @param {string} [config.shape='rect'] - 'rect', 'circle', 'ellipse', 'polygon', ...
828
+ * @param {Object|Array} [config.points] - Required for polygon: [{x, y}, ...] or [[x, y], ...]
829
+ * @param {number|function} [config.width/height/rx/ry/radius] - Can be number or function(canvas, options)
830
+ * @param {number|string|function} [config.left/top] - Absolute, %, or function
831
+ * @param {number|string} [config.angle] - Rotation angle (degree)
832
+ * @param {string} [config.color] - Fill color in CSS color format (default 'rgba(0,0,0,0.5)')
833
+ * @param {number} [config.alpha] - Opacity, from 0 to 1 (default 0.5)
834
+ * @param {boolean} [config.selectable=true]
835
+ * @param {Object} [config.styles] - Custom styles (stroke, dashArray, etc)
836
+ * @param {function} [config.onCreate] - Callback after mask created (receives Fabric object)
837
+ * @param {function} [config.fabricGenerator] - (cfg) => new FabricObj
838
+ * @returns {fabric.Rect|null} The created mask object, or null if canvas is not available.
839
+ * @public
840
+ */
841
+ addMask(config = {}) {
842
+ if (!this.canvas)
843
+ return null;
844
+ const shapeType = config.shape || "rect";
845
+ const cfg = {
846
+ shape: shapeType,
847
+ width: this.options.defaultMaskWidth,
848
+ height: this.options.defaultMaskHeight,
849
+ color: "rgba(0,0,0,0.5)",
850
+ alpha: 0.5,
851
+ gap: 5,
852
+ left: void 0,
853
+ top: void 0,
854
+ angle: 0,
855
+ selectable: true,
856
+ ...config
857
+ };
858
+ const firstOffset = 10;
859
+ let left = firstOffset;
860
+ let top = firstOffset;
861
+ const resolveValue = (val, fallback) => {
862
+ if (typeof val === "function")
863
+ return val(this.canvas, this.options);
864
+ if (typeof val === "string" && val.endsWith("%")) {
865
+ const percent = parseFloat(val) / 100;
866
+ return Math.floor((this.canvas ? this.canvas.getWidth() : 0) * percent);
867
+ }
868
+ return val != null ? val : fallback;
869
+ };
870
+ if (cfg.left === void 0 && this._lastMask) {
871
+ const prev = this._lastMask;
872
+ let prevRight = prev.left;
873
+ if (prev.getScaledWidth) {
874
+ prevRight += prev.getScaledWidth();
875
+ } else if (prev.width) {
876
+ prevRight += prev.width * (prev.scaleX ?? 1);
877
+ }
878
+ left = Math.round(prevRight + cfg.gap);
879
+ top = prev.top ?? firstOffset;
880
+ } else {
881
+ left = resolveValue(cfg.left, firstOffset);
882
+ top = resolveValue(cfg.top, firstOffset);
883
+ }
884
+ cfg.width = resolveValue(cfg.width, this.options.defaultMaskWidth);
885
+ cfg.height = resolveValue(cfg.height, this.options.defaultMaskHeight);
886
+ if (this.options.expandCanvasToImage && shapeType === "rect") {
887
+ const requiredW = Math.ceil(left + cfg.width + 10);
888
+ const requiredH = Math.ceil(top + cfg.height + 10);
889
+ const minW = this.containerEl ? Math.floor(this.containerEl.clientWidth || 0) : 0;
890
+ const minH = this.containerEl ? Math.floor(this.containerEl.clientHeight || 0) : 0;
891
+ const newW = Math.max(this.canvas.getWidth(), minW, requiredW);
892
+ const newH = Math.max(this.canvas.getHeight(), minH, requiredH);
893
+ this._setCanvasSizeInt(newW, newH);
894
+ }
895
+ let mask;
896
+ if (typeof cfg.fabricGenerator === "function") {
897
+ mask = cfg.fabricGenerator(cfg, this.canvas, this.options);
898
+ } else {
899
+ switch (shapeType) {
900
+ case "circle":
901
+ mask = new fabric.Circle({
902
+ left,
903
+ top,
904
+ radius: resolveValue(cfg.radius, Math.min(cfg.width, cfg.height) / 2),
905
+ fill: cfg.color,
906
+ opacity: cfg.alpha,
907
+ angle: cfg.angle,
908
+ ...cfg.styles
909
+ });
910
+ break;
911
+ case "ellipse":
912
+ mask = new fabric.Ellipse({
913
+ left,
914
+ top,
915
+ rx: resolveValue(cfg.rx, cfg.width / 2),
916
+ ry: resolveValue(cfg.ry, cfg.height / 2),
917
+ fill: cfg.color,
918
+ opacity: cfg.alpha,
919
+ angle: cfg.angle,
920
+ ...cfg.styles
921
+ });
922
+ break;
923
+ case "polygon": {
924
+ let polyPoints = cfg.points || [];
925
+ if (Array.isArray(polyPoints) && polyPoints.length && typeof polyPoints[0] === "object") {
926
+ polyPoints = polyPoints.map((pt) => ({ x: Number(pt.x), y: Number(pt.y) }));
927
+ }
928
+ mask = new fabric.Polygon(polyPoints, {
929
+ left,
930
+ top,
931
+ fill: cfg.color,
932
+ opacity: cfg.alpha,
933
+ angle: cfg.angle,
934
+ ...cfg.styles
935
+ });
936
+ break;
937
+ }
938
+ case "rect":
939
+ default:
940
+ mask = new fabric.Rect({
941
+ left,
942
+ top,
943
+ width: resolveValue(cfg.width, this.options.defaultMaskWidth),
944
+ height: resolveValue(cfg.height, this.options.defaultMaskHeight),
945
+ fill: cfg.color,
946
+ opacity: cfg.alpha,
947
+ angle: cfg.angle,
948
+ rx: cfg.rx,
949
+ // Rounded Corners
950
+ ry: cfg.ry,
951
+ ...cfg.styles
952
+ });
953
+ }
954
+ }
955
+ mask.selectable = cfg.selectable !== false;
956
+ mask.hasControls = "hasControls" in cfg ? cfg.hasControls : true;
957
+ mask.lockRotation = !this.options.maskRotatable;
958
+ mask.borderColor = cfg.borderColor || "red";
959
+ mask.cornerColor = cfg.cornerColor || "black";
960
+ mask.cornerSize = cfg.cornerSize || 8;
961
+ mask.transparentCorners = "transparentCorners" in cfg ? cfg.transparentCorners : false;
962
+ mask.stroke = cfg.styles && cfg.styles.stroke || "#ccc";
963
+ mask.strokeWidth = cfg.styles && cfg.styles.strokeWidth || 1;
964
+ mask.strokeUniform = "strokeUniform" in cfg ? cfg.strokeUniform : true;
965
+ if (cfg.styles && cfg.styles.strokeDashArray)
966
+ mask.strokeDashArray = cfg.styles.strokeDashArray;
967
+ mask.originalAlpha = cfg.alpha;
968
+ const normalStyle = { stroke: mask.stroke, strokeWidth: mask.strokeWidth, opacity: mask.originalAlpha };
969
+ const hoverStyle = { stroke: "#ff5500", strokeWidth: 2, opacity: Math.min(mask.originalAlpha + 0.2, 1) };
970
+ mask.on("mouseover", () => {
971
+ mask.set(hoverStyle);
972
+ mask.canvas.requestRenderAll();
973
+ });
974
+ mask.on("mouseout", () => {
975
+ mask.set(normalStyle);
976
+ mask.canvas.requestRenderAll();
977
+ });
978
+ this._lastMaskInitialLeft = left;
979
+ this._lastMaskInitialTop = top;
980
+ this._lastMaskInitialWidth = resolveValue(cfg.width, this.options.defaultMaskWidth);
981
+ mask.maskId = ++this.maskCounter;
982
+ mask.maskName = `${this.options.maskName}${mask.maskId}`;
983
+ this._lastMask = mask;
984
+ this.canvas.add(mask);
985
+ this.canvas.bringToFront(mask);
986
+ if (cfg.selectable)
987
+ this.canvas.setActiveObject(mask);
988
+ this._onSelectionChanged([mask]);
989
+ this._updateMaskList();
990
+ this._updateUI();
991
+ this.canvas.renderAll();
992
+ this.saveState();
993
+ if (typeof cfg.onCreate === "function")
994
+ cfg.onCreate(mask, this.canvas);
995
+ return mask;
996
+ }
997
+ /**
998
+ * Removes the currently selected mask from the canvas, if any.
999
+ * The associated label is also removed. UI and mask list are updated.
1000
+ */
1001
+ removeSelectedMask() {
1002
+ const active = this.canvas.getActiveObject();
1003
+ if (!active || !active.maskId)
1004
+ return;
1005
+ this._removeLabelForMask(active);
1006
+ this.canvas.remove(active);
1007
+ if (this._lastMask === active) {
1008
+ const masks = this.canvas.getObjects().filter((o) => o.maskId);
1009
+ this._lastMask = masks.length ? masks[masks.length - 1] : null;
1010
+ if (!this._lastMask) {
1011
+ this._lastMaskInitialLeft = null;
1012
+ this._lastMaskInitialTop = null;
1013
+ this._lastMaskInitialWidth = null;
1014
+ }
1015
+ }
1016
+ this.canvas.discardActiveObject();
1017
+ this._updateMaskList();
1018
+ this._updateUI();
1019
+ this.canvas.renderAll();
1020
+ this.saveState();
1021
+ }
1022
+ /**
1023
+ * Removes all masks from the canvas, including their labels.
1024
+ * UI and internal mask placement memory are reset.
1025
+ */
1026
+ removeAllMasks() {
1027
+ const masks = this.canvas.getObjects().filter((o) => o.maskId);
1028
+ masks.forEach((m) => this._removeLabelForMask(m));
1029
+ masks.forEach((m) => this.canvas.remove(m));
1030
+ this.canvas.discardActiveObject();
1031
+ this._lastMask = null;
1032
+ this._lastMaskInitialLeft = null;
1033
+ this._lastMaskInitialTop = null;
1034
+ this._lastMaskInitialWidth = null;
1035
+ this._updateMaskList();
1036
+ this._updateUI();
1037
+ this.canvas.renderAll();
1038
+ this.saveState();
1039
+ }
1040
+ /**
1041
+ * Removes the label associated with the specified mask object, if it exists.
1042
+ *
1043
+ * @param {fabric.Object} mask - The mask object whose label should be removed.
1044
+ * @private
1045
+ */
1046
+ _removeLabelForMask(mask) {
1047
+ if (!mask || !this.canvas)
1048
+ return;
1049
+ if (mask.__label) {
1050
+ try {
1051
+ const objs = this.canvas.getObjects();
1052
+ if (objs.includes(mask.__label)) {
1053
+ this.canvas.remove(mask.__label);
1054
+ }
1055
+ } catch (e) {
1056
+ }
1057
+ try {
1058
+ delete mask.__label;
1059
+ } catch (e) {
1060
+ }
1061
+ }
1062
+ }
1063
+ /**
1064
+ * Creates and adds a custom label (fabric.Text or fabric.IText) for the mask.
1065
+ * The label is default bound to the top-left of the mask and managed as a non-interactive overlay.
1066
+ *
1067
+ * @param {fabric.Object} mask - The mask to create a label for.
1068
+ * @private
1069
+ */
1070
+ _createLabelForMask(mask) {
1071
+ if (!mask || !this.options.maskLabelOnSelect)
1072
+ return;
1073
+ this._removeLabelForMask(mask);
1074
+ let textObj = null;
1075
+ if (this.options.label && typeof this.options.label.create === "function") {
1076
+ textObj = this.options.label.create(mask, fabric);
1077
+ }
1078
+ if (!textObj) {
1079
+ let txt = mask.maskName;
1080
+ let textOptions = {
1081
+ left: 0,
1082
+ top: 0,
1083
+ fontSize: 12,
1084
+ fill: "#fff",
1085
+ backgroundColor: "rgba(0,0,0,0.7)",
1086
+ selectable: false,
1087
+ evented: false,
1088
+ padding: 2,
1089
+ originX: "left",
1090
+ originY: "top"
1091
+ };
1092
+ if (this.options.label) {
1093
+ if (typeof this.options.label.getText === "function") {
1094
+ txt = this.options.label.getText(mask, this.maskCounter);
1095
+ }
1096
+ if (this.options.label.textOptions) {
1097
+ Object.assign(textOptions, this.options.label.textOptions);
1098
+ }
1099
+ }
1100
+ textObj = new fabric.Text(txt, textOptions);
1101
+ }
1102
+ textObj.maskLabel = true;
1103
+ mask.__label = textObj;
1104
+ this.canvas.add(textObj);
1105
+ this.canvas.bringToFront(textObj);
1106
+ this._syncMaskLabel(mask);
1107
+ }
1108
+ /**
1109
+ * Hides (removes) all mask labels from the canvas.
1110
+ * Internal label references on mask objects are also deleted.
1111
+ * @private
1112
+ */
1113
+ _hideAllMaskLabels() {
1114
+ if (!this.canvas)
1115
+ return;
1116
+ const objs = this.canvas.getObjects();
1117
+ const labels = objs.filter((o) => o.maskLabel);
1118
+ labels.forEach((l) => {
1119
+ try {
1120
+ if (objs.includes(l))
1121
+ this.canvas.remove(l);
1122
+ } catch (e) {
1123
+ }
1124
+ });
1125
+ objs.forEach((o) => {
1126
+ if (o.maskId && o.__label) {
1127
+ try {
1128
+ delete o.__label;
1129
+ } catch (e) {
1130
+ }
1131
+ }
1132
+ });
1133
+ }
1134
+ /**
1135
+ * Synchronizes the position, angle, and visibility of the mask's label so that it appears properly above the mask.
1136
+ *
1137
+ * @param {fabric.Object} mask - The mask whose label should be repositioned.
1138
+ * @private
1139
+ */
1140
+ _syncMaskLabel(mask) {
1141
+ if (!mask)
1142
+ return;
1143
+ if (!this.options.maskLabelOnSelect)
1144
+ return;
1145
+ if (!mask.__label)
1146
+ return;
1147
+ const coords = mask.getCoords ? mask.getCoords() : null;
1148
+ if (!coords || coords.length < 4)
1149
+ return;
1150
+ const tl = coords[0];
1151
+ const center = mask.getCenterPoint();
1152
+ const vx = center.x - tl.x;
1153
+ const vy = center.y - tl.y;
1154
+ const dist = Math.sqrt(vx * vx + vy * vy) || 1;
1155
+ const ux = vx / dist;
1156
+ const uy = vy / dist;
1157
+ const offset = Math.max(0, this.options.maskLabelOffset ?? 3);
1158
+ const px = tl.x + ux * offset;
1159
+ const py = tl.y + uy * offset;
1160
+ mask.__label.set({
1161
+ left: Math.round(px),
1162
+ top: Math.round(py),
1163
+ angle: mask.angle || 0,
1164
+ originX: "left",
1165
+ originY: "top",
1166
+ visible: true
1167
+ });
1168
+ mask.__label.setCoords();
1169
+ this.canvas.renderAll();
1170
+ }
1171
+ /**
1172
+ * Shows the label for the given mask, creating it if necessary and synchronizing its position.
1173
+ *
1174
+ * @param {fabric.Object} mask - The mask whose label should be shown.
1175
+ * @private
1176
+ */
1177
+ _showLabelForMask(mask) {
1178
+ if (!mask)
1179
+ return;
1180
+ if (!this.options.maskLabelOnSelect)
1181
+ return;
1182
+ if (!mask.__label)
1183
+ this._createLabelForMask(mask);
1184
+ mask.__label.visible = true;
1185
+ this._syncMaskLabel(mask);
1186
+ }
1187
+ /**
1188
+ * Handles changes to the selection of canvas objects (masks),
1189
+ * updates mask stroke and label display, and syncs mask list selection.
1190
+ *
1191
+ * @param {Array<Object>} selected - The currently selected objects (e.g. [mask] or []).
1192
+ * @private
1193
+ */
1194
+ _onSelectionChanged(selected) {
1195
+ const selectedMask = (selected || []).find((o) => o.maskId);
1196
+ const masks = this.canvas.getObjects().filter((o) => o.maskId);
1197
+ masks.forEach((m) => {
1198
+ if (m !== selectedMask) {
1199
+ if (m.__label) {
1200
+ try {
1201
+ this.canvas.remove(m.__label);
1202
+ } catch (e) {
1203
+ }
1204
+ delete m.__label;
1205
+ }
1206
+ m.set({ stroke: "#ccc", strokeWidth: 1 });
1207
+ } else {
1208
+ m.set({ stroke: "#ff0000", strokeWidth: 1 });
1209
+ }
1210
+ });
1211
+ if (selectedMask)
1212
+ this._showLabelForMask(selectedMask);
1213
+ this._updateMaskListSelection(selectedMask);
1214
+ this.canvas.renderAll();
1215
+ this._updateUI();
1216
+ }
1217
+ /**
1218
+ * Updates the mask list in the DOM to reflect the current masks on the canvas.
1219
+ * Each list entry becomes a clickable element for mask selection.
1220
+ * @private
1221
+ */
1222
+ _updateMaskList() {
1223
+ const listEl = document.getElementById(this.elements.maskList);
1224
+ if (!listEl)
1225
+ return;
1226
+ listEl.innerHTML = "";
1227
+ const masks = this.canvas.getObjects().filter((o) => o.maskId);
1228
+ masks.forEach((mask) => {
1229
+ const li = document.createElement("li");
1230
+ li.className = "list-group-item mask-item";
1231
+ li.textContent = mask.maskName;
1232
+ li.onclick = () => {
1233
+ this.canvas.setActiveObject(mask);
1234
+ this._onSelectionChanged([mask]);
1235
+ };
1236
+ listEl.appendChild(li);
1237
+ });
1238
+ }
1239
+ /**
1240
+ * Updates the visual selection (CSS 'active') state for the mask list in the DOM.
1241
+ *
1242
+ * @param {Object|null} selectedMask - The currently selected mask, or null if none selected.
1243
+ * @private
1244
+ */
1245
+ _updateMaskListSelection(selectedMask) {
1246
+ const listEl = document.getElementById(this.elements.maskList);
1247
+ if (!listEl)
1248
+ return;
1249
+ const items = listEl.querySelectorAll(".mask-item");
1250
+ items.forEach((item) => {
1251
+ const isSelected = !!selectedMask && item.textContent === selectedMask.maskName;
1252
+ item.classList.toggle("active", isSelected);
1253
+ });
1254
+ }
1255
+ /**
1256
+ * Merges current masks into the image: exports a masked/cropped image, removes all masks, and re-imports the merged image.
1257
+ * Will not run if no original image or no masks exist.
1258
+ * @async
1259
+ * @returns {Promise<void>} Resolves when merge and load are complete.
1260
+ */
1261
+ async merge() {
1262
+ if (!this.originalImage)
1263
+ return;
1264
+ const masks = this.canvas.getObjects().filter((o) => o.maskId);
1265
+ if (!masks.length)
1266
+ return;
1267
+ this.canvas.discardActiveObject();
1268
+ this.canvas.renderAll();
1269
+ try {
1270
+ const merged = await this.getImageBase64({ exportImageArea: true, multiplier: this.options.exportMultiplier });
1271
+ this.removeAllMasks();
1272
+ await this.loadImage(merged);
1273
+ this.saveState();
1274
+ } catch (err) {
1275
+ this._reportError("merge error", err);
1276
+ if (this.canvasEl)
1277
+ this.canvasEl.style.visibility = "";
1278
+ }
1279
+ }
1280
+ /**
1281
+ * Triggers a JPEG image download of the current canvas (image plus masks if configured).
1282
+ * The image area and multiplier are controlled by options.
1283
+ * @param {string} [fileName=this.options.defaultDownloadFileName] - Desired download file name.
1284
+ */
1285
+ downloadImage(fileName = this.options.defaultDownloadFileName) {
1286
+ if (!this.originalImage)
1287
+ return;
1288
+ const exportImageArea = this.options.exportImageAreaByDefault;
1289
+ this.getImageBase64({ exportImageArea, multiplier: this.options.exportMultiplier }).then((base64) => {
1290
+ const link = document.createElement("a");
1291
+ link.download = fileName;
1292
+ link.href = base64;
1293
+ document.body.appendChild(link);
1294
+ link.click();
1295
+ document.body.removeChild(link);
1296
+ }).catch((err) => this._reportError("download error", err));
1297
+ }
1298
+ /**
1299
+ * Exports the image as a Base64-encoded JPEG.
1300
+ * Can export either the original, or the current view including masks (clipped/cropped).
1301
+ * Will restore masks' state after temporary modifications for export.
1302
+ * @async
1303
+ * @param {Object} [opts={}] - Export options.
1304
+ * @param {boolean} [opts.exportImageArea] - If true, exports only the image bounding area with masks cropped and blended.
1305
+ * @param {number} [opts.multiplier=1] - Scaling multiplier for output (resolution).
1306
+ * @returns {Promise<string>} Promise resolving to a JPEG image data URL.
1307
+ * @throws {Error} If there is no image loaded.
1308
+ */
1309
+ async getImageBase64(opts = {}) {
1310
+ if (!this.originalImage)
1311
+ throw new Error("No image loaded");
1312
+ const exportImageArea = typeof opts.exportImageArea === "boolean" ? opts.exportImageArea : this.options.exportImageAreaByDefault;
1313
+ const multiplier = opts.multiplier || this.options.exportMultiplier || 1;
1314
+ if (!exportImageArea) {
1315
+ const imgEl = this.originalImage.getElement ? this.originalImage.getElement() : this.originalImage._element || null;
1316
+ if (!imgEl)
1317
+ return this.canvas.toDataURL({ format: "jpeg", quality: this.options.downsampleQuality, multiplier });
1318
+ const w = this.originalImage.width;
1319
+ const h = this.originalImage.height;
1320
+ const oc = document.createElement("canvas");
1321
+ oc.width = w;
1322
+ oc.height = h;
1323
+ const ctx = oc.getContext("2d");
1324
+ ctx.drawImage(imgEl, 0, 0, w, h);
1325
+ return oc.toDataURL("image/jpeg", this.options.downsampleQuality);
1326
+ }
1327
+ const masks = this.canvas.getObjects().filter((o) => o.maskId);
1328
+ const masksBackup = masks.map((m) => ({
1329
+ obj: m,
1330
+ opacity: m.opacity,
1331
+ fill: m.fill,
1332
+ strokeWidth: m.strokeWidth,
1333
+ stroke: m.stroke,
1334
+ selectable: m.selectable,
1335
+ lockRotation: m.lockRotation
1336
+ }));
1337
+ let finalBase64;
1338
+ try {
1339
+ masks.forEach((m) => this._removeLabelForMask(m));
1340
+ this.canvas.discardActiveObject();
1341
+ this.canvas.renderAll();
1342
+ masks.forEach((m) => {
1343
+ m.set({ opacity: 1, fill: "#000000", strokeWidth: 0, stroke: null, selectable: false });
1344
+ m.setCoords();
1345
+ });
1346
+ this.canvas.renderAll();
1347
+ this.originalImage.setCoords();
1348
+ const imgBr = this.originalImage.getBoundingRect(true, true);
1349
+ const sx = Math.max(0, Math.round(imgBr.left));
1350
+ const sy = Math.max(0, Math.round(imgBr.top));
1351
+ const sw = Math.max(1, Math.round(imgBr.width));
1352
+ const sh = Math.max(1, Math.round(imgBr.height));
1353
+ finalBase64 = await new Promise((resolve, reject) => {
1354
+ try {
1355
+ const fullDataUrl = this.canvas.toDataURL({
1356
+ format: "jpeg",
1357
+ quality: this.options.downsampleQuality,
1358
+ multiplier
1359
+ });
1360
+ const img = new Image();
1361
+ img.onload = () => {
1362
+ try {
1363
+ const sxM = Math.round(sx * multiplier);
1364
+ const syM = Math.round(sy * multiplier);
1365
+ const swM = Math.round(sw * multiplier);
1366
+ const shM = Math.round(sh * multiplier);
1367
+ const oc = document.createElement("canvas");
1368
+ oc.width = swM;
1369
+ oc.height = shM;
1370
+ const ctx = oc.getContext("2d");
1371
+ ctx.drawImage(img, sxM, syM, swM, shM, 0, 0, swM, shM);
1372
+ const out = oc.toDataURL("image/jpeg", this.options.downsampleQuality);
1373
+ resolve(out);
1374
+ } catch (e) {
1375
+ reject(e);
1376
+ }
1377
+ };
1378
+ img.onerror = reject;
1379
+ img.src = fullDataUrl;
1380
+ } catch (e) {
1381
+ reject(e);
1382
+ }
1383
+ });
1384
+ } finally {
1385
+ masksBackup.forEach((b) => {
1386
+ try {
1387
+ b.obj.set({
1388
+ opacity: b.opacity,
1389
+ fill: b.fill,
1390
+ strokeWidth: b.strokeWidth,
1391
+ stroke: b.stroke,
1392
+ selectable: b.selectable,
1393
+ lockRotation: b.lockRotation
1394
+ });
1395
+ b.obj.setCoords();
1396
+ } catch (e) {
1397
+ }
1398
+ });
1399
+ this.canvas.renderAll();
1400
+ }
1401
+ return finalBase64;
1402
+ }
1403
+ /**
1404
+ * Exports the current canvas (with or without masks) as a File object.
1405
+ * Allows you to choose whether to merge masks and specify file type (jpeg/png/webp).
1406
+ *
1407
+ * @async
1408
+ * @param {Object} [opts={}] - Export options.
1409
+ * @param {boolean} [opts.mergeMask=true] - If true, export image area with masks merged; if false, export the plain image without masks.
1410
+ * @param {string} [opts.fileType='jpeg'] - Output file type ('jpeg' | 'png' | 'webp'). Defaults to 'jpeg' on invalid input.
1411
+ * @param {number} [opts.quality=0.92] - Image quality for lossy types (0-1, default based on options.downsampleQuality).
1412
+ * @param {number} [opts.multiplier=1] - Output resolution multiplier.
1413
+ * @param {string} [opts.fileName] - Optional file name (only used for download).
1414
+ * @returns {Promise<File>} Resolves with the exported image as a File object.
1415
+ *
1416
+ * @example
1417
+ * const file = await this.exportImageFile({ mergeMask: false, fileType: 'png' });
1418
+ */
1419
+ async exportImageFile(opts = {}) {
1420
+ if (!this.originalImage)
1421
+ throw new Error("No image loaded");
1422
+ const {
1423
+ mergeMask = true,
1424
+ fileType = "jpeg",
1425
+ quality = this.options.downsampleQuality ?? 0.92,
1426
+ multiplier = this.options.exportMultiplier ?? 1,
1427
+ fileName = this.options.defaultDownloadFileName ?? "exported_image.jpg"
1428
+ } = opts;
1429
+ const typeMapping = {
1430
+ "jpeg": "jpeg",
1431
+ "jpg": "jpeg",
1432
+ "image/jpeg": "jpeg",
1433
+ "png": "png",
1434
+ "image/png": "png",
1435
+ "webp": "webp",
1436
+ "image/webp": "webp"
1437
+ };
1438
+ const safeFileType = typeMapping[String(fileType).toLowerCase()] || "jpeg";
1439
+ let base64;
1440
+ if (mergeMask) {
1441
+ base64 = await this.getImageBase64({
1442
+ exportImageArea: true,
1443
+ multiplier
1444
+ });
1445
+ } else {
1446
+ base64 = await this.getImageBase64({
1447
+ exportImageArea: false,
1448
+ multiplier
1449
+ });
1450
+ }
1451
+ let imageDataUrl = base64;
1452
+ if (!imageDataUrl.startsWith(`data:image/${safeFileType}`)) {
1453
+ imageDataUrl = await new Promise((resolve, reject) => {
1454
+ const img = new window.Image();
1455
+ img.crossOrigin = "Anonymous";
1456
+ img.onload = () => {
1457
+ try {
1458
+ const oc = document.createElement("canvas");
1459
+ oc.width = img.width;
1460
+ oc.height = img.height;
1461
+ const ctx = oc.getContext("2d");
1462
+ ctx.drawImage(img, 0, 0);
1463
+ const durl = oc.toDataURL(`image/${safeFileType}`, quality);
1464
+ resolve(durl);
1465
+ } catch (e) {
1466
+ reject(e);
1467
+ }
1468
+ };
1469
+ img.onerror = reject;
1470
+ img.src = base64;
1471
+ });
1472
+ }
1473
+ const bstr = atob(imageDataUrl.split(",")[1]);
1474
+ const mime = `image/${safeFileType}`;
1475
+ let n = bstr.length;
1476
+ const u8arr = new Uint8Array(n);
1477
+ while (n--) {
1478
+ u8arr[n] = bstr.charCodeAt(n);
1479
+ }
1480
+ const file = new File([u8arr], fileName, { type: mime });
1481
+ return file;
1482
+ }
1483
+ /**
1484
+ * Enter crop mode: create a resizable/movable selection rect on top of the image.
1485
+ * @public
1486
+ */
1487
+ enterCropMode() {
1488
+ if (!this.canvas || !this.originalImage || this._cropMode)
1489
+ return;
1490
+ if (!this.isImageLoaded())
1491
+ return;
1492
+ this._cropMode = true;
1493
+ this._prevSelectionSetting = this.canvas.selection;
1494
+ this.canvas.selection = false;
1495
+ this.canvas.discardActiveObject();
1496
+ this.originalImage.setCoords();
1497
+ const imgBr = this.originalImage.getBoundingRect(true, true);
1498
+ const padding = this.options.crop && this.options.crop.padding ? this.options.crop.padding : 10;
1499
+ const left = Math.max(0, Math.floor(imgBr.left + padding));
1500
+ const top = Math.max(0, Math.floor(imgBr.top + padding));
1501
+ const width = Math.min(this.options.crop.minWidth || 50, Math.floor(imgBr.width - padding * 2));
1502
+ const height = Math.min(this.options.crop.minHeight || 50, Math.floor(imgBr.height - padding * 2));
1503
+ const cropRect = new fabric.Rect({
1504
+ left,
1505
+ top,
1506
+ width,
1507
+ height,
1508
+ fill: "rgba(0,0,0,0.12)",
1509
+ stroke: "#00aaff",
1510
+ strokeDashArray: [6, 4],
1511
+ strokeWidth: 1,
1512
+ strokeUniform: true,
1513
+ selectable: true,
1514
+ hasRotatingPoint: !!(this.options.crop && this.options.crop.allowRotationOfCropRect),
1515
+ lockRotation: !(this.options.crop && this.options.crop.allowRotationOfCropRect),
1516
+ cornerSize: 8,
1517
+ objectCaching: false,
1518
+ originX: "left",
1519
+ originY: "top"
1520
+ });
1521
+ this.canvas.add(cropRect);
1522
+ cropRect.isCropRect = true;
1523
+ this.canvas.bringToFront(cropRect);
1524
+ this.canvas.setActiveObject(cropRect);
1525
+ this._cropRect = cropRect;
1526
+ this._cropPrevEvented = [];
1527
+ this.canvas.getObjects().forEach((o) => {
1528
+ if (o !== cropRect) {
1529
+ this._cropPrevEvented.push({ obj: o, evented: o.evented, selectable: o.selectable });
1530
+ try {
1531
+ o.evented = false;
1532
+ o.selectable = false;
1533
+ } catch (e) {
1534
+ }
1535
+ }
1536
+ });
1537
+ const onModified = () => {
1538
+ try {
1539
+ cropRect.setCoords();
1540
+ this.canvas.requestRenderAll();
1541
+ } catch (e) {
1542
+ }
1543
+ };
1544
+ cropRect.on("modified", onModified);
1545
+ cropRect.on("moving", onModified);
1546
+ cropRect.on("scaling", onModified);
1547
+ this._cropHandlers.push({ target: cropRect, handlers: [{ evt: "modified", fn: onModified }, { evt: "moving", fn: onModified }, { evt: "scaling", fn: onModified }] });
1548
+ this._updateUI();
1549
+ this.canvas.renderAll();
1550
+ }
1551
+ /**
1552
+ * Cancel crop mode and remove the temporary selection rect.
1553
+ * @public
1554
+ */
1555
+ cancelCrop() {
1556
+ if (!this.canvas || !this._cropMode)
1557
+ return;
1558
+ if (this._cropRect) {
1559
+ try {
1560
+ if (this._cropHandlers && this._cropHandlers.length) {
1561
+ this._cropHandlers.forEach((h) => {
1562
+ h.handlers.forEach((rec) => h.target.off(rec.evt, rec.fn));
1563
+ });
1564
+ }
1565
+ } catch (e) {
1566
+ }
1567
+ try {
1568
+ this.canvas.remove(this._cropRect);
1569
+ } catch (e) {
1570
+ }
1571
+ this._cropRect = null;
1572
+ }
1573
+ if (Array.isArray(this._cropPrevEvented)) {
1574
+ this._cropPrevEvented.forEach((i) => {
1575
+ try {
1576
+ i.obj.evented = i.evented;
1577
+ i.obj.selectable = i.selectable;
1578
+ } catch (e) {
1579
+ }
1580
+ });
1581
+ }
1582
+ this._cropPrevEvented = null;
1583
+ this._cropHandlers = [];
1584
+ this._cropMode = false;
1585
+ this.canvas.selection = !!this._prevSelectionSetting;
1586
+ this._prevSelectionSetting = void 0;
1587
+ this.canvas.discardActiveObject();
1588
+ this._updateUI();
1589
+ this.canvas.renderAll();
1590
+ }
1591
+ /**
1592
+ * Apply the current crop rectangle.
1593
+ * remove all masks and export canvas snapshot and crop via offscreen canvas
1594
+ * @public
1595
+ */
1596
+ async applyCrop() {
1597
+ if (!this.canvas || !this._cropMode || !this._cropRect)
1598
+ return;
1599
+ this._cropRect.setCoords();
1600
+ const rectBounds = this._cropRect.getBoundingRect(true, true);
1601
+ const sx = Math.max(0, Math.round(rectBounds.left));
1602
+ const sy = Math.max(0, Math.round(rectBounds.top));
1603
+ const sw = Math.max(1, Math.round(Math.min(rectBounds.width, this.canvas.getWidth() - sx)));
1604
+ const sh = Math.max(1, Math.round(Math.min(rectBounds.height, this.canvas.getHeight() - sy)));
1605
+ let beforeJson = null;
1606
+ try {
1607
+ const jsonObj = this.canvas.toJSON(["maskId", "maskName", "isCropRect"]);
1608
+ if (Array.isArray(jsonObj.objects)) {
1609
+ jsonObj.objects = jsonObj.objects.filter((o) => !o.isCropRect);
1610
+ }
1611
+ beforeJson = JSON.stringify(jsonObj);
1612
+ } catch (e) {
1613
+ this._reportWarning("applyCrop: could not serialize before state", e);
1614
+ beforeJson = null;
1615
+ }
1616
+ try {
1617
+ const masks = this.canvas.getObjects().filter((o) => o.maskId);
1618
+ if (masks && masks.length) {
1619
+ masks.forEach((m) => {
1620
+ try {
1621
+ this._removeLabelForMask(m);
1622
+ this.canvas.remove(m);
1623
+ } catch (err) {
1624
+ this._reportWarning("applyCrop: failed to remove mask", err);
1625
+ }
1626
+ });
1627
+ this._lastMask = null;
1628
+ this._lastMaskInitialLeft = null;
1629
+ this._lastMaskInitialTop = null;
1630
+ this._lastMaskInitialWidth = null;
1631
+ this.canvas.discardActiveObject();
1632
+ this.canvas.renderAll();
1633
+ }
1634
+ } catch (e) {
1635
+ this._reportWarning("applyCrop: error while removing masks", e);
1636
+ }
1637
+ try {
1638
+ if (this._cropRect) {
1639
+ try {
1640
+ if (this._cropHandlers && this._cropHandlers.length) {
1641
+ this._cropHandlers.forEach((h) => {
1642
+ h.handlers.forEach((rec) => h.target.off(rec.evt, rec.fn));
1643
+ });
1644
+ }
1645
+ } catch (e) {
1646
+ }
1647
+ try {
1648
+ this.canvas.remove(this._cropRect);
1649
+ } catch (e) {
1650
+ }
1651
+ this._cropRect = null;
1652
+ }
1653
+ } catch (e) {
1654
+ }
1655
+ this._cropMode = false;
1656
+ this.canvas.selection = !!this._prevSelectionSetting;
1657
+ this._prevSelectionSetting = void 0;
1658
+ let croppedBase64;
1659
+ try {
1660
+ const fullDataUrl = this.canvas.toDataURL({
1661
+ format: "jpeg",
1662
+ quality: this.options.downsampleQuality || 0.92,
1663
+ multiplier: 1
1664
+ });
1665
+ croppedBase64 = await new Promise((resolve, reject) => {
1666
+ const img = new Image();
1667
+ img.onload = () => {
1668
+ try {
1669
+ const oc = document.createElement("canvas");
1670
+ oc.width = sw;
1671
+ oc.height = sh;
1672
+ const ctx = oc.getContext("2d");
1673
+ ctx.drawImage(img, sx, sy, sw, sh, 0, 0, sw, sh);
1674
+ const out = oc.toDataURL("image/jpeg", this.options.downsampleQuality || 0.92);
1675
+ resolve(out);
1676
+ } catch (err) {
1677
+ reject(err);
1678
+ }
1679
+ };
1680
+ img.onerror = (e) => reject(e);
1681
+ img.src = fullDataUrl;
1682
+ });
1683
+ } catch (e) {
1684
+ this._reportError("applyCrop: failed to create cropped image", e);
1685
+ this._updateUI();
1686
+ return;
1687
+ }
1688
+ try {
1689
+ await this.loadImage(croppedBase64);
1690
+ } catch (e) {
1691
+ this._reportError("applyCrop: loadImage(croppedBase64) failed", e);
1692
+ this._updateUI();
1693
+ return;
1694
+ }
1695
+ let afterJson = null;
1696
+ try {
1697
+ const jsonObj2 = this.canvas.toJSON(["maskId", "maskName", "isCropRect"]);
1698
+ if (Array.isArray(jsonObj2.objects)) {
1699
+ jsonObj2.objects = jsonObj2.objects.filter((o) => !o.isCropRect);
1700
+ }
1701
+ afterJson = JSON.stringify(jsonObj2);
1702
+ } catch (e) {
1703
+ this._reportWarning("applyCrop: failed to serialize after state", e);
1704
+ afterJson = null;
1705
+ }
1706
+ try {
1707
+ const self2 = this;
1708
+ const cmd = new Command(
1709
+ () => {
1710
+ if (afterJson)
1711
+ self2.loadFromState(afterJson);
1712
+ },
1713
+ () => {
1714
+ if (beforeJson)
1715
+ self2.loadFromState(beforeJson);
1716
+ }
1717
+ );
1718
+ if (!this.historyManager)
1719
+ this.historyManager = new HistoryManager(this.maxHistorySize || 50);
1720
+ if (this.historyManager.currentIndex < this.historyManager.history.length - 1) {
1721
+ this.historyManager.history = this.historyManager.history.slice(0, this.historyManager.currentIndex + 1);
1722
+ }
1723
+ this.historyManager.history.push(cmd);
1724
+ if (this.historyManager.history.length > this.historyManager.maxSize) {
1725
+ this.historyManager.history.shift();
1726
+ } else {
1727
+ this.historyManager.currentIndex++;
1728
+ }
1729
+ } catch (e) {
1730
+ this._reportWarning("applyCrop: failed to push history command", e);
1731
+ }
1732
+ this._updateUI();
1733
+ this.canvas.renderAll();
1734
+ }
1735
+ /* ---------- Misc / UI ---------- */
1736
+ /**
1737
+ * Updates the scale input field in the UI to reflect the current scale.
1738
+ * Sets the value (as percentage) if the element is present.
1739
+ * @private
1740
+ */
1741
+ _updateInputs() {
1742
+ const scaleEl = document.getElementById(this.elements.scaleRate);
1743
+ if (scaleEl)
1744
+ scaleEl.value = Math.round(this.currentScale * 100);
1745
+ }
1746
+ /**
1747
+ * Updates the enabled/disabled state of various UI controls (buttons)
1748
+ * based on the current application state (image/mask presence, animation, etc).
1749
+ * @private
1750
+ */
1751
+ _updateUI() {
1752
+ const hasImg = !!this.originalImage;
1753
+ const masks = hasImg ? this.canvas.getObjects().filter((o) => o.maskId) : [];
1754
+ const hasMasks = masks.length > 0;
1755
+ const active = this.canvas.getActiveObject();
1756
+ const hasSelectedMask = active && active.maskId;
1757
+ const isDefault = this.currentScale === 1 && this.currentRotation === 0;
1758
+ const canUndo = this.historyManager?.canUndo();
1759
+ const canRedo = this.historyManager?.canRedo();
1760
+ const inCrop = !!this._cropMode;
1761
+ if (inCrop) {
1762
+ for (const k of Object.keys(this.elements || {})) {
1763
+ const el = document.getElementById(this.elements[k]);
1764
+ if (!el)
1765
+ continue;
1766
+ if (k === "applyCropBtn" || k === "cancelCropBtn") {
1767
+ el.disabled = false;
1768
+ } else {
1769
+ el.disabled = true;
1770
+ }
1771
+ }
1772
+ return;
1773
+ }
1774
+ this._setDisabled("zoomInBtn", !hasImg || this.isAnimating || this.currentScale >= this.options.maxScale);
1775
+ this._setDisabled("zoomOutBtn", !hasImg || this.isAnimating || this.currentScale <= this.options.minScale);
1776
+ this._setDisabled("rotateLeftBtn", !hasImg || this.isAnimating);
1777
+ this._setDisabled("rotateRightBtn", !hasImg || this.isAnimating);
1778
+ this._setDisabled("addMaskBtn", !hasImg || this.isAnimating);
1779
+ this._setDisabled("removeMaskBtn", !hasSelectedMask || this.isAnimating);
1780
+ this._setDisabled("removeAllMasksBtn", !hasMasks || this.isAnimating);
1781
+ this._setDisabled("mergeBtn", !hasImg || !hasMasks || this.isAnimating);
1782
+ this._setDisabled("downloadBtn", !hasImg || this.isAnimating);
1783
+ this._setDisabled("resetBtn", !hasImg || isDefault || this.isAnimating);
1784
+ this._setDisabled("undoBtn", !hasImg || this.isAnimating || !canUndo);
1785
+ this._setDisabled("redoBtn", !hasImg || this.isAnimating || !canRedo);
1786
+ this._setDisabled("cropBtn", !hasImg || this.isAnimating);
1787
+ this._setDisabled("applyCropBtn", true);
1788
+ this._setDisabled("cancelCropBtn", true);
1789
+ }
1790
+ /**
1791
+ * Enables or disables a specific UI element (typically a button) by its key.
1792
+ *
1793
+ * @param {string} key - Key of the element in this.elements (e.g. 'zoomInBtn').
1794
+ * @param {boolean} disabled - If true, disables the element; otherwise enables.
1795
+ * @private
1796
+ */
1797
+ _setDisabled(key, disabled) {
1798
+ const el = document.getElementById(this.elements[key]);
1799
+ if (el)
1800
+ el.disabled = !!disabled;
1801
+ }
1802
+ /**
1803
+ * Automatically display and hide placeholders and containers based on the current image content
1804
+ * @private
1805
+ */
1806
+ _updatePlaceholderStatus() {
1807
+ if (!this.options.showPlaceholder)
1808
+ return;
1809
+ this._setPlaceholderVisible(!this.originalImage);
1810
+ }
1811
+ /**
1812
+ * Controls the display/hiding of the Placeholder and Canvas container.
1813
+ * @param {boolean} show - true displays the placeholder, false displays the canvas container
1814
+ * @private
1815
+ */
1816
+ _setPlaceholderVisible(show) {
1817
+ if (!this.placeholderEl)
1818
+ return;
1819
+ if (show) {
1820
+ this.placeholderEl.classList.remove("d-none");
1821
+ this.placeholderEl.classList.add("d-flex");
1822
+ this.containerEl.classList.add("d-none");
1823
+ } else {
1824
+ this.placeholderEl.classList.remove("d-flex");
1825
+ this.placeholderEl.classList.add("d-none");
1826
+ this.containerEl.classList.remove("d-none");
1827
+ }
1828
+ }
1829
+ /**
1830
+ * Cleans up and disposes of the canvas and related references.
1831
+ * Call this method to free memory and remove canvas listeners when the editor is no longer needed.
1832
+ * @public
1833
+ */
1834
+ dispose() {
1835
+ try {
1836
+ for (const key in this._boundHandlers || {}) {
1837
+ const handlers = this._boundHandlers[key] || [];
1838
+ const el = document.getElementById(this.elements[key]);
1839
+ if (!el)
1840
+ continue;
1841
+ handlers.forEach((h) => {
1842
+ try {
1843
+ el.removeEventListener(h.event, h.handler);
1844
+ } catch (e) {
1845
+ }
1846
+ });
1847
+ }
1848
+ } catch (e) {
1849
+ }
1850
+ if (this._cropRect) {
1851
+ try {
1852
+ this.canvas.remove(this._cropRect);
1853
+ } catch (e) {
1854
+ }
1855
+ this._cropRect = null;
1856
+ }
1857
+ if (this.canvas) {
1858
+ try {
1859
+ this.canvas.dispose();
1860
+ } catch (e) {
1861
+ }
1862
+ this.canvas = null;
1863
+ this.canvasEl = null;
1864
+ this.isImageLoadedToCanvas = false;
1865
+ }
1866
+ this._boundHandlers = {};
1867
+ }
1868
+ };
1869
+ var AnimationQueue = class {
1870
+ /**
1871
+ * Creates a new AnimationQueue.
1872
+ *
1873
+ * @constructor
1874
+ */
1875
+ constructor() {
1876
+ this.queue = [];
1877
+ this.running = false;
1878
+ }
1879
+ /**
1880
+ * Adds an animation function to the queue.
1881
+ *
1882
+ * @param {Function} animationFn A function that returns a Promise or any await-able.
1883
+ * @returns {Promise<*>} A Promise that resolves/rejects with the animation result.
1884
+ */
1885
+ async add(animationFn) {
1886
+ return new Promise((resolve, reject) => {
1887
+ this.queue.push({ fn: animationFn, resolve, reject });
1888
+ if (!this.running) {
1889
+ this.processQueue();
1890
+ }
1891
+ });
1892
+ }
1893
+ /**
1894
+ * Internal helper that processes the animation queue sequentially until it is empty.
1895
+ *
1896
+ * @private
1897
+ * @returns {Promise<void>}
1898
+ */
1899
+ async processQueue() {
1900
+ if (this.queue.length === 0) {
1901
+ this.running = false;
1902
+ return;
1903
+ }
1904
+ this.running = true;
1905
+ const { fn, resolve, reject } = this.queue.shift();
1906
+ try {
1907
+ const result = await fn();
1908
+ resolve(result);
1909
+ } catch (error) {
1910
+ reject(error);
1911
+ }
1912
+ this.processQueue();
1913
+ }
1914
+ };
1915
+ var Command = class {
1916
+ /**
1917
+ * @param {Function} execute The function that performs the action.
1918
+ * @param {Function} undo The function that reverts the action.
1919
+ */
1920
+ constructor(execute, undo) {
1921
+ this.execute = execute;
1922
+ this.undo = undo;
1923
+ }
1924
+ };
1925
+ var HistoryManager = class {
1926
+ /**
1927
+ * @param {number} [maxSize=50] Maximum number of commands to keep in history.
1928
+ */
1929
+ constructor(maxSize = 50) {
1930
+ this.history = [];
1931
+ this.currentIndex = -1;
1932
+ this.maxSize = maxSize;
1933
+ }
1934
+ /**
1935
+ * Executes a new command and pushes it onto the history stack.
1936
+ * Truncates any "future" history when branching.
1937
+ *
1938
+ * @param {Command} command The command to execute.
1939
+ * @returns {void}
1940
+ */
1941
+ execute(command) {
1942
+ command.execute();
1943
+ if (this.currentIndex < this.history.length - 1) {
1944
+ this.history = this.history.slice(0, this.currentIndex + 1);
1945
+ }
1946
+ this.history.push(command);
1947
+ if (this.history.length > this.maxSize) {
1948
+ this.history.shift();
1949
+ } else {
1950
+ this.currentIndex++;
1951
+ }
1952
+ }
1953
+ /**
1954
+ * Checks whether an undo operation is possible.
1955
+ *
1956
+ * @returns {boolean} True if undo can be performed.
1957
+ */
1958
+ canUndo() {
1959
+ return this.currentIndex >= 0;
1960
+ }
1961
+ /**
1962
+ * Checks whether a redo operation is possible.
1963
+ *
1964
+ * @returns {boolean} True if redo can be performed.
1965
+ */
1966
+ canRedo() {
1967
+ return this.currentIndex < this.history.length - 1;
1968
+ }
1969
+ /**
1970
+ * Undoes the last executed command if possible.
1971
+ *
1972
+ * @returns {void}
1973
+ */
1974
+ undo() {
1975
+ if (this.currentIndex >= 0) {
1976
+ this.history[this.currentIndex].undo();
1977
+ this.currentIndex--;
1978
+ }
1979
+ }
1980
+ /**
1981
+ * Redoes the next command in history if possible.
1982
+ *
1983
+ * @returns {void}
1984
+ */
1985
+ redo() {
1986
+ if (this.currentIndex < this.history.length - 1) {
1987
+ this.currentIndex++;
1988
+ this.history[this.currentIndex].execute();
1989
+ }
1990
+ }
1991
+ };
1992
+ var image_editor_default = ImageEditor;
1993
+
1994
+ // src/browser.js
1995
+ var scope = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : null;
1996
+ setFabric(scope && scope.fabric);
1997
+ if (scope) {
1998
+ scope.ImageEditor = image_editor_default;
1999
+ }
2000
+ })();
2001
+ //# sourceMappingURL=image-editor.js.map