web-mojo 2.1.46

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 (91) hide show
  1. package/LICENSE +198 -0
  2. package/README.md +510 -0
  3. package/dist/admin.cjs.js +2 -0
  4. package/dist/admin.cjs.js.map +1 -0
  5. package/dist/admin.css +621 -0
  6. package/dist/admin.es.js +7973 -0
  7. package/dist/admin.es.js.map +1 -0
  8. package/dist/auth.cjs.js +2 -0
  9. package/dist/auth.cjs.js.map +1 -0
  10. package/dist/auth.css +804 -0
  11. package/dist/auth.es.js +2168 -0
  12. package/dist/auth.es.js.map +1 -0
  13. package/dist/charts.cjs.js +2 -0
  14. package/dist/charts.cjs.js.map +1 -0
  15. package/dist/charts.css +1002 -0
  16. package/dist/charts.es.js +16 -0
  17. package/dist/charts.es.js.map +1 -0
  18. package/dist/chunks/ContextMenu-BrHqj0fn.js +80 -0
  19. package/dist/chunks/ContextMenu-BrHqj0fn.js.map +1 -0
  20. package/dist/chunks/ContextMenu-gEcpSz56.js +2 -0
  21. package/dist/chunks/ContextMenu-gEcpSz56.js.map +1 -0
  22. package/dist/chunks/DataView-DPryYpEW.js +2 -0
  23. package/dist/chunks/DataView-DPryYpEW.js.map +1 -0
  24. package/dist/chunks/DataView-DjZQrpba.js +843 -0
  25. package/dist/chunks/DataView-DjZQrpba.js.map +1 -0
  26. package/dist/chunks/Dialog-BsRx4eg3.js +2 -0
  27. package/dist/chunks/Dialog-BsRx4eg3.js.map +1 -0
  28. package/dist/chunks/Dialog-DSlctbon.js +1377 -0
  29. package/dist/chunks/Dialog-DSlctbon.js.map +1 -0
  30. package/dist/chunks/FilePreviewView-BmFHzK5K.js +5868 -0
  31. package/dist/chunks/FilePreviewView-BmFHzK5K.js.map +1 -0
  32. package/dist/chunks/FilePreviewView-DcdRl_ta.js +2 -0
  33. package/dist/chunks/FilePreviewView-DcdRl_ta.js.map +1 -0
  34. package/dist/chunks/FormView-CmBuwKGD.js +2 -0
  35. package/dist/chunks/FormView-CmBuwKGD.js.map +1 -0
  36. package/dist/chunks/FormView-DqUBMPJ9.js +5054 -0
  37. package/dist/chunks/FormView-DqUBMPJ9.js.map +1 -0
  38. package/dist/chunks/MetricsChart-CM4CI6eA.js +2095 -0
  39. package/dist/chunks/MetricsChart-CM4CI6eA.js.map +1 -0
  40. package/dist/chunks/MetricsChart-CPidSMaN.js +2 -0
  41. package/dist/chunks/MetricsChart-CPidSMaN.js.map +1 -0
  42. package/dist/chunks/PDFViewer-BNQlnS83.js +2 -0
  43. package/dist/chunks/PDFViewer-BNQlnS83.js.map +1 -0
  44. package/dist/chunks/PDFViewer-Dyo-Oeyd.js +946 -0
  45. package/dist/chunks/PDFViewer-Dyo-Oeyd.js.map +1 -0
  46. package/dist/chunks/Page-B524zSQs.js +351 -0
  47. package/dist/chunks/Page-B524zSQs.js.map +1 -0
  48. package/dist/chunks/Page-BFgj0pAA.js +2 -0
  49. package/dist/chunks/Page-BFgj0pAA.js.map +1 -0
  50. package/dist/chunks/TokenManager-BXNva8Jk.js +287 -0
  51. package/dist/chunks/TokenManager-BXNva8Jk.js.map +1 -0
  52. package/dist/chunks/TokenManager-Bzn4guFm.js +2 -0
  53. package/dist/chunks/TokenManager-Bzn4guFm.js.map +1 -0
  54. package/dist/chunks/TopNav-D3I3_25f.js +371 -0
  55. package/dist/chunks/TopNav-D3I3_25f.js.map +1 -0
  56. package/dist/chunks/TopNav-MDjL4kV0.js +2 -0
  57. package/dist/chunks/TopNav-MDjL4kV0.js.map +1 -0
  58. package/dist/chunks/User-BalfYTEF.js +3 -0
  59. package/dist/chunks/User-BalfYTEF.js.map +1 -0
  60. package/dist/chunks/User-DwIT-CTQ.js +1937 -0
  61. package/dist/chunks/User-DwIT-CTQ.js.map +1 -0
  62. package/dist/chunks/WebApp-B6mgbNn2.js +4767 -0
  63. package/dist/chunks/WebApp-B6mgbNn2.js.map +1 -0
  64. package/dist/chunks/WebApp-DqDowtkl.js +2 -0
  65. package/dist/chunks/WebApp-DqDowtkl.js.map +1 -0
  66. package/dist/chunks/WebSocketClient-D6i85jl2.js +2 -0
  67. package/dist/chunks/WebSocketClient-D6i85jl2.js.map +1 -0
  68. package/dist/chunks/WebSocketClient-Dvl3AYx1.js +297 -0
  69. package/dist/chunks/WebSocketClient-Dvl3AYx1.js.map +1 -0
  70. package/dist/core.css +1181 -0
  71. package/dist/css/web-mojo.css +17 -0
  72. package/dist/css-manifest.json +6 -0
  73. package/dist/docit.cjs.js +2 -0
  74. package/dist/docit.cjs.js.map +1 -0
  75. package/dist/docit.es.js +959 -0
  76. package/dist/docit.es.js.map +1 -0
  77. package/dist/index.cjs.js +2 -0
  78. package/dist/index.cjs.js.map +1 -0
  79. package/dist/index.es.js +2681 -0
  80. package/dist/index.es.js.map +1 -0
  81. package/dist/lightbox.cjs.js +2 -0
  82. package/dist/lightbox.cjs.js.map +1 -0
  83. package/dist/lightbox.css +606 -0
  84. package/dist/lightbox.es.js +3737 -0
  85. package/dist/lightbox.es.js.map +1 -0
  86. package/dist/loader.es.js +115 -0
  87. package/dist/loader.umd.js +85 -0
  88. package/dist/portal.css +2446 -0
  89. package/dist/table.css +639 -0
  90. package/dist/toast.css +181 -0
  91. package/package.json +179 -0
