@pooder/kit 5.4.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/.test-dist/src/coordinate.js +74 -0
  2. package/.test-dist/src/extensions/background.js +547 -0
  3. package/.test-dist/src/extensions/bridgeSelection.js +20 -0
  4. package/.test-dist/src/extensions/constraints.js +237 -0
  5. package/.test-dist/src/extensions/dieline.js +931 -0
  6. package/.test-dist/src/extensions/dielineShape.js +66 -0
  7. package/.test-dist/src/extensions/edgeScale.js +12 -0
  8. package/.test-dist/src/extensions/feature.js +910 -0
  9. package/.test-dist/src/extensions/featureComplete.js +32 -0
  10. package/.test-dist/src/extensions/film.js +226 -0
  11. package/.test-dist/src/extensions/geometry.js +609 -0
  12. package/.test-dist/src/extensions/image.js +1613 -0
  13. package/.test-dist/src/extensions/index.js +28 -0
  14. package/.test-dist/src/extensions/maskOps.js +334 -0
  15. package/.test-dist/src/extensions/mirror.js +104 -0
  16. package/.test-dist/src/extensions/ruler.js +442 -0
  17. package/.test-dist/src/extensions/sceneLayout.js +96 -0
  18. package/.test-dist/src/extensions/sceneLayoutModel.js +202 -0
  19. package/.test-dist/src/extensions/sceneVisibility.js +55 -0
  20. package/.test-dist/src/extensions/size.js +331 -0
  21. package/.test-dist/src/extensions/tracer.js +709 -0
  22. package/.test-dist/src/extensions/white-ink.js +1200 -0
  23. package/.test-dist/src/extensions/wrappedOffsets.js +33 -0
  24. package/.test-dist/src/index.js +18 -0
  25. package/.test-dist/src/services/CanvasService.js +1011 -0
  26. package/.test-dist/src/services/ViewportSystem.js +76 -0
  27. package/.test-dist/src/services/index.js +25 -0
  28. package/.test-dist/src/services/renderSpec.js +2 -0
  29. package/.test-dist/src/services/visibility.js +54 -0
  30. package/.test-dist/src/units.js +30 -0
  31. package/.test-dist/tests/run.js +148 -0
  32. package/CHANGELOG.md +6 -0
  33. package/dist/index.d.mts +150 -62
  34. package/dist/index.d.ts +150 -62
  35. package/dist/index.js +2219 -1714
  36. package/dist/index.mjs +2226 -1718
  37. package/package.json +1 -1
  38. package/src/coordinate.ts +106 -106
  39. package/src/extensions/background.ts +716 -323
  40. package/src/extensions/bridgeSelection.ts +17 -17
  41. package/src/extensions/constraints.ts +322 -322
  42. package/src/extensions/dieline.ts +1169 -1149
  43. package/src/extensions/dielineShape.ts +109 -109
  44. package/src/extensions/edgeScale.ts +19 -19
  45. package/src/extensions/feature.ts +1140 -1137
  46. package/src/extensions/featureComplete.ts +46 -46
  47. package/src/extensions/film.ts +270 -266
  48. package/src/extensions/geometry.ts +851 -885
  49. package/src/extensions/image.ts +2007 -2054
  50. package/src/extensions/index.ts +10 -11
  51. package/src/extensions/maskOps.ts +283 -283
  52. package/src/extensions/mirror.ts +128 -128
  53. package/src/extensions/ruler.ts +664 -654
  54. package/src/extensions/sceneLayout.ts +140 -140
  55. package/src/extensions/sceneLayoutModel.ts +364 -364
  56. package/src/extensions/size.ts +389 -389
  57. package/src/extensions/tracer.ts +1019 -1019
  58. package/src/extensions/white-ink.ts +1508 -1575
  59. package/src/extensions/wrappedOffsets.ts +33 -33
  60. package/src/index.ts +2 -2
  61. package/src/services/CanvasService.ts +1286 -832
  62. package/src/services/ViewportSystem.ts +95 -95
  63. package/src/services/index.ts +4 -3
  64. package/src/services/renderSpec.ts +83 -53
  65. package/src/services/visibility.ts +78 -0
  66. package/src/units.ts +27 -27
  67. package/tests/run.ts +253 -118
  68. package/tsconfig.test.json +15 -15
  69. package/src/extensions/sceneVisibility.ts +0 -64
