@pixerate/editor 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1350 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/image-editor/index.ts
21
+ var image_editor_exports = {};
22
+ __export(image_editor_exports, {
23
+ DEFAULT_ADJUSTMENTS: () => DEFAULT_ADJUSTMENTS,
24
+ DEFAULT_DEPTH_MASK: () => DEFAULT_DEPTH_MASK,
25
+ DEFAULT_TRANSFORM: () => DEFAULT_TRANSFORM,
26
+ ImageEditorController: () => ImageEditorController,
27
+ ImageEditorRenderer: () => ImageEditorRenderer,
28
+ applyAdjustments: () => applyAdjustments,
29
+ applyDepthMask: () => applyDepthMask,
30
+ calculateCropDrag: () => calculateCropDrag,
31
+ canvasToImagePoint: () => canvasToImagePoint,
32
+ getAnnotationBounds: () => getAnnotationBounds,
33
+ getCropCursor: () => getCropCursor,
34
+ getViewportMetrics: () => getViewportMetrics,
35
+ globalImageCache: () => globalImageCache,
36
+ hitTestAnnotation: () => hitTestAnnotation,
37
+ hitTestCrop: () => hitTestCrop,
38
+ imageToCanvasPoint: () => imageToCanvasPoint,
39
+ removeAlpha: () => removeAlpha
40
+ });
41
+ module.exports = __toCommonJS(image_editor_exports);
42
+
43
+ // src/image-editor/filters.ts
44
+ function clamp(value, min = 0, max = 255) {
45
+ return Math.max(min, Math.min(max, value));
46
+ }
47
+ function applyAdjustments(imageData, adjustments) {
48
+ const { brightness, contrast, saturation, exposure, temperature, opacity, blur } = adjustments;
49
+ const data = imageData.data;
50
+ const len = data.length;
51
+ const hasBrightness = brightness !== 0;
52
+ const hasContrast = contrast !== 0;
53
+ const hasSaturation = saturation !== 0;
54
+ const hasExposure = exposure !== 0;
55
+ const hasTemperature = temperature !== 0;
56
+ const hasOpacity = opacity < 1;
57
+ const contrastFactor = hasContrast ? 259 * (contrast + 255) / (255 * (259 - contrast)) : 1;
58
+ const exposureMultiplier = hasExposure ? Math.pow(2, exposure / 50) : 1;
59
+ const satMultiplier = hasSaturation ? 1 + saturation / 100 : 1;
60
+ const tempOffset = hasTemperature ? temperature * 0.8 : 0;
61
+ if (hasBrightness || hasContrast || hasSaturation || hasExposure || hasTemperature || hasOpacity) {
62
+ for (let i = 0; i < len; i += 4) {
63
+ let r = data[i];
64
+ let g = data[i + 1];
65
+ let b = data[i + 2];
66
+ let a = data[i + 3];
67
+ if (hasExposure) {
68
+ r = clamp(r * exposureMultiplier);
69
+ g = clamp(g * exposureMultiplier);
70
+ b = clamp(b * exposureMultiplier);
71
+ }
72
+ if (hasBrightness) {
73
+ const bOffset = brightness * 2.55;
74
+ r = clamp(r + bOffset);
75
+ g = clamp(g + bOffset);
76
+ b = clamp(b + bOffset);
77
+ }
78
+ if (hasContrast) {
79
+ r = clamp(contrastFactor * (r - 128) + 128);
80
+ g = clamp(contrastFactor * (g - 128) + 128);
81
+ b = clamp(contrastFactor * (b - 128) + 128);
82
+ }
83
+ if (hasSaturation) {
84
+ const luminance = 0.2989 * r + 0.587 * g + 0.114 * b;
85
+ r = clamp(luminance + (r - luminance) * satMultiplier);
86
+ g = clamp(luminance + (g - luminance) * satMultiplier);
87
+ b = clamp(luminance + (b - luminance) * satMultiplier);
88
+ }
89
+ if (hasTemperature) {
90
+ r = clamp(r + tempOffset);
91
+ b = clamp(b - tempOffset);
92
+ }
93
+ if (hasOpacity) {
94
+ a = clamp(a * opacity);
95
+ }
96
+ data[i] = r;
97
+ data[i + 1] = g;
98
+ data[i + 2] = b;
99
+ data[i + 3] = a;
100
+ }
101
+ }
102
+ if (blur > 0) {
103
+ applyFastBoxBlur(imageData, Math.min(Math.round(blur), 40));
104
+ }
105
+ }
106
+ function applyFastBoxBlur(imageData, radius) {
107
+ if (radius < 1) return;
108
+ const w = imageData.width;
109
+ const h = imageData.height;
110
+ const src = imageData.data;
111
+ const temp = new Uint8ClampedArray(src.length);
112
+ for (let y = 0; y < h; y++) {
113
+ for (let x = 0; x < w; x++) {
114
+ let r = 0, g = 0, b = 0, a = 0;
115
+ let count = 0;
116
+ for (let k = -radius; k <= radius; k++) {
117
+ const px = Math.min(w - 1, Math.max(0, x + k));
118
+ const idx = (y * w + px) * 4;
119
+ r += src[idx];
120
+ g += src[idx + 1];
121
+ b += src[idx + 2];
122
+ a += src[idx + 3];
123
+ count++;
124
+ }
125
+ const dstIdx = (y * w + x) * 4;
126
+ temp[dstIdx] = Math.round(r / count);
127
+ temp[dstIdx + 1] = Math.round(g / count);
128
+ temp[dstIdx + 2] = Math.round(b / count);
129
+ temp[dstIdx + 3] = Math.round(a / count);
130
+ }
131
+ }
132
+ for (let x = 0; x < w; x++) {
133
+ for (let y = 0; y < h; y++) {
134
+ let r = 0, g = 0, b = 0, a = 0;
135
+ let count = 0;
136
+ for (let k = -radius; k <= radius; k++) {
137
+ const py = Math.min(h - 1, Math.max(0, y + k));
138
+ const idx = (py * w + x) * 4;
139
+ r += temp[idx];
140
+ g += temp[idx + 1];
141
+ b += temp[idx + 2];
142
+ a += temp[idx + 3];
143
+ count++;
144
+ }
145
+ const dstIdx = (y * w + x) * 4;
146
+ src[dstIdx] = Math.round(r / count);
147
+ src[dstIdx + 1] = Math.round(g / count);
148
+ src[dstIdx + 2] = Math.round(b / count);
149
+ src[dstIdx + 3] = Math.round(a / count);
150
+ }
151
+ }
152
+ }
153
+ function applyDepthMask(mainImageData, maskImageData, options) {
154
+ const { mode, depthRange, softness, invert } = options;
155
+ const mainData = mainImageData.data;
156
+ const maskData = maskImageData.data;
157
+ const len = Math.min(mainData.length, maskData.length);
158
+ const effectiveSoftness = Math.max(1, softness || 10);
159
+ const minDepth = depthRange[0];
160
+ const maxDepth = depthRange[1];
161
+ for (let i = 0; i < len; i += 4) {
162
+ let maskValue = maskData[i];
163
+ if (invert) {
164
+ maskValue = 255 - maskValue;
165
+ }
166
+ let alphaValue;
167
+ if (mode === "threshold") {
168
+ if (maskValue >= maxDepth + effectiveSoftness) {
169
+ alphaValue = 0;
170
+ } else if (maskValue > maxDepth) {
171
+ alphaValue = Math.round((maxDepth + effectiveSoftness - maskValue) / effectiveSoftness * 255);
172
+ } else if (maskValue >= minDepth) {
173
+ alphaValue = 255;
174
+ } else if (maskValue < minDepth - effectiveSoftness) {
175
+ alphaValue = 0;
176
+ } else {
177
+ alphaValue = Math.round((maskValue - (minDepth - effectiveSoftness)) / effectiveSoftness * 255);
178
+ }
179
+ } else {
180
+ alphaValue = clamp(maskValue + minDepth);
181
+ }
182
+ mainData[i + 3] = clamp(mainData[i + 3] * alphaValue / 255);
183
+ }
184
+ }
185
+ function removeAlpha(imageData) {
186
+ const data = imageData.data;
187
+ const len = data.length;
188
+ for (let i = 3; i < len; i += 4) {
189
+ data[i] = 255;
190
+ }
191
+ }
192
+
193
+ // src/image-editor/renderer.ts
194
+ var ImageCache = class {
195
+ cache = /* @__PURE__ */ new Map();
196
+ async get(src) {
197
+ const existing = this.cache.get(src);
198
+ if (existing && existing.complete) {
199
+ return existing;
200
+ }
201
+ return new Promise((resolve, reject) => {
202
+ if (typeof window === "undefined" || typeof Image === "undefined") {
203
+ reject(new Error("Image loading is only supported in browser/DOM environments"));
204
+ return;
205
+ }
206
+ const img = new Image();
207
+ img.crossOrigin = "anonymous";
208
+ img.onload = () => {
209
+ this.cache.set(src, img);
210
+ resolve(img);
211
+ };
212
+ img.onerror = (e) => reject(new Error(`Failed to load image from: ${src}`));
213
+ img.src = src;
214
+ });
215
+ }
216
+ set(src, img) {
217
+ this.cache.set(src, img);
218
+ }
219
+ clear() {
220
+ this.cache.clear();
221
+ }
222
+ };
223
+ var globalImageCache = new ImageCache();
224
+ var ImageEditorRenderer = class {
225
+ imageCache = globalImageCache;
226
+ cachedBaseCanvas = null;
227
+ cachedBaseKey = "";
228
+ /**
229
+ * Helper to create a canvas element safely in browser/JSDOM.
230
+ */
231
+ createCanvas(width, height) {
232
+ if (typeof document !== "undefined" && document.createElement) {
233
+ const c = document.createElement("canvas");
234
+ c.width = Math.max(1, Math.round(width));
235
+ c.height = Math.max(1, Math.round(height));
236
+ return c;
237
+ }
238
+ return {
239
+ width: Math.max(1, Math.round(width)),
240
+ height: Math.max(1, Math.round(height)),
241
+ getContext: () => null,
242
+ toDataURL: () => "",
243
+ toBlob: () => {
244
+ }
245
+ };
246
+ }
247
+ /**
248
+ * Renders the editor state onto a canvas (viewport or preview).
249
+ */
250
+ async renderToCanvas(targetCanvas, imageSource, state, options = {}) {
251
+ const ctx = targetCanvas.getContext("2d");
252
+ if (!ctx) return;
253
+ let img;
254
+ if (typeof imageSource === "string") {
255
+ img = await this.imageCache.get(imageSource);
256
+ } else {
257
+ img = imageSource;
258
+ }
259
+ const naturalWidth = img.naturalWidth || img.videoWidth || img.width || 800;
260
+ const naturalHeight = img.naturalHeight || img.videoHeight || img.height || 600;
261
+ const { crop, transform, adjustments, depthMask, annotations, selectedAnnotationId, zoom, pan, isOriginalCompared } = state;
262
+ const vpWidth = options.viewportWidth || targetCanvas.width;
263
+ const vpHeight = options.viewportHeight || targetCanvas.height;
264
+ targetCanvas.width = vpWidth;
265
+ targetCanvas.height = vpHeight;
266
+ ctx.clearRect(0, 0, vpWidth, vpHeight);
267
+ if (isOriginalCompared) {
268
+ this.drawFittedImage(ctx, img, naturalWidth, naturalHeight, vpWidth, vpHeight, zoom, pan);
269
+ return;
270
+ }
271
+ const isActivelyCropping = Boolean(options.showCropOverlay || state.activeTool === "crop");
272
+ const cropX = !isActivelyCropping && crop ? Math.max(0, crop.x) : 0;
273
+ const cropY = !isActivelyCropping && crop ? Math.max(0, crop.y) : 0;
274
+ const cropW = !isActivelyCropping && crop ? Math.min(naturalWidth - cropX, crop.width) : naturalWidth;
275
+ const cropH = !isActivelyCropping && crop ? Math.min(naturalHeight - cropY, crop.height) : naturalHeight;
276
+ const angle = (transform.rotate % 360 + 360) % 360;
277
+ const isSwapped = angle === 90 || angle === 270;
278
+ const baseW = isSwapped ? cropH : cropW;
279
+ const baseH = isSwapped ? cropW : cropH;
280
+ const baseKey = `${state.sourceUrl}-${naturalWidth}x${naturalHeight}-${cropX},${cropY},${cropW},${cropH}-${angle},${transform.flipH},${transform.flipV}-${adjustments.brightness},${adjustments.contrast},${adjustments.saturation},${adjustments.exposure},${adjustments.temperature},${adjustments.blur},${adjustments.opacity}-${depthMask.enabled},${depthMask.depthRange?.[0]}-${depthMask.depthRange?.[1]},${depthMask.softness},${depthMask.invert},${depthMask.mode}`;
281
+ let baseCanvas = this.cachedBaseCanvas;
282
+ if (!baseCanvas || this.cachedBaseKey !== baseKey) {
283
+ baseCanvas = this.createCanvas(baseW, baseH);
284
+ const baseCtx = baseCanvas.getContext("2d");
285
+ if (baseCtx) {
286
+ baseCtx.save();
287
+ const rad = angle * Math.PI / 180;
288
+ baseCtx.translate(baseW / 2, baseH / 2);
289
+ baseCtx.rotate(rad);
290
+ baseCtx.scale(transform.flipH ? -1 : 1, transform.flipV ? -1 : 1);
291
+ baseCtx.drawImage(
292
+ img,
293
+ cropX,
294
+ cropY,
295
+ cropW,
296
+ cropH,
297
+ -cropW / 2,
298
+ -cropH / 2,
299
+ cropW,
300
+ cropH
301
+ );
302
+ baseCtx.restore();
303
+ const imageData = baseCtx.getImageData(0, 0, baseW, baseH);
304
+ if (imageData) {
305
+ applyAdjustments(imageData, adjustments);
306
+ if (depthMask.enabled && depthMask.maskSource) {
307
+ try {
308
+ const maskImg = await this.imageCache.get(depthMask.maskSource);
309
+ const maskCanvas = this.createCanvas(baseW, baseH);
310
+ const maskCtx = maskCanvas.getContext("2d");
311
+ if (maskCtx) {
312
+ maskCtx.drawImage(maskImg, cropX, cropY, cropW, cropH, 0, 0, baseW, baseH);
313
+ const maskData = maskCtx.getImageData(0, 0, baseW, baseH);
314
+ if (maskData) {
315
+ applyDepthMask(imageData, maskData, depthMask);
316
+ }
317
+ }
318
+ } catch {
319
+ }
320
+ }
321
+ baseCtx.putImageData(imageData, 0, 0);
322
+ }
323
+ }
324
+ this.cachedBaseCanvas = baseCanvas;
325
+ this.cachedBaseKey = baseKey;
326
+ }
327
+ ctx.save();
328
+ ctx.translate(vpWidth / 2 + pan.x, vpHeight / 2 + pan.y);
329
+ ctx.scale(zoom, zoom);
330
+ const fitScale = Math.min(vpWidth * 0.85 / baseW, vpHeight * 0.85 / baseH, 1);
331
+ const renderW = baseW * fitScale;
332
+ const renderH = baseH * fitScale;
333
+ ctx.drawImage(baseCanvas, -renderW / 2, -renderH / 2, renderW, renderH);
334
+ const scaleFactor = fitScale;
335
+ ctx.save();
336
+ ctx.translate(-renderW / 2, -renderH / 2);
337
+ ctx.scale(scaleFactor, scaleFactor);
338
+ for (const ann of annotations) {
339
+ await this.drawAnnotation(ctx, ann);
340
+ if (options.showSelectionOverlay && ann.id === selectedAnnotationId) {
341
+ this.drawAnnotationSelection(ctx, ann);
342
+ }
343
+ }
344
+ if (options.draftAnnotation) {
345
+ await this.drawAnnotation(ctx, options.draftAnnotation);
346
+ }
347
+ ctx.restore();
348
+ ctx.restore();
349
+ const isCroppingActive = Boolean(options.showCropOverlay || state.activeTool === "crop");
350
+ const activeCrop = options.draftCrop !== void 0 && options.draftCrop !== null ? options.draftCrop : crop ?? (isCroppingActive ? {
351
+ x: 0,
352
+ y: 0,
353
+ width: naturalWidth,
354
+ height: naturalHeight
355
+ } : null);
356
+ if (isCroppingActive && activeCrop) {
357
+ this.drawCropOverlay(ctx, state, vpWidth, vpHeight, naturalWidth, naturalHeight, activeCrop);
358
+ }
359
+ }
360
+ /**
361
+ * Draws an individual annotation onto the canvas.
362
+ */
363
+ async drawAnnotation(ctx, ann) {
364
+ ctx.save();
365
+ if (ann.opacity !== void 0) {
366
+ ctx.globalAlpha = ann.opacity;
367
+ }
368
+ if (ann.rotation) {
369
+ ctx.translate(ann.x, ann.y);
370
+ ctx.rotate(ann.rotation * Math.PI / 180);
371
+ ctx.translate(-ann.x, -ann.y);
372
+ }
373
+ switch (ann.type) {
374
+ case "pen": {
375
+ const pen = ann;
376
+ if (pen.points.length > 0) {
377
+ ctx.beginPath();
378
+ ctx.strokeStyle = pen.strokeColor;
379
+ ctx.lineWidth = pen.strokeWidth;
380
+ ctx.lineCap = "round";
381
+ ctx.lineJoin = "round";
382
+ ctx.moveTo(pen.points[0].x, pen.points[0].y);
383
+ for (let i = 1; i < pen.points.length; i++) {
384
+ ctx.lineTo(pen.points[i].x, pen.points[i].y);
385
+ }
386
+ ctx.stroke();
387
+ }
388
+ break;
389
+ }
390
+ case "rect": {
391
+ const rect = ann;
392
+ ctx.strokeStyle = rect.strokeColor;
393
+ ctx.lineWidth = rect.strokeWidth;
394
+ if (rect.fillColor) {
395
+ ctx.fillStyle = rect.fillColor;
396
+ ctx.fillRect(rect.x, rect.y, rect.width, rect.height);
397
+ }
398
+ if (rect.strokeWidth > 0) {
399
+ ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);
400
+ }
401
+ break;
402
+ }
403
+ case "circle": {
404
+ const circle = ann;
405
+ ctx.beginPath();
406
+ ctx.strokeStyle = circle.strokeColor;
407
+ ctx.lineWidth = circle.strokeWidth;
408
+ ctx.ellipse(circle.x, circle.y, Math.abs(circle.radiusX), Math.abs(circle.radiusY), 0, 0, 2 * Math.PI);
409
+ if (circle.fillColor) {
410
+ ctx.fillStyle = circle.fillColor;
411
+ ctx.fill();
412
+ }
413
+ if (circle.strokeWidth > 0) {
414
+ ctx.stroke();
415
+ }
416
+ break;
417
+ }
418
+ case "arrow": {
419
+ const arrow = ann;
420
+ ctx.strokeStyle = arrow.strokeColor;
421
+ ctx.fillStyle = arrow.strokeColor;
422
+ ctx.lineWidth = arrow.strokeWidth;
423
+ ctx.beginPath();
424
+ ctx.moveTo(arrow.x, arrow.y);
425
+ ctx.lineTo(arrow.endX, arrow.endY);
426
+ ctx.stroke();
427
+ const angle = Math.atan2(arrow.endY - arrow.y, arrow.endX - arrow.x);
428
+ const headLen = Math.max(12, arrow.strokeWidth * 3);
429
+ ctx.beginPath();
430
+ ctx.moveTo(arrow.endX, arrow.endY);
431
+ ctx.lineTo(
432
+ arrow.endX - headLen * Math.cos(angle - Math.PI / 6),
433
+ arrow.endY - headLen * Math.sin(angle - Math.PI / 6)
434
+ );
435
+ ctx.lineTo(
436
+ arrow.endX - headLen * Math.cos(angle + Math.PI / 6),
437
+ arrow.endY - headLen * Math.sin(angle + Math.PI / 6)
438
+ );
439
+ ctx.closePath();
440
+ ctx.fill();
441
+ break;
442
+ }
443
+ case "line": {
444
+ const line = ann;
445
+ ctx.beginPath();
446
+ ctx.strokeStyle = line.strokeColor;
447
+ ctx.lineWidth = line.strokeWidth;
448
+ ctx.moveTo(line.x, line.y);
449
+ ctx.lineTo(line.endX, line.endY);
450
+ ctx.stroke();
451
+ break;
452
+ }
453
+ case "text": {
454
+ const textAnn = ann;
455
+ ctx.font = `${textAnn.fontWeight || "normal"} ${textAnn.fontSize}px ${textAnn.fontFamily || "sans-serif"}`;
456
+ ctx.fillStyle = textAnn.color;
457
+ ctx.textBaseline = "top";
458
+ ctx.fillText(textAnn.text, textAnn.x, textAnn.y);
459
+ break;
460
+ }
461
+ case "image": {
462
+ const imgAnn = ann;
463
+ try {
464
+ const loadedImg = await this.imageCache.get(imgAnn.src);
465
+ ctx.drawImage(loadedImg, imgAnn.x, imgAnn.y, imgAnn.width, imgAnn.height);
466
+ } catch {
467
+ }
468
+ break;
469
+ }
470
+ }
471
+ ctx.restore();
472
+ }
473
+ /**
474
+ * Draws selection box around active annotation.
475
+ */
476
+ drawAnnotationSelection(ctx, ann) {
477
+ ctx.save();
478
+ ctx.strokeStyle = "#3b82f6";
479
+ ctx.lineWidth = 1.5;
480
+ ctx.setLineDash([4, 4]);
481
+ const bounds = this.getAnnotationBounds(ann);
482
+ const pad = 4;
483
+ ctx.strokeRect(bounds.x - pad, bounds.y - pad, bounds.width + pad * 2, bounds.height + pad * 2);
484
+ ctx.fillStyle = "#ffffff";
485
+ ctx.strokeStyle = "#3b82f6";
486
+ ctx.setLineDash([]);
487
+ const handleSize = 6;
488
+ const corners = [
489
+ { x: bounds.x - pad, y: bounds.y - pad },
490
+ { x: bounds.x + bounds.width + pad, y: bounds.y - pad },
491
+ { x: bounds.x - pad, y: bounds.y + bounds.height + pad },
492
+ { x: bounds.x + bounds.width + pad, y: bounds.y + bounds.height + pad }
493
+ ];
494
+ for (const c of corners) {
495
+ ctx.fillRect(c.x - handleSize / 2, c.y - handleSize / 2, handleSize, handleSize);
496
+ ctx.strokeRect(c.x - handleSize / 2, c.y - handleSize / 2, handleSize, handleSize);
497
+ }
498
+ ctx.restore();
499
+ }
500
+ getAnnotationBounds(ann) {
501
+ switch (ann.type) {
502
+ case "rect":
503
+ return { x: ann.x, y: ann.y, width: ann.width, height: ann.height };
504
+ case "circle":
505
+ return {
506
+ x: ann.x - Math.abs(ann.radiusX),
507
+ y: ann.y - Math.abs(ann.radiusY),
508
+ width: Math.abs(ann.radiusX) * 2,
509
+ height: Math.abs(ann.radiusY) * 2
510
+ };
511
+ case "arrow":
512
+ case "line": {
513
+ const minX = Math.min(ann.x, ann.endX);
514
+ const minY = Math.min(ann.y, ann.endY);
515
+ return {
516
+ x: minX,
517
+ y: minY,
518
+ width: Math.max(Math.abs(ann.endX - ann.x), 10),
519
+ height: Math.max(Math.abs(ann.endY - ann.y), 10)
520
+ };
521
+ }
522
+ case "pen": {
523
+ if (!ann.points.length) return { x: ann.x, y: ann.y, width: 0, height: 0 };
524
+ let minX = ann.points[0].x, maxX = ann.points[0].x;
525
+ let minY = ann.points[0].y, maxY = ann.points[0].y;
526
+ for (const pt of ann.points) {
527
+ if (pt.x < minX) minX = pt.x;
528
+ if (pt.x > maxX) maxX = pt.x;
529
+ if (pt.y < minY) minY = pt.y;
530
+ if (pt.y > maxY) maxY = pt.y;
531
+ }
532
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
533
+ }
534
+ case "text":
535
+ return {
536
+ x: ann.x,
537
+ y: ann.y,
538
+ width: ann.text.length * ann.fontSize * 0.6,
539
+ height: ann.fontSize * 1.2
540
+ };
541
+ case "image":
542
+ return { x: ann.x, y: ann.y, width: ann.width, height: ann.height };
543
+ }
544
+ }
545
+ /**
546
+ * Draws a rule-of-thirds crop grid overlay.
547
+ */
548
+ drawCropOverlay(ctx, state, vpWidth, vpHeight, imgWidth, imgHeight, cropOverride) {
549
+ const crop = cropOverride !== void 0 && cropOverride !== null ? cropOverride : state.crop ?? {
550
+ x: 0,
551
+ y: 0,
552
+ width: imgWidth,
553
+ height: imgHeight
554
+ };
555
+ if (!crop) return;
556
+ const { transform, pan, zoom } = state;
557
+ const angle = (transform.rotate % 360 + 360) % 360;
558
+ const isSwapped = angle === 90 || angle === 270;
559
+ const baseW = isSwapped ? imgHeight : imgWidth;
560
+ const baseH = isSwapped ? imgWidth : imgHeight;
561
+ ctx.save();
562
+ ctx.translate(vpWidth / 2 + pan.x, vpHeight / 2 + pan.y);
563
+ ctx.scale(zoom, zoom);
564
+ const fitScale = Math.min(vpWidth * 0.85 / baseW, vpHeight * 0.85 / baseH, 1);
565
+ const renderW = baseW * fitScale;
566
+ const renderH = baseH * fitScale;
567
+ const startX = -renderW / 2 + crop.x / imgWidth * renderW;
568
+ const startY = -renderH / 2 + crop.y / imgHeight * renderH;
569
+ const cropBoxW = crop.width / imgWidth * renderW;
570
+ const cropBoxH = crop.height / imgHeight * renderH;
571
+ ctx.fillStyle = "rgba(0, 0, 0, 0.45)";
572
+ ctx.fillRect(-renderW / 2, -renderH / 2, renderW, startY - -renderH / 2);
573
+ ctx.fillRect(-renderW / 2, startY + cropBoxH, renderW, renderH / 2 - (startY + cropBoxH));
574
+ ctx.fillRect(-renderW / 2, startY, startX - -renderW / 2, cropBoxH);
575
+ ctx.fillRect(startX + cropBoxW, startY, renderW / 2 - (startX + cropBoxW), cropBoxH);
576
+ ctx.strokeStyle = "#ffffff";
577
+ ctx.lineWidth = 2;
578
+ ctx.strokeRect(startX, startY, cropBoxW, cropBoxH);
579
+ ctx.strokeStyle = "rgba(255, 255, 255, 0.4)";
580
+ ctx.lineWidth = 1;
581
+ ctx.beginPath();
582
+ ctx.moveTo(startX + cropBoxW / 3, startY);
583
+ ctx.lineTo(startX + cropBoxW / 3, startY + cropBoxH);
584
+ ctx.moveTo(startX + cropBoxW * 2 / 3, startY);
585
+ ctx.lineTo(startX + cropBoxW * 2 / 3, startY + cropBoxH);
586
+ ctx.moveTo(startX, startY + cropBoxH / 3);
587
+ ctx.lineTo(startX + cropBoxW, startY + cropBoxH / 3);
588
+ ctx.moveTo(startX, startY + cropBoxH * 2 / 3);
589
+ ctx.lineTo(startX + cropBoxW, startY + cropBoxH * 2 / 3);
590
+ ctx.stroke();
591
+ ctx.fillStyle = "#ffffff";
592
+ ctx.strokeStyle = "#0284c7";
593
+ ctx.lineWidth = 1.5;
594
+ const handleSize = 10;
595
+ const handles = [
596
+ // Corners
597
+ { x: startX, y: startY },
598
+ { x: startX + cropBoxW, y: startY },
599
+ { x: startX, y: startY + cropBoxH },
600
+ { x: startX + cropBoxW, y: startY + cropBoxH },
601
+ // Edges
602
+ { x: startX + cropBoxW / 2, y: startY },
603
+ { x: startX + cropBoxW / 2, y: startY + cropBoxH },
604
+ { x: startX, y: startY + cropBoxH / 2 },
605
+ { x: startX + cropBoxW, y: startY + cropBoxH / 2 }
606
+ ];
607
+ for (const h of handles) {
608
+ ctx.fillRect(h.x - handleSize / 2, h.y - handleSize / 2, handleSize, handleSize);
609
+ ctx.strokeRect(h.x - handleSize / 2, h.y - handleSize / 2, handleSize, handleSize);
610
+ }
611
+ ctx.restore();
612
+ }
613
+ drawFittedImage(ctx, img, imgW, imgH, vpW, vpH, zoom, pan) {
614
+ ctx.save();
615
+ ctx.translate(vpW / 2 + pan.x, vpH / 2 + pan.y);
616
+ ctx.scale(zoom, zoom);
617
+ const fitScale = Math.min(vpW * 0.85 / imgW, vpH * 0.85 / imgH, 1);
618
+ const renderW = imgW * fitScale;
619
+ const renderH = imgH * fitScale;
620
+ ctx.drawImage(img, -renderW / 2, -renderH / 2, renderW, renderH);
621
+ ctx.restore();
622
+ }
623
+ /**
624
+ * Performs an export render at exact pixel dimensions without zoom/pan viewport offsets.
625
+ */
626
+ async renderExport(imageSource, state, options = {}) {
627
+ let img;
628
+ if (typeof imageSource === "string") {
629
+ img = await this.imageCache.get(imageSource);
630
+ } else {
631
+ img = imageSource;
632
+ }
633
+ const naturalWidth = img.naturalWidth || img.videoWidth || img.width || 800;
634
+ const naturalHeight = img.naturalHeight || img.videoHeight || img.height || 600;
635
+ const { crop, transform, adjustments, depthMask, annotations } = state;
636
+ const cropX = crop ? Math.max(0, crop.x) : 0;
637
+ const cropY = crop ? Math.max(0, crop.y) : 0;
638
+ const cropW = crop ? Math.min(naturalWidth - cropX, crop.width) : naturalWidth;
639
+ const cropH = crop ? Math.min(naturalHeight - cropY, crop.height) : naturalHeight;
640
+ const angle = (transform.rotate % 360 + 360) % 360;
641
+ const isSwapped = angle === 90 || angle === 270;
642
+ const baseW = isSwapped ? cropH : cropW;
643
+ const baseH = isSwapped ? cropW : cropH;
644
+ const exportW = options.width || baseW;
645
+ const exportH = options.height || baseH;
646
+ const exportCanvas = this.createCanvas(exportW, exportH);
647
+ const ctx = exportCanvas.getContext("2d");
648
+ if (!ctx) return exportCanvas;
649
+ const intermediateCanvas = this.createCanvas(baseW, baseH);
650
+ const interCtx = intermediateCanvas.getContext("2d");
651
+ if (interCtx) {
652
+ interCtx.save();
653
+ const rad = angle * Math.PI / 180;
654
+ interCtx.translate(baseW / 2, baseH / 2);
655
+ interCtx.rotate(rad);
656
+ interCtx.scale(transform.flipH ? -1 : 1, transform.flipV ? -1 : 1);
657
+ interCtx.drawImage(img, cropX, cropY, cropW, cropH, -cropW / 2, -cropH / 2, cropW, cropH);
658
+ interCtx.restore();
659
+ const imageData = interCtx.getImageData(0, 0, baseW, baseH);
660
+ if (imageData) {
661
+ applyAdjustments(imageData, adjustments);
662
+ if (depthMask.enabled && depthMask.maskSource) {
663
+ try {
664
+ const maskImg = await this.imageCache.get(depthMask.maskSource);
665
+ const maskCanvas = this.createCanvas(baseW, baseH);
666
+ const maskCtx = maskCanvas.getContext("2d");
667
+ if (maskCtx) {
668
+ maskCtx.drawImage(maskImg, cropX, cropY, cropW, cropH, 0, 0, baseW, baseH);
669
+ const maskData = maskCtx.getImageData(0, 0, baseW, baseH);
670
+ if (maskData) {
671
+ applyDepthMask(imageData, maskData, depthMask);
672
+ }
673
+ }
674
+ } catch {
675
+ }
676
+ }
677
+ interCtx.putImageData(imageData, 0, 0);
678
+ }
679
+ }
680
+ ctx.drawImage(intermediateCanvas, 0, 0, baseW, baseH, 0, 0, exportW, exportH);
681
+ if (options.includeAnnotations !== false && annotations.length > 0) {
682
+ const annScaleX = exportW / baseW;
683
+ const annScaleY = exportH / baseH;
684
+ ctx.save();
685
+ ctx.scale(annScaleX, annScaleY);
686
+ for (const ann of annotations) {
687
+ await this.drawAnnotation(ctx, ann);
688
+ }
689
+ ctx.restore();
690
+ }
691
+ return exportCanvas;
692
+ }
693
+ };
694
+
695
+ // src/image-editor/controller.ts
696
+ var DEFAULT_ADJUSTMENTS = {
697
+ brightness: 0,
698
+ contrast: 0,
699
+ saturation: 0,
700
+ exposure: 0,
701
+ temperature: 0,
702
+ blur: 0,
703
+ opacity: 1
704
+ };
705
+ var DEFAULT_TRANSFORM = {
706
+ rotate: 0,
707
+ flipH: false,
708
+ flipV: false
709
+ };
710
+ var DEFAULT_DEPTH_MASK = {
711
+ enabled: false,
712
+ maskSource: null,
713
+ mode: "threshold",
714
+ depthRange: [0, 255],
715
+ softness: 10,
716
+ invert: false
717
+ };
718
+ var ImageEditorController = class {
719
+ state;
720
+ renderer;
721
+ imageElement = null;
722
+ listeners = /* @__PURE__ */ new Set();
723
+ onStateChange;
724
+ // History stacks
725
+ undoStack = [];
726
+ redoStack = [];
727
+ maxHistoryDepth;
728
+ isApplyingHistory = false;
729
+ initialSnapshot;
730
+ constructor(options = {}) {
731
+ this.maxHistoryDepth = options.maxHistoryDepth ?? 50;
732
+ this.onStateChange = options.onStateChange;
733
+ this.renderer = new ImageEditorRenderer();
734
+ const initialAdjustments = {
735
+ ...DEFAULT_ADJUSTMENTS,
736
+ ...options.initialState?.adjustments
737
+ };
738
+ const initialTransform = {
739
+ ...DEFAULT_TRANSFORM,
740
+ ...options.initialState?.transform
741
+ };
742
+ const initialDepthMask = {
743
+ ...DEFAULT_DEPTH_MASK,
744
+ ...options.initialState?.depthMask
745
+ };
746
+ this.state = {
747
+ sourceUrl: typeof options.image === "string" ? options.image : null,
748
+ imageDimensions: { width: 800, height: 600 },
749
+ crop: options.initialState?.crop ?? null,
750
+ transform: initialTransform,
751
+ adjustments: initialAdjustments,
752
+ depthMask: initialDepthMask,
753
+ annotations: options.initialState?.annotations ?? [],
754
+ selectedAnnotationId: null,
755
+ activeTool: "select",
756
+ zoom: 1,
757
+ pan: { x: 0, y: 0 },
758
+ isOriginalCompared: false
759
+ };
760
+ if (options.image instanceof Object && "width" in options.image) {
761
+ this.imageElement = options.image;
762
+ this.state.imageDimensions = {
763
+ width: options.image.naturalWidth || options.image.width || 800,
764
+ height: options.image.naturalHeight || options.image.height || 600
765
+ };
766
+ }
767
+ this.initialSnapshot = this.serializeState();
768
+ if (typeof options.image === "string") {
769
+ this.loadImage(options.image);
770
+ }
771
+ }
772
+ // --- Image Loading ---
773
+ async loadImage(src) {
774
+ if (typeof src === "string") {
775
+ this.state.sourceUrl = src;
776
+ try {
777
+ const img = await this.renderer.imageCache.get(src);
778
+ this.imageElement = img;
779
+ this.state.imageDimensions = {
780
+ width: img.naturalWidth || img.width || 800,
781
+ height: img.naturalHeight || img.height || 600
782
+ };
783
+ } catch (err) {
784
+ }
785
+ } else {
786
+ this.imageElement = src;
787
+ this.state.sourceUrl = src.src || null;
788
+ this.state.imageDimensions = {
789
+ width: src.naturalWidth || src.width || 800,
790
+ height: src.naturalHeight || src.height || 600
791
+ };
792
+ }
793
+ this.initialSnapshot = this.serializeState();
794
+ this.notify();
795
+ }
796
+ getImageElement() {
797
+ return this.imageElement;
798
+ }
799
+ // --- State & Subscription ---
800
+ getState() {
801
+ return this.state;
802
+ }
803
+ subscribe(listener) {
804
+ this.listeners.add(listener);
805
+ listener(this.state);
806
+ return () => {
807
+ this.listeners.delete(listener);
808
+ };
809
+ }
810
+ notify() {
811
+ const currentState = { ...this.state };
812
+ this.onStateChange?.(currentState);
813
+ this.listeners.forEach((l) => l(currentState));
814
+ }
815
+ // --- History (Undo / Redo / Reset) ---
816
+ recordHistory() {
817
+ if (this.isApplyingHistory) return;
818
+ this.undoStack.push(this.serializeState());
819
+ if (this.undoStack.length > this.maxHistoryDepth) {
820
+ this.undoStack.shift();
821
+ }
822
+ this.redoStack = [];
823
+ }
824
+ get canUndo() {
825
+ return this.undoStack.length > 0;
826
+ }
827
+ get canRedo() {
828
+ return this.redoStack.length > 0;
829
+ }
830
+ undo() {
831
+ if (!this.canUndo) return false;
832
+ this.isApplyingHistory = true;
833
+ const current = this.serializeState();
834
+ this.redoStack.push(current);
835
+ const prev = this.undoStack.pop();
836
+ this.applySerializedState(prev);
837
+ this.isApplyingHistory = false;
838
+ this.notify();
839
+ return true;
840
+ }
841
+ redo() {
842
+ if (!this.canRedo) return false;
843
+ this.isApplyingHistory = true;
844
+ const current = this.serializeState();
845
+ this.undoStack.push(current);
846
+ const next = this.redoStack.pop();
847
+ this.applySerializedState(next);
848
+ this.isApplyingHistory = false;
849
+ this.notify();
850
+ return true;
851
+ }
852
+ reset() {
853
+ this.recordHistory();
854
+ this.applySerializedState(this.initialSnapshot);
855
+ this.state.zoom = 1;
856
+ this.state.pan = { x: 0, y: 0 };
857
+ this.state.activeTool = "select";
858
+ this.state.selectedAnnotationId = null;
859
+ this.notify();
860
+ }
861
+ // --- Active Tool ---
862
+ setTool(tool) {
863
+ if (this.state.activeTool === tool) return;
864
+ this.state.activeTool = tool;
865
+ if (tool !== "select") {
866
+ this.state.selectedAnnotationId = null;
867
+ }
868
+ if (tool === "crop" && !this.state.crop) {
869
+ this.state.crop = {
870
+ x: 0,
871
+ y: 0,
872
+ width: this.state.imageDimensions.width,
873
+ height: this.state.imageDimensions.height
874
+ };
875
+ }
876
+ this.notify();
877
+ }
878
+ // --- Crop ---
879
+ setCrop(crop, addToHistory = true) {
880
+ if (addToHistory) {
881
+ this.recordHistory();
882
+ }
883
+ this.state.crop = crop;
884
+ this.notify();
885
+ }
886
+ applyCropPreset(ratio) {
887
+ this.recordHistory();
888
+ const { width, height } = this.state.imageDimensions;
889
+ if (!ratio) {
890
+ this.state.crop = { x: 0, y: 0, width, height };
891
+ } else {
892
+ let targetW = width;
893
+ let targetH = targetW / ratio;
894
+ if (targetH > height) {
895
+ targetH = height;
896
+ targetW = targetH * ratio;
897
+ }
898
+ const x = Math.max(0, Math.round((width - targetW) / 2));
899
+ const y = Math.max(0, Math.round((height - targetH) / 2));
900
+ this.state.crop = {
901
+ x,
902
+ y,
903
+ width: Math.round(targetW),
904
+ height: Math.round(targetH)
905
+ };
906
+ }
907
+ this.notify();
908
+ }
909
+ resetCrop() {
910
+ this.recordHistory();
911
+ this.state.crop = null;
912
+ this.notify();
913
+ }
914
+ // --- Transformations (Rotate / Flip) ---
915
+ rotate(degrees) {
916
+ this.recordHistory();
917
+ const current = this.state.transform.rotate;
918
+ this.state.transform.rotate = (current + degrees) % 360;
919
+ this.notify();
920
+ }
921
+ setRotation(degrees) {
922
+ this.recordHistory();
923
+ this.state.transform.rotate = degrees % 360;
924
+ this.notify();
925
+ }
926
+ flipHorizontal() {
927
+ this.recordHistory();
928
+ this.state.transform.flipH = !this.state.transform.flipH;
929
+ this.notify();
930
+ }
931
+ flipVertical() {
932
+ this.recordHistory();
933
+ this.state.transform.flipV = !this.state.transform.flipV;
934
+ this.notify();
935
+ }
936
+ // --- Adjustments ---
937
+ setAdjustments(partial, commitToHistory = true) {
938
+ if (commitToHistory) {
939
+ this.recordHistory();
940
+ }
941
+ this.state.adjustments = {
942
+ ...this.state.adjustments,
943
+ ...partial
944
+ };
945
+ this.notify();
946
+ }
947
+ resetAdjustments() {
948
+ this.recordHistory();
949
+ this.state.adjustments = { ...DEFAULT_ADJUSTMENTS };
950
+ this.notify();
951
+ }
952
+ // --- Depth Masking (Gleamforge) ---
953
+ setDepthMask(partial) {
954
+ this.recordHistory();
955
+ this.state.depthMask = {
956
+ ...this.state.depthMask,
957
+ ...partial
958
+ };
959
+ this.notify();
960
+ }
961
+ resetDepthMask() {
962
+ this.recordHistory();
963
+ this.state.depthMask = { ...DEFAULT_DEPTH_MASK };
964
+ this.notify();
965
+ }
966
+ // --- Annotations & Layers ---
967
+ addAnnotation(annotation) {
968
+ this.recordHistory();
969
+ const id = `ann_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`;
970
+ const fullAnnotation = { ...annotation, id };
971
+ this.state.annotations = [...this.state.annotations, fullAnnotation];
972
+ this.state.selectedAnnotationId = id;
973
+ this.notify();
974
+ return id;
975
+ }
976
+ updateAnnotation(id, partial, commitToHistory = true) {
977
+ if (commitToHistory) {
978
+ this.recordHistory();
979
+ }
980
+ this.state.annotations = this.state.annotations.map((ann) => {
981
+ if (ann.id === id) {
982
+ return { ...ann, ...partial };
983
+ }
984
+ return ann;
985
+ });
986
+ this.notify();
987
+ }
988
+ removeAnnotation(id) {
989
+ this.recordHistory();
990
+ this.state.annotations = this.state.annotations.filter((ann) => ann.id !== id);
991
+ if (this.state.selectedAnnotationId === id) {
992
+ this.state.selectedAnnotationId = null;
993
+ }
994
+ this.notify();
995
+ }
996
+ clearAnnotations() {
997
+ this.recordHistory();
998
+ this.state.annotations = [];
999
+ this.state.selectedAnnotationId = null;
1000
+ this.notify();
1001
+ }
1002
+ selectAnnotation(id) {
1003
+ this.state.selectedAnnotationId = id;
1004
+ this.notify();
1005
+ }
1006
+ // --- Zoom & Pan ---
1007
+ setZoom(zoom) {
1008
+ this.state.zoom = Math.max(0.1, Math.min(10, zoom));
1009
+ this.notify();
1010
+ }
1011
+ zoomIn(factor = 1.2) {
1012
+ this.setZoom(this.state.zoom * factor);
1013
+ }
1014
+ zoomOut(factor = 1.2) {
1015
+ this.setZoom(this.state.zoom / factor);
1016
+ }
1017
+ resetZoom() {
1018
+ this.state.zoom = 1;
1019
+ this.state.pan = { x: 0, y: 0 };
1020
+ this.notify();
1021
+ }
1022
+ setPan(pan) {
1023
+ this.state.pan = pan;
1024
+ this.notify();
1025
+ }
1026
+ setComparing(comparing) {
1027
+ if (this.state.isOriginalCompared === comparing) return;
1028
+ this.state.isOriginalCompared = comparing;
1029
+ this.notify();
1030
+ }
1031
+ // --- Rendering & Export ---
1032
+ async render(targetCanvas, options) {
1033
+ const source = this.imageElement || this.state.sourceUrl;
1034
+ if (!source) return;
1035
+ await this.renderer.renderToCanvas(targetCanvas, source, this.state, options);
1036
+ }
1037
+ async renderExport(options) {
1038
+ const source = this.imageElement || this.state.sourceUrl;
1039
+ if (!source) {
1040
+ return this.renderer.createCanvas(1, 1);
1041
+ }
1042
+ return this.renderer.renderExport(source, this.state, options);
1043
+ }
1044
+ async toDataURL(options = {}) {
1045
+ const canvas = await this.renderExport(options);
1046
+ const format = options.format || "image/png";
1047
+ const quality = options.quality ?? 0.92;
1048
+ return canvas.toDataURL(format, quality);
1049
+ }
1050
+ async toBlob(options = {}) {
1051
+ const canvas = await this.renderExport(options);
1052
+ const format = options.format || "image/png";
1053
+ const quality = options.quality ?? 0.92;
1054
+ return new Promise((resolve, reject) => {
1055
+ if (canvas.toBlob) {
1056
+ canvas.toBlob((blob) => {
1057
+ if (blob) resolve(blob);
1058
+ else reject(new Error("Failed to create Blob from canvas"));
1059
+ }, format, quality);
1060
+ } else {
1061
+ try {
1062
+ const dataUrl = canvas.toDataURL(format, quality);
1063
+ const parts = dataUrl.split(",");
1064
+ const byteStr = atob(parts[1]);
1065
+ const ab = new ArrayBuffer(byteStr.length);
1066
+ const ia = new Uint8Array(ab);
1067
+ for (let i = 0; i < byteStr.length; i++) {
1068
+ ia[i] = byteStr.charCodeAt(i);
1069
+ }
1070
+ resolve(new Blob([ab], { type: format }));
1071
+ } catch (err) {
1072
+ reject(err);
1073
+ }
1074
+ }
1075
+ });
1076
+ }
1077
+ // --- Serialization ---
1078
+ toJSON() {
1079
+ return this.serializeState();
1080
+ }
1081
+ loadJSON(data) {
1082
+ this.recordHistory();
1083
+ this.applySerializedState(data);
1084
+ this.notify();
1085
+ }
1086
+ serializeState() {
1087
+ return {
1088
+ version: 1,
1089
+ crop: this.state.crop ? { ...this.state.crop } : null,
1090
+ transform: { ...this.state.transform },
1091
+ adjustments: { ...this.state.adjustments },
1092
+ depthMask: {
1093
+ ...this.state.depthMask,
1094
+ depthRange: [...this.state.depthMask.depthRange]
1095
+ },
1096
+ annotations: JSON.parse(JSON.stringify(this.state.annotations))
1097
+ };
1098
+ }
1099
+ applySerializedState(data) {
1100
+ this.state.crop = data.crop ? { ...data.crop } : null;
1101
+ this.state.transform = { ...data.transform };
1102
+ this.state.adjustments = { ...data.adjustments };
1103
+ this.state.depthMask = {
1104
+ ...data.depthMask,
1105
+ depthRange: [...data.depthMask.depthRange]
1106
+ };
1107
+ this.state.annotations = JSON.parse(JSON.stringify(data.annotations || []));
1108
+ }
1109
+ };
1110
+
1111
+ // src/image-editor/geometry.ts
1112
+ function getViewportMetrics(state, vpWidth, vpHeight, isActivelyCropping = false, cropOverride) {
1113
+ const { imageDimensions, crop: stateCrop, transform, zoom, pan } = state;
1114
+ const naturalWidth = imageDimensions.width || 800;
1115
+ const naturalHeight = imageDimensions.height || 600;
1116
+ const activeCrop = cropOverride !== void 0 && cropOverride !== null ? cropOverride : stateCrop ?? (isActivelyCropping ? { x: 0, y: 0, width: naturalWidth, height: naturalHeight } : null);
1117
+ const cropW = !isActivelyCropping && activeCrop ? activeCrop.width : naturalWidth;
1118
+ const cropH = !isActivelyCropping && activeCrop ? activeCrop.height : naturalHeight;
1119
+ const angle = (transform.rotate % 360 + 360) % 360;
1120
+ const isSwapped = angle === 90 || angle === 270;
1121
+ const baseW = isSwapped ? cropH : cropW;
1122
+ const baseH = isSwapped ? cropW : cropH;
1123
+ const fitScale = Math.min(vpWidth * 0.85 / baseW, vpHeight * 0.85 / baseH, 1);
1124
+ const renderW = baseW * fitScale;
1125
+ const renderH = baseH * fitScale;
1126
+ const totalScale = zoom * fitScale;
1127
+ const centerX = vpWidth / 2 + pan.x;
1128
+ const centerY = vpHeight / 2 + pan.y;
1129
+ const imageRect = {
1130
+ x: centerX - renderW * zoom / 2,
1131
+ y: centerY - renderH * zoom / 2,
1132
+ width: renderW * zoom,
1133
+ height: renderH * zoom
1134
+ };
1135
+ let cropRect = null;
1136
+ if (activeCrop) {
1137
+ const startX = -renderW / 2 + activeCrop.x / naturalWidth * renderW;
1138
+ const startY = -renderH / 2 + activeCrop.y / naturalHeight * renderH;
1139
+ const cropBoxW = activeCrop.width / naturalWidth * renderW;
1140
+ const cropBoxH = activeCrop.height / naturalHeight * renderH;
1141
+ cropRect = {
1142
+ x: centerX + zoom * startX,
1143
+ y: centerY + zoom * startY,
1144
+ width: zoom * cropBoxW,
1145
+ height: zoom * cropBoxH
1146
+ };
1147
+ }
1148
+ return {
1149
+ vpWidth,
1150
+ vpHeight,
1151
+ centerX,
1152
+ centerY,
1153
+ baseW,
1154
+ baseH,
1155
+ fitScale,
1156
+ renderW,
1157
+ renderH,
1158
+ totalScale,
1159
+ imageRect,
1160
+ cropRect
1161
+ };
1162
+ }
1163
+ function canvasToImagePoint(canvasPt, state, vpWidth, vpHeight, isActivelyCropping = false) {
1164
+ const metrics = getViewportMetrics(state, vpWidth, vpHeight, isActivelyCropping);
1165
+ const unzoomedX = (canvasPt.x - metrics.centerX) / state.zoom;
1166
+ const unzoomedY = (canvasPt.y - metrics.centerY) / state.zoom;
1167
+ const x = (unzoomedX + metrics.renderW / 2) / metrics.fitScale;
1168
+ const y = (unzoomedY + metrics.renderH / 2) / metrics.fitScale;
1169
+ return { x: Math.round(x), y: Math.round(y) };
1170
+ }
1171
+ function imageToCanvasPoint(imgPt, state, vpWidth, vpHeight, isActivelyCropping = false) {
1172
+ const metrics = getViewportMetrics(state, vpWidth, vpHeight, isActivelyCropping);
1173
+ const unzoomedX = (imgPt.x - metrics.baseW / 2) * metrics.fitScale;
1174
+ const unzoomedY = (imgPt.y - metrics.baseH / 2) * metrics.fitScale;
1175
+ const canvasX = metrics.centerX + unzoomedX * state.zoom;
1176
+ const canvasY = metrics.centerY + unzoomedY * state.zoom;
1177
+ return { x: Math.round(canvasX), y: Math.round(canvasY) };
1178
+ }
1179
+ function hitTestCrop(canvasPt, state, vpWidth, vpHeight, handleThreshold = 14, cropOverride) {
1180
+ const metrics = getViewportMetrics(state, vpWidth, vpHeight, true, cropOverride);
1181
+ if (!metrics.cropRect) return null;
1182
+ const { x, y, width: w, height: h } = metrics.cropRect;
1183
+ const px = canvasPt.x;
1184
+ const py = canvasPt.y;
1185
+ const dist = (x1, y1, x2, y2) => Math.hypot(x1 - x2, y1 - y2);
1186
+ if (dist(px, py, x, y) <= handleThreshold) return "nw";
1187
+ if (dist(px, py, x + w, y) <= handleThreshold) return "ne";
1188
+ if (dist(px, py, x + w, y + h) <= handleThreshold) return "se";
1189
+ if (dist(px, py, x, y + h) <= handleThreshold) return "sw";
1190
+ const nearX = px >= x - handleThreshold && px <= x + w + handleThreshold;
1191
+ const nearY = py >= y - handleThreshold && py <= y + h + handleThreshold;
1192
+ if (nearX && Math.abs(py - y) <= handleThreshold) return "n";
1193
+ if (nearX && Math.abs(py - (y + h)) <= handleThreshold) return "s";
1194
+ if (nearY && Math.abs(px - x) <= handleThreshold) return "w";
1195
+ if (nearY && Math.abs(px - (x + w)) <= handleThreshold) return "e";
1196
+ if (px >= x && px <= x + w && py >= y && py <= y + h) {
1197
+ return "inside";
1198
+ }
1199
+ return null;
1200
+ }
1201
+ function getCropCursor(handle) {
1202
+ switch (handle) {
1203
+ case "nw":
1204
+ case "se":
1205
+ return "nwse-resize";
1206
+ case "ne":
1207
+ case "sw":
1208
+ return "nesw-resize";
1209
+ case "n":
1210
+ case "s":
1211
+ return "ns-resize";
1212
+ case "e":
1213
+ case "w":
1214
+ return "ew-resize";
1215
+ case "inside":
1216
+ return "move";
1217
+ default:
1218
+ return "crosshair";
1219
+ }
1220
+ }
1221
+ function calculateCropDrag(startCrop, handle, startImgPt, currentImgPt, imgWidth, imgHeight, aspectRatio) {
1222
+ const dx = currentImgPt.x - startImgPt.x;
1223
+ const dy = currentImgPt.y - startImgPt.y;
1224
+ if (handle === "inside") {
1225
+ const maxX = Math.max(0, imgWidth - startCrop.width);
1226
+ const maxY = Math.max(0, imgHeight - startCrop.height);
1227
+ const newX = Math.max(0, Math.min(maxX, startCrop.x + dx));
1228
+ const newY = Math.max(0, Math.min(maxY, startCrop.y + dy));
1229
+ return {
1230
+ x: Math.round(newX),
1231
+ y: Math.round(newY),
1232
+ width: startCrop.width,
1233
+ height: startCrop.height
1234
+ };
1235
+ }
1236
+ let left = startCrop.x;
1237
+ let top = startCrop.y;
1238
+ let right = startCrop.x + startCrop.width;
1239
+ let bottom = startCrop.y + startCrop.height;
1240
+ const minSize = 20;
1241
+ if (handle === "e" || handle === "ne" || handle === "se") {
1242
+ right = Math.min(imgWidth, Math.max(left + minSize, startCrop.x + startCrop.width + dx));
1243
+ }
1244
+ if (handle === "w" || handle === "nw" || handle === "sw") {
1245
+ left = Math.max(0, Math.min(right - minSize, startCrop.x + dx));
1246
+ }
1247
+ if (handle === "s" || handle === "se" || handle === "sw") {
1248
+ bottom = Math.min(imgHeight, Math.max(top + minSize, startCrop.y + startCrop.height + dy));
1249
+ }
1250
+ if (handle === "n" || handle === "nw" || handle === "ne") {
1251
+ top = Math.max(0, Math.min(bottom - minSize, startCrop.y + dy));
1252
+ }
1253
+ if (aspectRatio && aspectRatio > 0) {
1254
+ let currentW = right - left;
1255
+ let currentH = bottom - top;
1256
+ if (handle === "e" || handle === "w") {
1257
+ currentH = Math.min(imgHeight, currentW / aspectRatio);
1258
+ bottom = Math.min(imgHeight, top + currentH);
1259
+ } else if (handle === "n" || handle === "s") {
1260
+ currentW = Math.min(imgWidth, currentH * aspectRatio);
1261
+ right = Math.min(imgWidth, left + currentW);
1262
+ } else {
1263
+ const targetH = currentW / aspectRatio;
1264
+ if (top + targetH <= imgHeight) {
1265
+ bottom = top + targetH;
1266
+ } else {
1267
+ const targetW = currentH * aspectRatio;
1268
+ right = Math.min(imgWidth, left + targetW);
1269
+ }
1270
+ }
1271
+ }
1272
+ return {
1273
+ x: Math.round(left),
1274
+ y: Math.round(top),
1275
+ width: Math.round(Math.max(minSize, right - left)),
1276
+ height: Math.round(Math.max(minSize, bottom - top))
1277
+ };
1278
+ }
1279
+ function getAnnotationBounds(ann) {
1280
+ switch (ann.type) {
1281
+ case "rect":
1282
+ return { x: ann.x, y: ann.y, width: ann.width, height: ann.height };
1283
+ case "circle":
1284
+ return {
1285
+ x: ann.x - ann.radiusX,
1286
+ y: ann.y - ann.radiusY,
1287
+ width: ann.radiusX * 2,
1288
+ height: ann.radiusY * 2
1289
+ };
1290
+ case "arrow":
1291
+ case "line": {
1292
+ const minX = Math.min(ann.x, ann.endX);
1293
+ const minY = Math.min(ann.y, ann.endY);
1294
+ return {
1295
+ x: minX,
1296
+ y: minY,
1297
+ width: Math.max(Math.abs(ann.endX - ann.x), 10),
1298
+ height: Math.max(Math.abs(ann.endY - ann.y), 10)
1299
+ };
1300
+ }
1301
+ case "pen": {
1302
+ if (!ann.points.length) return { x: ann.x, y: ann.y, width: 0, height: 0 };
1303
+ let minX = ann.points[0].x;
1304
+ let maxX = ann.points[0].x;
1305
+ let minY = ann.points[0].y;
1306
+ let maxY = ann.points[0].y;
1307
+ for (const pt of ann.points) {
1308
+ if (pt.x < minX) minX = pt.x;
1309
+ if (pt.x > maxX) maxX = pt.x;
1310
+ if (pt.y < minY) minY = pt.y;
1311
+ if (pt.y > maxY) maxY = pt.y;
1312
+ }
1313
+ return { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
1314
+ }
1315
+ case "text":
1316
+ return {
1317
+ x: ann.x,
1318
+ y: ann.y,
1319
+ width: ann.text.length * ann.fontSize * 0.6,
1320
+ height: ann.fontSize * 1.2
1321
+ };
1322
+ case "image":
1323
+ return { x: ann.x, y: ann.y, width: ann.width, height: ann.height };
1324
+ }
1325
+ }
1326
+ function hitTestAnnotation(imgPt, ann, padding = 10) {
1327
+ const b = getAnnotationBounds(ann);
1328
+ return imgPt.x >= b.x - padding && imgPt.x <= b.x + b.width + padding && imgPt.y >= b.y - padding && imgPt.y <= b.y + b.height + padding;
1329
+ }
1330
+ // Annotate the CommonJS export names for ESM import in node:
1331
+ 0 && (module.exports = {
1332
+ DEFAULT_ADJUSTMENTS,
1333
+ DEFAULT_DEPTH_MASK,
1334
+ DEFAULT_TRANSFORM,
1335
+ ImageEditorController,
1336
+ ImageEditorRenderer,
1337
+ applyAdjustments,
1338
+ applyDepthMask,
1339
+ calculateCropDrag,
1340
+ canvasToImagePoint,
1341
+ getAnnotationBounds,
1342
+ getCropCursor,
1343
+ getViewportMetrics,
1344
+ globalImageCache,
1345
+ hitTestAnnotation,
1346
+ hitTestCrop,
1347
+ imageToCanvasPoint,
1348
+ removeAlpha
1349
+ });
1350
+ //# sourceMappingURL=index.cjs.map