@@ -0,0 +1,3737 @@
1
+ import { V as View } from "./chunks/WebApp-B6mgbNn2.js";
2
+ import { B, b, a, c, e, f, W } from "./chunks/WebApp-B6mgbNn2.js";
3
+ import Dialog from "./chunks/Dialog-DSlctbon.js";
4
+ import { L, P } from "./chunks/PDFViewer-Dyo-Oeyd.js";
5
+ class ImageViewer extends View {
6
+ constructor(options = {}) {
7
+ super({
8
+ ...options,
9
+ className: `image-viewer ${options.className || ""}`,
10
+ tagName: "div"
11
+ });
12
+ this.imageUrl = options.imageUrl || options.src || "";
13
+ this.alt = options.alt || "Image";
14
+ this.title = options.title || "";
15
+ this.canvas = null;
16
+ this.context = null;
17
+ this.image = null;
18
+ this.scale = 1;
19
+ this.rotation = 0;
20
+ this.translateX = 0;
21
+ this.translateY = 0;
22
+ this.minScale = 0.1;
23
+ this.maxScale = 5;
24
+ this.scaleStep = 0.1;
25
+ this.isDragging = false;
26
+ this.lastPointerX = 0;
27
+ this.lastPointerY = 0;
28
+ this.isLoaded = false;
29
+ this.showControls = options.showControls !== false;
30
+ this.allowRotate = options.allowRotate !== false;
31
+ this.allowZoom = options.allowZoom !== false;
32
+ this.allowPan = options.allowPan !== false;
33
+ this.allowDownload = options.allowDownload !== false;
34
+ this.autoFit = options.autoFit !== false;
35
+ this.containerElement = null;
36
+ this.controlsElement = null;
37
+ }
38
+ async getTemplate() {
39
+ return `
40
+ <div class="image-viewer-container d-flex flex-column h-100" data-container="imageContainer">
41
+ <div class="image-viewer-content flex-grow-1 position-relative">
42
+ <canvas class="image-viewer-canvas w-100 h-100" data-container="canvas"></canvas>
43
+ <div class="image-viewer-overlay">
44
+ <div class="image-viewer-loading">
45
+ <div class="spinner-border text-light" role="status">
46
+ <span class="visually-hidden">Loading...</span>
47
+ </div>
48
+ </div>
49
+ </div>
50
+ </div>
51
+
52
+ {{#showControls}}
53
+ <div class="image-viewer-controls position-absolute top-0 start-50 translate-middle-x mt-3" data-container="controls" style="z-index: 10;">
54
+ <div class="btn-group" role="group">
55
+ {{#allowZoom}}
56
+ <button type="button" class="btn btn-dark btn-sm" data-action="zoom-in" title="Zoom In">
57
+ <i class="bi bi-zoom-in"></i>
58
+ </button>
59
+ <button type="button" class="btn btn-dark btn-sm" data-action="zoom-out" title="Zoom Out">
60
+ <i class="bi bi-zoom-out"></i>
61
+ </button>
62
+ <button type="button" class="btn btn-dark btn-sm" data-action="zoom-fit" title="Fit to Screen">
63
+ <i class="bi bi-arrows-fullscreen"></i>
64
+ </button>
65
+ <button type="button" class="btn btn-dark btn-sm" data-action="zoom-actual" title="Actual Size">
66
+ <i class="bi bi-1-square"></i>
67
+ </button>
68
+ {{/allowZoom}}
69
+
70
+ {{#allowRotate}}
71
+ <button type="button" class="btn btn-dark btn-sm" data-action="rotate-left" title="Rotate Left">
72
+ <i class="bi bi-arrow-counterclockwise"></i>
73
+ </button>
74
+ <button type="button" class="btn btn-dark btn-sm" data-action="rotate-right" title="Rotate Right">
75
+ <i class="bi bi-arrow-clockwise"></i>
76
+ </button>
77
+ {{/allowRotate}}
78
+
79
+ <button type="button" class="btn btn-dark btn-sm" data-action="reset" title="Reset View">
80
+ <i class="bi bi-arrow-repeat"></i>
81
+ </button>
82
+
83
+ {{#allowDownload}}
84
+ <button type="button" class="btn btn-dark btn-sm" data-action="download" title="Download Image">
85
+ <i class="bi bi-download"></i>
86
+ </button>
87
+ {{/allowDownload}}
88
+ </div>
89
+
90
+ <div class="image-viewer-info">
91
+ <span class="zoom-level">{{scale}}%</span>
92
+ </div>
93
+ </div>
94
+ {{/showControls}}
95
+ </div>
96
+ `;
97
+ }
98
+ async onAfterRender() {
99
+ this.canvas = this.element.querySelector(".image-viewer-canvas");
100
+ this.context = this.canvas.getContext("2d");
101
+ this.containerElement = this.element.querySelector(".image-viewer-content");
102
+ this.controlsElement = this.element.querySelector(".image-viewer-controls");
103
+ this.setupCanvas();
104
+ this.setupEventListeners();
105
+ if (this.imageUrl) {
106
+ this.loadImage(this.imageUrl);
107
+ }
108
+ }
109
+ setupCanvas() {
110
+ if (!this.canvas || !this.containerElement) return;
111
+ if (this.context) {
112
+ this.context.imageSmoothingEnabled = true;
113
+ this.context.imageSmoothingQuality = "high";
114
+ }
115
+ setTimeout(() => {
116
+ this.resizeCanvas();
117
+ if (this.isLoaded && this.image) {
118
+ this.renderCanvas();
119
+ }
120
+ }, 2e3);
121
+ }
122
+ resizeCanvas() {
123
+ if (!this.canvas) return;
124
+ const viewportWidth = window.innerWidth;
125
+ const viewportHeight = window.innerHeight;
126
+ const canvasWidth = Math.floor(viewportWidth * 0.8);
127
+ const canvasHeight = Math.floor(viewportHeight * 0.8);
128
+ if (canvasWidth === this.canvasWidth && canvasHeight === this.canvasHeight) {
129
+ return;
130
+ }
131
+ const dpr = window.devicePixelRatio || 1;
132
+ this.canvasWidth = canvasWidth;
133
+ this.canvasHeight = canvasHeight;
134
+ this.canvas.width = canvasWidth * dpr;
135
+ this.canvas.height = canvasHeight * dpr;
136
+ this.canvas.style.width = canvasWidth + "px";
137
+ this.canvas.style.height = canvasHeight + "px";
138
+ this.context.setTransform(dpr, 0, 0, dpr, 0, 0);
139
+ if (this.isLoaded && this.image) {
140
+ this.renderCanvas();
141
+ }
142
+ }
143
+ setupEventListeners() {
144
+ if (!this.canvas) return;
145
+ if (this.allowPan) {
146
+ this.canvas.addEventListener("mousedown", (e2) => this.handleMouseDown(e2));
147
+ document.addEventListener("mousemove", (e2) => this.handleMouseMove(e2));
148
+ document.addEventListener("mouseup", (e2) => this.handleMouseUp(e2));
149
+ }
150
+ if (this.allowZoom) {
151
+ this.canvas.addEventListener("wheel", (e2) => this.handleWheel(e2), { passive: false });
152
+ }
153
+ this.canvas.addEventListener("touchstart", (e2) => this.handleTouchStart(e2), { passive: false });
154
+ this.canvas.addEventListener("touchmove", (e2) => this.handleTouchMove(e2), { passive: false });
155
+ this.canvas.addEventListener("touchend", (e2) => this.handleTouchEnd(e2));
156
+ this.canvas.addEventListener("contextmenu", (e2) => e2.preventDefault());
157
+ }
158
+ // Action handlers
159
+ async handleActionZoomIn() {
160
+ this.zoomIn();
161
+ }
162
+ async handleActionZoomOut() {
163
+ this.zoomOut();
164
+ }
165
+ async handleActionZoomFit() {
166
+ this.fitToContainer();
167
+ }
168
+ async handleActionZoomActual() {
169
+ this.setScale(1);
170
+ this.renderCanvas();
171
+ }
172
+ async handleActionRotateLeft() {
173
+ this.rotate(-90);
174
+ }
175
+ async handleActionRotateRight() {
176
+ this.rotate(90);
177
+ }
178
+ async handleActionReset() {
179
+ this.reset();
180
+ }
181
+ async handleActionDownload() {
182
+ this.downloadImage();
183
+ }
184
+ // Image loading
185
+ loadImage(imageUrl) {
186
+ this.isLoaded = false;
187
+ this.element.classList.remove("loaded");
188
+ const img = new Image();
189
+ img.crossOrigin = "anonymous";
190
+ img.onload = () => {
191
+ this.image = img;
192
+ this.handleImageLoad();
193
+ };
194
+ img.onerror = () => {
195
+ this.handleImageError();
196
+ };
197
+ img.src = imageUrl;
198
+ }
199
+ handleImageLoad() {
200
+ this.isLoaded = true;
201
+ this.element.classList.add("loaded");
202
+ const ensureCanvasReady = () => {
203
+ if (!this.canvasWidth || !this.canvasHeight) {
204
+ this.resizeCanvas();
205
+ }
206
+ if (this.autoFit) {
207
+ this.fitToContainer();
208
+ } else {
209
+ this.smartFit();
210
+ }
211
+ this.renderCanvas();
212
+ this.updateControls();
213
+ };
214
+ if (!this.canvasWidth || !this.canvasHeight) {
215
+ setTimeout(ensureCanvasReady, 2e3);
216
+ } else {
217
+ requestAnimationFrame(ensureCanvasReady);
218
+ }
219
+ const eventBus = this.getApp()?.events;
220
+ if (eventBus) {
221
+ eventBus.emit("imageviewer:loaded", {
222
+ viewer: this,
223
+ imageUrl: this.imageUrl,
224
+ naturalWidth: this.image.naturalWidth,
225
+ naturalHeight: this.image.naturalHeight
226
+ });
227
+ }
228
+ }
229
+ handleImageError() {
230
+ console.error("Failed to load image:", this.imageUrl);
231
+ const eventBus = this.getApp()?.events;
232
+ if (eventBus) {
233
+ eventBus.emit("imageviewer:error", {
234
+ viewer: this,
235
+ imageUrl: this.imageUrl,
236
+ error: "Failed to load image"
237
+ });
238
+ }
239
+ }
240
+ // Mouse interaction
241
+ handleMouseDown(e2) {
242
+ if (!this.allowPan || e2.button !== 0) return;
243
+ e2.preventDefault();
244
+ this.isDragging = true;
245
+ const rect = this.canvas.getBoundingClientRect();
246
+ this.lastPointerX = e2.clientX - rect.left;
247
+ this.lastPointerY = e2.clientY - rect.top;
248
+ this.canvas.style.cursor = "grabbing";
249
+ }
250
+ handleMouseMove(e2) {
251
+ if (!this.isDragging || !this.allowPan) return;
252
+ e2.preventDefault();
253
+ const rect = this.canvas.getBoundingClientRect();
254
+ const currentX = e2.clientX - rect.left;
255
+ const currentY = e2.clientY - rect.top;
256
+ const deltaX = currentX - this.lastPointerX;
257
+ const deltaY = currentY - this.lastPointerY;
258
+ this.pan(deltaX, deltaY);
259
+ this.lastPointerX = currentX;
260
+ this.lastPointerY = currentY;
261
+ }
262
+ handleMouseUp(e2) {
263
+ if (!this.isDragging) return;
264
+ this.isDragging = false;
265
+ this.canvas.style.cursor = this.allowPan ? "grab" : "default";
266
+ }
267
+ handleWheel(e2) {
268
+ if (!this.allowZoom) return;
269
+ e2.preventDefault();
270
+ const rect = this.canvas.getBoundingClientRect();
271
+ const x = e2.clientX - rect.left;
272
+ const y = e2.clientY - rect.top;
273
+ const delta = e2.deltaY > 0 ? -this.scaleStep * 0.5 : this.scaleStep * 0.5;
274
+ this.zoomAtPoint(this.scale + delta, x, y);
275
+ }
276
+ // Touch events
277
+ handleTouchStart(e2) {
278
+ if (e2.touches.length === 1 && this.allowPan) {
279
+ e2.preventDefault();
280
+ const touch = e2.touches[0];
281
+ const rect = this.canvas.getBoundingClientRect();
282
+ this.isDragging = true;
283
+ this.lastPointerX = touch.clientX - rect.left;
284
+ this.lastPointerY = touch.clientY - rect.top;
285
+ }
286
+ }
287
+ handleTouchMove(e2) {
288
+ if (e2.touches.length === 1 && this.isDragging && this.allowPan) {
289
+ e2.preventDefault();
290
+ const touch = e2.touches[0];
291
+ const rect = this.canvas.getBoundingClientRect();
292
+ const currentX = touch.clientX - rect.left;
293
+ const currentY = touch.clientY - rect.top;
294
+ const deltaX = currentX - this.lastPointerX;
295
+ const deltaY = currentY - this.lastPointerY;
296
+ this.pan(deltaX, deltaY);
297
+ this.lastPointerX = currentX;
298
+ this.lastPointerY = currentY;
299
+ }
300
+ }
301
+ handleTouchEnd(e2) {
302
+ this.isDragging = false;
303
+ }
304
+ // Transform methods
305
+ zoomIn() {
306
+ this.setScale(this.scale + this.scaleStep);
307
+ }
308
+ zoomOut() {
309
+ this.setScale(this.scale - this.scaleStep);
310
+ }
311
+ setScale(scale) {
312
+ const oldScale = this.scale;
313
+ this.scale = Math.max(this.minScale, Math.min(this.maxScale, scale));
314
+ this.renderCanvas();
315
+ this.updateControls();
316
+ const eventBus = this.getApp()?.events;
317
+ if (eventBus && oldScale !== this.scale) {
318
+ eventBus.emit("imageviewer:scale-changed", {
319
+ viewer: this,
320
+ oldScale,
321
+ newScale: this.scale
322
+ });
323
+ }
324
+ }
325
+ zoomAtPoint(scale, x, y) {
326
+ if (!this.image) return;
327
+ const oldScale = this.scale;
328
+ this.setScale(scale);
329
+ if (oldScale !== this.scale) {
330
+ const scaleDiff = this.scale / oldScale;
331
+ const centerX = this.canvasWidth / 2;
332
+ const centerY = this.canvasHeight / 2;
333
+ this.translateX = (this.translateX - (x - centerX)) * scaleDiff + (x - centerX);
334
+ this.translateY = (this.translateY - (y - centerY)) * scaleDiff + (y - centerY);
335
+ this.renderCanvas();
336
+ }
337
+ }
338
+ pan(deltaX, deltaY) {
339
+ this.translateX += deltaX;
340
+ this.translateY += deltaY;
341
+ this.renderCanvas();
342
+ }
343
+ rotate(degrees) {
344
+ const oldRotation = this.rotation;
345
+ this.rotation = (this.rotation + degrees) % 360;
346
+ if (this.rotation < 0) this.rotation += 360;
347
+ this.renderCanvas();
348
+ const eventBus = this.getApp()?.events;
349
+ if (eventBus) {
350
+ eventBus.emit("imageviewer:rotated", {
351
+ viewer: this,
352
+ oldRotation,
353
+ newRotation: this.rotation,
354
+ degrees
355
+ });
356
+ }
357
+ }
358
+ center() {
359
+ this.translateX = 0;
360
+ this.translateY = 0;
361
+ this.renderCanvas();
362
+ }
363
+ fitToContainer() {
364
+ if (!this.image || !this.canvasWidth || !this.canvasHeight) return;
365
+ const padding = 40;
366
+ const availableWidth = this.canvasWidth - padding;
367
+ const availableHeight = this.canvasHeight - padding;
368
+ const scaleX = availableWidth / this.image.naturalWidth;
369
+ const scaleY = availableHeight / this.image.naturalHeight;
370
+ const scale = Math.min(scaleX, scaleY, 1);
371
+ this.setScale(scale);
372
+ this.renderCanvas();
373
+ }
374
+ smartFit() {
375
+ if (!this.image || !this.canvasWidth || !this.canvasHeight) return;
376
+ const padding = 80;
377
+ const scaleX = (this.canvasWidth - padding) / this.image.naturalWidth;
378
+ const scaleY = (this.canvasHeight - padding) / this.image.naturalHeight;
379
+ const fitScale = Math.min(scaleX, scaleY);
380
+ if (fitScale < 1) {
381
+ this.setScale(fitScale);
382
+ }
383
+ this.renderCanvas();
384
+ }
385
+ reset() {
386
+ this.scale = 1;
387
+ this.rotation = 0;
388
+ this.translateX = 0;
389
+ this.translateY = 0;
390
+ this.renderCanvas();
391
+ this.updateControls();
392
+ }
393
+ // Canvas rendering
394
+ renderCanvas() {
395
+ if (!this.context || !this.canvasWidth || !this.canvasHeight) return;
396
+ this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
397
+ if (!this.image || !this.isLoaded) return;
398
+ this.context.save();
399
+ this.context.translate(
400
+ this.canvasWidth / 2 + this.translateX,
401
+ this.canvasHeight / 2 + this.translateY
402
+ );
403
+ this.context.scale(this.scale, this.scale);
404
+ this.context.rotate(this.rotation * Math.PI / 180);
405
+ this.context.drawImage(
406
+ this.image,
407
+ -this.image.naturalWidth / 2,
408
+ -this.image.naturalHeight / 2
409
+ );
410
+ this.context.restore();
411
+ }
412
+ // Download functionality
413
+ downloadImage() {
414
+ if (!this.canvas) return;
415
+ try {
416
+ const link = document.createElement("a");
417
+ link.download = this.getDownloadFilename();
418
+ link.href = this.canvas.toDataURL("image/png");
419
+ document.body.appendChild(link);
420
+ link.click();
421
+ document.body.removeChild(link);
422
+ const eventBus = this.getApp()?.events;
423
+ if (eventBus) {
424
+ eventBus.emit("imageviewer:downloaded", {
425
+ viewer: this,
426
+ filename: link.download
427
+ });
428
+ }
429
+ } catch (error) {
430
+ console.error("Failed to download image:", error);
431
+ const eventBus = this.getApp()?.events;
432
+ if (eventBus) {
433
+ eventBus.emit("imageviewer:download-error", {
434
+ viewer: this,
435
+ error: error.message
436
+ });
437
+ }
438
+ }
439
+ }
440
+ getDownloadFilename() {
441
+ if (this.title) {
442
+ return `${this.title.replace(/[^a-z0-9]/gi, "_").toLowerCase()}.png`;
443
+ }
444
+ try {
445
+ const url = new URL(this.imageUrl);
446
+ const pathname = url.pathname;
447
+ const filename = pathname.split("/").pop();
448
+ if (filename && filename.includes(".")) {
449
+ return filename.replace(/\.[^.]+$/, ".png");
450
+ }
451
+ } catch (e2) {
452
+ }
453
+ return "image.png";
454
+ }
455
+ updateControls() {
456
+ if (!this.controlsElement) return;
457
+ const zoomLevel = this.controlsElement.querySelector(".zoom-level");
458
+ if (zoomLevel) {
459
+ zoomLevel.textContent = `${Math.round(this.scale * 100)}%`;
460
+ }
461
+ const zoomInBtn = this.controlsElement.querySelector('[data-action="zoom-in"]');
462
+ const zoomOutBtn = this.controlsElement.querySelector('[data-action="zoom-out"]');
463
+ if (zoomInBtn) {
464
+ zoomInBtn.disabled = this.scale >= this.maxScale;
465
+ }
466
+ if (zoomOutBtn) {
467
+ zoomOutBtn.disabled = this.scale <= this.minScale;
468
+ }
469
+ }
470
+ // Public API methods
471
+ setImage(imageUrl, alt = "", title = "") {
472
+ const oldImageUrl = this.imageUrl;
473
+ this.imageUrl = imageUrl;
474
+ this.alt = alt;
475
+ this.title = title;
476
+ this.reset();
477
+ this.loadImage(imageUrl);
478
+ const eventBus = this.getApp()?.events;
479
+ if (eventBus) {
480
+ eventBus.emit("imageviewer:image-changed", {
481
+ viewer: this,
482
+ oldImageUrl,
483
+ newImageUrl: imageUrl
484
+ });
485
+ }
486
+ }
487
+ getCurrentState() {
488
+ return {
489
+ scale: this.scale,
490
+ rotation: this.rotation,
491
+ translateX: this.translateX,
492
+ translateY: this.translateY
493
+ };
494
+ }
495
+ setState(state) {
496
+ if (state.scale !== void 0) this.scale = state.scale;
497
+ if (state.rotation !== void 0) this.rotation = state.rotation;
498
+ if (state.translateX !== void 0) this.translateX = state.translateX;
499
+ if (state.translateY !== void 0) this.translateY = state.translateY;
500
+ this.renderCanvas();
501
+ this.updateControls();
502
+ }
503
+ async onBeforeDestroy() {
504
+ if (this.isDragging) {
505
+ this.isDragging = false;
506
+ }
507
+ const eventBus = this.getApp()?.events;
508
+ if (eventBus) {
509
+ eventBus.emit("imageviewer:destroyed", { viewer: this });
510
+ }
511
+ }
512
+ // Static method to show image in a fullscreen dialog
513
+ static async showDialog(imageUrl, options = {}) {
514
+ const {
515
+ title = "Image Viewer",
516
+ alt = "Image",
517
+ size = "fullscreen",
518
+ showControls = true,
519
+ allowRotate = true,
520
+ allowZoom = true,
521
+ allowPan = true,
522
+ allowDownload = true,
523
+ ...dialogOptions
524
+ } = options;
525
+ const viewer = new ImageViewer({
526
+ imageUrl,
527
+ alt,
528
+ title,
529
+ showControls,
530
+ allowRotate,
531
+ allowZoom,
532
+ allowPan,
533
+ allowDownload,
534
+ autoFit: true
535
+ });
536
+ return Dialog.showDialog({
537
+ title,
538
+ body: viewer,
539
+ size,
540
+ centered: true,
541
+ backdrop: "static",
542
+ keyboard: true,
543
+ buttons: [
544
+ {
545
+ text: "Close",
546
+ action: "close",
547
+ class: "btn btn-secondary",
548
+ dismiss: true
549
+ }
550
+ ],
551
+ ...dialogOptions
552
+ });
553
+ }
554
+ }
555
+ window.ImageViewer = ImageViewer;
556
+ class ImageCanvasView extends View {
557
+ constructor(options = {}) {
558
+ super({
559
+ ...options,
560
+ className: `image-canvas-view ${options.className || ""}`,
561
+ tagName: "div"
562
+ });
563
+ this.imageUrl = options.imageUrl || options.src || "";
564
+ this.alt = options.alt || "Image";
565
+ this.title = options.title || "";
566
+ this.canvas = null;
567
+ this.context = null;
568
+ this.image = null;
569
+ this.canvasWidth = 0;
570
+ this.canvasHeight = 0;
571
+ this.maxCanvasHeightPercent = options.maxCanvasHeightPercent || 0.7;
572
+ this.maxCanvasWidthPercent = options.maxCanvasWidthPercent || 0.8;
573
+ this.canvasSizes = {
574
+ sm: { width: 400, height: 300 },
575
+ // Small - thumbnails, previews
576
+ md: { width: 600, height: 450 },
577
+ // Medium - dialogs, cards
578
+ lg: { width: 800, height: 600 },
579
+ // Large - main editing
580
+ xl: { width: 1e3, height: 750 },
581
+ // Extra Large - detailed work
582
+ fullscreen: { width: 0, height: 0 },
583
+ // Special case - use viewport
584
+ auto: { width: 0, height: 0 }
585
+ // Auto-size based on image + viewport
586
+ };
587
+ this.canvasSize = options.canvasSize || "auto";
588
+ this.isLoaded = false;
589
+ this.isRendering = false;
590
+ this.autoFit = options.autoFit !== false;
591
+ this.crossOrigin = options.crossOrigin || "anonymous";
592
+ }
593
+ async getTemplate() {
594
+ return `
595
+ <div class="image-canvas-container d-flex flex-column h-100">
596
+ <div class="image-canvas-content flex-grow-1 position-relative d-flex justify-content-center align-items-center">
597
+ <canvas class="image-canvas w-100 h-100" data-container="canvas"></canvas>
598
+
599
+ <!-- Loading Overlay -->
600
+ <div class="image-canvas-loading position-absolute top-50 start-50 translate-middle"
601
+ style="display: none; z-index: 10;">
602
+ <div class="spinner-border text-primary" role="status">
603
+ <span class="visually-hidden">Loading...</span>
604
+ </div>
605
+ </div>
606
+ </div>
607
+ </div>
608
+ `;
609
+ }
610
+ async onAfterRender() {
611
+ this.canvas = this.element.querySelector("canvas");
612
+ this.context = this.canvas.getContext("2d");
613
+ this.containerElement = this.element.querySelector(".image-canvas-content");
614
+ this.loadingElement = this.element.querySelector(".image-canvas-loading");
615
+ this.setupCanvas();
616
+ if (this.imageUrl) {
617
+ this.loadImage(this.imageUrl);
618
+ }
619
+ }
620
+ setupCanvas() {
621
+ if (!this.canvas || !this.containerElement) return;
622
+ this.setCanvasSize(this.canvasSize);
623
+ if (this.canvasSize === "fullscreen") {
624
+ this._resizeHandler = () => this.setCanvasSize("fullscreen");
625
+ window.addEventListener("resize", this._resizeHandler);
626
+ }
627
+ this.context.imageSmoothingEnabled = true;
628
+ this.context.imageSmoothingQuality = "high";
629
+ }
630
+ setCanvasSize(size) {
631
+ const preset = this.canvasSizes[size];
632
+ if (!preset && size !== "auto") return;
633
+ let canvasWidth, canvasHeight;
634
+ if (size === "fullscreen") {
635
+ canvasWidth = Math.min(1200, window.innerWidth * 0.9);
636
+ canvasHeight = Math.min(900, window.innerHeight * 0.8);
637
+ } else if (size === "auto" || !preset) {
638
+ if (this.image) {
639
+ const maxWidth = window.innerWidth * this.maxCanvasWidthPercent;
640
+ const maxHeight = window.innerHeight * this.maxCanvasHeightPercent;
641
+ const scaleX = maxWidth / this.image.naturalWidth;
642
+ const scaleY = maxHeight / this.image.naturalHeight;
643
+ const scale = Math.min(scaleX, scaleY, 1);
644
+ canvasWidth = Math.floor(this.image.naturalWidth * scale);
645
+ canvasHeight = Math.floor(this.image.naturalHeight * scale);
646
+ canvasWidth = Math.max(300, canvasWidth);
647
+ canvasHeight = Math.max(200, canvasHeight);
648
+ } else {
649
+ canvasWidth = Math.min(600, window.innerWidth * this.maxCanvasWidthPercent);
650
+ canvasHeight = Math.min(450, window.innerHeight * this.maxCanvasHeightPercent);
651
+ }
652
+ } else {
653
+ const maxWidth = window.innerWidth * this.maxCanvasWidthPercent;
654
+ const maxHeight = window.innerHeight * this.maxCanvasHeightPercent;
655
+ if (preset.width > maxWidth || preset.height > maxHeight) {
656
+ if (this.image) {
657
+ const scaleX = maxWidth / this.image.naturalWidth;
658
+ const scaleY = maxHeight / this.image.naturalHeight;
659
+ const scale = Math.min(scaleX, scaleY, 1);
660
+ canvasWidth = Math.floor(this.image.naturalWidth * scale);
661
+ canvasHeight = Math.floor(this.image.naturalHeight * scale);
662
+ canvasWidth = Math.max(300, canvasWidth);
663
+ canvasHeight = Math.max(200, canvasHeight);
664
+ } else {
665
+ canvasWidth = Math.min(600, maxWidth);
666
+ canvasHeight = Math.min(450, maxHeight);
667
+ }
668
+ } else {
669
+ canvasWidth = preset.width;
670
+ canvasHeight = preset.height;
671
+ }
672
+ }
673
+ canvasWidth = Math.min(canvasWidth, window.innerWidth * this.maxCanvasWidthPercent);
674
+ canvasHeight = Math.min(canvasHeight, window.innerHeight * this.maxCanvasHeightPercent);
675
+ if (Math.abs(canvasWidth - this.canvasWidth) < 10 && Math.abs(canvasHeight - this.canvasHeight) < 10) {
676
+ return;
677
+ }
678
+ const dpr = window.devicePixelRatio || 1;
679
+ this.canvasWidth = canvasWidth;
680
+ this.canvasHeight = canvasHeight;
681
+ this.canvas.width = canvasWidth * dpr;
682
+ this.canvas.height = canvasHeight * dpr;
683
+ this.canvas.style.width = canvasWidth + "px";
684
+ this.canvas.style.height = canvasHeight + "px";
685
+ this.context.setTransform(dpr, 0, 0, dpr, 0, 0);
686
+ if (this.isLoaded) {
687
+ this.renderCanvas();
688
+ }
689
+ }
690
+ // Image loading
691
+ loadImage(imageUrl) {
692
+ if (!imageUrl) return;
693
+ this.imageUrl = imageUrl;
694
+ this.isLoaded = false;
695
+ this.element.classList.remove("loaded");
696
+ this.showLoading();
697
+ const img = new Image();
698
+ if (this.crossOrigin) {
699
+ img.crossOrigin = this.crossOrigin;
700
+ }
701
+ img.onload = () => {
702
+ this.image = img;
703
+ this.handleImageLoad();
704
+ };
705
+ img.onerror = () => {
706
+ this.handleImageError();
707
+ };
708
+ img.src = imageUrl;
709
+ }
710
+ handleImageLoad() {
711
+ this.isLoaded = true;
712
+ this.element.classList.add("loaded");
713
+ this.hideLoading();
714
+ if (this.canvasSize === "auto") {
715
+ this.setCanvasSize("auto");
716
+ } else if (this.autoFit) {
717
+ this.fitToContainer();
718
+ }
719
+ this.renderCanvas();
720
+ const eventBus = this.getApp()?.events;
721
+ if (eventBus) {
722
+ eventBus.emit("imagecanvas:loaded", {
723
+ view: this,
724
+ imageUrl: this.imageUrl,
725
+ naturalWidth: this.image.naturalWidth,
726
+ naturalHeight: this.image.naturalHeight
727
+ });
728
+ }
729
+ }
730
+ handleImageError() {
731
+ console.error("Failed to load image:", this.imageUrl);
732
+ this.hideLoading();
733
+ const eventBus = this.getApp()?.events;
734
+ if (eventBus) {
735
+ eventBus.emit("imagecanvas:error", {
736
+ view: this,
737
+ imageUrl: this.imageUrl,
738
+ error: "Failed to load image"
739
+ });
740
+ }
741
+ }
742
+ showLoading() {
743
+ if (this.loadingElement) {
744
+ this.loadingElement.style.display = "block";
745
+ }
746
+ }
747
+ hideLoading() {
748
+ if (this.loadingElement) {
749
+ this.loadingElement.style.display = "none";
750
+ }
751
+ }
752
+ // Base canvas rendering - to be extended by child classes
753
+ renderCanvas() {
754
+ if (!this.context || !this.canvasWidth || !this.canvasHeight || this.isRendering) return;
755
+ this.isRendering = true;
756
+ this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
757
+ if (!this.image || !this.isLoaded) {
758
+ this.isRendering = false;
759
+ return;
760
+ }
761
+ this.context.save();
762
+ this.renderImage();
763
+ this.context.restore();
764
+ this.isRendering = false;
765
+ }
766
+ // Basic image rendering with smart scaling - can be overridden
767
+ renderImage() {
768
+ if (!this.image) return;
769
+ const scaleX = this.canvasWidth / this.image.naturalWidth;
770
+ const scaleY = this.canvasHeight / this.image.naturalHeight;
771
+ const scale = Math.min(scaleX, scaleY, 1);
772
+ const scaledWidth = this.image.naturalWidth * scale;
773
+ const scaledHeight = this.image.naturalHeight * scale;
774
+ const x = (this.canvasWidth - scaledWidth) / 2;
775
+ const y = (this.canvasHeight - scaledHeight) / 2;
776
+ this.context.drawImage(this.image, x, y, scaledWidth, scaledHeight);
777
+ }
778
+ // Utility methods
779
+ fitToContainer() {
780
+ if (!this.image || !this.canvasWidth || !this.canvasHeight) return;
781
+ const padding = 40;
782
+ const availableWidth = this.canvasWidth - padding;
783
+ const availableHeight = this.canvasHeight - padding;
784
+ availableWidth / this.image.naturalWidth;
785
+ availableHeight / this.image.naturalHeight;
786
+ if (this.canvasSize === "auto") {
787
+ this.setCanvasSize("auto");
788
+ }
789
+ this.renderCanvas();
790
+ }
791
+ center() {
792
+ this.renderCanvas();
793
+ }
794
+ reset() {
795
+ this.renderCanvas();
796
+ }
797
+ // Export functionality
798
+ exportImageData() {
799
+ if (!this.canvas) return null;
800
+ try {
801
+ return this.canvas.toDataURL("image/png");
802
+ } catch (error) {
803
+ console.error("Failed to export image data:", error);
804
+ return null;
805
+ }
806
+ }
807
+ exportImageBlob(quality = 0.9) {
808
+ if (!this.canvas) return Promise.resolve(null);
809
+ return new Promise((resolve) => {
810
+ try {
811
+ this.canvas.toBlob((blob) => {
812
+ resolve(blob);
813
+ }, "image/png", quality);
814
+ } catch (error) {
815
+ console.error("Failed to export image blob:", error);
816
+ resolve(null);
817
+ }
818
+ });
819
+ }
820
+ // Public API
821
+ setImage(imageUrl, alt = "", title = "") {
822
+ const oldImageUrl = this.imageUrl;
823
+ this.alt = alt;
824
+ this.title = title;
825
+ this.loadImage(imageUrl);
826
+ const eventBus = this.getApp()?.events;
827
+ if (eventBus) {
828
+ eventBus.emit("imagecanvas:image-changed", {
829
+ view: this,
830
+ oldImageUrl,
831
+ newImageUrl: imageUrl
832
+ });
833
+ }
834
+ }
835
+ getImageData() {
836
+ return {
837
+ imageUrl: this.imageUrl,
838
+ alt: this.alt,
839
+ title: this.title,
840
+ naturalWidth: this.image?.naturalWidth || 0,
841
+ naturalHeight: this.image?.naturalHeight || 0,
842
+ isLoaded: this.isLoaded
843
+ };
844
+ }
845
+ async onBeforeDestroy() {
846
+ this.isLoaded = false;
847
+ this.isRendering = false;
848
+ this.image = null;
849
+ if (this._resizeHandler) {
850
+ window.removeEventListener("resize", this._resizeHandler);
851
+ }
852
+ const eventBus = this.getApp()?.events;
853
+ if (eventBus) {
854
+ eventBus.emit("imagecanvas:destroyed", { view: this });
855
+ }
856
+ }
857
+ }
858
+ window.ImageCanvasView = ImageCanvasView;
859
+ class ImageTransformView extends ImageCanvasView {
860
+ constructor(options = {}) {
861
+ super({
862
+ ...options,
863
+ className: `image-transform-view ${options.className || ""}`
864
+ });
865
+ this.scale = 1;
866
+ this.rotation = 0;
867
+ this.translateX = 0;
868
+ this.translateY = 0;
869
+ this.minScale = 0.1;
870
+ this.maxScale = 5;
871
+ this.scaleStep = 0.02;
872
+ this.isDragging = false;
873
+ this.lastPointerX = 0;
874
+ this.lastPointerY = 0;
875
+ this.allowPan = options.allowPan !== false;
876
+ this.allowZoom = options.allowZoom !== false;
877
+ this.allowRotate = options.allowRotate !== false;
878
+ this.allowKeyboard = options.allowKeyboard !== false;
879
+ this._handleMouseMove = this.handleMouseMove.bind(this);
880
+ this._handleMouseUp = this.handleMouseUp.bind(this);
881
+ this._handleKeyboard = this.handleKeyboard.bind(this);
882
+ if (!options.maxCanvasHeightPercent) {
883
+ this.maxCanvasHeightPercent = 0.6;
884
+ }
885
+ }
886
+ async getTemplate() {
887
+ return `
888
+ <div class="image-transform-container d-flex flex-column h-100">
889
+ <!-- Transform Toolbar -->
890
+ <div class="image-transform-toolbar bg-light border-bottom p-2">
891
+ <div class="btn-toolbar justify-content-center" role="toolbar">
892
+ <div class="btn-group me-2" role="group" aria-label="Zoom controls">
893
+ <button type="button" class="btn btn-outline-primary btn-sm" data-action="zoom-in" title="Zoom In">
894
+ <i class="bi bi-zoom-in"></i>
895
+ </button>
896
+ <button type="button" class="btn btn-outline-primary btn-sm" data-action="zoom-out" title="Zoom Out">
897
+ <i class="bi bi-zoom-out"></i>
898
+ </button>
899
+ <button type="button" class="btn btn-outline-secondary btn-sm" data-action="fit-to-screen" title="Fit to Screen">
900
+ <i class="bi bi-arrows-fullscreen"></i>
901
+ </button>
902
+ <button type="button" class="btn btn-outline-secondary btn-sm" data-action="actual-size" title="Actual Size">
903
+ <i class="bi bi-1-square"></i>
904
+ </button>
905
+ </div>
906
+
907
+ <div class="btn-group me-2" role="group" aria-label="Rotate controls">
908
+ <button type="button" class="btn btn-outline-info btn-sm" data-action="rotate-left" title="Rotate Left">
909
+ <i class="bi bi-arrow-counterclockwise"></i>
910
+ </button>
911
+ <button type="button" class="btn btn-outline-info btn-sm" data-action="rotate-right" title="Rotate Right">
912
+ <i class="bi bi-arrow-clockwise"></i>
913
+ </button>
914
+ </div>
915
+
916
+ <div class="btn-group" role="group" aria-label="Position controls">
917
+ <button type="button" class="btn btn-outline-secondary btn-sm" data-action="center-image" title="Center Image">
918
+ <i class="bi bi-bullseye"></i>
919
+ </button>
920
+ </div>
921
+ </div>
922
+ </div>
923
+
924
+ <!-- Canvas Area -->
925
+ <div class="image-canvas-content flex-grow-1 position-relative d-flex justify-content-center align-items-center">
926
+ <canvas class="image-canvas" data-container="canvas"></canvas>
927
+
928
+ <!-- Loading Overlay -->
929
+ <div class="image-canvas-loading position-absolute top-50 start-50 translate-middle"
930
+ style="display: none; z-index: 10;">
931
+ <div class="spinner-border text-primary" role="status">
932
+ <span class="visually-hidden">Loading...</span>
933
+ </div>
934
+ </div>
935
+ </div>
936
+ </div>
937
+ `;
938
+ }
939
+ async onAfterRender() {
940
+ await super.onAfterRender();
941
+ this.setupInteractionListeners();
942
+ }
943
+ setupInteractionListeners() {
944
+ if (!this.canvas) return;
945
+ if (this.allowPan) {
946
+ this.canvas.addEventListener("mousedown", (e2) => this.handleMouseDown(e2));
947
+ document.addEventListener("mousemove", this._handleMouseMove);
948
+ document.addEventListener("mouseup", this._handleMouseUp);
949
+ }
950
+ if (this.allowZoom) {
951
+ this.canvas.addEventListener("wheel", (e2) => this.handleWheel(e2), { passive: false });
952
+ }
953
+ this.canvas.addEventListener("touchstart", (e2) => this.handleTouchStart(e2), { passive: false });
954
+ this.canvas.addEventListener("touchmove", (e2) => this.handleTouchMove(e2), { passive: false });
955
+ this.canvas.addEventListener("touchend", (e2) => this.handleTouchEnd(e2));
956
+ if (this.allowKeyboard) {
957
+ document.addEventListener("keydown", this._handleKeyboard);
958
+ }
959
+ this.canvas.addEventListener("contextmenu", (e2) => e2.preventDefault());
960
+ this.canvas.style.cursor = this.allowPan ? "grab" : "default";
961
+ }
962
+ // Override renderImage to apply transforms
963
+ renderImage() {
964
+ if (!this.image) return;
965
+ this.context.translate(
966
+ this.canvasWidth / 2 + this.translateX,
967
+ this.canvasHeight / 2 + this.translateY
968
+ );
969
+ this.context.scale(this.scale, this.scale);
970
+ this.context.rotate(this.rotation * Math.PI / 180);
971
+ this.context.drawImage(
972
+ this.image,
973
+ -this.image.naturalWidth / 2,
974
+ -this.image.naturalHeight / 2
975
+ );
976
+ }
977
+ // Mouse interaction
978
+ handleMouseDown(e2) {
979
+ if (!this.allowPan || e2.button !== 0) return;
980
+ e2.preventDefault();
981
+ this.isDragging = true;
982
+ const rect = this.canvas.getBoundingClientRect();
983
+ this.lastPointerX = e2.clientX - rect.left;
984
+ this.lastPointerY = e2.clientY - rect.top;
985
+ this.canvas.style.cursor = "grabbing";
986
+ }
987
+ handleMouseMove(e2) {
988
+ if (!this.isDragging || !this.allowPan) return;
989
+ e2.preventDefault();
990
+ const rect = this.canvas.getBoundingClientRect();
991
+ const currentX = e2.clientX - rect.left;
992
+ const currentY = e2.clientY - rect.top;
993
+ const deltaX = currentX - this.lastPointerX;
994
+ const deltaY = currentY - this.lastPointerY;
995
+ this.pan(deltaX, deltaY);
996
+ this.lastPointerX = currentX;
997
+ this.lastPointerY = currentY;
998
+ }
999
+ handleMouseUp(e2) {
1000
+ if (!this.isDragging) return;
1001
+ this.isDragging = false;
1002
+ this.canvas.style.cursor = this.allowPan ? "grab" : "default";
1003
+ }
1004
+ handleWheel(e2) {
1005
+ if (!this.allowZoom) return;
1006
+ e2.preventDefault();
1007
+ const rect = this.canvas.getBoundingClientRect();
1008
+ const x = e2.clientX - rect.left;
1009
+ const y = e2.clientY - rect.top;
1010
+ const delta = e2.deltaY > 0 ? -this.scaleStep * 0.5 : this.scaleStep * 0.5;
1011
+ this.zoomAtPoint(this.scale + delta, x, y);
1012
+ }
1013
+ // Touch events
1014
+ handleTouchStart(e2) {
1015
+ if (e2.touches.length === 1 && this.allowPan) {
1016
+ e2.preventDefault();
1017
+ const touch = e2.touches[0];
1018
+ const rect = this.canvas.getBoundingClientRect();
1019
+ this.isDragging = true;
1020
+ this.lastPointerX = touch.clientX - rect.left;
1021
+ this.lastPointerY = touch.clientY - rect.top;
1022
+ }
1023
+ }
1024
+ handleTouchMove(e2) {
1025
+ if (e2.touches.length === 1 && this.isDragging && this.allowPan) {
1026
+ e2.preventDefault();
1027
+ const touch = e2.touches[0];
1028
+ const rect = this.canvas.getBoundingClientRect();
1029
+ const currentX = touch.clientX - rect.left;
1030
+ const currentY = touch.clientY - rect.top;
1031
+ const deltaX = currentX - this.lastPointerX;
1032
+ const deltaY = currentY - this.lastPointerY;
1033
+ this.pan(deltaX, deltaY);
1034
+ this.lastPointerX = currentX;
1035
+ this.lastPointerY = currentY;
1036
+ }
1037
+ }
1038
+ handleTouchEnd(e2) {
1039
+ this.isDragging = false;
1040
+ }
1041
+ // Keyboard shortcuts
1042
+ handleKeyboard(e2) {
1043
+ if (e2.target.tagName === "INPUT" || e2.target.tagName === "TEXTAREA") return;
1044
+ switch (e2.key) {
1045
+ case "+":
1046
+ case "=":
1047
+ if (this.allowZoom) {
1048
+ e2.preventDefault();
1049
+ this.zoomIn();
1050
+ }
1051
+ break;
1052
+ case "-":
1053
+ if (this.allowZoom) {
1054
+ e2.preventDefault();
1055
+ this.zoomOut();
1056
+ }
1057
+ break;
1058
+ case "0":
1059
+ e2.preventDefault();
1060
+ this.fitToContainer();
1061
+ break;
1062
+ case "1":
1063
+ e2.preventDefault();
1064
+ this.actualSize();
1065
+ break;
1066
+ case "r":
1067
+ case "R":
1068
+ if (this.allowRotate) {
1069
+ e2.preventDefault();
1070
+ this.rotateRight();
1071
+ }
1072
+ break;
1073
+ }
1074
+ }
1075
+ // Transform methods
1076
+ zoomIn() {
1077
+ this.setScale(this.scale + this.scaleStep);
1078
+ }
1079
+ zoomOut() {
1080
+ this.setScale(this.scale - this.scaleStep);
1081
+ }
1082
+ setScale(scale) {
1083
+ const oldScale = this.scale;
1084
+ this.scale = Math.max(this.minScale, Math.min(this.maxScale, scale));
1085
+ if (oldScale !== this.scale) {
1086
+ this.renderCanvas();
1087
+ this.emitTransformEvent("scale-changed", { oldScale, newScale: this.scale });
1088
+ }
1089
+ }
1090
+ zoomAtPoint(scale, x, y) {
1091
+ if (!this.image) return;
1092
+ const oldScale = this.scale;
1093
+ this.setScale(scale);
1094
+ if (oldScale !== this.scale) {
1095
+ const scaleDiff = this.scale / oldScale;
1096
+ const centerX = this.canvasWidth / 2;
1097
+ const centerY = this.canvasHeight / 2;
1098
+ this.translateX = (this.translateX - (x - centerX)) * scaleDiff + (x - centerX);
1099
+ this.translateY = (this.translateY - (y - centerY)) * scaleDiff + (y - centerY);
1100
+ this.renderCanvas();
1101
+ }
1102
+ }
1103
+ pan(deltaX, deltaY) {
1104
+ this.translateX += deltaX;
1105
+ this.translateY += deltaY;
1106
+ this.renderCanvas();
1107
+ this.emitTransformEvent("panned", { deltaX, deltaY });
1108
+ }
1109
+ rotate(degrees) {
1110
+ const oldRotation = this.rotation;
1111
+ this.rotation = (this.rotation + degrees) % 360;
1112
+ if (this.rotation < 0) this.rotation += 360;
1113
+ this.renderCanvas();
1114
+ this.emitTransformEvent("rotated", { oldRotation, newRotation: this.rotation, degrees });
1115
+ }
1116
+ rotateLeft() {
1117
+ this.rotate(-90);
1118
+ }
1119
+ rotateRight() {
1120
+ this.rotate(90);
1121
+ }
1122
+ center() {
1123
+ this.translateX = 0;
1124
+ this.translateY = 0;
1125
+ this.renderCanvas();
1126
+ this.emitTransformEvent("centered");
1127
+ }
1128
+ actualSize() {
1129
+ this.setScale(1);
1130
+ this.center();
1131
+ }
1132
+ // Override fitToContainer with actual scaling logic
1133
+ fitToContainer() {
1134
+ if (!this.image || !this.canvasWidth || !this.canvasHeight) return;
1135
+ const padding = 40;
1136
+ const availableWidth = this.canvasWidth - padding;
1137
+ const availableHeight = this.canvasHeight - padding;
1138
+ const scaleX = availableWidth / this.image.naturalWidth;
1139
+ const scaleY = availableHeight / this.image.naturalHeight;
1140
+ const scale = Math.min(scaleX, scaleY, 1);
1141
+ this.setScale(scale);
1142
+ this.center();
1143
+ }
1144
+ smartFit() {
1145
+ if (!this.image || !this.canvasWidth || !this.canvasHeight) return;
1146
+ const padding = 80;
1147
+ const scaleX = (this.canvasWidth - padding) / this.image.naturalWidth;
1148
+ const scaleY = (this.canvasHeight - padding) / this.image.naturalHeight;
1149
+ const fitScale = Math.min(scaleX, scaleY);
1150
+ if (fitScale < 1) {
1151
+ this.setScale(fitScale);
1152
+ }
1153
+ this.center();
1154
+ }
1155
+ // Override reset with transform-specific logic
1156
+ reset() {
1157
+ this.scale = 1;
1158
+ this.rotation = 0;
1159
+ this.translateX = 0;
1160
+ this.translateY = 0;
1161
+ this.renderCanvas();
1162
+ this.emitTransformEvent("reset");
1163
+ }
1164
+ // Override handleImageLoad to apply initial transforms
1165
+ handleImageLoad() {
1166
+ super.handleImageLoad();
1167
+ if (this.autoFit) {
1168
+ this.fitToContainer();
1169
+ } else {
1170
+ this.smartFit();
1171
+ }
1172
+ }
1173
+ // State management
1174
+ getTransformState() {
1175
+ return {
1176
+ scale: this.scale,
1177
+ rotation: this.rotation,
1178
+ translateX: this.translateX,
1179
+ translateY: this.translateY
1180
+ };
1181
+ }
1182
+ setTransformState(state) {
1183
+ if (state.scale !== void 0) this.scale = state.scale;
1184
+ if (state.rotation !== void 0) this.rotation = state.rotation;
1185
+ if (state.translateX !== void 0) this.translateX = state.translateX;
1186
+ if (state.translateY !== void 0) this.translateY = state.translateY;
1187
+ this.renderCanvas();
1188
+ }
1189
+ // Event emission
1190
+ emitTransformEvent(type, data = {}) {
1191
+ const eventBus = this.getApp()?.events;
1192
+ if (eventBus) {
1193
+ eventBus.emit(`imagetransform:${type}`, {
1194
+ view: this,
1195
+ transform: this.getTransformState(),
1196
+ ...data
1197
+ });
1198
+ }
1199
+ }
1200
+ // Action handlers for toolbar buttons
1201
+ async handleActionZoomIn() {
1202
+ this.zoomIn();
1203
+ }
1204
+ async handleActionZoomOut() {
1205
+ this.zoomOut();
1206
+ }
1207
+ async handleActionFitToScreen() {
1208
+ this.fitToContainer();
1209
+ }
1210
+ async handleActionActualSize() {
1211
+ this.actualSize();
1212
+ }
1213
+ async handleActionRotateLeft() {
1214
+ this.rotateLeft();
1215
+ }
1216
+ async handleActionRotateRight() {
1217
+ this.rotateRight();
1218
+ }
1219
+ async handleActionCenterImage() {
1220
+ this.center();
1221
+ }
1222
+ // Cleanup
1223
+ async onBeforeDestroy() {
1224
+ await super.onBeforeDestroy();
1225
+ if (this.isDragging) {
1226
+ this.isDragging = false;
1227
+ }
1228
+ document.removeEventListener("mousemove", this._handleMouseMove);
1229
+ document.removeEventListener("mouseup", this._handleMouseUp);
1230
+ document.removeEventListener("keydown", this._handleKeyboard);
1231
+ this.emitTransformEvent("destroyed");
1232
+ }
1233
+ // Static method to show transform view in a dialog for standalone testing
1234
+ static async showDialog(imageUrl, options = {}) {
1235
+ const {
1236
+ title = "Transform Image",
1237
+ alt = "Image",
1238
+ size = "xl",
1239
+ allowPan = true,
1240
+ allowZoom = true,
1241
+ allowRotate = true,
1242
+ ...dialogOptions
1243
+ } = options;
1244
+ const transformView = new ImageTransformView({
1245
+ imageUrl,
1246
+ alt,
1247
+ title,
1248
+ allowPan,
1249
+ allowZoom,
1250
+ allowRotate
1251
+ });
1252
+ const dialog = new Dialog({
1253
+ title,
1254
+ body: transformView,
1255
+ size,
1256
+ centered: true,
1257
+ backdrop: "static",
1258
+ keyboard: true,
1259
+ noBodyPadding: true,
1260
+ maxCanvasHeightPercent: 0.5,
1261
+ buttons: [
1262
+ {
1263
+ text: "Cancel",
1264
+ action: "cancel",
1265
+ class: "btn btn-secondary",
1266
+ dismiss: true
1267
+ },
1268
+ {
1269
+ text: "Apply Transform",
1270
+ action: "apply-transform",
1271
+ class: "btn btn-primary"
1272
+ }
1273
+ ],
1274
+ ...dialogOptions
1275
+ });
1276
+ await dialog.render(true, document.body);
1277
+ dialog.show();
1278
+ return new Promise((resolve) => {
1279
+ dialog.on("hidden", () => {
1280
+ dialog.destroy();
1281
+ resolve({ action: "cancel", view: transformView });
1282
+ });
1283
+ dialog.on("action:cancel", () => {
1284
+ dialog.hide();
1285
+ });
1286
+ dialog.on("action:apply-transform", async () => {
1287
+ const imageData = transformView.exportImageData();
1288
+ dialog.hide();
1289
+ resolve({
1290
+ action: "transform",
1291
+ view: transformView,
1292
+ data: imageData,
1293
+ transformState: transformView.getTransformState()
1294
+ });
1295
+ });
1296
+ });
1297
+ }
1298
+ }
1299
+ window.ImageTransformView = Image;
1300
+ class ImageCropView extends ImageCanvasView {
1301
+ constructor(options = {}) {
1302
+ super({
1303
+ ...options,
1304
+ className: `image-crop-view ${options.className || ""}`
1305
+ });
1306
+ this.originalImageUrl = options.imageUrl;
1307
+ this.cropMode = false;
1308
+ this.cropBox = { x: 0, y: 0, width: 0, height: 0 };
1309
+ this.aspectRatio = options.aspectRatio || null;
1310
+ this.minCropSize = options.minCropSize || 50;
1311
+ this.fixedCropSize = options.fixedCropSize || null;
1312
+ this.cropAndScale = options.cropAndScale || null;
1313
+ this.isDragging = false;
1314
+ this.isResizing = false;
1315
+ this.dragHandle = null;
1316
+ this.dragStartImageX = 0;
1317
+ this.dragStartImageY = 0;
1318
+ this.initialCropBox = null;
1319
+ this.newCropStart = null;
1320
+ this.handles = {
1321
+ "nw": { cursor: "nw-resize", x: 0, y: 0 },
1322
+ "ne": { cursor: "ne-resize", x: 1, y: 0 },
1323
+ "sw": { cursor: "sw-resize", x: 0, y: 1 },
1324
+ "se": { cursor: "se-resize", x: 1, y: 1 },
1325
+ "n": { cursor: "n-resize", x: 0.5, y: 0 },
1326
+ "s": { cursor: "s-resize", x: 0.5, y: 1 },
1327
+ "w": { cursor: "w-resize", x: 0, y: 0.5 },
1328
+ "e": { cursor: "e-resize", x: 1, y: 0.5 }
1329
+ };
1330
+ this.handleSize = options.handleSize || 12;
1331
+ this.showGrid = options.showGrid !== false;
1332
+ this.showToolbar = options.showToolbar !== false;
1333
+ this.autoFit = options.autoFit !== false;
1334
+ this.imageOffsetX = 0;
1335
+ this.imageOffsetY = 0;
1336
+ this._handleMouseMove = this.handleMouseMove.bind(this);
1337
+ this._handleMouseUp = this.handleMouseUp.bind(this);
1338
+ if (!options.maxCanvasHeightPercent && this.showToolbar) {
1339
+ this.maxCanvasHeightPercent = 0.6;
1340
+ }
1341
+ }
1342
+ // Coordinate conversion helpers
1343
+ imageToCanvas(imageCoords) {
1344
+ if (!this.image) return imageCoords;
1345
+ const scaleX = this.canvasWidth / this.image.naturalWidth;
1346
+ const scaleY = this.canvasHeight / this.image.naturalHeight;
1347
+ let imageScale;
1348
+ if (this.autoFit) {
1349
+ imageScale = Math.min(scaleX, scaleY, 1);
1350
+ } else {
1351
+ imageScale = 1;
1352
+ }
1353
+ const scaledImageWidth = this.image.naturalWidth * imageScale;
1354
+ const scaledImageHeight = this.image.naturalHeight * imageScale;
1355
+ const imageX = (this.canvasWidth - scaledImageWidth) / 2;
1356
+ const imageY = (this.canvasHeight - scaledImageHeight) / 2;
1357
+ return {
1358
+ x: imageCoords.x * imageScale + imageX,
1359
+ y: imageCoords.y * imageScale + imageY,
1360
+ width: imageCoords.width * imageScale,
1361
+ height: imageCoords.height * imageScale
1362
+ };
1363
+ }
1364
+ canvasToImage(canvasCoords) {
1365
+ if (!this.image) return canvasCoords;
1366
+ const scaleX = this.canvasWidth / this.image.naturalWidth;
1367
+ const scaleY = this.canvasHeight / this.image.naturalHeight;
1368
+ let imageScale;
1369
+ if (this.autoFit) {
1370
+ imageScale = Math.min(scaleX, scaleY, 1);
1371
+ } else {
1372
+ imageScale = 1;
1373
+ }
1374
+ const scaledImageWidth = this.image.naturalWidth * imageScale;
1375
+ const scaledImageHeight = this.image.naturalHeight * imageScale;
1376
+ const imageX = (this.canvasWidth - scaledImageWidth) / 2;
1377
+ const imageY = (this.canvasHeight - scaledImageHeight) / 2;
1378
+ return {
1379
+ x: (canvasCoords.x - imageX) / imageScale,
1380
+ y: (canvasCoords.y - imageY) / imageScale,
1381
+ width: canvasCoords.width / imageScale,
1382
+ height: canvasCoords.height / imageScale
1383
+ };
1384
+ }
1385
+ pointCanvasToImage(canvasX, canvasY) {
1386
+ const result = this.canvasToImage({ x: canvasX, y: canvasY, width: 0, height: 0 });
1387
+ return { x: result.x, y: result.y };
1388
+ }
1389
+ async getTemplate() {
1390
+ return `
1391
+ <div class="image-crop-container d-flex flex-column h-100">
1392
+ {{#showToolbar}}
1393
+ <!-- Crop Toolbar -->
1394
+ <div class="image-crop-toolbar bg-light border-bottom p-2">
1395
+ <div class="btn-toolbar justify-content-center" role="toolbar">
1396
+ <div class="btn-group me-2" role="group" aria-label="Aspect ratio">
1397
+ <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle"
1398
+ data-bs-toggle="dropdown" title="Aspect Ratio">
1399
+ <i class="bi bi-aspect-ratio"></i> Ratio
1400
+ </button>
1401
+ <ul class="dropdown-menu">
1402
+ <li><a class="dropdown-item" href="#" data-action="set-aspect-ratio" data-ratio="free">Free</a></li>
1403
+ <li><a class="dropdown-item" href="#" data-action="set-aspect-ratio" data-ratio="1">1:1 Square</a></li>
1404
+ <li><a class="dropdown-item" href="#" data-action="set-aspect-ratio" data-ratio="1.333">4:3</a></li>
1405
+ <li><a class="dropdown-item" href="#" data-action="set-aspect-ratio" data-ratio="1.777">16:9</a></li>
1406
+ <li><a class="dropdown-item" href="#" data-action="set-aspect-ratio" data-ratio="0.75">3:4 Portrait</a></li>
1407
+ </ul>
1408
+ </div>
1409
+
1410
+ <div class="btn-group me-2" role="group" aria-label="Fit mode">
1411
+ <button type="button" class="btn btn-outline-info btn-sm" data-action="toggle-auto-fit" title="Toggle Auto-fit">
1412
+ <i class="bi bi-arrows-fullscreen"></i> <span class="auto-fit-text">Fit</span>
1413
+ </button>
1414
+ </div>
1415
+
1416
+ <div class="btn-group me-2" role="group" aria-label="Crop actions">
1417
+ <button type="button" class="btn btn-success btn-sm" data-action="apply-crop" title="Apply Crop">
1418
+ <i class="bi bi-check"></i> Apply
1419
+ </button>
1420
+ <button type="button" class="btn btn-outline-secondary btn-sm" data-action="reset-crop" title="Reset Crop">
1421
+ <i class="bi bi-arrow-repeat"></i> Reset
1422
+ </button>
1423
+ </div>
1424
+ </div>
1425
+ </div>
1426
+ {{/showToolbar}}
1427
+
1428
+ <!-- Canvas Area -->
1429
+ <div class="image-canvas-content flex-grow-1 position-relative d-flex justify-content-center align-items-center">
1430
+ <canvas class="image-crop-canvas" data-container="canvas"></canvas>
1431
+
1432
+ <!-- Loading Overlay -->
1433
+ <div class="image-canvas-loading position-absolute top-50 start-50 translate-middle"
1434
+ style="display: none; z-index: 10;">
1435
+ <div class="spinner-border text-primary" role="status">
1436
+ <span class="visually-hidden">Loading...</span>
1437
+ </div>
1438
+ </div>
1439
+ </div>
1440
+ </div>
1441
+ `;
1442
+ }
1443
+ async onAfterRender() {
1444
+ await super.onAfterRender();
1445
+ this.setupCropListeners();
1446
+ this.updateAutoFitButtonState();
1447
+ }
1448
+ updateAutoFitButtonState() {
1449
+ if (!this.showToolbar) return;
1450
+ const button = this.element.querySelector('[data-action="toggle-auto-fit"]');
1451
+ const textSpan = button?.querySelector(".auto-fit-text");
1452
+ if (button && textSpan) {
1453
+ if (this.autoFit) {
1454
+ button.classList.remove("btn-outline-warning");
1455
+ button.classList.add("btn-outline-info");
1456
+ button.title = "Toggle Auto-fit (currently: fit to canvas)";
1457
+ textSpan.textContent = "Fit";
1458
+ } else {
1459
+ button.classList.remove("btn-outline-info");
1460
+ button.classList.add("btn-outline-warning");
1461
+ button.title = "Toggle Auto-fit (currently: actual size)";
1462
+ textSpan.textContent = "1:1";
1463
+ }
1464
+ }
1465
+ }
1466
+ handleImageLoad() {
1467
+ super.handleImageLoad();
1468
+ this.updateImageOffset();
1469
+ setTimeout(() => {
1470
+ if (this.isLoaded && this.canvasWidth > 0 && this.canvasHeight > 0) {
1471
+ this.startCropMode();
1472
+ }
1473
+ }, 10);
1474
+ }
1475
+ updateImageOffset() {
1476
+ if (!this.image) return;
1477
+ const scaleX = this.canvasWidth / this.image.naturalWidth;
1478
+ const scaleY = this.canvasHeight / this.image.naturalHeight;
1479
+ let scale;
1480
+ if (this.autoFit) {
1481
+ scale = Math.min(scaleX, scaleY, 1);
1482
+ } else {
1483
+ scale = 1;
1484
+ }
1485
+ const scaledWidth = this.image.naturalWidth * scale;
1486
+ const scaledHeight = this.image.naturalHeight * scale;
1487
+ this.imageOffsetX = (this.canvasWidth - scaledWidth) / 2;
1488
+ this.imageOffsetY = (this.canvasHeight - scaledHeight) / 2;
1489
+ this.imageScale = scale;
1490
+ console.log("Updated image offset:", this.imageOffsetX, this.imageOffsetY, "scale:", this.imageScale, "autoFit:", this.autoFit);
1491
+ }
1492
+ // Override setCanvasSize to update image offset when canvas is resized
1493
+ setCanvasSize(size) {
1494
+ super.setCanvasSize(size);
1495
+ if (this.image && this.isLoaded) {
1496
+ this.updateImageOffset();
1497
+ }
1498
+ }
1499
+ // Override renderImage to scale and center the image (consistent with coordinate conversion)
1500
+ renderImage() {
1501
+ if (!this.image) return;
1502
+ const scaleX = this.canvasWidth / this.image.naturalWidth;
1503
+ const scaleY = this.canvasHeight / this.image.naturalHeight;
1504
+ let scale;
1505
+ if (this.autoFit) {
1506
+ scale = Math.min(scaleX, scaleY, 1);
1507
+ } else {
1508
+ scale = 1;
1509
+ }
1510
+ const scaledWidth = this.image.naturalWidth * scale;
1511
+ const scaledHeight = this.image.naturalHeight * scale;
1512
+ const x = (this.canvasWidth - scaledWidth) / 2;
1513
+ const y = (this.canvasHeight - scaledHeight) / 2;
1514
+ this.context.drawImage(this.image, x, y, scaledWidth, scaledHeight);
1515
+ }
1516
+ setupCropListeners() {
1517
+ if (!this.canvas) return;
1518
+ this.canvas.addEventListener("mousedown", (e2) => this.handleMouseDown(e2));
1519
+ document.addEventListener("mousemove", this._handleMouseMove);
1520
+ document.addEventListener("mouseup", this._handleMouseUp);
1521
+ this.canvas.addEventListener("touchstart", (e2) => this.handleTouchStart(e2), { passive: false });
1522
+ this.canvas.addEventListener("touchmove", (e2) => this.handleTouchMove(e2), { passive: false });
1523
+ this.canvas.addEventListener("touchend", (e2) => this.handleTouchEnd(e2));
1524
+ this.canvas.style.cursor = "crosshair";
1525
+ }
1526
+ // Override renderCanvas to include crop overlay
1527
+ renderCanvas() {
1528
+ super.renderCanvas();
1529
+ if (this.cropMode) {
1530
+ this.renderCropOverlay();
1531
+ }
1532
+ }
1533
+ renderCropOverlay() {
1534
+ if (!this.cropMode || !this.cropBox) return;
1535
+ const canvasBox = this.imageToCanvas(this.cropBox);
1536
+ this.context.save();
1537
+ this.context.globalAlpha = 0.5;
1538
+ this.context.fillStyle = "#000000";
1539
+ this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
1540
+ this.context.globalCompositeOperation = "destination-out";
1541
+ this.context.fillRect(
1542
+ canvasBox.x,
1543
+ canvasBox.y,
1544
+ canvasBox.width,
1545
+ canvasBox.height
1546
+ );
1547
+ this.context.globalCompositeOperation = "source-over";
1548
+ this.context.globalAlpha = 1;
1549
+ this.context.strokeStyle = "rgba(255, 255, 255, 0.9)";
1550
+ this.context.lineWidth = 2;
1551
+ this.context.strokeRect(
1552
+ canvasBox.x,
1553
+ canvasBox.y,
1554
+ canvasBox.width,
1555
+ canvasBox.height
1556
+ );
1557
+ if (this.showGrid) {
1558
+ this.drawGrid();
1559
+ }
1560
+ this.drawHandles();
1561
+ this.context.restore();
1562
+ }
1563
+ // Override parent's exportImageBlob to export only the cropped area without overlay
1564
+ exportImageBlob(quality = 0.9) {
1565
+ if (!this.canvas || !this.image || !this.isLoaded || !this.cropMode) {
1566
+ return super.exportImageBlob(quality);
1567
+ }
1568
+ return new Promise((resolve) => {
1569
+ try {
1570
+ console.log("[ImageCropView] Exporting cropped image without overlay");
1571
+ console.log("[ImageCropView] Crop box:", this.cropBox);
1572
+ const cropArea = {
1573
+ x: Math.max(0, Math.min(this.cropBox.x, this.image.naturalWidth)),
1574
+ y: Math.max(0, Math.min(this.cropBox.y, this.image.naturalHeight)),
1575
+ width: Math.min(this.cropBox.width, this.image.naturalWidth - this.cropBox.x),
1576
+ height: Math.min(this.cropBox.height, this.image.naturalHeight - this.cropBox.y)
1577
+ };
1578
+ console.log("[ImageCropView] Crop area in image coords:", cropArea);
1579
+ let outputWidth = cropArea.width;
1580
+ let outputHeight = cropArea.height;
1581
+ if (this.cropAndScale) {
1582
+ outputWidth = this.cropAndScale.width;
1583
+ outputHeight = this.cropAndScale.height;
1584
+ console.log("[ImageCropView] Scaling to:", outputWidth, "x", outputHeight);
1585
+ }
1586
+ const tempCanvas = document.createElement("canvas");
1587
+ tempCanvas.width = outputWidth;
1588
+ tempCanvas.height = outputHeight;
1589
+ const tempContext = tempCanvas.getContext("2d");
1590
+ tempContext.drawImage(
1591
+ this.image,
1592
+ cropArea.x,
1593
+ cropArea.y,
1594
+ cropArea.width,
1595
+ cropArea.height,
1596
+ // Source rectangle
1597
+ 0,
1598
+ 0,
1599
+ outputWidth,
1600
+ outputHeight
1601
+ // Destination rectangle
1602
+ );
1603
+ tempCanvas.toBlob((blob) => {
1604
+ console.log("[ImageCropView] Successfully exported cropped image blob:", blob?.size, "bytes");
1605
+ resolve(blob);
1606
+ }, "image/png", quality);
1607
+ } catch (error) {
1608
+ console.error("Failed to export cropped image blob:", error);
1609
+ resolve(null);
1610
+ }
1611
+ });
1612
+ }
1613
+ drawGrid() {
1614
+ const canvasBox = this.imageToCanvas(this.cropBox);
1615
+ this.context.globalAlpha = 0.6;
1616
+ this.context.strokeStyle = "rgba(255, 255, 255, 0.7)";
1617
+ this.context.lineWidth = 1;
1618
+ const thirdW = canvasBox.width / 3;
1619
+ const thirdH = canvasBox.height / 3;
1620
+ for (let i = 1; i < 3; i++) {
1621
+ const x = canvasBox.x + thirdW * i;
1622
+ this.context.beginPath();
1623
+ this.context.moveTo(x, canvasBox.y);
1624
+ this.context.lineTo(x, canvasBox.y + canvasBox.height);
1625
+ this.context.stroke();
1626
+ }
1627
+ for (let i = 1; i < 3; i++) {
1628
+ const y = canvasBox.y + thirdH * i;
1629
+ this.context.beginPath();
1630
+ this.context.moveTo(canvasBox.x, y);
1631
+ this.context.lineTo(canvasBox.x + canvasBox.width, y);
1632
+ this.context.stroke();
1633
+ }
1634
+ }
1635
+ drawHandles() {
1636
+ if (this.fixedCropSize) return;
1637
+ const canvasBox = this.imageToCanvas(this.cropBox);
1638
+ this.context.globalAlpha = 1;
1639
+ this.context.fillStyle = "#ffffff";
1640
+ this.context.strokeStyle = "#000000";
1641
+ this.context.lineWidth = 1;
1642
+ Object.keys(this.handles).forEach((handleName) => {
1643
+ const handle = this.handles[handleName];
1644
+ const centerX = canvasBox.x + canvasBox.width * handle.x;
1645
+ const centerY = canvasBox.y + canvasBox.height * handle.y;
1646
+ const x = centerX - this.handleSize / 2;
1647
+ const y = centerY - this.handleSize / 2;
1648
+ this.context.fillRect(x, y, this.handleSize, this.handleSize);
1649
+ this.context.strokeRect(x, y, this.handleSize, this.handleSize);
1650
+ });
1651
+ }
1652
+ // Mouse interaction
1653
+ handleMouseDown(e2) {
1654
+ if (!this.cropMode) return;
1655
+ e2.preventDefault();
1656
+ const rect = this.canvas.getBoundingClientRect();
1657
+ const canvasX = e2.clientX - rect.left;
1658
+ const canvasY = e2.clientY - rect.top;
1659
+ const imagePoint = this.pointCanvasToImage(canvasX, canvasY);
1660
+ this.dragStartImageX = imagePoint.x;
1661
+ this.dragStartImageY = imagePoint.y;
1662
+ this.initialCropBox = { ...this.cropBox };
1663
+ if (this.fixedCropSize) {
1664
+ if (this.isPointInCropBox(canvasX, canvasY)) {
1665
+ this.isDragging = true;
1666
+ this.canvas.style.cursor = "move";
1667
+ }
1668
+ } else {
1669
+ const handle = this.getHandleAt(canvasX, canvasY);
1670
+ if (handle) {
1671
+ this.isResizing = true;
1672
+ this.dragHandle = handle;
1673
+ this.canvas.style.cursor = this.handles[handle].cursor;
1674
+ } else if (this.isPointInCropBox(canvasX, canvasY)) {
1675
+ this.isDragging = true;
1676
+ this.canvas.style.cursor = "move";
1677
+ } else {
1678
+ this.startNewCrop(imagePoint.x, imagePoint.y);
1679
+ }
1680
+ }
1681
+ }
1682
+ handleMouseMove(e2) {
1683
+ if (!this.cropMode) return;
1684
+ const rect = this.canvas.getBoundingClientRect();
1685
+ const canvasX = e2.clientX - rect.left;
1686
+ const canvasY = e2.clientY - rect.top;
1687
+ if (this.isResizing && this.dragHandle) {
1688
+ this.resizeCropBox(canvasX, canvasY);
1689
+ } else if (this.isDragging) {
1690
+ this.moveCropBox(canvasX, canvasY);
1691
+ } else if (!this.isDragging && !this.isResizing) {
1692
+ this.updateCursor(canvasX, canvasY);
1693
+ }
1694
+ }
1695
+ handleMouseUp(e2) {
1696
+ if (!this.cropMode) return;
1697
+ this.isDragging = false;
1698
+ this.isResizing = false;
1699
+ this.dragHandle = null;
1700
+ this.initialCropBox = null;
1701
+ this.newCropStart = null;
1702
+ const rect = this.canvas.getBoundingClientRect();
1703
+ const canvasX = e2.clientX - rect.left;
1704
+ const canvasY = e2.clientY - rect.top;
1705
+ this.updateCursor(canvasX, canvasY);
1706
+ }
1707
+ // Touch events
1708
+ handleTouchStart(e2) {
1709
+ if (!this.cropMode || e2.touches.length !== 1) return;
1710
+ e2.preventDefault();
1711
+ const touch = e2.touches[0];
1712
+ const rect = this.canvas.getBoundingClientRect();
1713
+ touch.clientX - rect.left;
1714
+ touch.clientY - rect.top;
1715
+ this.handleMouseDown({ clientX: touch.clientX, clientY: touch.clientY, preventDefault: () => {
1716
+ } });
1717
+ }
1718
+ handleTouchMove(_e) {
1719
+ if (!this.cropMode || _e.touches.length !== 1) return;
1720
+ _e.preventDefault();
1721
+ const touch = _e.touches[0];
1722
+ this.handleMouseMove({ clientX: touch.clientX, clientY: touch.clientY });
1723
+ }
1724
+ handleTouchEnd(_e) {
1725
+ if (!this.cropMode) return;
1726
+ this.handleMouseUp({});
1727
+ }
1728
+ // Crop utility methods
1729
+ getHandleAt(canvasX, canvasY) {
1730
+ const hitAreaPadding = 4;
1731
+ const canvasBox = this.imageToCanvas(this.cropBox);
1732
+ for (const [handleName, handle] of Object.entries(this.handles)) {
1733
+ const handleCenterX = canvasBox.x + canvasBox.width * handle.x;
1734
+ const handleCenterY = canvasBox.y + canvasBox.height * handle.y;
1735
+ const hitAreaSize = this.handleSize + hitAreaPadding;
1736
+ const handleX = handleCenterX - hitAreaSize / 2;
1737
+ const handleY = handleCenterY - hitAreaSize / 2;
1738
+ if (canvasX >= handleX && canvasX <= handleX + hitAreaSize && canvasY >= handleY && canvasY <= handleY + hitAreaSize) {
1739
+ return handleName;
1740
+ }
1741
+ }
1742
+ return null;
1743
+ }
1744
+ isPointInCropBox(canvasX, canvasY) {
1745
+ const imagePoint = this.pointCanvasToImage(canvasX, canvasY);
1746
+ return imagePoint.x >= this.cropBox.x && imagePoint.x <= this.cropBox.x + this.cropBox.width && imagePoint.y >= this.cropBox.y && imagePoint.y <= this.cropBox.y + this.cropBox.height;
1747
+ }
1748
+ updateCursor(canvasX, canvasY) {
1749
+ if (!this.cropMode) return;
1750
+ const imageX = canvasX;
1751
+ const imageY = canvasY;
1752
+ if (this.fixedCropSize) {
1753
+ if (this.isPointInCropBox(imageX, imageY)) {
1754
+ this.canvas.style.cursor = "move";
1755
+ } else {
1756
+ this.canvas.style.cursor = "default";
1757
+ }
1758
+ } else {
1759
+ const handle = this.getHandleAt(canvasX, canvasY);
1760
+ if (handle) {
1761
+ this.canvas.style.cursor = this.handles[handle].cursor;
1762
+ } else if (this.isPointInCropBox(imageX, imageY)) {
1763
+ this.canvas.style.cursor = "move";
1764
+ } else {
1765
+ this.canvas.style.cursor = "crosshair";
1766
+ }
1767
+ }
1768
+ }
1769
+ startNewCrop(x, y) {
1770
+ this.newCropStart = { x, y };
1771
+ this.cropBox = {
1772
+ x,
1773
+ y,
1774
+ width: 0,
1775
+ height: 0
1776
+ };
1777
+ this.isResizing = true;
1778
+ this.dragHandle = "se";
1779
+ }
1780
+ resizeCropBox(canvasX, canvasY) {
1781
+ if (!this.dragHandle) return;
1782
+ const imagePoint = this.pointCanvasToImage(canvasX, canvasY);
1783
+ if (this.newCropStart) {
1784
+ const startX = this.newCropStart.x;
1785
+ const startY = this.newCropStart.y;
1786
+ this.cropBox = {
1787
+ x: Math.min(startX, imagePoint.x),
1788
+ y: Math.min(startY, imagePoint.y),
1789
+ width: Math.abs(imagePoint.x - startX),
1790
+ height: Math.abs(imagePoint.y - startY)
1791
+ };
1792
+ if (this.aspectRatio) {
1793
+ this.constrainToAspectRatio(this.cropBox, "se");
1794
+ }
1795
+ if (this.cropBox.width < this.minCropSize) {
1796
+ this.cropBox.width = this.minCropSize;
1797
+ }
1798
+ if (this.cropBox.height < this.minCropSize) {
1799
+ this.cropBox.height = this.minCropSize;
1800
+ }
1801
+ this.constrainCropBox(this.cropBox);
1802
+ return;
1803
+ }
1804
+ if (!this.initialCropBox) return;
1805
+ const deltaX = imagePoint.x - this.dragStartImageX;
1806
+ const deltaY = imagePoint.y - this.dragStartImageY;
1807
+ let newBox = { ...this.initialCropBox };
1808
+ switch (this.dragHandle) {
1809
+ case "nw":
1810
+ newBox.x += deltaX;
1811
+ newBox.y += deltaY;
1812
+ newBox.width -= deltaX;
1813
+ newBox.height -= deltaY;
1814
+ break;
1815
+ case "ne":
1816
+ newBox.y += deltaY;
1817
+ newBox.width += deltaX;
1818
+ newBox.height -= deltaY;
1819
+ break;
1820
+ case "sw":
1821
+ newBox.x += deltaX;
1822
+ newBox.width -= deltaX;
1823
+ newBox.height += deltaY;
1824
+ break;
1825
+ case "se":
1826
+ newBox.width += deltaX;
1827
+ newBox.height += deltaY;
1828
+ break;
1829
+ case "n":
1830
+ newBox.y += deltaY;
1831
+ newBox.height -= deltaY;
1832
+ break;
1833
+ case "s":
1834
+ newBox.height += deltaY;
1835
+ break;
1836
+ case "w":
1837
+ newBox.x += deltaX;
1838
+ newBox.width -= deltaX;
1839
+ break;
1840
+ case "e":
1841
+ newBox.width += deltaX;
1842
+ break;
1843
+ }
1844
+ if (this.aspectRatio) {
1845
+ this.constrainToAspectRatio(newBox, this.dragHandle);
1846
+ }
1847
+ this.constrainCropBox(newBox);
1848
+ this.cropBox = newBox;
1849
+ this.renderCanvas();
1850
+ }
1851
+ moveCropBox(canvasX, canvasY) {
1852
+ if (!this.initialCropBox) return;
1853
+ const imagePoint = this.pointCanvasToImage(canvasX, canvasY);
1854
+ const deltaX = imagePoint.x - this.dragStartImageX;
1855
+ const deltaY = imagePoint.y - this.dragStartImageY;
1856
+ let newBox = {
1857
+ x: this.initialCropBox.x + deltaX,
1858
+ y: this.initialCropBox.y + deltaY,
1859
+ width: this.initialCropBox.width,
1860
+ height: this.initialCropBox.height
1861
+ };
1862
+ if (this.image) {
1863
+ newBox.x = Math.max(0, Math.min(this.image.naturalWidth - newBox.width, newBox.x));
1864
+ newBox.y = Math.max(0, Math.min(this.image.naturalHeight - newBox.height, newBox.y));
1865
+ }
1866
+ this.cropBox = newBox;
1867
+ this.renderCanvas();
1868
+ }
1869
+ constrainToAspectRatio(box, handle) {
1870
+ let ratio = this.aspectRatio;
1871
+ if (this.cropAndScale) {
1872
+ ratio = this.cropAndScale.width / this.cropAndScale.height;
1873
+ }
1874
+ if (!ratio) return;
1875
+ let anchorX, anchorY;
1876
+ if (["nw", "ne", "sw", "se"].includes(handle)) {
1877
+ switch (handle) {
1878
+ case "nw":
1879
+ anchorX = box.x + box.width;
1880
+ anchorY = box.y + box.height;
1881
+ break;
1882
+ case "ne":
1883
+ anchorX = box.x;
1884
+ anchorY = box.y + box.height;
1885
+ break;
1886
+ case "sw":
1887
+ anchorX = box.x + box.width;
1888
+ anchorY = box.y;
1889
+ break;
1890
+ case "se":
1891
+ anchorX = box.x;
1892
+ anchorY = box.y;
1893
+ break;
1894
+ }
1895
+ if (box.width / box.height > ratio) {
1896
+ box.width = box.height * ratio;
1897
+ } else {
1898
+ box.height = box.width / ratio;
1899
+ }
1900
+ switch (handle) {
1901
+ case "nw":
1902
+ box.x = anchorX - box.width;
1903
+ box.y = anchorY - box.height;
1904
+ break;
1905
+ case "ne":
1906
+ box.x = anchorX;
1907
+ box.y = anchorY - box.height;
1908
+ break;
1909
+ case "sw":
1910
+ box.x = anchorX - box.width;
1911
+ box.y = anchorY;
1912
+ break;
1913
+ case "se":
1914
+ box.x = anchorX;
1915
+ box.y = anchorY;
1916
+ break;
1917
+ }
1918
+ } else if (["n", "s"].includes(handle)) {
1919
+ const centerX = box.x + box.width / 2;
1920
+ box.width = box.height * ratio;
1921
+ box.x = centerX - box.width / 2;
1922
+ } else if (["w", "e"].includes(handle)) {
1923
+ const centerY = box.y + box.height / 2;
1924
+ box.height = box.width / ratio;
1925
+ box.y = centerY - box.height / 2;
1926
+ }
1927
+ }
1928
+ constrainCropBox(box) {
1929
+ box.width = Math.max(this.minCropSize, box.width);
1930
+ box.height = Math.max(this.minCropSize, box.height);
1931
+ if (this.image) {
1932
+ if (box.x < 0) {
1933
+ box.width += box.x;
1934
+ box.x = 0;
1935
+ }
1936
+ if (box.y < 0) {
1937
+ box.height += box.y;
1938
+ box.y = 0;
1939
+ }
1940
+ if (box.x + box.width > this.image.naturalWidth) {
1941
+ box.width = this.image.naturalWidth - box.x;
1942
+ }
1943
+ if (box.y + box.height > this.image.naturalHeight) {
1944
+ box.height = this.image.naturalHeight - box.y;
1945
+ }
1946
+ }
1947
+ box.width = Math.max(0, box.width);
1948
+ box.height = Math.max(0, box.height);
1949
+ }
1950
+ // Public API
1951
+ startCropMode() {
1952
+ if (this.cropMode) {
1953
+ console.log("Crop mode already active, skipping initialization");
1954
+ return;
1955
+ }
1956
+ this.cropMode = true;
1957
+ this.initializeCropBox();
1958
+ console.log("Crop mode started - SE handle should be at buffer coords (100, 100)");
1959
+ this.renderCanvas();
1960
+ this.emitCropEvent("crop-started");
1961
+ }
1962
+ exitCropMode() {
1963
+ this.cropMode = false;
1964
+ this.isDragging = false;
1965
+ this.isResizing = false;
1966
+ this.dragHandle = null;
1967
+ this.canvas.style.cursor = "default";
1968
+ this.renderCanvas();
1969
+ this.emitCropEvent("crop-exited");
1970
+ }
1971
+ initializeCropBox() {
1972
+ if (!this.canvasWidth || !this.canvasHeight || !this.image) return;
1973
+ const imageWidth = this.image.naturalWidth;
1974
+ const imageHeight = this.image.naturalHeight;
1975
+ let cropWidth, cropHeight;
1976
+ if (this.fixedCropSize) {
1977
+ cropWidth = this.fixedCropSize.width;
1978
+ cropHeight = this.fixedCropSize.height;
1979
+ } else {
1980
+ cropWidth = Math.floor(imageWidth * 0.8);
1981
+ cropHeight = Math.floor(imageHeight * 0.8);
1982
+ let aspectRatio = this.aspectRatio;
1983
+ if (this.cropAndScale) {
1984
+ aspectRatio = this.cropAndScale.width / this.cropAndScale.height;
1985
+ }
1986
+ this.aspectRatio = aspectRatio;
1987
+ if (aspectRatio) {
1988
+ if (cropWidth / cropHeight > aspectRatio) {
1989
+ cropWidth = cropHeight * aspectRatio;
1990
+ } else {
1991
+ cropHeight = cropWidth / aspectRatio;
1992
+ }
1993
+ }
1994
+ cropWidth = Math.max(this.minCropSize || 50, cropWidth);
1995
+ cropHeight = Math.max(this.minCropSize || 50, cropHeight);
1996
+ }
1997
+ const x = Math.floor((imageWidth - cropWidth) / 2);
1998
+ const y = Math.floor((imageHeight - cropHeight) / 2);
1999
+ this.cropBox = {
2000
+ x,
2001
+ // relative to image, not canvas
2002
+ y,
2003
+ // relative to image, not canvas
2004
+ width: cropWidth,
2005
+ height: cropHeight
2006
+ };
2007
+ }
2008
+ setAspectRatio(ratio) {
2009
+ this.aspectRatio = ratio;
2010
+ if (this.cropMode) {
2011
+ this.initializeCropBox();
2012
+ this.renderCanvas();
2013
+ }
2014
+ this.emitCropEvent("aspect-ratio-changed", { aspectRatio: ratio });
2015
+ }
2016
+ getCropData() {
2017
+ if (!this.cropBox || !this.image) return null;
2018
+ return {
2019
+ x: Math.max(0, Math.min(this.cropBox.x, this.image.naturalWidth)),
2020
+ y: Math.max(0, Math.min(this.cropBox.y, this.image.naturalHeight)),
2021
+ width: Math.min(this.cropBox.width, this.image.naturalWidth - this.cropBox.x),
2022
+ height: Math.min(this.cropBox.height, this.image.naturalHeight - this.cropBox.y),
2023
+ originalWidth: this.image.naturalWidth,
2024
+ originalHeight: this.image.naturalHeight
2025
+ };
2026
+ }
2027
+ async applyCrop() {
2028
+ const cropData = this.getCropData();
2029
+ if (!cropData || !this.image) {
2030
+ return null;
2031
+ }
2032
+ const croppedCanvas = document.createElement("canvas");
2033
+ const croppedContext = croppedCanvas.getContext("2d");
2034
+ if (this.cropAndScale) {
2035
+ croppedCanvas.width = this.cropAndScale.width;
2036
+ croppedCanvas.height = this.cropAndScale.height;
2037
+ croppedContext.drawImage(
2038
+ this.image,
2039
+ cropData.x,
2040
+ cropData.y,
2041
+ cropData.width,
2042
+ cropData.height,
2043
+ 0,
2044
+ 0,
2045
+ this.cropAndScale.width,
2046
+ this.cropAndScale.height
2047
+ );
2048
+ } else {
2049
+ croppedCanvas.width = cropData.width;
2050
+ croppedCanvas.height = cropData.height;
2051
+ croppedContext.drawImage(
2052
+ this.image,
2053
+ cropData.x,
2054
+ cropData.y,
2055
+ cropData.width,
2056
+ cropData.height,
2057
+ 0,
2058
+ 0,
2059
+ cropData.width,
2060
+ cropData.height
2061
+ );
2062
+ }
2063
+ const croppedImageData = croppedCanvas.toDataURL("image/png");
2064
+ return {
2065
+ canvas: croppedCanvas,
2066
+ imageData: croppedImageData,
2067
+ cropData
2068
+ };
2069
+ }
2070
+ // Event emission
2071
+ emitCropEvent(type, data = {}) {
2072
+ const eventBus = this.getApp()?.events;
2073
+ if (eventBus) {
2074
+ eventBus.emit(`imagecrop:${type}`, {
2075
+ view: this,
2076
+ cropBox: this.cropBox,
2077
+ aspectRatio: this.aspectRatio,
2078
+ ...data
2079
+ });
2080
+ }
2081
+ }
2082
+ // Toolbar control methods
2083
+ showToolbarElement() {
2084
+ if (!this.showToolbar) {
2085
+ this.showToolbar = true;
2086
+ const toolbar = this.element.querySelector(".image-crop-toolbar");
2087
+ if (toolbar) {
2088
+ toolbar.style.display = "block";
2089
+ }
2090
+ this.updateAutoFitButtonState();
2091
+ }
2092
+ }
2093
+ hideToolbarElement() {
2094
+ if (this.showToolbar) {
2095
+ this.showToolbar = false;
2096
+ const toolbar = this.element.querySelector(".image-crop-toolbar");
2097
+ if (toolbar) {
2098
+ toolbar.style.display = "none";
2099
+ }
2100
+ }
2101
+ }
2102
+ toggleToolbarElement() {
2103
+ if (this.showToolbar) {
2104
+ this.hideToolbarElement();
2105
+ } else {
2106
+ this.showToolbarElement();
2107
+ }
2108
+ }
2109
+ // Cleanup
2110
+ // Action handlers for toolbar buttons
2111
+ async onPassThruActionSetAspectRatio(e2, el) {
2112
+ const ratio = el.getAttribute("data-ratio");
2113
+ const aspectRatio = ratio === "free" ? null : parseFloat(ratio);
2114
+ this.setAspectRatio(aspectRatio);
2115
+ }
2116
+ async handleActionApplyCrop() {
2117
+ if (this.cropMode) {
2118
+ const result = await this.applyCrop();
2119
+ if (result && result.imageData) {
2120
+ this.loadImage(result.imageData);
2121
+ this.exitCropMode();
2122
+ this.emitCropEvent("crop-applied", { result });
2123
+ }
2124
+ }
2125
+ }
2126
+ async handleActionToggleAutoFit() {
2127
+ if (!this.showToolbar) return;
2128
+ this.autoFit = !this.autoFit;
2129
+ this.updateAutoFitButtonState();
2130
+ this.updateImageOffset();
2131
+ this.renderCanvas();
2132
+ this.emitCropEvent("auto-fit-changed", { autoFit: this.autoFit });
2133
+ }
2134
+ async handleActionResetCrop() {
2135
+ if (this.cropMode) {
2136
+ this.exitCropMode();
2137
+ }
2138
+ if (this.originalImageUrl) {
2139
+ await this.loadImage(this.originalImageUrl);
2140
+ }
2141
+ this.startCropMode();
2142
+ this.emitCropEvent("crop-reset");
2143
+ }
2144
+ async onBeforeDestroy() {
2145
+ await super.onBeforeDestroy();
2146
+ this.cropMode = false;
2147
+ this.isDragging = false;
2148
+ this.isResizing = false;
2149
+ document.removeEventListener("mousemove", this._handleMouseMove);
2150
+ document.removeEventListener("mouseup", this._handleMouseUp);
2151
+ this.emitCropEvent("destroyed");
2152
+ }
2153
+ // Static method to show crop view in a dialog for standalone testing
2154
+ static async showDialog(imageUrl, options = {}) {
2155
+ const {
2156
+ title = "Crop Image",
2157
+ alt = "Image",
2158
+ size = "xl",
2159
+ aspectRatio = null,
2160
+ minCropSize = 50,
2161
+ showGrid = true,
2162
+ showToolbar = false,
2163
+ autoFit = true,
2164
+ fixedCropSize = null,
2165
+ cropAndScale = null,
2166
+ canvasSize = size || "auto",
2167
+ ...dialogOptions
2168
+ } = options;
2169
+ const cropView = new ImageCropView({
2170
+ imageUrl,
2171
+ alt,
2172
+ title,
2173
+ aspectRatio,
2174
+ minCropSize,
2175
+ canvasSize: canvasSize || size || "md",
2176
+ fixedCropSize,
2177
+ cropAndScale,
2178
+ showGrid,
2179
+ showToolbar,
2180
+ autoFit
2181
+ });
2182
+ const dialog = new Dialog({
2183
+ title,
2184
+ body: cropView,
2185
+ size,
2186
+ centered: true,
2187
+ backdrop: "static",
2188
+ keyboard: true,
2189
+ noBodyPadding: true,
2190
+ buttons: [
2191
+ {
2192
+ text: "Cancel",
2193
+ action: "cancel",
2194
+ class: "btn btn-secondary",
2195
+ dismiss: true
2196
+ },
2197
+ {
2198
+ text: "Apply Crop",
2199
+ action: "apply-crop",
2200
+ class: "btn btn-primary"
2201
+ }
2202
+ ],
2203
+ ...dialogOptions
2204
+ });
2205
+ await dialog.render(true, document.body);
2206
+ dialog.show();
2207
+ const initializeCrop = () => {
2208
+ if (cropView.setupCanvas) {
2209
+ cropView.setupCanvas();
2210
+ }
2211
+ if (cropView.isLoaded && cropView.canvasWidth > 0) {
2212
+ cropView.startCropMode();
2213
+ } else {
2214
+ const checkReady = setInterval(() => {
2215
+ if (cropView.isLoaded && cropView.canvasWidth > 0) {
2216
+ clearInterval(checkReady);
2217
+ cropView.startCropMode();
2218
+ }
2219
+ }, 100);
2220
+ setTimeout(() => clearInterval(checkReady), 5e3);
2221
+ }
2222
+ };
2223
+ dialog.on("shown", initializeCrop);
2224
+ return new Promise((resolve) => {
2225
+ dialog.on("hidden", () => {
2226
+ dialog.destroy();
2227
+ resolve({ action: "cancel", view: cropView });
2228
+ });
2229
+ dialog.on("action:cancel", () => {
2230
+ dialog.hide();
2231
+ });
2232
+ dialog.on("action:apply-crop", async () => {
2233
+ let result;
2234
+ if (cropView.cropMode && cropView.cropBox) {
2235
+ result = await cropView.applyCrop();
2236
+ } else {
2237
+ const currentImageData = cropView.canvas.toDataURL("image/png");
2238
+ result = {
2239
+ canvas: cropView.canvas,
2240
+ imageData: currentImageData,
2241
+ cropData: null
2242
+ // No crop was applied
2243
+ };
2244
+ }
2245
+ dialog.hide();
2246
+ resolve({
2247
+ action: "crop",
2248
+ view: cropView,
2249
+ data: result?.imageData,
2250
+ cropData: result?.cropData
2251
+ });
2252
+ });
2253
+ });
2254
+ }
2255
+ }
2256
+ window.ImageCropView = ImageCropView;
2257
+ class ImageFiltersView extends ImageCanvasView {
2258
+ constructor(options = {}) {
2259
+ super({
2260
+ ...options,
2261
+ className: `image-filters-view ${options.className || ""}`
2262
+ });
2263
+ this.filters = {
2264
+ brightness: 100,
2265
+ contrast: 100,
2266
+ saturation: 100,
2267
+ hue: 0,
2268
+ blur: 0,
2269
+ grayscale: 0,
2270
+ sepia: 0
2271
+ };
2272
+ this.showControls = options.showControls ?? true;
2273
+ this.allowReset = options.allowReset ?? true;
2274
+ this.showPresets = options.showPresets ?? true;
2275
+ this.showBasicControls = options.showBasicControls ?? true;
2276
+ this.showAdvancedControls = options.showAdvancedControls ?? true;
2277
+ this.controlsInDropdowns = options.controlsInDropdowns ?? true;
2278
+ this.presetEffects = {
2279
+ none: { name: "Original", filters: {} },
2280
+ blackWhite: { name: "Black & White", filters: { grayscale: 100 } },
2281
+ sepia: { name: "Sepia", filters: { sepia: 100 } },
2282
+ vintage: { name: "Vintage", filters: { sepia: 60, contrast: 110, brightness: 110, saturation: 80 } },
2283
+ cool: { name: "Cool Tones", filters: { hue: 200, saturation: 120, brightness: 95 } },
2284
+ warm: { name: "Warm Tones", filters: { hue: 25, saturation: 110, brightness: 105 } },
2285
+ vibrant: { name: "Vibrant", filters: { brightness: 105, contrast: 115, saturation: 140, hue: 5 } },
2286
+ dramatic: { name: "Dramatic", filters: { brightness: 90, contrast: 150, saturation: 120 } },
2287
+ soft: { name: "Soft", filters: { brightness: 110, contrast: 85, blur: 1 } }
2288
+ };
2289
+ this.currentPreset = "none";
2290
+ }
2291
+ async getTemplate() {
2292
+ return `
2293
+ <div class="image-filters-container d-flex flex-column h-100">
2294
+ {{#showControls}}
2295
+ <!-- Filter Toolbar -->
2296
+ <div class="image-filters-toolbar bg-light border-bottom p-2">
2297
+ <div class="btn-toolbar justify-content-center flex-wrap" role="toolbar">
2298
+
2299
+ {{#showPresets}}
2300
+ <!-- Preset Effects -->
2301
+ <div class="btn-group me-2 mb-2" role="group" aria-label="Preset effects">
2302
+ <div class="dropdown">
2303
+ <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle"
2304
+ data-bs-toggle="dropdown" aria-expanded="false" title="Preset Effects">
2305
+ <i class="bi bi-palette"></i> Effects
2306
+ </button>
2307
+ <ul class="dropdown-menu">
2308
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="none">Original</a></li>
2309
+ <li><hr class="dropdown-divider"></li>
2310
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="blackWhite">Black & White</a></li>
2311
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="sepia">Sepia</a></li>
2312
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="vintage">Vintage</a></li>
2313
+ <li><hr class="dropdown-divider"></li>
2314
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="cool">Cool Tones</a></li>
2315
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="warm">Warm Tones</a></li>
2316
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="vibrant">Vibrant</a></li>
2317
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="dramatic">Dramatic</a></li>
2318
+ <li><a class="dropdown-item" href="#" data-action="apply-preset" data-preset="soft">Soft</a></li>
2319
+ </ul>
2320
+ </div>
2321
+ </div>
2322
+ {{/showPresets}}
2323
+
2324
+ {{#showBasicControls}}
2325
+ {{#controlsInDropdowns}}
2326
+ <!-- Basic Controls in Dropdown -->
2327
+ <div class="btn-group me-2 mb-2" role="group" aria-label="Basic controls">
2328
+ <div class="dropdown">
2329
+ <button type="button" class="btn btn-outline-secondary btn-sm dropdown-toggle"
2330
+ data-bs-toggle="dropdown" aria-expanded="false" title="Basic Adjustments">
2331
+ <i class="bi bi-sliders"></i> Basic
2332
+ </button>
2333
+ <div class="dropdown-menu p-3" style="min-width: 300px;">
2334
+ <div class="mb-3">
2335
+ <label class="form-label small fw-bold">Brightness</label>
2336
+ <input type="range" class="form-range"
2337
+ min="0" max="200" value="{{filters.brightness}}"
2338
+ data-change-action="filter-change" data-filter="brightness">
2339
+ <div class="d-flex justify-content-between">
2340
+ <small class="text-muted">0%</small>
2341
+ <small class="text-muted filter-value" data-filter="brightness">{{filters.brightness}}%</small>
2342
+ <small class="text-muted">200%</small>
2343
+ </div>
2344
+ </div>
2345
+ <div class="mb-3">
2346
+ <label class="form-label small fw-bold">Contrast</label>
2347
+ <input type="range" class="form-range"
2348
+ min="0" max="200" value="{{filters.contrast}}"
2349
+ data-change-action="filter-change" data-filter="contrast">
2350
+ <div class="d-flex justify-content-between">
2351
+ <small class="text-muted">0%</small>
2352
+ <small class="text-muted filter-value" data-filter="contrast">{{filters.contrast}}%</small>
2353
+ <small class="text-muted">200%</small>
2354
+ </div>
2355
+ </div>
2356
+ <div class="mb-0">
2357
+ <label class="form-label small fw-bold">Saturation</label>
2358
+ <input type="range" class="form-range"
2359
+ min="0" max="200" value="{{filters.saturation}}"
2360
+ data-change-action="filter-change" data-filter="saturation">
2361
+ <div class="d-flex justify-content-between">
2362
+ <small class="text-muted">0%</small>
2363
+ <small class="text-muted filter-value" data-filter="saturation">{{filters.saturation}}%</small>
2364
+ <small class="text-muted">200%</small>
2365
+ </div>
2366
+ </div>
2367
+ </div>
2368
+ </div>
2369
+ </div>
2370
+ {{/controlsInDropdowns}}
2371
+ {{/showBasicControls}}
2372
+
2373
+ {{#showAdvancedControls}}
2374
+ {{#controlsInDropdowns}}
2375
+ <!-- Advanced Controls in Dropdown -->
2376
+ <div class="btn-group me-2 mb-2" role="group" aria-label="Advanced controls">
2377
+ <div class="dropdown">
2378
+ <button type="button" class="btn btn-outline-warning btn-sm dropdown-toggle"
2379
+ data-bs-toggle="dropdown" aria-expanded="false" title="Advanced Adjustments">
2380
+ <i class="bi bi-gear"></i> Advanced
2381
+ </button>
2382
+ <div class="dropdown-menu p-3" style="min-width: 300px;">
2383
+ <div class="mb-3">
2384
+ <label class="form-label small fw-bold">Hue</label>
2385
+ <input type="range" class="form-range"
2386
+ min="0" max="360" value="{{filters.hue}}"
2387
+ data-change-action="filter-change" data-filter="hue">
2388
+ <div class="d-flex justify-content-between">
2389
+ <small class="text-muted">0°</small>
2390
+ <small class="text-muted filter-value" data-filter="hue">{{filters.hue}}°</small>
2391
+ <small class="text-muted">360°</small>
2392
+ </div>
2393
+ </div>
2394
+ <div class="mb-3">
2395
+ <label class="form-label small fw-bold">Blur</label>
2396
+ <input type="range" class="form-range"
2397
+ min="0" max="10" value="{{filters.blur}}"
2398
+ data-change-action="filter-change" data-filter="blur">
2399
+ <div class="d-flex justify-content-between">
2400
+ <small class="text-muted">0px</small>
2401
+ <small class="text-muted filter-value" data-filter="blur">{{filters.blur}}px</small>
2402
+ <small class="text-muted">10px</small>
2403
+ </div>
2404
+ </div>
2405
+ <div class="mb-3">
2406
+ <label class="form-label small fw-bold">Grayscale</label>
2407
+ <input type="range" class="form-range"
2408
+ min="0" max="100" value="{{filters.grayscale}}"
2409
+ data-change-action="filter-change" data-filter="grayscale">
2410
+ <div class="d-flex justify-content-between">
2411
+ <small class="text-muted">0%</small>
2412
+ <small class="text-muted filter-value" data-filter="grayscale">{{filters.grayscale}}%</small>
2413
+ <small class="text-muted">100%</small>
2414
+ </div>
2415
+ </div>
2416
+ <div class="mb-0">
2417
+ <label class="form-label small fw-bold">Sepia</label>
2418
+ <input type="range" class="form-range"
2419
+ min="0" max="100" value="{{filters.sepia}}"
2420
+ data-change-action="filter-change" data-filter="sepia">
2421
+ <div class="d-flex justify-content-between">
2422
+ <small class="text-muted">0%</small>
2423
+ <small class="text-muted filter-value" data-filter="sepia">{{filters.sepia}}%</small>
2424
+ <small class="text-muted">100%</small>
2425
+ </div>
2426
+ </div>
2427
+ </div>
2428
+ </div>
2429
+ </div>
2430
+ {{/controlsInDropdowns}}
2431
+ {{/showAdvancedControls}}
2432
+
2433
+ {{#allowReset}}
2434
+ <!-- Reset & Preview Controls -->
2435
+ <div class="btn-group me-2 mb-2" role="group" aria-label="Reset controls">
2436
+ <button type="button" class="btn btn-outline-secondary btn-sm" data-action="reset-filters" title="Reset All Filters">
2437
+ <i class="bi bi-arrow-repeat"></i> Reset
2438
+ </button>
2439
+ <button type="button" class="btn btn-outline-info btn-sm" data-action="preview-original" title="Preview Original"
2440
+ onmousedown="this.dataset.previewing='true'"
2441
+ onmouseup="this.dataset.previewing='false'"
2442
+ onmouseleave="this.dataset.previewing='false'">
2443
+ <i class="bi bi-eye"></i> Original
2444
+ </button>
2445
+ </div>
2446
+ {{/allowReset}}
2447
+
2448
+ </div>
2449
+ </div>
2450
+ {{/showControls}}
2451
+
2452
+ <!-- Canvas Area -->
2453
+ <div class="image-canvas-content flex-grow-1 position-relative d-flex justify-content-center align-items-center">
2454
+ <canvas class="image-filters-canvas" data-container="canvas"></canvas>
2455
+
2456
+ <!-- Loading Overlay -->
2457
+ <div class="image-canvas-loading position-absolute top-50 start-50 translate-middle"
2458
+ style="display: none; z-index: 10;">
2459
+ <div class="spinner-border text-primary" role="status">
2460
+ <span class="visually-hidden">Loading...</span>
2461
+ </div>
2462
+ </div>
2463
+ </div>
2464
+
2465
+ {{#showControls}}
2466
+ {{^controlsInDropdowns}}
2467
+ <!-- Expanded Controls Panel (when not in dropdowns) -->
2468
+ <div class="image-filters-controls bg-light border-top p-3" data-container="controls" style="max-height: 300px; overflow-y: auto;">
2469
+ <div class="row g-3">
2470
+ {{#showBasicControls}}
2471
+ <div class="col-md-6 col-lg-4">
2472
+ <label class="form-label small fw-bold">Brightness</label>
2473
+ <input type="range" class="form-range"
2474
+ min="0" max="200" value="{{filters.brightness}}"
2475
+ data-change-action="filter-change" data-filter="brightness">
2476
+ <div class="d-flex justify-content-between">
2477
+ <small class="text-muted">0%</small>
2478
+ <small class="text-muted filter-value" data-filter="brightness">{{filters.brightness}}%</small>
2479
+ <small class="text-muted">200%</small>
2480
+ </div>
2481
+ </div>
2482
+ <div class="col-md-6 col-lg-4">
2483
+ <label class="form-label small fw-bold">Contrast</label>
2484
+ <input type="range" class="form-range"
2485
+ min="0" max="200" value="{{filters.contrast}}"
2486
+ data-change-action="filter-change" data-filter="contrast">
2487
+ <div class="d-flex justify-content-between">
2488
+ <small class="text-muted">0%</small>
2489
+ <small class="text-muted filter-value" data-filter="contrast">{{filters.contrast}}%</small>
2490
+ <small class="text-muted">200%</small>
2491
+ </div>
2492
+ </div>
2493
+ <div class="col-md-6 col-lg-4">
2494
+ <label class="form-label small fw-bold">Saturation</label>
2495
+ <input type="range" class="form-range"
2496
+ min="0" max="200" value="{{filters.saturation}}"
2497
+ data-change-action="filter-change" data-filter="saturation">
2498
+ <div class="d-flex justify-content-between">
2499
+ <small class="text-muted">0%</small>
2500
+ <small class="text-muted filter-value" data-filter="saturation">{{filters.saturation}}%</small>
2501
+ <small class="text-muted">200%</small>
2502
+ </div>
2503
+ </div>
2504
+ {{/showBasicControls}}
2505
+
2506
+ {{#showAdvancedControls}}
2507
+ <div class="col-md-6 col-lg-4">
2508
+ <label class="form-label small fw-bold">Hue</label>
2509
+ <input type="range" class="form-range"
2510
+ min="0" max="360" value="{{filters.hue}}"
2511
+ data-change-action="filter-change" data-filter="hue">
2512
+ <div class="d-flex justify-content-between">
2513
+ <small class="text-muted">0°</small>
2514
+ <small class="text-muted filter-value" data-filter="hue">{{filters.hue}}°</small>
2515
+ <small class="text-muted">360°</small>
2516
+ </div>
2517
+ </div>
2518
+ <div class="col-md-6 col-lg-4">
2519
+ <label class="form-label small fw-bold">Blur</label>
2520
+ <input type="range" class="form-range"
2521
+ min="0" max="10" value="{{filters.blur}}"
2522
+ data-change-action="filter-change" data-filter="blur">
2523
+ <div class="d-flex justify-content-between">
2524
+ <small class="text-muted">0px</small>
2525
+ <small class="text-muted filter-value" data-filter="blur">{{filters.blur}}px</small>
2526
+ <small class="text-muted">10px</small>
2527
+ </div>
2528
+ </div>
2529
+ <div class="col-md-6 col-lg-4">
2530
+ <label class="form-label small fw-bold">Grayscale</label>
2531
+ <input type="range" class="form-range"
2532
+ min="0" max="100" value="{{filters.grayscale}}"
2533
+ data-change-action="filter-change" data-filter="grayscale">
2534
+ <div class="d-flex justify-content-between">
2535
+ <small class="text-muted">0%</small>
2536
+ <small class="text-muted filter-value" data-filter="grayscale">{{filters.grayscale}}%</small>
2537
+ <small class="text-muted">100%</small>
2538
+ </div>
2539
+ </div>
2540
+ <div class="col-md-6 col-lg-4">
2541
+ <label class="form-label small fw-bold">Sepia</label>
2542
+ <input type="range" class="form-range"
2543
+ min="0" max="100" value="{{filters.sepia}}"
2544
+ data-change-action="filter-change" data-filter="sepia">
2545
+ <div class="d-flex justify-content-between">
2546
+ <small class="text-muted">0%</small>
2547
+ <small class="text-muted filter-value" data-filter="sepia">{{filters.sepia}}%</small>
2548
+ <small class="text-muted">100%</small>
2549
+ </div>
2550
+ </div>
2551
+ {{/showAdvancedControls}}
2552
+ </div>
2553
+ </div>
2554
+ {{/controlsInDropdowns}}
2555
+ {{/showControls}}
2556
+ </div>
2557
+ `;
2558
+ }
2559
+ async onAfterRender() {
2560
+ await super.onAfterRender();
2561
+ this.controlsElement = this.element.querySelector(".image-filters-controls");
2562
+ }
2563
+ // Override canvas sizing for container-aware dimensions
2564
+ setupCanvas() {
2565
+ if (!this.canvas || !this.containerElement) return;
2566
+ this.setCanvasSize(this.canvasSize);
2567
+ if (this.canvasSize === "fullscreen" || this.canvasSize === "auto") {
2568
+ this._resizeHandler = () => this.setCanvasSize(this.canvasSize);
2569
+ window.addEventListener("resize", this._resizeHandler);
2570
+ }
2571
+ this.context.imageSmoothingEnabled = true;
2572
+ this.context.imageSmoothingQuality = "high";
2573
+ }
2574
+ // Override setCanvasSize to be more container-aware for dialogs
2575
+ setCanvasSize(size) {
2576
+ if (!this.canvas || !this.containerElement) return;
2577
+ if (size === "auto") {
2578
+ const container = this.containerElement;
2579
+ let availableWidth = container.clientWidth - 40;
2580
+ let availableHeight = container.clientHeight - 40;
2581
+ if (availableWidth <= 40 || availableHeight <= 40) {
2582
+ let parent = container.parentElement;
2583
+ while (parent && (parent.clientWidth <= 40 || parent.clientHeight <= 40)) {
2584
+ parent = parent.parentElement;
2585
+ if (parent && (parent.classList.contains("modal-body") || parent.classList.contains("card-body") || parent.classList.contains("dialog-body") || parent.tagName === "MAIN" || parent.tagName === "BODY")) {
2586
+ break;
2587
+ }
2588
+ }
2589
+ if (parent) {
2590
+ availableWidth = parent.clientWidth - 80;
2591
+ availableHeight = parent.clientHeight - 80;
2592
+ }
2593
+ }
2594
+ if (availableWidth > 100 && availableHeight > 100) {
2595
+ let canvasWidth, canvasHeight;
2596
+ if (this.image) {
2597
+ const imageAspect = this.image.naturalWidth / this.image.naturalHeight;
2598
+ const availableAspect = availableWidth / availableHeight;
2599
+ if (imageAspect > availableAspect) {
2600
+ canvasWidth = availableWidth;
2601
+ canvasHeight = availableWidth / imageAspect;
2602
+ } else {
2603
+ canvasHeight = availableHeight;
2604
+ canvasWidth = availableHeight * imageAspect;
2605
+ }
2606
+ canvasWidth = Math.max(300, Math.floor(canvasWidth));
2607
+ canvasHeight = Math.max(200, Math.floor(canvasHeight));
2608
+ } else {
2609
+ canvasWidth = Math.min(600, Math.max(300, availableWidth));
2610
+ canvasHeight = Math.min(450, Math.max(200, availableHeight));
2611
+ }
2612
+ this.applyCanvasSize(canvasWidth, canvasHeight);
2613
+ return;
2614
+ }
2615
+ }
2616
+ super.setCanvasSize(size);
2617
+ }
2618
+ // Helper method to apply calculated canvas size
2619
+ applyCanvasSize(canvasWidth, canvasHeight) {
2620
+ if (Math.abs(canvasWidth - this.canvasWidth) < 10 && Math.abs(canvasHeight - this.canvasHeight) < 10) {
2621
+ return;
2622
+ }
2623
+ const dpr = window.devicePixelRatio || 1;
2624
+ this.canvasWidth = canvasWidth;
2625
+ this.canvasHeight = canvasHeight;
2626
+ this.canvas.width = canvasWidth * dpr;
2627
+ this.canvas.height = canvasHeight * dpr;
2628
+ this.canvas.style.width = canvasWidth + "px";
2629
+ this.canvas.style.height = canvasHeight + "px";
2630
+ this.context.setTransform(dpr, 0, 0, dpr, 0, 0);
2631
+ if (this.isLoaded) {
2632
+ this.renderCanvas();
2633
+ }
2634
+ }
2635
+ // Override image loading to re-render with current filters
2636
+ async loadImage(imageUrl) {
2637
+ await super.loadImage(imageUrl);
2638
+ this.renderCanvas();
2639
+ }
2640
+ // Override renderImage to apply filters consistently
2641
+ renderImage() {
2642
+ if (!this.image) return;
2643
+ this.context.filter = this.getFilterString();
2644
+ const imageScale = Math.min(
2645
+ this.canvasWidth / this.image.naturalWidth,
2646
+ this.canvasHeight / this.image.naturalHeight
2647
+ );
2648
+ const scaledWidth = this.image.naturalWidth * imageScale;
2649
+ const scaledHeight = this.image.naturalHeight * imageScale;
2650
+ const x = (this.canvasWidth - scaledWidth) / 2;
2651
+ const y = (this.canvasHeight - scaledHeight) / 2;
2652
+ this.context.drawImage(this.image, x, y, scaledWidth, scaledHeight);
2653
+ this.context.filter = "none";
2654
+ }
2655
+ // Get combined filter values from both sliders and current preset
2656
+ getCombinedFilters() {
2657
+ const combined = { ...this.filters };
2658
+ if (this.currentPreset !== "none" && this.presetEffects[this.currentPreset]) {
2659
+ const presetFilters = this.presetEffects[this.currentPreset].filters;
2660
+ if (presetFilters) {
2661
+ Object.assign(combined, presetFilters);
2662
+ }
2663
+ }
2664
+ return combined;
2665
+ }
2666
+ getFilterString() {
2667
+ const filters = this.getCombinedFilters();
2668
+ if (!this.hasFilters() && this.currentPreset === "none") return "none";
2669
+ return [
2670
+ `brightness(${filters.brightness}%)`,
2671
+ `contrast(${filters.contrast}%)`,
2672
+ `saturate(${filters.saturation}%)`,
2673
+ `hue-rotate(${filters.hue}deg)`,
2674
+ `blur(${filters.blur}px)`,
2675
+ `grayscale(${filters.grayscale}%)`,
2676
+ `sepia(${filters.sepia}%)`
2677
+ ].join(" ");
2678
+ }
2679
+ hasFilters() {
2680
+ return this.filters.brightness !== 100 || this.filters.contrast !== 100 || this.filters.saturation !== 100 || this.filters.hue !== 0 || this.filters.blur !== 0 || this.filters.grayscale !== 0 || this.filters.sepia !== 0;
2681
+ }
2682
+ // Action Handlers
2683
+ async onPassThruActionResetFilters() {
2684
+ this.resetFilters();
2685
+ }
2686
+ async onPassThruActionApplyPreset(e2, el) {
2687
+ e2.preventDefault();
2688
+ const presetName = el.getAttribute("data-preset");
2689
+ if (presetName && this.presetEffects[presetName]) {
2690
+ this.applyPreset(presetName);
2691
+ }
2692
+ }
2693
+ async onPassThruActionPreviewOriginal(e2, el) {
2694
+ const isPreviewing = el.dataset.previewing === "true";
2695
+ if (isPreviewing) {
2696
+ this.context.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
2697
+ this.context.filter = "none";
2698
+ const x = (this.canvasWidth - this.image.naturalWidth) / 2;
2699
+ const y = (this.canvasHeight - this.image.naturalHeight) / 2;
2700
+ this.context.drawImage(this.image, x, y);
2701
+ } else {
2702
+ this.renderCanvas();
2703
+ }
2704
+ }
2705
+ // Change Handler for filter sliders
2706
+ async onChangeFilterChange(e2, el) {
2707
+ const filterName = el.getAttribute("data-filter");
2708
+ const value = parseFloat(el.value);
2709
+ this.updateFilter(filterName, value);
2710
+ }
2711
+ // Filter methods
2712
+ updateFilter(name, value) {
2713
+ if (!(name in this.filters)) return;
2714
+ const oldValue = this.filters[name];
2715
+ this.filters[name] = value;
2716
+ this.updateFilterDisplay(name, value);
2717
+ this.renderCanvas();
2718
+ this.emitFilterEvent("filter-changed", {
2719
+ filter: name,
2720
+ oldValue,
2721
+ newValue: value,
2722
+ allFilters: { ...this.filters }
2723
+ });
2724
+ }
2725
+ updateFilterDisplay(name, value) {
2726
+ const valueElement = this.element.querySelector(`[data-filter="${name}"].filter-value`);
2727
+ if (valueElement) {
2728
+ const unit = name === "hue" ? "°" : name === "blur" ? "px" : "%";
2729
+ valueElement.textContent = `${value}${unit}`;
2730
+ }
2731
+ }
2732
+ resetFilters() {
2733
+ const oldFilters = { ...this.filters };
2734
+ const oldPreset = this.currentPreset;
2735
+ this.filters = {
2736
+ brightness: 100,
2737
+ contrast: 100,
2738
+ saturation: 100,
2739
+ hue: 0,
2740
+ blur: 0,
2741
+ grayscale: 0,
2742
+ sepia: 0
2743
+ };
2744
+ this.currentPreset = "none";
2745
+ this.updateAllFilterInputs();
2746
+ this.renderCanvas();
2747
+ this.emitFilterEvent("filters-reset", {
2748
+ oldFilters,
2749
+ newFilters: { ...this.filters },
2750
+ oldPreset,
2751
+ newPreset: this.currentPreset
2752
+ });
2753
+ }
2754
+ updateAllFilterInputs() {
2755
+ Object.keys(this.filters).forEach((filterName) => {
2756
+ const input = this.element.querySelector(`[data-filter="${filterName}"][type="range"]`);
2757
+ if (input) {
2758
+ input.value = this.filters[filterName];
2759
+ this.updateFilterDisplay(filterName, this.filters[filterName]);
2760
+ }
2761
+ });
2762
+ }
2763
+ // Enhanced preset system
2764
+ applyPreset(presetName) {
2765
+ if (!this.presetEffects[presetName]) return;
2766
+ this.presetEffects[presetName];
2767
+ this.currentPreset = presetName;
2768
+ this.currentPreset = presetName;
2769
+ this.renderCanvas();
2770
+ this.emitFilterEvent("preset-applied", { preset: presetName, filters: { ...this.filters } });
2771
+ }
2772
+ // State management
2773
+ getFilterState() {
2774
+ return { ...this.filters };
2775
+ }
2776
+ setFilterState(filters) {
2777
+ this.filters = { ...this.filters, ...filters };
2778
+ this.updateAllFilterInputs();
2779
+ this.renderCanvas();
2780
+ this.emitFilterEvent("filters-set", { filters: { ...this.filters } });
2781
+ }
2782
+ // Export with filters applied
2783
+ exportFilteredImageData() {
2784
+ if (!this.canvas) return null;
2785
+ return this.exportImageData();
2786
+ }
2787
+ async exportFilteredImageBlob(quality = 0.9) {
2788
+ if (!this.canvas) return null;
2789
+ return this.exportImageBlob(quality);
2790
+ }
2791
+ // Create a new canvas with original image + filters applied
2792
+ createFilteredCanvas() {
2793
+ if (!this.image) return null;
2794
+ const canvas = document.createElement("canvas");
2795
+ const context = canvas.getContext("2d");
2796
+ canvas.width = this.image.naturalWidth;
2797
+ canvas.height = this.image.naturalHeight;
2798
+ context.filter = this.getFilterString();
2799
+ context.drawImage(this.image, 0, 0);
2800
+ context.filter = "none";
2801
+ return canvas;
2802
+ }
2803
+ // Event emission
2804
+ emitFilterEvent(type, data = {}) {
2805
+ const eventBus = this.getApp()?.events;
2806
+ if (eventBus) {
2807
+ eventBus.emit(`imagefilters:${type}`, {
2808
+ view: this,
2809
+ hasFilters: this.hasFilters(),
2810
+ filterString: this.getFilterString(),
2811
+ ...data
2812
+ });
2813
+ }
2814
+ }
2815
+ // Override handleImageLoad to emit filter-ready event
2816
+ handleImageLoad() {
2817
+ super.handleImageLoad();
2818
+ this.emitFilterEvent("ready", { filters: { ...this.filters } });
2819
+ }
2820
+ // Cleanup
2821
+ async onBeforeDestroy() {
2822
+ await super.onBeforeDestroy();
2823
+ if (this._resizeHandler) {
2824
+ window.removeEventListener("resize", this._resizeHandler);
2825
+ }
2826
+ this.emitFilterEvent("destroyed");
2827
+ }
2828
+ // Static method to show filters view in a dialog for standalone testing
2829
+ static async showDialog(imageUrl, options = {}) {
2830
+ const {
2831
+ title = "Apply Filters",
2832
+ alt = "Image",
2833
+ size = "xl",
2834
+ showControls = true,
2835
+ allowReset = true,
2836
+ showPresets = true,
2837
+ showBasicControls = true,
2838
+ showAdvancedControls = true,
2839
+ controlsInDropdowns = true,
2840
+ canvasSize = "auto",
2841
+ autoFit = true,
2842
+ crossOrigin = "anonymous",
2843
+ ...dialogOptions
2844
+ } = options;
2845
+ const filtersView = new ImageFiltersView({
2846
+ imageUrl,
2847
+ alt,
2848
+ title,
2849
+ canvasSize,
2850
+ autoFit,
2851
+ crossOrigin,
2852
+ showControls,
2853
+ allowReset,
2854
+ showPresets,
2855
+ showBasicControls,
2856
+ showAdvancedControls,
2857
+ controlsInDropdowns
2858
+ });
2859
+ const dialog = new Dialog({
2860
+ title,
2861
+ body: filtersView,
2862
+ size,
2863
+ centered: true,
2864
+ backdrop: "static",
2865
+ keyboard: true,
2866
+ noBodyPadding: true,
2867
+ buttons: [
2868
+ {
2869
+ text: "Cancel",
2870
+ action: "cancel",
2871
+ class: "btn btn-secondary",
2872
+ dismiss: true
2873
+ },
2874
+ {
2875
+ text: "Apply Filters",
2876
+ action: "apply-filters",
2877
+ class: "btn btn-primary"
2878
+ }
2879
+ ],
2880
+ ...dialogOptions
2881
+ });
2882
+ await dialog.render(true, document.body);
2883
+ dialog.show();
2884
+ return new Promise((resolve) => {
2885
+ dialog.on("hidden", () => {
2886
+ dialog.destroy();
2887
+ resolve({ action: "cancel", view: filtersView });
2888
+ });
2889
+ dialog.on("action:cancel", () => {
2890
+ dialog.hide();
2891
+ });
2892
+ dialog.on("action:apply-filters", async () => {
2893
+ const imageData = filtersView.exportFilteredImageData();
2894
+ dialog.hide();
2895
+ resolve({
2896
+ action: "filters",
2897
+ view: filtersView,
2898
+ data: imageData,
2899
+ filterState: filtersView.getFilterState()
2900
+ });
2901
+ });
2902
+ });
2903
+ }
2904
+ }
2905
+ window.ImageFiltersView = ImageFiltersView;
2906
+ class ImageEditor extends View {
2907
+ constructor(options = {}) {
2908
+ super({
2909
+ ...options,
2910
+ className: `image-editor ${options.className || ""}`,
2911
+ tagName: "div"
2912
+ });
2913
+ this.imageUrl = options.imageUrl || options.src || "";
2914
+ this.alt = options.alt || "Image";
2915
+ this.title = options.title || "";
2916
+ this.currentImageData = null;
2917
+ this.currentMode = options.startMode || "transform";
2918
+ this.history = [];
2919
+ this.historyIndex = -1;
2920
+ this.maxHistory = options.maxHistory || 20;
2921
+ this.showToolbar = options.showToolbar !== false;
2922
+ this.allowTransform = options.allowTransform !== false;
2923
+ this.allowCrop = options.allowCrop !== false;
2924
+ this.allowFilters = options.allowFilters !== false;
2925
+ this.allowExport = options.allowExport !== false;
2926
+ this.allowHistory = options.allowHistory !== false;
2927
+ this.currentView = null;
2928
+ this.isInitialized = false;
2929
+ }
2930
+ async getTemplate() {
2931
+ return `
2932
+ <div class="image-editor-container d-flex flex-column h-100">
2933
+ {{#showToolbar}}
2934
+ <!-- Toolbar -->
2935
+ <div class="image-editor-toolbar bg-light border-bottom p-3" data-container="toolbar">
2936
+ <div class="d-flex justify-content-between align-items-center">
2937
+ <!-- Mode Buttons -->
2938
+ <div class="btn-group" role="group" aria-label="Editing modes">
2939
+ {{#allowTransform}}
2940
+ <button type="button" class="btn btn-outline-primary mode-btn"
2941
+ data-action="switch-mode" data-mode="transform"
2942
+ title="Transform: Zoom, Pan, Rotate">
2943
+ <i class="bi bi-arrows-move"></i> Transform
2944
+ </button>
2945
+ {{/allowTransform}}
2946
+
2947
+ {{#allowCrop}}
2948
+ <button type="button" class="btn btn-outline-primary mode-btn"
2949
+ data-action="switch-mode" data-mode="crop"
2950
+ title="Crop: Select and crop image">
2951
+ <i class="bi bi-crop"></i> Crop
2952
+ </button>
2953
+ {{/allowCrop}}
2954
+
2955
+ {{#allowFilters}}
2956
+ <button type="button" class="btn btn-outline-primary mode-btn"
2957
+ data-action="switch-mode" data-mode="filters"
2958
+ title="Filters: Brightness, Contrast, Effects">
2959
+ <i class="bi bi-palette"></i> Filters
2960
+ </button>
2961
+ {{/allowFilters}}
2962
+ </div>
2963
+
2964
+ <!-- Action Buttons -->
2965
+ <div class="btn-group" role="group" aria-label="Actions">
2966
+ {{#allowHistory}}
2967
+ <button type="button" class="btn btn-outline-secondary btn-sm"
2968
+ data-action="undo" title="Undo" disabled>
2969
+ <i class="bi bi-arrow-counterclockwise"></i>
2970
+ </button>
2971
+ <button type="button" class="btn btn-outline-secondary btn-sm"
2972
+ data-action="redo" title="Redo" disabled>
2973
+ <i class="bi bi-arrow-clockwise"></i>
2974
+ </button>
2975
+ {{/allowHistory}}
2976
+
2977
+ <button type="button" class="btn btn-outline-secondary btn-sm"
2978
+ data-action="reset" title="Reset All Changes">
2979
+ <i class="bi bi-arrow-repeat"></i>
2980
+ </button>
2981
+
2982
+ {{#allowExport}}
2983
+ <button type="button" class="btn btn-success btn-sm"
2984
+ data-action="export" title="Export Image">
2985
+ <i class="bi bi-download"></i> Export
2986
+ </button>
2987
+ {{/allowExport}}
2988
+ </div>
2989
+ </div>
2990
+
2991
+
2992
+ </div>
2993
+ {{/showToolbar}}
2994
+
2995
+ <!-- Main editing area where child views will be mounted -->
2996
+ <div class="image-editor-workspace flex-grow-1 position-relative" data-container="image-workspace">
2997
+ <!-- Child views will be added here dynamically -->
2998
+ </div>
2999
+
3000
+ <!-- Status bar -->
3001
+ <div class="image-editor-status bg-light border-top p-2" data-container="status">
3002
+ <div class="d-flex justify-content-between align-items-center">
3003
+ <small class="text-muted">
3004
+ Mode: <span class="current-mode fw-bold">Transform</span>
3005
+ </small>
3006
+ <small class="text-muted">
3007
+ <span class="image-info">Ready</span>
3008
+ </small>
3009
+ </div>
3010
+ </div>
3011
+ </div>
3012
+ `;
3013
+ }
3014
+ async onAfterRender() {
3015
+ this.toolbarElement = this.element.querySelector(".image-editor-toolbar");
3016
+ this.workspaceElement = this.element.querySelector(".image-editor-workspace");
3017
+ this.statusElement = this.element.querySelector(".image-editor-status");
3018
+ this.setupChildViewEvents();
3019
+ await this.switchMode(this.currentMode, true);
3020
+ this.saveState();
3021
+ this.isInitialized = true;
3022
+ }
3023
+ createChildView(mode) {
3024
+ const imageToUse = this.currentImageData || this.imageUrl;
3025
+ console.log(
3026
+ "[ImageEditor] Creating",
3027
+ mode,
3028
+ "view with:",
3029
+ this.currentImageData ? "preserved canvas data" : "original image"
3030
+ );
3031
+ const childOptions = {
3032
+ parent: this,
3033
+ containerId: "image-workspace",
3034
+ imageUrl: imageToUse,
3035
+ alt: this.alt,
3036
+ title: this.title
3037
+ };
3038
+ switch (mode) {
3039
+ case "transform":
3040
+ if (!this.allowTransform) return null;
3041
+ return new ImageTransformView({
3042
+ ...childOptions,
3043
+ allowPan: true,
3044
+ allowZoom: true,
3045
+ allowRotate: true
3046
+ });
3047
+ case "crop":
3048
+ if (!this.allowCrop) return null;
3049
+ return new ImageCropView({
3050
+ ...childOptions,
3051
+ showGrid: true,
3052
+ minCropSize: 50
3053
+ });
3054
+ case "filters":
3055
+ if (!this.allowFilters) return null;
3056
+ return new ImageFiltersView({
3057
+ ...childOptions,
3058
+ showControls: true,
3059
+ allowReset: true
3060
+ });
3061
+ default:
3062
+ return null;
3063
+ }
3064
+ }
3065
+ setupChildViewEvents() {
3066
+ const eventBus = this.getApp()?.events;
3067
+ if (!eventBus) return;
3068
+ eventBus.on("imagetransform:scale-changed", () => this.saveState());
3069
+ eventBus.on("imagetransform:rotated", () => this.saveState());
3070
+ eventBus.on("imagetransform:reset", () => this.saveState());
3071
+ eventBus.on("imagecrop:crop-applied", (data) => {
3072
+ const imageData = this.getCurrentImageData();
3073
+ if (imageData) {
3074
+ console.log("[ImageEditor] Crop applied - updating preserved canvas data");
3075
+ this.currentImageData = imageData;
3076
+ }
3077
+ this.saveState();
3078
+ this.updateStatus("Crop applied successfully");
3079
+ this.updateHistoryButtons();
3080
+ });
3081
+ eventBus.on("imagefilters:filter-changed", () => {
3082
+ this.saveState();
3083
+ this.updateStatus("Filter applied");
3084
+ });
3085
+ eventBus.on("imagefilters:filters-reset", () => {
3086
+ this.saveState();
3087
+ this.updateStatus("Filters reset");
3088
+ });
3089
+ }
3090
+ // Action handlers
3091
+ async handleActionSwitchMode(e2, el) {
3092
+ const mode = el.getAttribute("data-mode");
3093
+ await this.switchMode(mode);
3094
+ }
3095
+ async handleActionUndo() {
3096
+ this.undo();
3097
+ }
3098
+ async handleActionRedo() {
3099
+ this.redo();
3100
+ }
3101
+ async handleActionReset() {
3102
+ await this.resetAll();
3103
+ }
3104
+ async handleActionExport() {
3105
+ const result = await this.exportImage();
3106
+ if (result) {
3107
+ this.updateStatus("Image exported successfully");
3108
+ }
3109
+ }
3110
+ // Mode management
3111
+ async switchMode(mode, force = false) {
3112
+ if (mode === this.currentMode && !force) return;
3113
+ if (this.currentView && !force) {
3114
+ const imageData = this.getCurrentImageData();
3115
+ if (imageData) {
3116
+ console.log("[ImageEditor] Preserving canvas state from", this.currentMode, "mode");
3117
+ this.currentImageData = imageData;
3118
+ } else {
3119
+ console.log("[ImageEditor] No canvas data to preserve from", this.currentMode, "mode");
3120
+ }
3121
+ } else if (force) {
3122
+ console.log("[ImageEditor] Force mode switch - not preserving canvas state");
3123
+ }
3124
+ if (this.currentView) {
3125
+ await this.currentView.destroy();
3126
+ this.currentView = null;
3127
+ }
3128
+ const modeButtons = this.element.querySelectorAll(".mode-btn");
3129
+ modeButtons.forEach((btn) => {
3130
+ btn.classList.remove("active");
3131
+ if (btn.getAttribute("data-mode") === mode) {
3132
+ btn.classList.add("active");
3133
+ }
3134
+ });
3135
+ this.currentMode = mode;
3136
+ this.currentView = this.createChildView(mode);
3137
+ if (this.currentView) {
3138
+ await this.currentView.render();
3139
+ if (mode === "crop" && this.currentView.startCropMode) {
3140
+ this.currentView.startCropMode();
3141
+ this.updateStatus("Click and drag to select crop area");
3142
+ } else if (mode === "transform") {
3143
+ this.updateStatus("Use controls to transform the image");
3144
+ } else if (mode === "filters") {
3145
+ this.updateStatus("Adjust filters to enhance the image");
3146
+ }
3147
+ }
3148
+ this.updateCurrentModeDisplay();
3149
+ const eventBus = this.getApp()?.events;
3150
+ if (eventBus) {
3151
+ eventBus.emit("imageeditor:mode-changed", {
3152
+ editor: this,
3153
+ mode,
3154
+ currentView: this.currentView
3155
+ });
3156
+ }
3157
+ }
3158
+ updateCurrentModeDisplay() {
3159
+ const modeDisplay = this.element.querySelector(".current-mode");
3160
+ if (modeDisplay) {
3161
+ modeDisplay.textContent = this.currentMode.charAt(0).toUpperCase() + this.currentMode.slice(1);
3162
+ }
3163
+ }
3164
+ updateStatus(message) {
3165
+ const infoDisplay = this.element.querySelector(".image-info");
3166
+ if (infoDisplay) {
3167
+ infoDisplay.textContent = message;
3168
+ }
3169
+ }
3170
+ // History management
3171
+ saveState() {
3172
+ if (!this.isInitialized) return;
3173
+ const state = {
3174
+ mode: this.currentMode,
3175
+ transform: this.currentView?.getTransformState?.(),
3176
+ filters: this.currentView?.getFilterState?.(),
3177
+ imageData: this.currentImageData,
3178
+ timestamp: Date.now()
3179
+ };
3180
+ this.history = this.history.slice(0, this.historyIndex + 1);
3181
+ this.history.push(state);
3182
+ this.historyIndex = this.history.length - 1;
3183
+ if (this.history.length > this.maxHistory) {
3184
+ this.history.shift();
3185
+ this.historyIndex--;
3186
+ }
3187
+ this.updateHistoryButtons();
3188
+ }
3189
+ undo() {
3190
+ if (this.historyIndex > 0) {
3191
+ this.historyIndex--;
3192
+ this.restoreState(this.history[this.historyIndex]);
3193
+ }
3194
+ }
3195
+ redo() {
3196
+ if (this.historyIndex < this.history.length - 1) {
3197
+ this.historyIndex++;
3198
+ this.restoreState(this.history[this.historyIndex]);
3199
+ }
3200
+ }
3201
+ async restoreState(state) {
3202
+ if (state.imageData) {
3203
+ console.log("[ImageEditor] Restoring preserved canvas data from history");
3204
+ this.currentImageData = state.imageData;
3205
+ }
3206
+ await this.switchMode(state.mode, true);
3207
+ if (this.currentView) {
3208
+ if (state.transform && this.currentView.setTransformState) {
3209
+ this.currentView.setTransformState(state.transform);
3210
+ }
3211
+ if (state.filters && this.currentView.setFilterState) {
3212
+ this.currentView.setFilterState(state.filters);
3213
+ }
3214
+ }
3215
+ this.updateHistoryButtons();
3216
+ this.updateStatus(`Restored to ${state.mode} mode`);
3217
+ }
3218
+ updateHistoryButtons() {
3219
+ const undoBtn = this.element.querySelector('[data-action="undo"]');
3220
+ const redoBtn = this.element.querySelector('[data-action="redo"]');
3221
+ if (undoBtn) undoBtn.disabled = this.historyIndex <= 0;
3222
+ if (redoBtn) redoBtn.disabled = this.historyIndex >= this.history.length - 1;
3223
+ }
3224
+ async resetAll() {
3225
+ console.log("[ImageEditor] Resetting - clearing preserved canvas data");
3226
+ this.currentImageData = null;
3227
+ if (this.currentView && this.currentView.reset) {
3228
+ this.currentView.reset();
3229
+ }
3230
+ await this.switchMode("transform", true);
3231
+ this.history = [];
3232
+ this.historyIndex = -1;
3233
+ this.saveState();
3234
+ this.updateStatus("All changes reset");
3235
+ }
3236
+ // Export functionality
3237
+ async exportImage() {
3238
+ if (!this.currentView) return null;
3239
+ try {
3240
+ let imageData = null;
3241
+ imageData = this.getCurrentImageData();
3242
+ if (imageData) {
3243
+ const link = document.createElement("a");
3244
+ link.download = this.getExportFilename();
3245
+ link.href = imageData;
3246
+ document.body.appendChild(link);
3247
+ link.click();
3248
+ document.body.removeChild(link);
3249
+ const eventBus = this.getApp()?.events;
3250
+ if (eventBus) {
3251
+ eventBus.emit("imageeditor:exported", {
3252
+ editor: this,
3253
+ imageData,
3254
+ filename: link.download
3255
+ });
3256
+ }
3257
+ return { imageData, filename: link.download };
3258
+ }
3259
+ } catch (error) {
3260
+ console.error("Export failed:", error);
3261
+ this.updateStatus("Export failed");
3262
+ }
3263
+ return null;
3264
+ }
3265
+ getExportFilename() {
3266
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replace(/[:\-]/g, "");
3267
+ return `edited-image-${timestamp}.png`;
3268
+ }
3269
+ // Public API
3270
+ async setImage(imageUrl, alt = "", title = "") {
3271
+ console.log("[ImageEditor] Setting new image - clearing preserved canvas data");
3272
+ this.imageUrl = imageUrl;
3273
+ this.alt = alt;
3274
+ this.title = title;
3275
+ this.currentImageData = null;
3276
+ if (this.currentView && this.currentView.setImage) {
3277
+ this.currentView.setImage(imageUrl, alt, title);
3278
+ }
3279
+ await this.resetAll();
3280
+ }
3281
+ getCurrentImageData() {
3282
+ if (!this.currentView) return null;
3283
+ let imageData = null;
3284
+ if (this.currentView.exportImageData) {
3285
+ imageData = this.currentView.exportImageData();
3286
+ } else if (this.currentView.exportFilteredImageData) {
3287
+ imageData = this.currentView.exportFilteredImageData();
3288
+ }
3289
+ return imageData || null;
3290
+ }
3291
+ // Cleanup
3292
+ async onBeforeDestroy() {
3293
+ if (this.currentView) {
3294
+ await this.currentView.destroy();
3295
+ this.currentView = null;
3296
+ }
3297
+ const eventBus = this.getApp()?.events;
3298
+ if (eventBus) {
3299
+ eventBus.emit("imageeditor:destroyed", { editor: this });
3300
+ }
3301
+ }
3302
+ // Static method to show editor in a fullscreen dialog
3303
+ static async showDialog(imageUrl, options = {}) {
3304
+ const {
3305
+ title = "Image Editor",
3306
+ alt = "Image",
3307
+ size = "fullscreen",
3308
+ showToolbar = true,
3309
+ allowTransform = true,
3310
+ allowCrop = true,
3311
+ allowFilters = true,
3312
+ allowExport = true,
3313
+ ...dialogOptions
3314
+ } = options;
3315
+ const editor = new ImageEditor({
3316
+ imageUrl,
3317
+ alt,
3318
+ title,
3319
+ showToolbar,
3320
+ allowTransform,
3321
+ allowCrop,
3322
+ allowFilters,
3323
+ allowExport
3324
+ });
3325
+ const dialog = new Dialog({
3326
+ title,
3327
+ body: editor,
3328
+ size,
3329
+ centered: true,
3330
+ backdrop: "static",
3331
+ keyboard: true,
3332
+ buttons: [
3333
+ {
3334
+ text: "Cancel",
3335
+ action: "cancel",
3336
+ class: "btn btn-secondary",
3337
+ dismiss: true
3338
+ },
3339
+ {
3340
+ text: "Export & Close",
3341
+ action: "export-close",
3342
+ class: "btn btn-primary"
3343
+ }
3344
+ ],
3345
+ ...dialogOptions
3346
+ });
3347
+ await dialog.render(true, document.body);
3348
+ window.lastDialog = dialog;
3349
+ dialog.show();
3350
+ return new Promise((resolve) => {
3351
+ dialog.on("hidden", () => {
3352
+ dialog.destroy();
3353
+ resolve({ action: "cancel", editor });
3354
+ });
3355
+ dialog.on("action:cancel", () => {
3356
+ dialog.hide();
3357
+ });
3358
+ dialog.on("action:export-close", async () => {
3359
+ const result = await editor.exportImage();
3360
+ dialog.hide();
3361
+ resolve({
3362
+ action: "export",
3363
+ editor,
3364
+ data: result?.imageData,
3365
+ filename: result?.filename
3366
+ });
3367
+ });
3368
+ });
3369
+ }
3370
+ }
3371
+ window.ImageEditor = ImageEditor;
3372
+ class ImageUploadView extends View {
3373
+ constructor(options = {}) {
3374
+ super({
3375
+ ...options,
3376
+ className: `image-upload-view ${options.className || ""}`,
3377
+ tagName: "div"
3378
+ });
3379
+ this.autoUpload = options.autoUpload || false;
3380
+ this.acceptedTypes = options.acceptedTypes || ["image/jpeg", "image/png", "image/gif", "image/webp"];
3381
+ this.maxFileSize = options.maxFileSize || 10 * 1024 * 1024;
3382
+ this.uploadUrl = options.uploadUrl || null;
3383
+ this.onUpload = options.onUpload || null;
3384
+ this.selectedFile = null;
3385
+ this.isUploading = false;
3386
+ this.previewUrl = null;
3387
+ this._handleDragOver = this.handleDragOver.bind(this);
3388
+ this._handleDragLeave = this.handleDragLeave.bind(this);
3389
+ this._handleDrop = this.handleDrop.bind(this);
3390
+ this._handleFileSelect = this.handleFileSelect.bind(this);
3391
+ this._preventDefaults = this.preventDefaults.bind(this);
3392
+ }
3393
+ async getTemplate() {
3394
+ return `
3395
+ <div class="image-upload-container">
3396
+ <!-- Drop Zone -->
3397
+ <div class="upload-drop-zone border-2 border-dashed rounded p-4 text-center position-relative"
3398
+ style="border-color: #dee2e6; min-height: 200px; transition: all 0.2s ease;">
3399
+
3400
+ <!-- Default State -->
3401
+ <div class="upload-prompt">
3402
+ <i class="bi bi-cloud-upload text-muted" style="font-size: 3rem;"></i>
3403
+ <h5 class="mt-3 text-muted">Drop your image here</h5>
3404
+ <p class="text-muted mb-3">or</p>
3405
+ <button type="button" class="btn btn-outline-primary" data-action="select-file">
3406
+ <i class="bi bi-folder2-open"></i> Choose File
3407
+ </button>
3408
+ <input type="file" class="upload-file-input d-none" accept="image/*" multiple="false">
3409
+ <div class="mt-3">
3410
+ <small class="text-muted">Supported: JPEG, PNG, GIF, WebP (max ${Math.round(this.maxFileSize / 1024 / 1024)}MB)</small>
3411
+ </div>
3412
+ </div>
3413
+
3414
+ <!-- Preview State -->
3415
+ <div class="upload-preview d-none">
3416
+ <div class="preview-image-container mb-3">
3417
+ <img class="preview-image img-fluid rounded shadow-sm" style="max-height: 300px; max-width: 100%;">
3418
+ </div>
3419
+ <div class="preview-info">
3420
+ <div class="file-name fw-bold mb-2 text-truncate"></div>
3421
+ <div class="file-details text-muted small mb-3"></div>
3422
+ <div class="upload-actions">
3423
+ {{#autoUpload}}
3424
+ <button type="button" class="btn btn-outline-secondary" data-action="clear">
3425
+ <i class="bi bi-x"></i> Clear
3426
+ </button>
3427
+ {{/autoUpload}}
3428
+ {{^autoUpload}}
3429
+ <button type="button" class="btn btn-success me-2" data-action="upload">
3430
+ <i class="bi bi-cloud-arrow-up"></i> Upload
3431
+ </button>
3432
+ <button type="button" class="btn btn-outline-secondary" data-action="clear">
3433
+ <i class="bi bi-x"></i> Clear
3434
+ </button>
3435
+ {{/autoUpload}}
3436
+ </div>
3437
+ </div>
3438
+ </div>
3439
+
3440
+ <!-- Loading State -->
3441
+ <div class="upload-loading d-none">
3442
+ <div class="spinner-border text-primary mb-3" role="status">
3443
+ <span class="visually-hidden">Uploading...</span>
3444
+ </div>
3445
+ <div class="upload-progress">
3446
+ <div class="progress mb-2" style="height: 8px;">
3447
+ <div class="progress-bar progress-bar-striped progress-bar-animated"
3448
+ role="progressbar" style="width: 0%"></div>
3449
+ </div>
3450
+ <small class="text-muted upload-status">Uploading...</small>
3451
+ </div>
3452
+ </div>
3453
+ </div>
3454
+
3455
+ <!-- Upload Result -->
3456
+ <div class="upload-result mt-3 d-none">
3457
+ <div class="alert" role="alert"></div>
3458
+ </div>
3459
+ </div>
3460
+ `;
3461
+ }
3462
+ async onAfterRender() {
3463
+ this.dropZone = this.element.querySelector(".upload-drop-zone");
3464
+ this.fileInput = this.element.querySelector(".upload-file-input");
3465
+ this.promptElement = this.element.querySelector(".upload-prompt");
3466
+ this.previewElement = this.element.querySelector(".upload-preview");
3467
+ this.loadingElement = this.element.querySelector(".upload-loading");
3468
+ this.resultElement = this.element.querySelector(".upload-result");
3469
+ this.previewImage = this.element.querySelector(".preview-image");
3470
+ this.fileName = this.element.querySelector(".file-name");
3471
+ this.fileDetails = this.element.querySelector(".file-details");
3472
+ this.progressBar = this.element.querySelector(".progress-bar");
3473
+ this.uploadStatus = this.element.querySelector(".upload-status");
3474
+ this.setupEventListeners();
3475
+ }
3476
+ setupEventListeners() {
3477
+ this.dropZone.addEventListener("dragenter", this._preventDefaults);
3478
+ this.dropZone.addEventListener("dragover", this._handleDragOver);
3479
+ this.dropZone.addEventListener("dragleave", this._handleDragLeave);
3480
+ this.dropZone.addEventListener("drop", this._handleDrop);
3481
+ this.fileInput.addEventListener("change", this._handleFileSelect);
3482
+ ["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
3483
+ document.addEventListener(eventName, this._preventDefaults);
3484
+ });
3485
+ }
3486
+ preventDefaults(e2) {
3487
+ e2.preventDefault();
3488
+ e2.stopPropagation();
3489
+ }
3490
+ handleDragOver(e2) {
3491
+ this.preventDefaults(e2);
3492
+ this.dropZone.classList.add("border-primary", "bg-light");
3493
+ this.dropZone.style.borderColor = "#0d6efd";
3494
+ }
3495
+ handleDragLeave(e2) {
3496
+ this.preventDefaults(e2);
3497
+ if (!this.dropZone.contains(e2.relatedTarget)) {
3498
+ this.dropZone.classList.remove("border-primary", "bg-light");
3499
+ this.dropZone.style.borderColor = "#dee2e6";
3500
+ }
3501
+ }
3502
+ async handleDrop(e2) {
3503
+ this.preventDefaults(e2);
3504
+ this.dropZone.classList.remove("border-primary", "bg-light");
3505
+ this.dropZone.style.borderColor = "#dee2e6";
3506
+ const files = Array.from(e2.dataTransfer.files);
3507
+ if (files.length > 0) {
3508
+ await this.processFile(files[0]);
3509
+ }
3510
+ }
3511
+ async handleFileSelect(e2) {
3512
+ const files = Array.from(e2.target.files);
3513
+ if (files.length > 0) {
3514
+ await this.processFile(files[0]);
3515
+ }
3516
+ }
3517
+ async processFile(file) {
3518
+ const validation = this.validateFile(file);
3519
+ if (!validation.valid) {
3520
+ this.showError(validation.error);
3521
+ return;
3522
+ }
3523
+ this.selectedFile = file;
3524
+ await this.showPreview(file);
3525
+ if (this.autoUpload) {
3526
+ setTimeout(() => this.uploadFile(), 100);
3527
+ }
3528
+ }
3529
+ validateFile(file) {
3530
+ if (!this.acceptedTypes.includes(file.type)) {
3531
+ return {
3532
+ valid: false,
3533
+ error: `File type "${file.type}" is not supported. Please use: ${this.acceptedTypes.map((t) => t.split("/")[1].toUpperCase()).join(", ")}`
3534
+ };
3535
+ }
3536
+ if (file.size > this.maxFileSize) {
3537
+ return {
3538
+ valid: false,
3539
+ error: `File size (${this.formatFileSize(file.size)}) exceeds maximum allowed size (${this.formatFileSize(this.maxFileSize)})`
3540
+ };
3541
+ }
3542
+ return { valid: true };
3543
+ }
3544
+ async showPreview(file) {
3545
+ if (this.previewUrl) {
3546
+ URL.revokeObjectURL(this.previewUrl);
3547
+ }
3548
+ this.previewUrl = URL.createObjectURL(file);
3549
+ this.previewImage.src = this.previewUrl;
3550
+ this.fileName.textContent = file.name;
3551
+ this.fileDetails.textContent = `${this.formatFileSize(file.size)} • ${file.type.split("/")[1].toUpperCase()}`;
3552
+ this.promptElement.classList.add("d-none");
3553
+ this.previewElement.classList.remove("d-none");
3554
+ this.hideResult();
3555
+ this.emitUploadEvent("preview", { file, previewUrl: this.previewUrl });
3556
+ }
3557
+ async uploadFile() {
3558
+ if (!this.selectedFile || this.isUploading) return;
3559
+ this.isUploading = true;
3560
+ this.showLoading();
3561
+ try {
3562
+ let result;
3563
+ if (this.onUpload && typeof this.onUpload === "function") {
3564
+ result = await this.onUpload(this.selectedFile, this.updateProgress.bind(this));
3565
+ } else if (this.uploadUrl) {
3566
+ result = await this.uploadToUrl(this.selectedFile);
3567
+ } else {
3568
+ throw new Error("No upload method configured. Provide either uploadUrl or onUpload callback.");
3569
+ }
3570
+ this.showSuccess("File uploaded successfully!");
3571
+ this.emitUploadEvent("upload-success", { file: this.selectedFile, result });
3572
+ } catch (error) {
3573
+ console.error("Upload failed:", error);
3574
+ this.showError(`Upload failed: ${error.message}`);
3575
+ this.emitUploadEvent("upload-error", { file: this.selectedFile, error });
3576
+ } finally {
3577
+ this.isUploading = false;
3578
+ this.hideLoading();
3579
+ }
3580
+ }
3581
+ async uploadToUrl(file) {
3582
+ return new Promise((resolve, reject) => {
3583
+ const formData = new FormData();
3584
+ formData.append("image", file);
3585
+ const xhr = new XMLHttpRequest();
3586
+ xhr.upload.addEventListener("progress", (e2) => {
3587
+ if (e2.lengthComputable) {
3588
+ const progress = Math.round(e2.loaded / e2.total * 100);
3589
+ this.updateProgress(progress);
3590
+ }
3591
+ });
3592
+ xhr.addEventListener("load", () => {
3593
+ if (xhr.status >= 200 && xhr.status < 300) {
3594
+ try {
3595
+ const response = JSON.parse(xhr.responseText);
3596
+ resolve(response);
3597
+ } catch (e2) {
3598
+ resolve({ success: true, response: xhr.responseText });
3599
+ }
3600
+ } else {
3601
+ reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
3602
+ }
3603
+ });
3604
+ xhr.addEventListener("error", () => {
3605
+ reject(new Error("Network error occurred"));
3606
+ });
3607
+ xhr.addEventListener("timeout", () => {
3608
+ reject(new Error("Upload timeout"));
3609
+ });
3610
+ xhr.open("POST", this.uploadUrl);
3611
+ xhr.timeout = 3e4;
3612
+ xhr.send(formData);
3613
+ });
3614
+ }
3615
+ updateProgress(percent) {
3616
+ if (this.progressBar) {
3617
+ this.progressBar.style.width = `${percent}%`;
3618
+ this.progressBar.setAttribute("aria-valuenow", percent);
3619
+ }
3620
+ if (this.uploadStatus) {
3621
+ this.uploadStatus.textContent = `Uploading... ${percent}%`;
3622
+ }
3623
+ }
3624
+ showLoading() {
3625
+ this.previewElement.classList.add("d-none");
3626
+ this.loadingElement.classList.remove("d-none");
3627
+ this.updateProgress(0);
3628
+ }
3629
+ hideLoading() {
3630
+ this.loadingElement.classList.add("d-none");
3631
+ if (!this.autoUpload || this.selectedFile) {
3632
+ this.previewElement.classList.remove("d-none");
3633
+ }
3634
+ }
3635
+ showSuccess(message) {
3636
+ this.showResult("success", message);
3637
+ }
3638
+ showError(message) {
3639
+ this.showResult("danger", message);
3640
+ }
3641
+ showResult(type, message) {
3642
+ const alertElement = this.resultElement.querySelector(".alert");
3643
+ const icon = type === "success" ? "check-circle-fill" : "exclamation-triangle-fill";
3644
+ alertElement.className = `alert alert-${type}`;
3645
+ alertElement.innerHTML = `
3646
+ <i class="bi bi-${icon} me-2"></i>
3647
+ ${message}
3648
+ `;
3649
+ this.resultElement.classList.remove("d-none");
3650
+ if (type === "success") {
3651
+ setTimeout(() => this.hideResult(), 5e3);
3652
+ }
3653
+ }
3654
+ hideResult() {
3655
+ this.resultElement.classList.add("d-none");
3656
+ }
3657
+ clearFile() {
3658
+ if (this.previewUrl) {
3659
+ URL.revokeObjectURL(this.previewUrl);
3660
+ this.previewUrl = null;
3661
+ }
3662
+ this.selectedFile = null;
3663
+ this.isUploading = false;
3664
+ this.fileInput.value = "";
3665
+ this.previewElement.classList.add("d-none");
3666
+ this.loadingElement.classList.add("d-none");
3667
+ this.promptElement.classList.remove("d-none");
3668
+ this.hideResult();
3669
+ this.emitUploadEvent("cleared");
3670
+ }
3671
+ formatFileSize(bytes) {
3672
+ if (bytes === 0) return "0 Bytes";
3673
+ const k = 1024;
3674
+ const sizes = ["Bytes", "KB", "MB", "GB"];
3675
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
3676
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
3677
+ }
3678
+ emitUploadEvent(type, data = {}) {
3679
+ const eventBus = this.getApp()?.events;
3680
+ if (eventBus) {
3681
+ eventBus.emit(`imageupload:${type}`, {
3682
+ view: this,
3683
+ ...data
3684
+ });
3685
+ }
3686
+ }
3687
+ // Action handlers
3688
+ async handleActionSelectFile() {
3689
+ this.fileInput.click();
3690
+ }
3691
+ async handleActionUpload() {
3692
+ await this.uploadFile();
3693
+ }
3694
+ async handleActionClear() {
3695
+ this.clearFile();
3696
+ }
3697
+ // Cleanup
3698
+ async onBeforeDestroy() {
3699
+ if (this.previewUrl) {
3700
+ URL.revokeObjectURL(this.previewUrl);
3701
+ this.previewUrl = null;
3702
+ }
3703
+ if (this.dropZone) {
3704
+ this.dropZone.removeEventListener("dragenter", this._preventDefaults);
3705
+ this.dropZone.removeEventListener("dragover", this._handleDragOver);
3706
+ this.dropZone.removeEventListener("dragleave", this._handleDragLeave);
3707
+ this.dropZone.removeEventListener("drop", this._handleDrop);
3708
+ }
3709
+ if (this.fileInput) {
3710
+ this.fileInput.removeEventListener("change", this._handleFileSelect);
3711
+ }
3712
+ ["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
3713
+ document.removeEventListener(eventName, this._preventDefaults);
3714
+ });
3715
+ this.emitUploadEvent("destroyed");
3716
+ }
3717
+ }
3718
+ window.ImageUploadView = ImageUploadView;
3719
+ export {
3720
+ B as BUILD_TIME,
3721
+ ImageCanvasView,
3722
+ ImageCropView,
3723
+ ImageEditor,
3724
+ ImageFiltersView,
3725
+ ImageTransformView,
3726
+ ImageUploadView,
3727
+ ImageViewer,
3728
+ L as LightboxGallery,
3729
+ P as PDFViewer,
3730
+ b as VERSION,
3731
+ a as VERSION_INFO,
3732
+ c as VERSION_MAJOR,
3733
+ e as VERSION_MINOR,
3734
+ f as VERSION_REVISION,
3735
+ W as WebApp
3736
+ };
3737
+ //# sourceMappingURL=lightbox.es.js.map