@@ -0,0 +1,1613 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ImageTool = void 0;
4
+ const core_1 = require("@pooder/core");
5
+ const fabric_1 = require("fabric");
6
+ const dielineShape_1 = require("./dielineShape");
7
+ const geometry_1 = require("./geometry");
8
+ const sceneLayoutModel_1 = require("./sceneLayoutModel");
9
+ const IMAGE_OBJECT_LAYER_ID = "image.user";
10
+ const IMAGE_OVERLAY_LAYER_ID = "image-overlay";
11
+ class ImageTool {
12
+ constructor() {
13
+ this.id = "pooder.kit.image";
14
+ this.metadata = {
15
+ name: "ImageTool",
16
+ };
17
+ this.items = [];
18
+ this.workingItems = [];
19
+ this.hasWorkingChanges = false;
20
+ this.loadResolvers = new Map();
21
+ this.sourceSizeBySrc = new Map();
22
+ this.isUpdatingConfig = false;
23
+ this.isToolActive = false;
24
+ this.isImageSelectionActive = false;
25
+ this.focusedImageId = null;
26
+ this.renderSeq = 0;
27
+ this.imageSpecs = [];
28
+ this.overlaySpecs = [];
29
+ this.onToolActivated = (event) => {
30
+ const before = this.isToolActive;
31
+ this.syncToolActiveFromWorkbench(event.id);
32
+ if (!this.isToolActive) {
33
+ this.setImageFocus(null, {
34
+ syncCanvasSelection: true,
35
+ skipRender: true,
36
+ });
37
+ }
38
+ this.debug("tool:activated", {
39
+ id: event.id,
40
+ previous: event.previous,
41
+ reason: event.reason,
42
+ before,
43
+ isToolActive: this.isToolActive,
44
+ focusedImageId: this.focusedImageId,
45
+ });
46
+ if (!this.isToolActive && this.isDebugEnabled()) {
47
+ console.trace("[ImageTool] tool deactivated trace");
48
+ }
49
+ this.updateImages();
50
+ };
51
+ this.onSelectionChanged = (e) => {
52
+ const list = [];
53
+ if (Array.isArray(e?.selected)) {
54
+ list.push(...e.selected);
55
+ }
56
+ if (Array.isArray(e?.target?._objects)) {
57
+ list.push(...e.target._objects);
58
+ }
59
+ if (e?.target && !Array.isArray(e?.target?._objects)) {
60
+ list.push(e.target);
61
+ }
62
+ const selectedImage = list.find((obj) => obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID);
63
+ this.isImageSelectionActive = !!selectedImage;
64
+ if (selectedImage?.data?.id) {
65
+ this.focusedImageId = selectedImage.data.id;
66
+ }
67
+ else if (list.length > 0) {
68
+ this.focusedImageId = null;
69
+ }
70
+ this.debug("selection:changed", {
71
+ listSize: list.length,
72
+ isImageSelectionActive: this.isImageSelectionActive,
73
+ focusedImageId: this.focusedImageId,
74
+ });
75
+ this.updateImages();
76
+ };
77
+ this.onSelectionCleared = () => {
78
+ this.setImageFocus(null, {
79
+ syncCanvasSelection: false,
80
+ skipRender: true,
81
+ });
82
+ this.debug("selection:cleared applied");
83
+ this.updateImages();
84
+ };
85
+ this.onSceneLayoutChanged = () => {
86
+ this.updateImages();
87
+ };
88
+ this.onSceneGeometryChanged = () => {
89
+ this.updateImages();
90
+ };
91
+ this.onObjectModified = (e) => {
92
+ if (!this.isToolActive)
93
+ return;
94
+ const target = e?.target;
95
+ const id = target?.data?.id;
96
+ const layerId = target?.data?.layerId;
97
+ if (typeof id !== "string" || layerId !== IMAGE_OBJECT_LAYER_ID)
98
+ return;
99
+ const frame = this.getFrameRect();
100
+ if (!frame.width || !frame.height)
101
+ return;
102
+ const center = target.getCenterPoint
103
+ ? target.getCenterPoint()
104
+ : new fabric_1.Point(target.left ?? 0, target.top ?? 0);
105
+ const centerScene = this.canvasService
106
+ ? this.canvasService.toScenePoint({ x: center.x, y: center.y })
107
+ : { x: center.x, y: center.y };
108
+ const objectScale = Number.isFinite(target?.scaleX) ? target.scaleX : 1;
109
+ const objectScaleScene = this.toSceneObjectScale(objectScale || 1);
110
+ const workingItem = this.workingItems.find((item) => item.id === id);
111
+ const sourceKey = workingItem?.sourceUrl || workingItem?.url || "";
112
+ const sourceSize = this.getSourceSize(sourceKey, target);
113
+ const coverScale = this.getCoverScale(frame, sourceSize);
114
+ const updates = {
115
+ left: this.clampNormalized((centerScene.x - frame.left) / frame.width),
116
+ top: this.clampNormalized((centerScene.y - frame.top) / frame.height),
117
+ angle: Number.isFinite(target.angle) ? target.angle : 0,
118
+ scale: Math.max(0.05, objectScaleScene / coverScale),
119
+ };
120
+ this.focusedImageId = id;
121
+ this.updateImageInWorking(id, updates);
122
+ };
123
+ }
124
+ activate(context) {
125
+ this.context = context;
126
+ this.canvasService = context.services.get("CanvasService");
127
+ if (!this.canvasService) {
128
+ console.warn("CanvasService not found for ImageTool");
129
+ return;
130
+ }
131
+ this.renderProducerDisposable?.dispose();
132
+ this.renderProducerDisposable = this.canvasService.registerRenderProducer(this.id, () => ({
133
+ passes: [
134
+ {
135
+ id: IMAGE_OBJECT_LAYER_ID,
136
+ stack: 500,
137
+ order: 0,
138
+ visibility: {
139
+ op: "not",
140
+ expr: {
141
+ op: "sessionActive",
142
+ toolId: "pooder.kit.white-ink",
143
+ },
144
+ },
145
+ objects: this.imageSpecs,
146
+ },
147
+ {
148
+ id: IMAGE_OVERLAY_LAYER_ID,
149
+ stack: 800,
150
+ order: 0,
151
+ visibility: {
152
+ op: "not",
153
+ expr: {
154
+ op: "sessionActive",
155
+ toolId: "pooder.kit.white-ink",
156
+ },
157
+ },
158
+ objects: this.overlaySpecs,
159
+ },
160
+ ],
161
+ }), { priority: 300 });
162
+ context.eventBus.on("tool:activated", this.onToolActivated);
163
+ context.eventBus.on("object:modified", this.onObjectModified);
164
+ context.eventBus.on("selection:created", this.onSelectionChanged);
165
+ context.eventBus.on("selection:updated", this.onSelectionChanged);
166
+ context.eventBus.on("selection:cleared", this.onSelectionCleared);
167
+ context.eventBus.on("scene:layout:change", this.onSceneLayoutChanged);
168
+ context.eventBus.on("scene:geometry:change", this.onSceneGeometryChanged);
169
+ const configService = context.services.get("ConfigurationService");
170
+ if (configService) {
171
+ this.items = this.normalizeItems(configService.get("image.items", []) || []);
172
+ this.workingItems = this.cloneItems(this.items);
173
+ this.hasWorkingChanges = false;
174
+ configService.onAnyChange((e) => {
175
+ if (this.isUpdatingConfig)
176
+ return;
177
+ if (e.key === "image.items") {
178
+ this.items = this.normalizeItems(e.value || []);
179
+ if (!this.isToolActive || !this.hasWorkingChanges) {
180
+ this.workingItems = this.cloneItems(this.items);
181
+ this.hasWorkingChanges = false;
182
+ }
183
+ this.updateImages();
184
+ return;
185
+ }
186
+ if (e.key.startsWith("size.") || e.key.startsWith("image.frame.")) {
187
+ this.updateImages();
188
+ }
189
+ });
190
+ }
191
+ const toolSessionService = context.services.get("ToolSessionService");
192
+ this.dirtyTrackerDisposable = toolSessionService?.registerDirtyTracker(this.id, () => this.hasWorkingChanges);
193
+ this.updateImages();
194
+ }
195
+ deactivate(context) {
196
+ context.eventBus.off("tool:activated", this.onToolActivated);
197
+ context.eventBus.off("object:modified", this.onObjectModified);
198
+ context.eventBus.off("selection:created", this.onSelectionChanged);
199
+ context.eventBus.off("selection:updated", this.onSelectionChanged);
200
+ context.eventBus.off("selection:cleared", this.onSelectionCleared);
201
+ context.eventBus.off("scene:layout:change", this.onSceneLayoutChanged);
202
+ context.eventBus.off("scene:geometry:change", this.onSceneGeometryChanged);
203
+ this.dirtyTrackerDisposable?.dispose();
204
+ this.dirtyTrackerDisposable = undefined;
205
+ this.cropShapeHatchPattern = undefined;
206
+ this.cropShapeHatchPatternColor = undefined;
207
+ this.cropShapeHatchPatternKey = undefined;
208
+ this.imageSpecs = [];
209
+ this.overlaySpecs = [];
210
+ this.clearRenderedImages();
211
+ this.renderProducerDisposable?.dispose();
212
+ this.renderProducerDisposable = undefined;
213
+ if (this.canvasService) {
214
+ void this.canvasService.flushRenderFromProducers();
215
+ this.canvasService = undefined;
216
+ }
217
+ this.context = undefined;
218
+ }
219
+ syncToolActiveFromWorkbench(fallbackId) {
220
+ const wb = this.context?.services.get("WorkbenchService");
221
+ const activeId = wb?.activeToolId;
222
+ if (typeof activeId === "string" || activeId === null) {
223
+ this.isToolActive = activeId === this.id;
224
+ return;
225
+ }
226
+ this.isToolActive = fallbackId === this.id;
227
+ }
228
+ isImageEditingVisible() {
229
+ return (this.isToolActive || this.isImageSelectionActive || !!this.focusedImageId);
230
+ }
231
+ isDebugEnabled() {
232
+ return !!this.getConfig("image.debug", false);
233
+ }
234
+ debug(message, payload) {
235
+ if (!this.isDebugEnabled())
236
+ return;
237
+ if (payload === undefined) {
238
+ console.log(`[ImageTool] ${message}`);
239
+ return;
240
+ }
241
+ console.log(`[ImageTool] ${message}`, payload);
242
+ }
243
+ contribute() {
244
+ return {
245
+ [core_1.ContributionPointIds.TOOLS]: [
246
+ {
247
+ id: this.id,
248
+ name: "Image",
249
+ interaction: "session",
250
+ commands: {
251
+ begin: "resetWorkingImages",
252
+ commit: "completeImages",
253
+ rollback: "resetWorkingImages",
254
+ },
255
+ session: {
256
+ autoBegin: true,
257
+ leavePolicy: "block",
258
+ },
259
+ },
260
+ ],
261
+ [core_1.ContributionPointIds.CONFIGURATIONS]: [
262
+ {
263
+ id: "image.items",
264
+ type: "array",
265
+ label: "Images",
266
+ default: [],
267
+ },
268
+ {
269
+ id: "image.debug",
270
+ type: "boolean",
271
+ label: "Image Debug Log",
272
+ default: false,
273
+ },
274
+ {
275
+ id: "image.frame.strokeColor",
276
+ type: "color",
277
+ label: "Image Frame Stroke Color",
278
+ default: "#808080",
279
+ },
280
+ {
281
+ id: "image.frame.strokeWidth",
282
+ type: "number",
283
+ label: "Image Frame Stroke Width",
284
+ min: 0,
285
+ max: 20,
286
+ step: 0.5,
287
+ default: 2,
288
+ },
289
+ {
290
+ id: "image.frame.strokeStyle",
291
+ type: "select",
292
+ label: "Image Frame Stroke Style",
293
+ options: ["solid", "dashed", "hidden"],
294
+ default: "dashed",
295
+ },
296
+ {
297
+ id: "image.frame.dashLength",
298
+ type: "number",
299
+ label: "Image Frame Dash Length",
300
+ min: 1,
301
+ max: 40,
302
+ step: 1,
303
+ default: 8,
304
+ },
305
+ {
306
+ id: "image.frame.innerBackground",
307
+ type: "color",
308
+ label: "Image Frame Inner Background",
309
+ default: "rgba(0,0,0,0)",
310
+ },
311
+ {
312
+ id: "image.frame.outerBackground",
313
+ type: "color",
314
+ label: "Image Frame Outer Background",
315
+ default: "#f5f5f5",
316
+ },
317
+ ],
318
+ [core_1.ContributionPointIds.COMMANDS]: [
319
+ {
320
+ command: "addImage",
321
+ title: "Add Image",
322
+ handler: async (url, options) => {
323
+ const result = await this.upsertImageEntry(url, {
324
+ mode: "add",
325
+ addOptions: options,
326
+ });
327
+ return result.id;
328
+ },
329
+ },
330
+ {
331
+ command: "upsertImage",
332
+ title: "Upsert Image",
333
+ handler: async (url, options = {}) => {
334
+ return await this.upsertImageEntry(url, options);
335
+ },
336
+ },
337
+ {
338
+ command: "getWorkingImages",
339
+ title: "Get Working Images",
340
+ handler: () => {
341
+ return this.cloneItems(this.workingItems);
342
+ },
343
+ },
344
+ {
345
+ command: "setWorkingImage",
346
+ title: "Set Working Image",
347
+ handler: (id, updates) => {
348
+ this.updateImageInWorking(id, updates);
349
+ },
350
+ },
351
+ {
352
+ command: "resetWorkingImages",
353
+ title: "Reset Working Images",
354
+ handler: () => {
355
+ this.workingItems = this.cloneItems(this.items);
356
+ this.hasWorkingChanges = false;
357
+ this.updateImages();
358
+ this.emitWorkingChange();
359
+ },
360
+ },
361
+ {
362
+ command: "completeImages",
363
+ title: "Complete Images",
364
+ handler: async () => {
365
+ return await this.commitWorkingImagesAsCropped();
366
+ },
367
+ },
368
+ {
369
+ command: "exportUserCroppedImage",
370
+ title: "Export User Cropped Image",
371
+ handler: async (options = {}) => {
372
+ return await this.exportUserCroppedImage(options);
373
+ },
374
+ },
375
+ {
376
+ command: "fitImageToArea",
377
+ title: "Fit Image to Area",
378
+ handler: async (id, area) => {
379
+ await this.fitImageToArea(id, area);
380
+ },
381
+ },
382
+ {
383
+ command: "fitImageToDefaultArea",
384
+ title: "Fit Image to Default Area",
385
+ handler: async (id) => {
386
+ await this.fitImageToDefaultArea(id);
387
+ },
388
+ },
389
+ {
390
+ command: "focusImage",
391
+ title: "Focus Image",
392
+ handler: (id, options = {}) => {
393
+ return this.setImageFocus(id, options);
394
+ },
395
+ },
396
+ {
397
+ command: "removeImage",
398
+ title: "Remove Image",
399
+ handler: (id) => {
400
+ const removed = this.items.find((item) => item.id === id);
401
+ const next = this.items.filter((item) => item.id !== id);
402
+ if (next.length !== this.items.length) {
403
+ this.purgeSourceSizeCacheForItem(removed);
404
+ if (this.focusedImageId === id) {
405
+ this.setImageFocus(null, {
406
+ syncCanvasSelection: true,
407
+ skipRender: true,
408
+ });
409
+ }
410
+ this.updateConfig(next);
411
+ }
412
+ },
413
+ },
414
+ {
415
+ command: "updateImage",
416
+ title: "Update Image",
417
+ handler: async (id, updates, options = {}) => {
418
+ await this.updateImage(id, updates, options);
419
+ },
420
+ },
421
+ {
422
+ command: "clearImages",
423
+ title: "Clear Images",
424
+ handler: () => {
425
+ this.sourceSizeBySrc.clear();
426
+ this.setImageFocus(null, {
427
+ syncCanvasSelection: true,
428
+ skipRender: true,
429
+ });
430
+ this.updateConfig([]);
431
+ },
432
+ },
433
+ {
434
+ command: "bringToFront",
435
+ title: "Bring Image to Front",
436
+ handler: (id) => {
437
+ const index = this.items.findIndex((item) => item.id === id);
438
+ if (index !== -1 && index < this.items.length - 1) {
439
+ const next = [...this.items];
440
+ const [item] = next.splice(index, 1);
441
+ next.push(item);
442
+ this.updateConfig(next);
443
+ }
444
+ },
445
+ },
446
+ {
447
+ command: "sendToBack",
448
+ title: "Send Image to Back",
449
+ handler: (id) => {
450
+ const index = this.items.findIndex((item) => item.id === id);
451
+ if (index > 0) {
452
+ const next = [...this.items];
453
+ const [item] = next.splice(index, 1);
454
+ next.unshift(item);
455
+ this.updateConfig(next);
456
+ }
457
+ },
458
+ },
459
+ ],
460
+ };
461
+ }
462
+ normalizeItem(item) {
463
+ const url = typeof item.url === "string" ? item.url : "";
464
+ const sourceUrl = typeof item.sourceUrl === "string" && item.sourceUrl.length > 0
465
+ ? item.sourceUrl
466
+ : url;
467
+ const committedUrl = typeof item.committedUrl === "string" && item.committedUrl.length > 0
468
+ ? item.committedUrl
469
+ : undefined;
470
+ return {
471
+ ...item,
472
+ url: url || sourceUrl,
473
+ sourceUrl,
474
+ committedUrl,
475
+ opacity: Number.isFinite(item.opacity) ? item.opacity : 1,
476
+ scale: Number.isFinite(item.scale) ? item.scale : 1,
477
+ angle: Number.isFinite(item.angle) ? item.angle : 0,
478
+ left: Number.isFinite(item.left) ? item.left : 0.5,
479
+ top: Number.isFinite(item.top) ? item.top : 0.5,
480
+ };
481
+ }
482
+ normalizeItems(items) {
483
+ return (items || []).map((item) => this.normalizeItem(item));
484
+ }
485
+ cloneItems(items) {
486
+ return this.normalizeItems((items || []).map((i) => ({ ...i })));
487
+ }
488
+ emitWorkingChange(changedId = null) {
489
+ this.context?.eventBus.emit("image:working:change", {
490
+ changedId,
491
+ items: this.cloneItems(this.workingItems),
492
+ });
493
+ }
494
+ generateId() {
495
+ return Math.random().toString(36).substring(2, 9);
496
+ }
497
+ hasImageItem(id) {
498
+ return (this.items.some((item) => item.id === id) ||
499
+ this.workingItems.some((item) => item.id === id));
500
+ }
501
+ setImageFocus(id, options = {}) {
502
+ const syncCanvasSelection = options.syncCanvasSelection !== false;
503
+ if (id && !this.hasImageItem(id)) {
504
+ return { ok: false, reason: "image-not-found" };
505
+ }
506
+ this.focusedImageId = id;
507
+ this.isImageSelectionActive = !!id;
508
+ if (syncCanvasSelection && this.canvasService) {
509
+ const canvas = this.canvasService.canvas;
510
+ if (!id) {
511
+ canvas.discardActiveObject();
512
+ }
513
+ else {
514
+ const obj = this.getImageObject(id);
515
+ if (obj) {
516
+ obj.set({
517
+ selectable: true,
518
+ evented: true,
519
+ hasControls: true,
520
+ hasBorders: true,
521
+ });
522
+ canvas.setActiveObject(obj);
523
+ }
524
+ }
525
+ this.canvasService.requestRenderAll();
526
+ }
527
+ if (!options.skipRender) {
528
+ this.updateImages();
529
+ }
530
+ return { ok: true, id };
531
+ }
532
+ async addImageEntry(url, options, fitOnAdd = true) {
533
+ const id = this.generateId();
534
+ const newItem = this.normalizeItem({
535
+ id,
536
+ url,
537
+ opacity: 1,
538
+ ...options,
539
+ });
540
+ const sessionDirtyBeforeAdd = this.isToolActive && this.hasWorkingChanges;
541
+ const waitLoaded = this.waitImageLoaded(id, true);
542
+ this.updateConfig([...this.items, newItem]);
543
+ this.addItemToWorkingSessionIfNeeded(newItem, sessionDirtyBeforeAdd);
544
+ const loaded = await waitLoaded;
545
+ if (loaded && fitOnAdd) {
546
+ await this.fitImageToDefaultArea(id);
547
+ }
548
+ if (loaded) {
549
+ this.setImageFocus(id);
550
+ }
551
+ return id;
552
+ }
553
+ async upsertImageEntry(url, options = {}) {
554
+ const mode = options.mode || (options.id ? "replace" : "add");
555
+ const fitOnAdd = options.fitOnAdd !== false;
556
+ if (mode === "replace") {
557
+ if (!options.id) {
558
+ throw new Error("replace-target-id-required");
559
+ }
560
+ const targetId = options.id;
561
+ if (!this.hasImageItem(targetId)) {
562
+ throw new Error("replace-target-not-found");
563
+ }
564
+ await this.updateImageInConfig(targetId, { url });
565
+ return { id: targetId, mode: "replace" };
566
+ }
567
+ const id = await this.addImageEntry(url, options.addOptions, fitOnAdd);
568
+ return { id, mode: "add" };
569
+ }
570
+ addItemToWorkingSessionIfNeeded(item, sessionDirtyBeforeAdd) {
571
+ if (!sessionDirtyBeforeAdd || !this.isToolActive)
572
+ return;
573
+ if (this.workingItems.some((existing) => existing.id === item.id))
574
+ return;
575
+ this.workingItems = this.cloneItems([...this.workingItems, item]);
576
+ this.updateImages();
577
+ this.emitWorkingChange(item.id);
578
+ }
579
+ async updateImage(id, updates, options = {}) {
580
+ this.syncToolActiveFromWorkbench();
581
+ const target = options.target || "auto";
582
+ if (target === "working" || (target === "auto" && this.isToolActive)) {
583
+ this.updateImageInWorking(id, updates);
584
+ return;
585
+ }
586
+ await this.updateImageInConfig(id, updates);
587
+ }
588
+ getConfig(key, fallback) {
589
+ if (!this.context)
590
+ return fallback;
591
+ const configService = this.context.services.get("ConfigurationService");
592
+ if (!configService)
593
+ return fallback;
594
+ return configService.get(key, fallback) ?? fallback;
595
+ }
596
+ updateConfig(newItems, skipCanvasUpdate = false) {
597
+ if (!this.context)
598
+ return;
599
+ this.isUpdatingConfig = true;
600
+ this.items = this.normalizeItems(newItems);
601
+ if (!this.isToolActive || !this.hasWorkingChanges) {
602
+ this.workingItems = this.cloneItems(this.items);
603
+ this.hasWorkingChanges = false;
604
+ }
605
+ const configService = this.context.services.get("ConfigurationService");
606
+ configService?.update("image.items", this.items);
607
+ if (!skipCanvasUpdate) {
608
+ this.updateImages();
609
+ }
610
+ setTimeout(() => {
611
+ this.isUpdatingConfig = false;
612
+ }, 50);
613
+ }
614
+ getFrameRect() {
615
+ if (!this.canvasService) {
616
+ return { left: 0, top: 0, width: 0, height: 0 };
617
+ }
618
+ const configService = this.context?.services.get("ConfigurationService");
619
+ if (!configService) {
620
+ return { left: 0, top: 0, width: 0, height: 0 };
621
+ }
622
+ const sizeState = (0, sceneLayoutModel_1.readSizeState)(configService);
623
+ const layout = (0, sceneLayoutModel_1.computeSceneLayout)(this.canvasService, sizeState);
624
+ if (!layout) {
625
+ return { left: 0, top: 0, width: 0, height: 0 };
626
+ }
627
+ return this.canvasService.toSceneRect({
628
+ left: layout.cutRect.left,
629
+ top: layout.cutRect.top,
630
+ width: layout.cutRect.width,
631
+ height: layout.cutRect.height,
632
+ });
633
+ }
634
+ getFrameRectScreen(frame) {
635
+ if (!this.canvasService) {
636
+ return { left: 0, top: 0, width: 0, height: 0 };
637
+ }
638
+ return this.canvasService.toScreenRect(frame || this.getFrameRect());
639
+ }
640
+ toLayoutSceneRect(rect) {
641
+ return {
642
+ left: rect.left,
643
+ top: rect.top,
644
+ width: rect.width,
645
+ height: rect.height,
646
+ space: "scene",
647
+ };
648
+ }
649
+ async resolveDefaultFitArea() {
650
+ if (!this.canvasService)
651
+ return null;
652
+ const frame = this.getFrameRect();
653
+ if (frame.width <= 0 || frame.height <= 0)
654
+ return null;
655
+ return {
656
+ width: Math.max(1, frame.width),
657
+ height: Math.max(1, frame.height),
658
+ left: frame.left + frame.width / 2,
659
+ top: frame.top + frame.height / 2,
660
+ };
661
+ }
662
+ async fitImageToDefaultArea(id) {
663
+ if (!this.canvasService)
664
+ return;
665
+ const area = await this.resolveDefaultFitArea();
666
+ if (area) {
667
+ await this.fitImageToArea(id, area);
668
+ return;
669
+ }
670
+ const viewport = this.canvasService.getSceneViewportRect();
671
+ const canvasW = Math.max(1, viewport.width || 0);
672
+ const canvasH = Math.max(1, viewport.height || 0);
673
+ await this.fitImageToArea(id, {
674
+ width: canvasW,
675
+ height: canvasH,
676
+ left: viewport.left + canvasW / 2,
677
+ top: viewport.top + canvasH / 2,
678
+ });
679
+ }
680
+ getImageObjects() {
681
+ if (!this.canvasService)
682
+ return [];
683
+ return this.canvasService.canvas.getObjects().filter((obj) => {
684
+ return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
685
+ });
686
+ }
687
+ getOverlayObjects() {
688
+ if (!this.canvasService)
689
+ return [];
690
+ return this.canvasService.getPassObjects(IMAGE_OVERLAY_LAYER_ID);
691
+ }
692
+ getImageObject(id) {
693
+ return this.getImageObjects().find((obj) => obj?.data?.id === id);
694
+ }
695
+ clearRenderedImages() {
696
+ if (!this.canvasService)
697
+ return;
698
+ this.imageSpecs = [];
699
+ this.overlaySpecs = [];
700
+ this.canvasService.requestRenderFromProducers();
701
+ }
702
+ purgeSourceSizeCacheForItem(item) {
703
+ if (!item)
704
+ return;
705
+ const sources = [item.url, item.sourceUrl, item.committedUrl].filter((value) => typeof value === "string" && value.length > 0);
706
+ sources.forEach((src) => this.sourceSizeBySrc.delete(src));
707
+ }
708
+ rememberSourceSize(src, obj) {
709
+ const width = Number(obj?.width || 0);
710
+ const height = Number(obj?.height || 0);
711
+ if (src && width > 0 && height > 0) {
712
+ this.sourceSizeBySrc.set(src, { width, height });
713
+ }
714
+ }
715
+ getSourceSize(src, obj) {
716
+ const cached = src ? this.sourceSizeBySrc.get(src) : undefined;
717
+ if (cached)
718
+ return cached;
719
+ const width = Number(obj?.width || 0);
720
+ const height = Number(obj?.height || 0);
721
+ if (src && width > 0 && height > 0) {
722
+ const size = { width, height };
723
+ this.sourceSizeBySrc.set(src, size);
724
+ return size;
725
+ }
726
+ return { width: 1, height: 1 };
727
+ }
728
+ async ensureSourceSize(src) {
729
+ if (!src)
730
+ return null;
731
+ const cached = this.sourceSizeBySrc.get(src);
732
+ if (cached)
733
+ return cached;
734
+ try {
735
+ const image = await fabric_1.Image.fromURL(src, {
736
+ crossOrigin: "anonymous",
737
+ });
738
+ const width = Number(image?.width || 0);
739
+ const height = Number(image?.height || 0);
740
+ if (width > 0 && height > 0) {
741
+ const size = { width, height };
742
+ this.sourceSizeBySrc.set(src, size);
743
+ return size;
744
+ }
745
+ }
746
+ catch (error) {
747
+ this.debug("image:size:load-failed", {
748
+ src,
749
+ error: error instanceof Error ? error.message : String(error),
750
+ });
751
+ }
752
+ return null;
753
+ }
754
+ getCoverScale(frame, size) {
755
+ const sw = Math.max(1, size.width);
756
+ const sh = Math.max(1, size.height);
757
+ const fw = Math.max(1, frame.width);
758
+ const fh = Math.max(1, frame.height);
759
+ return Math.max(fw / sw, fh / sh);
760
+ }
761
+ getFrameVisualConfig() {
762
+ const strokeStyleRaw = (this.getConfig("image.frame.strokeStyle", "dashed") || "dashed");
763
+ const strokeStyle = strokeStyleRaw === "dashed" || strokeStyleRaw === "hidden"
764
+ ? strokeStyleRaw
765
+ : "dashed";
766
+ const strokeWidth = Number(this.getConfig("image.frame.strokeWidth", 2) ?? 2);
767
+ const dashLength = Number(this.getConfig("image.frame.dashLength", 8) ?? 8);
768
+ return {
769
+ strokeColor: this.getConfig("image.frame.strokeColor", "#808080") ||
770
+ "#808080",
771
+ strokeWidth: Number.isFinite(strokeWidth) ? Math.max(0, strokeWidth) : 2,
772
+ strokeStyle,
773
+ dashLength: Number.isFinite(dashLength) ? Math.max(1, dashLength) : 8,
774
+ innerBackground: this.getConfig("image.frame.innerBackground", "rgba(0,0,0,0)") || "rgba(0,0,0,0)",
775
+ outerBackground: this.getConfig("image.frame.outerBackground", "#f5f5f5") ||
776
+ "#f5f5f5",
777
+ };
778
+ }
779
+ toSceneGeometryLike(raw) {
780
+ const shape = raw?.shape;
781
+ if (!(0, dielineShape_1.isDielineShape)(shape)) {
782
+ return null;
783
+ }
784
+ const radiusRaw = Number(raw?.radius);
785
+ const offsetRaw = Number(raw?.offset);
786
+ const unit = typeof raw?.unit === "string" ? raw.unit : "px";
787
+ const radius = unit === "scene" || !this.canvasService
788
+ ? radiusRaw
789
+ : this.canvasService.toSceneLength(radiusRaw);
790
+ const offset = unit === "scene" || !this.canvasService
791
+ ? offsetRaw
792
+ : this.canvasService.toSceneLength(offsetRaw);
793
+ return {
794
+ shape,
795
+ shapeStyle: (0, dielineShape_1.normalizeShapeStyle)(raw?.shapeStyle),
796
+ radius: Number.isFinite(radius) ? radius : 0,
797
+ offset: Number.isFinite(offset) ? offset : 0,
798
+ };
799
+ }
800
+ async resolveSceneGeometryForOverlay() {
801
+ if (!this.context)
802
+ return null;
803
+ const commandService = this.context.services.get("CommandService");
804
+ if (commandService) {
805
+ try {
806
+ const raw = await Promise.resolve(commandService.executeCommand("getSceneGeometry"));
807
+ const geometry = this.toSceneGeometryLike(raw);
808
+ if (geometry) {
809
+ this.debug("overlay:sceneGeometry:command", geometry);
810
+ return geometry;
811
+ }
812
+ this.debug("overlay:sceneGeometry:command:invalid", { raw });
813
+ }
814
+ catch (error) {
815
+ this.debug("overlay:sceneGeometry:command:error", {
816
+ error: error instanceof Error ? error.message : String(error),
817
+ });
818
+ }
819
+ }
820
+ if (!this.canvasService)
821
+ return null;
822
+ const configService = this.context.services.get("ConfigurationService");
823
+ if (!configService)
824
+ return null;
825
+ const sizeState = (0, sceneLayoutModel_1.readSizeState)(configService);
826
+ const layout = (0, sceneLayoutModel_1.computeSceneLayout)(this.canvasService, sizeState);
827
+ if (!layout) {
828
+ this.debug("overlay:sceneGeometry:fallback:missing-layout");
829
+ return null;
830
+ }
831
+ const geometry = this.toSceneGeometryLike((0, sceneLayoutModel_1.buildSceneGeometry)(configService, layout));
832
+ if (geometry) {
833
+ this.debug("overlay:sceneGeometry:fallback", geometry);
834
+ }
835
+ return geometry;
836
+ }
837
+ resolveCutShapeRadius(geometry, frame) {
838
+ const visualRadius = Number.isFinite(geometry.radius)
839
+ ? Math.max(0, geometry.radius)
840
+ : 0;
841
+ const visualOffset = Number.isFinite(geometry.offset) ? geometry.offset : 0;
842
+ const rawCutRadius = visualRadius === 0 ? 0 : Math.max(0, visualRadius + visualOffset);
843
+ const maxRadius = Math.max(0, Math.min(frame.width, frame.height) / 2);
844
+ return Math.max(0, Math.min(maxRadius, rawCutRadius));
845
+ }
846
+ getCropShapeHatchPattern(color = "rgba(255, 0, 0, 0.6)") {
847
+ if (typeof document === "undefined")
848
+ return undefined;
849
+ const sceneScale = this.canvasService?.getSceneScale() || 1;
850
+ const cacheKey = `${color}::${sceneScale.toFixed(6)}`;
851
+ if (this.cropShapeHatchPattern &&
852
+ this.cropShapeHatchPatternColor === color &&
853
+ this.cropShapeHatchPatternKey === cacheKey) {
854
+ return this.cropShapeHatchPattern;
855
+ }
856
+ const size = 16;
857
+ const patternCanvas = document.createElement("canvas");
858
+ patternCanvas.width = size;
859
+ patternCanvas.height = size;
860
+ const ctx = patternCanvas.getContext("2d");
861
+ if (!ctx)
862
+ return undefined;
863
+ ctx.clearRect(0, 0, size, size);
864
+ ctx.fillStyle = "rgba(255, 0, 0, 0.08)";
865
+ ctx.fillRect(0, 0, size, size);
866
+ ctx.strokeStyle = color;
867
+ ctx.lineWidth = 1.5;
868
+ ctx.beginPath();
869
+ ctx.moveTo(-size, size);
870
+ ctx.lineTo(size, -size);
871
+ ctx.moveTo(-size / 2, size + size / 2);
872
+ ctx.lineTo(size + size / 2, -size / 2);
873
+ ctx.moveTo(0, size);
874
+ ctx.lineTo(size, 0);
875
+ ctx.moveTo(size / 2, size + size / 2);
876
+ ctx.lineTo(size + size + size / 2, -size / 2);
877
+ ctx.stroke();
878
+ const pattern = new fabric_1.Pattern({
879
+ source: patternCanvas,
880
+ // @ts-ignore: Fabric Pattern accepts canvas source here.
881
+ repetition: "repeat",
882
+ });
883
+ // Scene specs are scaled to screen by CanvasService; keep hatch density in screen pixels.
884
+ pattern.patternTransform = [
885
+ 1 / sceneScale,
886
+ 0,
887
+ 0,
888
+ 1 / sceneScale,
889
+ 0,
890
+ 0,
891
+ ];
892
+ this.cropShapeHatchPattern = pattern;
893
+ this.cropShapeHatchPatternColor = color;
894
+ this.cropShapeHatchPatternKey = cacheKey;
895
+ return pattern;
896
+ }
897
+ buildCropShapeOverlaySpecs(frame, sceneGeometry) {
898
+ if (!sceneGeometry) {
899
+ this.debug("overlay:shape:skip", { reason: "scene-geometry-missing" });
900
+ return [];
901
+ }
902
+ if (sceneGeometry.shape === "custom") {
903
+ this.debug("overlay:shape:skip", { reason: "shape-custom" });
904
+ return [];
905
+ }
906
+ const shape = sceneGeometry.shape;
907
+ const shapeStyle = sceneGeometry.shapeStyle;
908
+ const inset = 0;
909
+ const shapeWidth = Math.max(1, frame.width);
910
+ const shapeHeight = Math.max(1, frame.height);
911
+ const radius = this.resolveCutShapeRadius(sceneGeometry, frame);
912
+ this.debug("overlay:shape:geometry", {
913
+ shape,
914
+ frameWidth: frame.width,
915
+ frameHeight: frame.height,
916
+ offset: sceneGeometry.offset,
917
+ shapeStyle,
918
+ inset,
919
+ shapeWidth,
920
+ shapeHeight,
921
+ baseRadius: sceneGeometry.radius,
922
+ radius,
923
+ });
924
+ const isSameAsFrame = Math.abs(shapeWidth - frame.width) <= 0.0001 &&
925
+ Math.abs(shapeHeight - frame.height) <= 0.0001;
926
+ if (shape === "rect" && radius <= 0.0001 && isSameAsFrame) {
927
+ this.debug("overlay:shape:skip", {
928
+ reason: "shape-rect-no-radius",
929
+ });
930
+ return [];
931
+ }
932
+ const baseOptions = {
933
+ shape,
934
+ width: shapeWidth,
935
+ height: shapeHeight,
936
+ radius,
937
+ x: frame.width / 2,
938
+ y: frame.height / 2,
939
+ features: [],
940
+ shapeStyle,
941
+ canvasWidth: frame.width,
942
+ canvasHeight: frame.height,
943
+ };
944
+ try {
945
+ const shapePathData = (0, geometry_1.generateDielinePath)(baseOptions);
946
+ const outerRectPathData = `M 0 0 L ${frame.width} 0 L ${frame.width} ${frame.height} L 0 ${frame.height} Z`;
947
+ const hatchPathData = `${outerRectPathData} ${shapePathData}`;
948
+ if (!shapePathData || !hatchPathData) {
949
+ this.debug("overlay:shape:skip", {
950
+ reason: "path-generation-empty",
951
+ shape,
952
+ radius,
953
+ });
954
+ return [];
955
+ }
956
+ const patternFill = this.getCropShapeHatchPattern();
957
+ const hatchFill = patternFill || "rgba(255, 0, 0, 0.22)";
958
+ const shapeBounds = (0, geometry_1.getPathBounds)(shapePathData);
959
+ const hatchBounds = (0, geometry_1.getPathBounds)(hatchPathData);
960
+ const frameRect = this.toLayoutSceneRect(frame);
961
+ const hatchPathLength = hatchPathData.length;
962
+ const shapePathLength = shapePathData.length;
963
+ const specs = [
964
+ {
965
+ id: "image.cropShapeHatch",
966
+ type: "path",
967
+ data: { id: "image.cropShapeHatch", zIndex: 5 },
968
+ layout: {
969
+ reference: "custom",
970
+ referenceRect: frameRect,
971
+ alignX: "start",
972
+ alignY: "start",
973
+ offsetX: hatchBounds.x,
974
+ offsetY: hatchBounds.y,
975
+ },
976
+ props: {
977
+ pathData: hatchPathData,
978
+ originX: "left",
979
+ originY: "top",
980
+ fill: hatchFill,
981
+ opacity: patternFill ? 1 : 0.8,
982
+ stroke: null,
983
+ fillRule: "evenodd",
984
+ selectable: false,
985
+ evented: false,
986
+ excludeFromExport: true,
987
+ objectCaching: false,
988
+ },
989
+ },
990
+ {
991
+ id: "image.cropShapePath",
992
+ type: "path",
993
+ data: { id: "image.cropShapePath", zIndex: 6 },
994
+ layout: {
995
+ reference: "custom",
996
+ referenceRect: frameRect,
997
+ alignX: "start",
998
+ alignY: "start",
999
+ offsetX: shapeBounds.x,
1000
+ offsetY: shapeBounds.y,
1001
+ },
1002
+ props: {
1003
+ pathData: shapePathData,
1004
+ originX: "left",
1005
+ originY: "top",
1006
+ fill: "rgba(0,0,0,0)",
1007
+ stroke: "rgba(255, 0, 0, 0.9)",
1008
+ strokeWidth: this.canvasService?.toSceneLength(1) ?? 1,
1009
+ selectable: false,
1010
+ evented: false,
1011
+ excludeFromExport: true,
1012
+ objectCaching: false,
1013
+ },
1014
+ },
1015
+ ];
1016
+ this.debug("overlay:shape:built", {
1017
+ shape,
1018
+ radius,
1019
+ inset,
1020
+ shapeWidth,
1021
+ shapeHeight,
1022
+ fillRule: "evenodd",
1023
+ shapePathLength,
1024
+ hatchPathLength,
1025
+ shapeBounds,
1026
+ hatchBounds,
1027
+ hatchFillType: hatchFill && typeof hatchFill === "object" ? "pattern" : "color",
1028
+ ids: specs.map((spec) => spec.id),
1029
+ });
1030
+ return specs;
1031
+ }
1032
+ catch (error) {
1033
+ this.debug("overlay:shape:error", {
1034
+ shape,
1035
+ radius,
1036
+ error: error instanceof Error ? error.message : String(error),
1037
+ });
1038
+ return [];
1039
+ }
1040
+ }
1041
+ resolveRenderImageState(item) {
1042
+ const active = this.isToolActive;
1043
+ const sourceUrl = item.sourceUrl || item.url;
1044
+ const committedUrl = item.committedUrl;
1045
+ if (!active && committedUrl) {
1046
+ return {
1047
+ src: committedUrl,
1048
+ left: 0.5,
1049
+ top: 0.5,
1050
+ scale: 1,
1051
+ angle: 0,
1052
+ opacity: item.opacity,
1053
+ };
1054
+ }
1055
+ return {
1056
+ src: sourceUrl || item.url,
1057
+ left: Number.isFinite(item.left) ? item.left : 0.5,
1058
+ top: Number.isFinite(item.top) ? item.top : 0.5,
1059
+ scale: Math.max(0.05, item.scale ?? 1),
1060
+ angle: Number.isFinite(item.angle) ? item.angle : 0,
1061
+ opacity: item.opacity,
1062
+ };
1063
+ }
1064
+ computeCanvasProps(render, size, frame) {
1065
+ const left = render.left;
1066
+ const top = render.top;
1067
+ const zoom = render.scale;
1068
+ const angle = render.angle;
1069
+ const centerX = frame.left + left * frame.width;
1070
+ const centerY = frame.top + top * frame.height;
1071
+ const scale = this.getCoverScale(frame, size) * zoom;
1072
+ return {
1073
+ left: centerX,
1074
+ top: centerY,
1075
+ scaleX: scale,
1076
+ scaleY: scale,
1077
+ angle,
1078
+ originX: "center",
1079
+ originY: "center",
1080
+ uniformScaling: true,
1081
+ lockScalingFlip: true,
1082
+ selectable: this.isImageEditingVisible(),
1083
+ evented: this.isImageEditingVisible(),
1084
+ hasControls: this.isImageEditingVisible(),
1085
+ hasBorders: this.isImageEditingVisible(),
1086
+ opacity: render.opacity,
1087
+ };
1088
+ }
1089
+ toSceneObjectScale(value) {
1090
+ if (!this.canvasService)
1091
+ return value;
1092
+ return value / this.canvasService.getSceneScale();
1093
+ }
1094
+ getCurrentSrc(obj) {
1095
+ if (!obj)
1096
+ return undefined;
1097
+ if (typeof obj.getSrc === "function")
1098
+ return obj.getSrc();
1099
+ return obj?._originalElement?.src;
1100
+ }
1101
+ async buildImageSpecs(items, frame) {
1102
+ const specs = [];
1103
+ for (const item of items) {
1104
+ const render = this.resolveRenderImageState(item);
1105
+ if (!render.src)
1106
+ continue;
1107
+ const ensured = await this.ensureSourceSize(render.src);
1108
+ const sourceSize = ensured || this.getSourceSize(render.src);
1109
+ const props = this.computeCanvasProps(render, sourceSize, frame);
1110
+ specs.push({
1111
+ id: item.id,
1112
+ type: "image",
1113
+ src: render.src,
1114
+ data: {
1115
+ id: item.id,
1116
+ layerId: IMAGE_OBJECT_LAYER_ID,
1117
+ type: "image-item",
1118
+ },
1119
+ props,
1120
+ });
1121
+ }
1122
+ return specs;
1123
+ }
1124
+ buildOverlaySpecs(frame, sceneGeometry) {
1125
+ const visible = this.isImageEditingVisible();
1126
+ if (!visible ||
1127
+ frame.width <= 0 ||
1128
+ frame.height <= 0 ||
1129
+ !this.canvasService) {
1130
+ this.debug("overlay:hidden", {
1131
+ visible,
1132
+ frame,
1133
+ isToolActive: this.isToolActive,
1134
+ isImageSelectionActive: this.isImageSelectionActive,
1135
+ focusedImageId: this.focusedImageId,
1136
+ });
1137
+ return [];
1138
+ }
1139
+ const viewport = this.canvasService.getSceneViewportRect();
1140
+ const canvasW = viewport.width || 0;
1141
+ const canvasH = viewport.height || 0;
1142
+ const canvasLeft = viewport.left || 0;
1143
+ const canvasTop = viewport.top || 0;
1144
+ const visual = this.getFrameVisualConfig();
1145
+ const strokeWidthScene = this.canvasService.toSceneLength(visual.strokeWidth);
1146
+ const dashLengthScene = this.canvasService.toSceneLength(visual.dashLength);
1147
+ const frameLeft = Math.max(canvasLeft, Math.min(canvasLeft + canvasW, frame.left));
1148
+ const frameTop = Math.max(canvasTop, Math.min(canvasTop + canvasH, frame.top));
1149
+ const frameRight = Math.max(frameLeft, Math.min(canvasLeft + canvasW, frame.left + frame.width));
1150
+ const frameBottom = Math.max(frameTop, Math.min(canvasTop + canvasH, frame.top + frame.height));
1151
+ const visibleFrameH = Math.max(0, frameBottom - frameTop);
1152
+ const topH = Math.max(0, frameTop - canvasTop);
1153
+ const bottomH = Math.max(0, canvasTop + canvasH - frameBottom);
1154
+ const leftW = Math.max(0, frameLeft - canvasLeft);
1155
+ const rightW = Math.max(0, canvasLeft + canvasW - frameRight);
1156
+ const viewportRect = this.toLayoutSceneRect({
1157
+ left: canvasLeft,
1158
+ top: canvasTop,
1159
+ width: canvasW,
1160
+ height: canvasH,
1161
+ });
1162
+ const visibleFrameBandRect = this.toLayoutSceneRect({
1163
+ left: canvasLeft,
1164
+ top: frameTop,
1165
+ width: canvasW,
1166
+ height: visibleFrameH,
1167
+ });
1168
+ const frameRect = this.toLayoutSceneRect(frame);
1169
+ const shapeOverlay = this.buildCropShapeOverlaySpecs(frame, sceneGeometry);
1170
+ const mask = [
1171
+ {
1172
+ id: "image.cropMask.top",
1173
+ type: "rect",
1174
+ data: { id: "image.cropMask.top", zIndex: 1 },
1175
+ layout: {
1176
+ reference: "custom",
1177
+ referenceRect: viewportRect,
1178
+ alignX: "start",
1179
+ alignY: "start",
1180
+ width: "100%",
1181
+ height: topH,
1182
+ },
1183
+ props: {
1184
+ originX: "left",
1185
+ originY: "top",
1186
+ fill: visual.outerBackground,
1187
+ selectable: false,
1188
+ evented: false,
1189
+ },
1190
+ },
1191
+ {
1192
+ id: "image.cropMask.bottom",
1193
+ type: "rect",
1194
+ data: { id: "image.cropMask.bottom", zIndex: 2 },
1195
+ layout: {
1196
+ reference: "custom",
1197
+ referenceRect: viewportRect,
1198
+ alignX: "start",
1199
+ alignY: "end",
1200
+ width: "100%",
1201
+ height: bottomH,
1202
+ },
1203
+ props: {
1204
+ originX: "left",
1205
+ originY: "top",
1206
+ fill: visual.outerBackground,
1207
+ selectable: false,
1208
+ evented: false,
1209
+ },
1210
+ },
1211
+ {
1212
+ id: "image.cropMask.left",
1213
+ type: "rect",
1214
+ data: { id: "image.cropMask.left", zIndex: 3 },
1215
+ layout: {
1216
+ reference: "custom",
1217
+ referenceRect: visibleFrameBandRect,
1218
+ alignX: "start",
1219
+ alignY: "start",
1220
+ width: leftW,
1221
+ height: "100%",
1222
+ },
1223
+ props: {
1224
+ originX: "left",
1225
+ originY: "top",
1226
+ fill: visual.outerBackground,
1227
+ selectable: false,
1228
+ evented: false,
1229
+ },
1230
+ },
1231
+ {
1232
+ id: "image.cropMask.right",
1233
+ type: "rect",
1234
+ data: { id: "image.cropMask.right", zIndex: 4 },
1235
+ layout: {
1236
+ reference: "custom",
1237
+ referenceRect: visibleFrameBandRect,
1238
+ alignX: "end",
1239
+ alignY: "start",
1240
+ width: rightW,
1241
+ height: "100%",
1242
+ },
1243
+ props: {
1244
+ originX: "left",
1245
+ originY: "top",
1246
+ fill: visual.outerBackground,
1247
+ selectable: false,
1248
+ evented: false,
1249
+ },
1250
+ },
1251
+ ];
1252
+ const frameSpec = {
1253
+ id: "image.cropFrame",
1254
+ type: "rect",
1255
+ data: { id: "image.cropFrame", zIndex: 7 },
1256
+ layout: {
1257
+ reference: "custom",
1258
+ referenceRect: frameRect,
1259
+ alignX: "start",
1260
+ alignY: "start",
1261
+ width: "100%",
1262
+ height: "100%",
1263
+ },
1264
+ props: {
1265
+ originX: "left",
1266
+ originY: "top",
1267
+ fill: visual.innerBackground,
1268
+ stroke: visual.strokeStyle === "hidden"
1269
+ ? "rgba(0,0,0,0)"
1270
+ : visual.strokeColor,
1271
+ strokeWidth: visual.strokeStyle === "hidden" ? 0 : strokeWidthScene,
1272
+ strokeDashArray: visual.strokeStyle === "dashed"
1273
+ ? [dashLengthScene, dashLengthScene]
1274
+ : undefined,
1275
+ selectable: false,
1276
+ evented: false,
1277
+ },
1278
+ };
1279
+ const specs = shapeOverlay.length > 0
1280
+ ? [...mask, ...shapeOverlay]
1281
+ : [...mask, ...shapeOverlay, frameSpec];
1282
+ this.debug("overlay:built", {
1283
+ frame,
1284
+ shape: sceneGeometry?.shape,
1285
+ overlayIds: specs.map((spec) => ({
1286
+ id: spec.id,
1287
+ zIndex: spec.data?.zIndex,
1288
+ })),
1289
+ });
1290
+ return specs;
1291
+ }
1292
+ updateImages() {
1293
+ void this.updateImagesAsync();
1294
+ }
1295
+ async updateImagesAsync() {
1296
+ if (!this.canvasService)
1297
+ return;
1298
+ this.syncToolActiveFromWorkbench();
1299
+ const seq = ++this.renderSeq;
1300
+ const renderItems = this.isToolActive ? this.workingItems : this.items;
1301
+ const frame = this.getFrameRect();
1302
+ const desiredIds = new Set(renderItems.map((item) => item.id));
1303
+ if (this.focusedImageId && !desiredIds.has(this.focusedImageId)) {
1304
+ this.setImageFocus(null, {
1305
+ syncCanvasSelection: false,
1306
+ skipRender: true,
1307
+ });
1308
+ }
1309
+ const imageSpecs = await this.buildImageSpecs(renderItems, frame);
1310
+ if (seq !== this.renderSeq)
1311
+ return;
1312
+ const sceneGeometry = await this.resolveSceneGeometryForOverlay();
1313
+ if (seq !== this.renderSeq)
1314
+ return;
1315
+ this.imageSpecs = imageSpecs;
1316
+ this.overlaySpecs = this.buildOverlaySpecs(frame, sceneGeometry);
1317
+ await this.canvasService.flushRenderFromProducers();
1318
+ if (seq !== this.renderSeq)
1319
+ return;
1320
+ renderItems.forEach((item) => {
1321
+ if (!this.getImageObject(item.id))
1322
+ return;
1323
+ const resolver = this.loadResolvers.get(item.id);
1324
+ if (!resolver)
1325
+ return;
1326
+ resolver();
1327
+ this.loadResolvers.delete(item.id);
1328
+ });
1329
+ if (this.focusedImageId && this.isToolActive) {
1330
+ this.setImageFocus(this.focusedImageId, {
1331
+ syncCanvasSelection: true,
1332
+ skipRender: true,
1333
+ });
1334
+ }
1335
+ const overlayCanvasCount = this.getOverlayObjects().length;
1336
+ this.debug("render:done", {
1337
+ seq,
1338
+ renderCount: renderItems.length,
1339
+ overlayCount: this.overlaySpecs.length,
1340
+ overlayCanvasCount,
1341
+ isToolActive: this.isToolActive,
1342
+ isImageSelectionActive: this.isImageSelectionActive,
1343
+ focusedImageId: this.focusedImageId,
1344
+ });
1345
+ this.canvasService.requestRenderAll();
1346
+ }
1347
+ clampNormalized(value) {
1348
+ return Math.max(-1, Math.min(2, value));
1349
+ }
1350
+ updateImageInWorking(id, updates) {
1351
+ const index = this.workingItems.findIndex((item) => item.id === id);
1352
+ if (index < 0)
1353
+ return;
1354
+ const next = [...this.workingItems];
1355
+ next[index] = this.normalizeItem({ ...next[index], ...updates });
1356
+ this.workingItems = next;
1357
+ this.hasWorkingChanges = true;
1358
+ this.setImageFocus(id, {
1359
+ syncCanvasSelection: false,
1360
+ skipRender: true,
1361
+ });
1362
+ if (this.isToolActive) {
1363
+ this.updateImages();
1364
+ }
1365
+ this.emitWorkingChange(id);
1366
+ }
1367
+ async updateImageInConfig(id, updates) {
1368
+ const index = this.items.findIndex((item) => item.id === id);
1369
+ if (index < 0)
1370
+ return;
1371
+ const replacingSource = typeof updates.url === "string" && updates.url.length > 0;
1372
+ const next = [...this.items];
1373
+ const base = next[index];
1374
+ const replacingUrl = replacingSource ? updates.url : undefined;
1375
+ next[index] = this.normalizeItem({
1376
+ ...base,
1377
+ ...updates,
1378
+ ...(replacingSource
1379
+ ? {
1380
+ url: replacingUrl,
1381
+ sourceUrl: replacingUrl,
1382
+ committedUrl: undefined,
1383
+ scale: updates.scale ?? 1,
1384
+ angle: updates.angle ?? 0,
1385
+ left: updates.left ?? 0.5,
1386
+ top: updates.top ?? 0.5,
1387
+ }
1388
+ : {}),
1389
+ });
1390
+ this.updateConfig(next);
1391
+ if (replacingSource) {
1392
+ this.debug("replace:image:begin", { id, replacingUrl });
1393
+ this.purgeSourceSizeCacheForItem(base);
1394
+ const loaded = await this.waitImageLoaded(id, true);
1395
+ this.debug("replace:image:loaded", { id, loaded });
1396
+ if (loaded) {
1397
+ await this.refitImageToFrame(id);
1398
+ this.setImageFocus(id);
1399
+ }
1400
+ }
1401
+ }
1402
+ waitImageLoaded(id, forceWait = false) {
1403
+ if (!forceWait && this.getImageObject(id)) {
1404
+ return Promise.resolve(true);
1405
+ }
1406
+ return new Promise((resolve) => {
1407
+ const timeout = setTimeout(() => {
1408
+ this.loadResolvers.delete(id);
1409
+ resolve(false);
1410
+ }, 4000);
1411
+ this.loadResolvers.set(id, () => {
1412
+ clearTimeout(timeout);
1413
+ resolve(true);
1414
+ });
1415
+ });
1416
+ }
1417
+ async refitImageToFrame(id) {
1418
+ const obj = this.getImageObject(id);
1419
+ if (!obj || !this.canvasService)
1420
+ return;
1421
+ const current = this.items.find((item) => item.id === id);
1422
+ if (!current)
1423
+ return;
1424
+ const render = this.resolveRenderImageState(current);
1425
+ this.rememberSourceSize(render.src, obj);
1426
+ const source = this.getSourceSize(render.src, obj);
1427
+ const frame = this.getFrameRect();
1428
+ const coverScale = this.getCoverScale(frame, source);
1429
+ const currentScale = this.toSceneObjectScale(obj.scaleX || 1);
1430
+ const zoom = Math.max(0.05, currentScale / coverScale);
1431
+ const updated = {
1432
+ scale: Number.isFinite(zoom) ? zoom : 1,
1433
+ angle: 0,
1434
+ left: 0.5,
1435
+ top: 0.5,
1436
+ };
1437
+ const index = this.items.findIndex((item) => item.id === id);
1438
+ if (index < 0)
1439
+ return;
1440
+ const next = [...this.items];
1441
+ next[index] = this.normalizeItem({ ...next[index], ...updated });
1442
+ this.updateConfig(next);
1443
+ this.workingItems = this.cloneItems(next);
1444
+ this.hasWorkingChanges = false;
1445
+ this.updateImages();
1446
+ this.emitWorkingChange(id);
1447
+ }
1448
+ async fitImageToArea(id, area) {
1449
+ if (!this.canvasService)
1450
+ return;
1451
+ const loaded = await this.waitImageLoaded(id, false);
1452
+ if (!loaded)
1453
+ return;
1454
+ const obj = this.getImageObject(id);
1455
+ if (!obj)
1456
+ return;
1457
+ const renderItems = this.isToolActive ? this.workingItems : this.items;
1458
+ const current = renderItems.find((item) => item.id === id);
1459
+ if (!current)
1460
+ return;
1461
+ const render = this.resolveRenderImageState(current);
1462
+ this.rememberSourceSize(render.src, obj);
1463
+ const source = this.getSourceSize(render.src, obj);
1464
+ const frame = this.getFrameRect();
1465
+ const baseCover = this.getCoverScale(frame, source);
1466
+ const desiredScale = Math.max(Math.max(1, area.width) / Math.max(1, source.width), Math.max(1, area.height) / Math.max(1, source.height));
1467
+ const viewport = this.canvasService.getSceneViewportRect();
1468
+ const canvasW = viewport.width || 1;
1469
+ const canvasH = viewport.height || 1;
1470
+ const areaLeftInput = area.left ?? 0.5;
1471
+ const areaTopInput = area.top ?? 0.5;
1472
+ const areaLeftPx = areaLeftInput <= 1.5
1473
+ ? viewport.left + areaLeftInput * canvasW
1474
+ : areaLeftInput;
1475
+ const areaTopPx = areaTopInput <= 1.5
1476
+ ? viewport.top + areaTopInput * canvasH
1477
+ : areaTopInput;
1478
+ const updates = {
1479
+ scale: Math.max(0.05, desiredScale / baseCover),
1480
+ left: this.clampNormalized((areaLeftPx - frame.left) / Math.max(1, frame.width)),
1481
+ top: this.clampNormalized((areaTopPx - frame.top) / Math.max(1, frame.height)),
1482
+ };
1483
+ if (this.isToolActive) {
1484
+ this.updateImageInWorking(id, updates);
1485
+ return;
1486
+ }
1487
+ await this.updateImageInConfig(id, updates);
1488
+ }
1489
+ async commitWorkingImagesAsCropped() {
1490
+ if (!this.canvasService) {
1491
+ return { ok: false, reason: "canvas-not-ready" };
1492
+ }
1493
+ await this.updateImagesAsync();
1494
+ const frame = this.getFrameRect();
1495
+ if (!frame.width || !frame.height) {
1496
+ return { ok: false, reason: "frame-not-ready" };
1497
+ }
1498
+ const next = [];
1499
+ for (const item of this.workingItems) {
1500
+ const exported = await this.exportCroppedImageByIds([item.id], {
1501
+ multiplier: 2,
1502
+ format: "png",
1503
+ });
1504
+ const url = exported.url;
1505
+ const sourceUrl = item.sourceUrl || item.url;
1506
+ const previousCommitted = item.committedUrl;
1507
+ next.push(this.normalizeItem({
1508
+ ...item,
1509
+ url,
1510
+ // Keep original source for next image-tool session editing,
1511
+ // and use committedUrl as non-image-tools render source.
1512
+ sourceUrl,
1513
+ committedUrl: url,
1514
+ }));
1515
+ if (previousCommitted && previousCommitted !== url) {
1516
+ this.sourceSizeBySrc.delete(previousCommitted);
1517
+ }
1518
+ }
1519
+ this.hasWorkingChanges = false;
1520
+ this.workingItems = this.cloneItems(next);
1521
+ this.updateConfig(next);
1522
+ this.emitWorkingChange(this.focusedImageId);
1523
+ return { ok: true };
1524
+ }
1525
+ async exportCroppedImageByIds(imageIds, options) {
1526
+ if (!this.canvasService) {
1527
+ throw new Error("CanvasService not initialized");
1528
+ }
1529
+ const normalizedIds = [...new Set(imageIds)].filter((id) => typeof id === "string" && id.length > 0);
1530
+ if (!normalizedIds.length) {
1531
+ throw new Error("image-ids-required");
1532
+ }
1533
+ const frameScene = this.getFrameRect();
1534
+ const frame = this.getFrameRectScreen(frameScene);
1535
+ const multiplier = Math.max(1, options.multiplier ?? 2);
1536
+ const format = options.format === "jpeg" ? "jpeg" : "png";
1537
+ const width = Math.max(1, Math.round(frame.width * multiplier));
1538
+ const height = Math.max(1, Math.round(frame.height * multiplier));
1539
+ const el = document.createElement("canvas");
1540
+ const tempCanvas = new fabric_1.Canvas(el, {
1541
+ renderOnAddRemove: false,
1542
+ selection: false,
1543
+ enableRetinaScaling: false,
1544
+ preserveObjectStacking: true,
1545
+ });
1546
+ tempCanvas.setDimensions({ width, height });
1547
+ try {
1548
+ const idSet = new Set(normalizedIds);
1549
+ const sourceObjects = this.canvasService.canvas
1550
+ .getObjects()
1551
+ .filter((obj) => {
1552
+ return (obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID &&
1553
+ typeof obj?.data?.id === "string" &&
1554
+ idSet.has(obj.data.id));
1555
+ });
1556
+ if (!sourceObjects.length) {
1557
+ throw new Error("image-objects-not-found");
1558
+ }
1559
+ for (const source of sourceObjects) {
1560
+ const clone = await source.clone();
1561
+ const center = source.getCenterPoint
1562
+ ? source.getCenterPoint()
1563
+ : new fabric_1.Point(source.left ?? 0, source.top ?? 0);
1564
+ clone.set({
1565
+ originX: "center",
1566
+ originY: "center",
1567
+ left: (center.x - frame.left) * multiplier,
1568
+ top: (center.y - frame.top) * multiplier,
1569
+ scaleX: (source.scaleX || 1) * multiplier,
1570
+ scaleY: (source.scaleY || 1) * multiplier,
1571
+ angle: source.angle || 0,
1572
+ selectable: false,
1573
+ evented: false,
1574
+ });
1575
+ clone.setCoords();
1576
+ tempCanvas.add(clone);
1577
+ }
1578
+ tempCanvas.renderAll();
1579
+ const blob = await tempCanvas.toBlob({ format, multiplier: 1 });
1580
+ if (!blob) {
1581
+ throw new Error("image-export-failed");
1582
+ }
1583
+ return {
1584
+ url: URL.createObjectURL(blob),
1585
+ width,
1586
+ height,
1587
+ multiplier,
1588
+ format,
1589
+ imageIds: sourceObjects
1590
+ .map((obj) => obj?.data?.id)
1591
+ .filter((id) => typeof id === "string"),
1592
+ };
1593
+ }
1594
+ finally {
1595
+ tempCanvas.dispose();
1596
+ }
1597
+ }
1598
+ async exportUserCroppedImage(options = {}) {
1599
+ if (!this.canvasService) {
1600
+ throw new Error("CanvasService not initialized");
1601
+ }
1602
+ await this.updateImagesAsync();
1603
+ this.syncToolActiveFromWorkbench();
1604
+ const imageIds = options.imageIds && options.imageIds.length > 0
1605
+ ? options.imageIds
1606
+ : (this.isToolActive ? this.workingItems : this.items).map((item) => item.id);
1607
+ if (!imageIds.length) {
1608
+ throw new Error("no-images-to-export");
1609
+ }
1610
+ return await this.exportCroppedImageByIds(imageIds, options);
1611
+ }
1612
+ }
1613
+ exports.ImageTool = ImageTool;