@pooder/kit 5.3.1 → 5.4.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 (90) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.d.mts +243 -36
  3. package/dist/index.d.ts +243 -36
  4. package/dist/index.js +2278 -1041
  5. package/dist/index.mjs +2278 -1041
  6. package/package.json +1 -1
  7. package/src/coordinate.ts +106 -106
  8. package/src/extensions/background.ts +323 -230
  9. package/src/extensions/bridgeSelection.ts +17 -17
  10. package/src/extensions/constraints.ts +322 -322
  11. package/src/extensions/dieline.ts +1149 -1076
  12. package/src/extensions/dielineShape.ts +109 -0
  13. package/src/extensions/edgeScale.ts +19 -19
  14. package/src/extensions/feature.ts +1137 -1021
  15. package/src/extensions/featureComplete.ts +46 -46
  16. package/src/extensions/film.ts +266 -194
  17. package/src/extensions/geometry.ts +885 -752
  18. package/src/extensions/image.ts +2054 -1926
  19. package/src/extensions/index.ts +11 -11
  20. package/src/extensions/maskOps.ts +283 -283
  21. package/src/extensions/mirror.ts +128 -128
  22. package/src/extensions/ruler.ts +654 -451
  23. package/src/extensions/sceneLayout.ts +140 -140
  24. package/src/extensions/sceneLayoutModel.ts +364 -352
  25. package/src/extensions/sceneVisibility.ts +64 -71
  26. package/src/extensions/size.ts +389 -389
  27. package/src/extensions/tracer.ts +1019 -1019
  28. package/src/extensions/white-ink.ts +1567 -1514
  29. package/src/extensions/wrappedOffsets.ts +33 -33
  30. package/src/index.ts +2 -2
  31. package/src/services/CanvasService.ts +832 -300
  32. package/src/services/ViewportSystem.ts +95 -95
  33. package/src/services/index.ts +3 -3
  34. package/src/services/renderSpec.ts +53 -18
  35. package/src/units.ts +27 -27
  36. package/tests/run.ts +118 -118
  37. package/tsconfig.test.json +15 -15
  38. package/.test-dist/src/CanvasService.js +0 -249
  39. package/.test-dist/src/ViewportSystem.js +0 -75
  40. package/.test-dist/src/background.js +0 -203
  41. package/.test-dist/src/bridgeSelection.js +0 -20
  42. package/.test-dist/src/constraints.js +0 -237
  43. package/.test-dist/src/coordinate.js +0 -74
  44. package/.test-dist/src/dieline.js +0 -818
  45. package/.test-dist/src/edgeScale.js +0 -12
  46. package/.test-dist/src/extensions/background.js +0 -203
  47. package/.test-dist/src/extensions/bridgeSelection.js +0 -20
  48. package/.test-dist/src/extensions/constraints.js +0 -237
  49. package/.test-dist/src/extensions/dieline.js +0 -828
  50. package/.test-dist/src/extensions/edgeScale.js +0 -12
  51. package/.test-dist/src/extensions/feature.js +0 -825
  52. package/.test-dist/src/extensions/featureComplete.js +0 -32
  53. package/.test-dist/src/extensions/film.js +0 -167
  54. package/.test-dist/src/extensions/geometry.js +0 -545
  55. package/.test-dist/src/extensions/image.js +0 -1529
  56. package/.test-dist/src/extensions/index.js +0 -30
  57. package/.test-dist/src/extensions/maskOps.js +0 -279
  58. package/.test-dist/src/extensions/mirror.js +0 -104
  59. package/.test-dist/src/extensions/ruler.js +0 -345
  60. package/.test-dist/src/extensions/sceneLayout.js +0 -96
  61. package/.test-dist/src/extensions/sceneLayoutModel.js +0 -196
  62. package/.test-dist/src/extensions/sceneVisibility.js +0 -62
  63. package/.test-dist/src/extensions/size.js +0 -331
  64. package/.test-dist/src/extensions/tracer.js +0 -538
  65. package/.test-dist/src/extensions/white-ink.js +0 -1190
  66. package/.test-dist/src/extensions/wrappedOffsets.js +0 -33
  67. package/.test-dist/src/feature.js +0 -826
  68. package/.test-dist/src/featureComplete.js +0 -32
  69. package/.test-dist/src/film.js +0 -167
  70. package/.test-dist/src/geometry.js +0 -506
  71. package/.test-dist/src/image.js +0 -1250
  72. package/.test-dist/src/index.js +0 -18
  73. package/.test-dist/src/maskOps.js +0 -270
  74. package/.test-dist/src/mirror.js +0 -104
  75. package/.test-dist/src/renderSpec.js +0 -2
  76. package/.test-dist/src/ruler.js +0 -343
  77. package/.test-dist/src/sceneLayout.js +0 -99
  78. package/.test-dist/src/sceneLayoutModel.js +0 -196
  79. package/.test-dist/src/sceneView.js +0 -40
  80. package/.test-dist/src/sceneVisibility.js +0 -42
  81. package/.test-dist/src/services/CanvasService.js +0 -249
  82. package/.test-dist/src/services/ViewportSystem.js +0 -76
  83. package/.test-dist/src/services/index.js +0 -24
  84. package/.test-dist/src/services/renderSpec.js +0 -2
  85. package/.test-dist/src/size.js +0 -332
  86. package/.test-dist/src/tracer.js +0 -544
  87. package/.test-dist/src/units.js +0 -30
  88. package/.test-dist/src/white-ink.js +0 -829
  89. package/.test-dist/src/wrappedOffsets.js +0 -33
  90. package/.test-dist/tests/run.js +0 -94
@@ -1,1926 +1,2054 @@
1
- import {
2
- Extension,
3
- ExtensionContext,
4
- ContributionPointIds,
5
- CommandContribution,
6
- ConfigurationContribution,
7
- ConfigurationService,
8
- ToolSessionService,
9
- WorkbenchService,
10
- } from "@pooder/core";
11
- import {
12
- Canvas as FabricCanvas,
13
- Image as FabricImage,
14
- Pattern,
15
- Point,
16
- } from "fabric";
17
- import { CanvasService, RenderObjectSpec } from "../services";
18
- import { generateDielinePath } from "./geometry";
19
- import {
20
- buildSceneGeometry,
21
- computeSceneLayout,
22
- readSizeState,
23
- } from "./sceneLayoutModel";
24
-
25
- export interface ImageItem {
26
- id: string;
27
- url: string;
28
- opacity: number;
29
- scale?: number;
30
- angle?: number;
31
- left?: number;
32
- top?: number;
33
- sourceUrl?: string;
34
- committedUrl?: string;
35
- }
36
-
37
- interface FrameRect {
38
- left: number;
39
- top: number;
40
- width: number;
41
- height: number;
42
- }
43
-
44
- interface SourceSize {
45
- width: number;
46
- height: number;
47
- }
48
-
49
- interface RenderImageState {
50
- src: string;
51
- left: number;
52
- top: number;
53
- scale: number;
54
- angle: number;
55
- opacity: number;
56
- }
57
-
58
- interface FrameVisualConfig {
59
- strokeColor: string;
60
- strokeWidth: number;
61
- strokeStyle: "solid" | "dashed" | "hidden";
62
- dashLength: number;
63
- innerBackground: string;
64
- outerBackground: string;
65
- }
66
-
67
- type DielineShape = "rect" | "circle" | "ellipse" | "custom";
68
- type ShapeOverlayShape = Exclude<DielineShape, "custom">;
69
-
70
- interface SceneGeometryLike {
71
- shape: DielineShape;
72
- radius: number;
73
- offset: number;
74
- }
75
-
76
- interface UpsertImageOptions {
77
- id?: string;
78
- mode?: "replace" | "add";
79
- addOptions?: Partial<ImageItem>;
80
- fitOnAdd?: boolean;
81
- }
82
-
83
- interface DielineFitArea {
84
- width: number;
85
- height: number;
86
- left: number;
87
- top: number;
88
- }
89
-
90
- interface UpdateImageOptions {
91
- target?: "auto" | "config" | "working";
92
- }
93
-
94
- interface ExportCroppedImageOptions {
95
- multiplier?: number;
96
- format?: "png" | "jpeg";
97
- }
98
-
99
- interface ExportUserCroppedImageOptions extends ExportCroppedImageOptions {
100
- imageIds?: string[];
101
- }
102
-
103
- interface ExportUserCroppedImageResult {
104
- url: string;
105
- width: number;
106
- height: number;
107
- multiplier: number;
108
- format: "png" | "jpeg";
109
- imageIds: string[];
110
- }
111
-
112
- const IMAGE_OBJECT_LAYER_ID = "image.user";
113
- const IMAGE_OVERLAY_LAYER_ID = "image-overlay";
114
-
115
- export class ImageTool implements Extension {
116
- id = "pooder.kit.image";
117
-
118
- metadata = {
119
- name: "ImageTool",
120
- };
121
-
122
- private items: ImageItem[] = [];
123
- private workingItems: ImageItem[] = [];
124
- private hasWorkingChanges = false;
125
- private loadResolvers: Map<string, () => void> = new Map();
126
- private sourceSizeBySrc: Map<string, SourceSize> = new Map();
127
- private canvasService?: CanvasService;
128
- private context?: ExtensionContext;
129
- private isUpdatingConfig = false;
130
- private isToolActive = false;
131
- private isImageSelectionActive = false;
132
- private focusedImageId: string | null = null;
133
- private renderSeq = 0;
134
- private dirtyTrackerDisposable?: { dispose(): void };
135
- private cropShapeHatchPattern?: Pattern;
136
- private cropShapeHatchPatternColor?: string;
137
-
138
- activate(context: ExtensionContext) {
139
- this.context = context;
140
- this.canvasService = context.services.get<CanvasService>("CanvasService");
141
- if (!this.canvasService) {
142
- console.warn("CanvasService not found for ImageTool");
143
- return;
144
- }
145
-
146
- context.eventBus.on("tool:activated", this.onToolActivated);
147
- context.eventBus.on("object:modified", this.onObjectModified);
148
- context.eventBus.on("selection:created", this.onSelectionChanged);
149
- context.eventBus.on("selection:updated", this.onSelectionChanged);
150
- context.eventBus.on("selection:cleared", this.onSelectionCleared);
151
- context.eventBus.on("scene:layout:change", this.onSceneLayoutChanged);
152
- context.eventBus.on("scene:geometry:change", this.onSceneGeometryChanged);
153
-
154
- const configService = context.services.get<ConfigurationService>(
155
- "ConfigurationService",
156
- );
157
- if (configService) {
158
- this.items = this.normalizeItems(
159
- configService.get("image.items", []) || [],
160
- );
161
- this.workingItems = this.cloneItems(this.items);
162
- this.hasWorkingChanges = false;
163
-
164
- configService.onAnyChange((e: { key: string; value: any }) => {
165
- if (this.isUpdatingConfig) return;
166
-
167
- if (e.key === "image.items") {
168
- this.items = this.normalizeItems(e.value || []);
169
- if (!this.isToolActive || !this.hasWorkingChanges) {
170
- this.workingItems = this.cloneItems(this.items);
171
- this.hasWorkingChanges = false;
172
- }
173
- this.updateImages();
174
- return;
175
- }
176
-
177
- if (e.key.startsWith("size.") || e.key.startsWith("image.frame.")) {
178
- this.updateImages();
179
- }
180
- });
181
- }
182
-
183
- const toolSessionService =
184
- context.services.get<ToolSessionService>("ToolSessionService");
185
- this.dirtyTrackerDisposable = toolSessionService?.registerDirtyTracker(
186
- this.id,
187
- () => this.hasWorkingChanges,
188
- );
189
-
190
- this.updateImages();
191
- }
192
-
193
- deactivate(context: ExtensionContext) {
194
- context.eventBus.off("tool:activated", this.onToolActivated);
195
- context.eventBus.off("object:modified", this.onObjectModified);
196
- context.eventBus.off("selection:created", this.onSelectionChanged);
197
- context.eventBus.off("selection:updated", this.onSelectionChanged);
198
- context.eventBus.off("selection:cleared", this.onSelectionCleared);
199
- context.eventBus.off("scene:layout:change", this.onSceneLayoutChanged);
200
- context.eventBus.off("scene:geometry:change", this.onSceneGeometryChanged);
201
- this.dirtyTrackerDisposable?.dispose();
202
- this.dirtyTrackerDisposable = undefined;
203
- this.cropShapeHatchPattern = undefined;
204
- this.cropShapeHatchPatternColor = undefined;
205
-
206
- this.clearRenderedImages();
207
- if (this.canvasService) {
208
- void this.canvasService.applyObjectSpecsToRootLayer(
209
- IMAGE_OVERLAY_LAYER_ID,
210
- [],
211
- );
212
- this.canvasService = undefined;
213
- }
214
- this.context = undefined;
215
- }
216
-
217
- private onToolActivated = (event: {
218
- id: string | null;
219
- previous?: string | null;
220
- reason?: string;
221
- }) => {
222
- const before = this.isToolActive;
223
- this.syncToolActiveFromWorkbench(event.id);
224
- if (!this.isToolActive) {
225
- this.setImageFocus(null, {
226
- syncCanvasSelection: true,
227
- skipRender: true,
228
- });
229
- }
230
- this.debug("tool:activated", {
231
- id: event.id,
232
- previous: event.previous,
233
- reason: event.reason,
234
- before,
235
- isToolActive: this.isToolActive,
236
- focusedImageId: this.focusedImageId,
237
- });
238
- if (!this.isToolActive && this.isDebugEnabled()) {
239
- console.trace("[ImageTool] tool deactivated trace");
240
- }
241
- this.updateImages();
242
- };
243
-
244
- private onSelectionChanged = (e: any) => {
245
- const list: any[] = [];
246
- if (Array.isArray(e?.selected)) {
247
- list.push(...e.selected);
248
- }
249
- if (Array.isArray(e?.target?._objects)) {
250
- list.push(...e.target._objects);
251
- }
252
- if (e?.target && !Array.isArray(e?.target?._objects)) {
253
- list.push(e.target);
254
- }
255
-
256
- const selectedImage = list.find(
257
- (obj: any) => obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID,
258
- );
259
- this.isImageSelectionActive = !!selectedImage;
260
- if (selectedImage?.data?.id) {
261
- this.focusedImageId = selectedImage.data.id;
262
- } else if (list.length > 0) {
263
- this.focusedImageId = null;
264
- }
265
- this.debug("selection:changed", {
266
- listSize: list.length,
267
- isImageSelectionActive: this.isImageSelectionActive,
268
- focusedImageId: this.focusedImageId,
269
- });
270
- this.updateImages();
271
- };
272
-
273
- private onSelectionCleared = () => {
274
- this.setImageFocus(null, {
275
- syncCanvasSelection: false,
276
- skipRender: true,
277
- });
278
- this.debug("selection:cleared applied");
279
- this.updateImages();
280
- };
281
-
282
- private onSceneLayoutChanged = () => {
283
- this.updateImages();
284
- };
285
-
286
- private onSceneGeometryChanged = () => {
287
- this.updateImages();
288
- };
289
-
290
- private syncToolActiveFromWorkbench(fallbackId?: string | null) {
291
- const wb = this.context?.services.get<WorkbenchService>("WorkbenchService");
292
- const activeId = wb?.activeToolId;
293
- if (typeof activeId === "string" || activeId === null) {
294
- this.isToolActive = activeId === this.id;
295
- return;
296
- }
297
- this.isToolActive = fallbackId === this.id;
298
- }
299
-
300
- private isImageEditingVisible(): boolean {
301
- return (
302
- this.isToolActive || this.isImageSelectionActive || !!this.focusedImageId
303
- );
304
- }
305
-
306
- private isDebugEnabled(): boolean {
307
- return !!this.getConfig<boolean>("image.debug", false);
308
- }
309
-
310
- private debug(message: string, payload?: any) {
311
- if (!this.isDebugEnabled()) return;
312
- if (payload === undefined) {
313
- console.log(`[ImageTool] ${message}`);
314
- return;
315
- }
316
- console.log(`[ImageTool] ${message}`, payload);
317
- }
318
-
319
- contribute() {
320
- return {
321
- [ContributionPointIds.TOOLS]: [
322
- {
323
- id: this.id,
324
- name: "Image",
325
- interaction: "session",
326
- commands: {
327
- begin: "resetWorkingImages",
328
- commit: "completeImages",
329
- rollback: "resetWorkingImages",
330
- },
331
- session: {
332
- autoBegin: true,
333
- leavePolicy: "block",
334
- },
335
- },
336
- ],
337
- [ContributionPointIds.CONFIGURATIONS]: [
338
- {
339
- id: "image.items",
340
- type: "array",
341
- label: "Images",
342
- default: [],
343
- },
344
- {
345
- id: "image.debug",
346
- type: "boolean",
347
- label: "Image Debug Log",
348
- default: false,
349
- },
350
- {
351
- id: "image.frame.strokeColor",
352
- type: "color",
353
- label: "Image Frame Stroke Color",
354
- default: "#808080",
355
- },
356
- {
357
- id: "image.frame.strokeWidth",
358
- type: "number",
359
- label: "Image Frame Stroke Width",
360
- min: 0,
361
- max: 20,
362
- step: 0.5,
363
- default: 2,
364
- },
365
- {
366
- id: "image.frame.strokeStyle",
367
- type: "select",
368
- label: "Image Frame Stroke Style",
369
- options: ["solid", "dashed", "hidden"],
370
- default: "dashed",
371
- },
372
- {
373
- id: "image.frame.dashLength",
374
- type: "number",
375
- label: "Image Frame Dash Length",
376
- min: 1,
377
- max: 40,
378
- step: 1,
379
- default: 8,
380
- },
381
- {
382
- id: "image.frame.innerBackground",
383
- type: "color",
384
- label: "Image Frame Inner Background",
385
- default: "rgba(0,0,0,0)",
386
- },
387
- {
388
- id: "image.frame.outerBackground",
389
- type: "color",
390
- label: "Image Frame Outer Background",
391
- default: "#f5f5f5",
392
- },
393
- ] as ConfigurationContribution[],
394
- [ContributionPointIds.COMMANDS]: [
395
- {
396
- command: "addImage",
397
- title: "Add Image",
398
- handler: async (url: string, options?: Partial<ImageItem>) => {
399
- const result = await this.upsertImageEntry(url, {
400
- mode: "add",
401
- addOptions: options,
402
- });
403
- return result.id;
404
- },
405
- },
406
- {
407
- command: "upsertImage",
408
- title: "Upsert Image",
409
- handler: async (url: string, options: UpsertImageOptions = {}) => {
410
- return await this.upsertImageEntry(url, options);
411
- },
412
- },
413
- {
414
- command: "getWorkingImages",
415
- title: "Get Working Images",
416
- handler: () => {
417
- return this.cloneItems(this.workingItems);
418
- },
419
- },
420
- {
421
- command: "setWorkingImage",
422
- title: "Set Working Image",
423
- handler: (id: string, updates: Partial<ImageItem>) => {
424
- this.updateImageInWorking(id, updates);
425
- },
426
- },
427
- {
428
- command: "resetWorkingImages",
429
- title: "Reset Working Images",
430
- handler: () => {
431
- this.workingItems = this.cloneItems(this.items);
432
- this.hasWorkingChanges = false;
433
- this.updateImages();
434
- this.emitWorkingChange();
435
- },
436
- },
437
- {
438
- command: "completeImages",
439
- title: "Complete Images",
440
- handler: async () => {
441
- return await this.commitWorkingImagesAsCropped();
442
- },
443
- },
444
- {
445
- command: "exportUserCroppedImage",
446
- title: "Export User Cropped Image",
447
- handler: async (options: ExportUserCroppedImageOptions = {}) => {
448
- return await this.exportUserCroppedImage(options);
449
- },
450
- },
451
- {
452
- command: "fitImageToArea",
453
- title: "Fit Image to Area",
454
- handler: async (
455
- id: string,
456
- area: {
457
- width: number;
458
- height: number;
459
- left?: number;
460
- top?: number;
461
- },
462
- ) => {
463
- await this.fitImageToArea(id, area);
464
- },
465
- },
466
- {
467
- command: "fitImageToDefaultArea",
468
- title: "Fit Image to Default Area",
469
- handler: async (id: string) => {
470
- await this.fitImageToDefaultArea(id);
471
- },
472
- },
473
- {
474
- command: "focusImage",
475
- title: "Focus Image",
476
- handler: (
477
- id: string | null,
478
- options: { syncCanvasSelection?: boolean } = {},
479
- ) => {
480
- return this.setImageFocus(id, options);
481
- },
482
- },
483
- {
484
- command: "removeImage",
485
- title: "Remove Image",
486
- handler: (id: string) => {
487
- const removed = this.items.find((item) => item.id === id);
488
- const next = this.items.filter((item) => item.id !== id);
489
- if (next.length !== this.items.length) {
490
- this.purgeSourceSizeCacheForItem(removed);
491
- if (this.focusedImageId === id) {
492
- this.setImageFocus(null, {
493
- syncCanvasSelection: true,
494
- skipRender: true,
495
- });
496
- }
497
- this.updateConfig(next);
498
- }
499
- },
500
- },
501
- {
502
- command: "updateImage",
503
- title: "Update Image",
504
- handler: async (
505
- id: string,
506
- updates: Partial<ImageItem>,
507
- options: UpdateImageOptions = {},
508
- ) => {
509
- await this.updateImage(id, updates, options);
510
- },
511
- },
512
- {
513
- command: "clearImages",
514
- title: "Clear Images",
515
- handler: () => {
516
- this.sourceSizeBySrc.clear();
517
- this.setImageFocus(null, {
518
- syncCanvasSelection: true,
519
- skipRender: true,
520
- });
521
- this.updateConfig([]);
522
- },
523
- },
524
- {
525
- command: "bringToFront",
526
- title: "Bring Image to Front",
527
- handler: (id: string) => {
528
- const index = this.items.findIndex((item) => item.id === id);
529
- if (index !== -1 && index < this.items.length - 1) {
530
- const next = [...this.items];
531
- const [item] = next.splice(index, 1);
532
- next.push(item);
533
- this.updateConfig(next);
534
- }
535
- },
536
- },
537
- {
538
- command: "sendToBack",
539
- title: "Send Image to Back",
540
- handler: (id: string) => {
541
- const index = this.items.findIndex((item) => item.id === id);
542
- if (index > 0) {
543
- const next = [...this.items];
544
- const [item] = next.splice(index, 1);
545
- next.unshift(item);
546
- this.updateConfig(next);
547
- }
548
- },
549
- },
550
- ] as CommandContribution[],
551
- };
552
- }
553
-
554
- private normalizeItem(item: ImageItem): ImageItem {
555
- const url = typeof item.url === "string" ? item.url : "";
556
- const sourceUrl =
557
- typeof item.sourceUrl === "string" && item.sourceUrl.length > 0
558
- ? item.sourceUrl
559
- : url;
560
- const committedUrl =
561
- typeof item.committedUrl === "string" && item.committedUrl.length > 0
562
- ? item.committedUrl
563
- : undefined;
564
-
565
- return {
566
- ...item,
567
- url: url || sourceUrl,
568
- sourceUrl,
569
- committedUrl,
570
- opacity: Number.isFinite(item.opacity as any) ? item.opacity : 1,
571
- scale: Number.isFinite(item.scale as any) ? item.scale : 1,
572
- angle: Number.isFinite(item.angle as any) ? item.angle : 0,
573
- left: Number.isFinite(item.left as any) ? item.left : 0.5,
574
- top: Number.isFinite(item.top as any) ? item.top : 0.5,
575
- };
576
- }
577
-
578
- private normalizeItems(items: ImageItem[]): ImageItem[] {
579
- return (items || []).map((item) => this.normalizeItem(item));
580
- }
581
-
582
- private cloneItems(items: ImageItem[]): ImageItem[] {
583
- return this.normalizeItems((items || []).map((i) => ({ ...i })));
584
- }
585
-
586
- private emitWorkingChange(changedId: string | null = null) {
587
- this.context?.eventBus.emit("image:working:change", {
588
- changedId,
589
- items: this.cloneItems(this.workingItems),
590
- });
591
- }
592
-
593
- private generateId(): string {
594
- return Math.random().toString(36).substring(2, 9);
595
- }
596
-
597
- private hasImageItem(id: string): boolean {
598
- return (
599
- this.items.some((item) => item.id === id) ||
600
- this.workingItems.some((item) => item.id === id)
601
- );
602
- }
603
-
604
- private setImageFocus(
605
- id: string | null,
606
- options: { syncCanvasSelection?: boolean; skipRender?: boolean } = {},
607
- ) {
608
- const syncCanvasSelection = options.syncCanvasSelection !== false;
609
-
610
- if (id && !this.hasImageItem(id)) {
611
- return { ok: false, reason: "image-not-found" as const };
612
- }
613
-
614
- this.focusedImageId = id;
615
- this.isImageSelectionActive = !!id;
616
-
617
- if (syncCanvasSelection && this.canvasService) {
618
- const canvas = this.canvasService.canvas;
619
- if (!id) {
620
- canvas.discardActiveObject();
621
- } else {
622
- const obj = this.getImageObject(id);
623
- if (obj) {
624
- obj.set({
625
- selectable: true,
626
- evented: true,
627
- hasControls: true,
628
- hasBorders: true,
629
- });
630
- canvas.setActiveObject(obj);
631
- }
632
- }
633
- this.canvasService.requestRenderAll();
634
- }
635
-
636
- if (!options.skipRender) {
637
- this.updateImages();
638
- }
639
-
640
- return { ok: true, id };
641
- }
642
-
643
- private async addImageEntry(
644
- url: string,
645
- options?: Partial<ImageItem>,
646
- fitOnAdd = true,
647
- ): Promise<string> {
648
- const id = this.generateId();
649
- const newItem = this.normalizeItem({
650
- id,
651
- url,
652
- opacity: 1,
653
- ...options,
654
- } as ImageItem);
655
-
656
- const sessionDirtyBeforeAdd = this.isToolActive && this.hasWorkingChanges;
657
- const waitLoaded = this.waitImageLoaded(id, true);
658
- this.updateConfig([...this.items, newItem]);
659
- this.addItemToWorkingSessionIfNeeded(newItem, sessionDirtyBeforeAdd);
660
- const loaded = await waitLoaded;
661
- if (loaded && fitOnAdd) {
662
- await this.fitImageToDefaultArea(id);
663
- }
664
- if (loaded) {
665
- this.setImageFocus(id);
666
- }
667
- return id;
668
- }
669
-
670
- private async upsertImageEntry(
671
- url: string,
672
- options: UpsertImageOptions = {},
673
- ): Promise<{ id: string; mode: "replace" | "add" }> {
674
- const mode = options.mode || (options.id ? "replace" : "add");
675
- const fitOnAdd = options.fitOnAdd !== false;
676
- if (mode === "replace") {
677
- if (!options.id) {
678
- throw new Error("replace-target-id-required");
679
- }
680
- const targetId = options.id;
681
- if (!this.hasImageItem(targetId)) {
682
- throw new Error("replace-target-not-found");
683
- }
684
- await this.updateImageInConfig(targetId, { url });
685
- return { id: targetId, mode: "replace" };
686
- }
687
-
688
- const id = await this.addImageEntry(url, options.addOptions, fitOnAdd);
689
- return { id, mode: "add" };
690
- }
691
-
692
- private addItemToWorkingSessionIfNeeded(
693
- item: ImageItem,
694
- sessionDirtyBeforeAdd: boolean,
695
- ) {
696
- if (!sessionDirtyBeforeAdd || !this.isToolActive) return;
697
- if (this.workingItems.some((existing) => existing.id === item.id)) return;
698
- this.workingItems = this.cloneItems([...this.workingItems, item]);
699
- this.updateImages();
700
- this.emitWorkingChange(item.id);
701
- }
702
-
703
- private async updateImage(
704
- id: string,
705
- updates: Partial<ImageItem>,
706
- options: UpdateImageOptions = {},
707
- ) {
708
- this.syncToolActiveFromWorkbench();
709
- const target = options.target || "auto";
710
-
711
- if (target === "working" || (target === "auto" && this.isToolActive)) {
712
- this.updateImageInWorking(id, updates);
713
- return;
714
- }
715
-
716
- await this.updateImageInConfig(id, updates);
717
- }
718
-
719
- private getConfig<T>(key: string, fallback?: T): T | undefined {
720
- if (!this.context) return fallback;
721
- const configService = this.context.services.get<ConfigurationService>(
722
- "ConfigurationService",
723
- );
724
- if (!configService) return fallback;
725
- return (configService.get(key, fallback) as T) ?? fallback;
726
- }
727
-
728
- private updateConfig(newItems: ImageItem[], skipCanvasUpdate = false) {
729
- if (!this.context) return;
730
-
731
- this.isUpdatingConfig = true;
732
- this.items = this.normalizeItems(newItems);
733
- if (!this.isToolActive || !this.hasWorkingChanges) {
734
- this.workingItems = this.cloneItems(this.items);
735
- this.hasWorkingChanges = false;
736
- }
737
-
738
- const configService = this.context.services.get<ConfigurationService>(
739
- "ConfigurationService",
740
- );
741
- configService?.update("image.items", this.items);
742
-
743
- if (!skipCanvasUpdate) {
744
- this.updateImages();
745
- }
746
-
747
- setTimeout(() => {
748
- this.isUpdatingConfig = false;
749
- }, 50);
750
- }
751
-
752
- private getFrameRect(): FrameRect {
753
- if (!this.canvasService) {
754
- return { left: 0, top: 0, width: 0, height: 0 };
755
- }
756
- const configService = this.context?.services.get<ConfigurationService>(
757
- "ConfigurationService",
758
- );
759
- if (!configService) {
760
- return { left: 0, top: 0, width: 0, height: 0 };
761
- }
762
-
763
- const sizeState = readSizeState(configService);
764
- const layout = computeSceneLayout(this.canvasService, sizeState);
765
- if (!layout) {
766
- return { left: 0, top: 0, width: 0, height: 0 };
767
- }
768
-
769
- return {
770
- left: layout.cutRect.left,
771
- top: layout.cutRect.top,
772
- width: layout.cutRect.width,
773
- height: layout.cutRect.height,
774
- };
775
- }
776
-
777
- private async resolveDefaultFitArea(): Promise<DielineFitArea | null> {
778
- if (!this.context || !this.canvasService) return null;
779
- const commandService = this.context.services.get<any>("CommandService");
780
- if (!commandService) return null;
781
-
782
- try {
783
- const layout = await Promise.resolve(
784
- commandService.executeCommand("getSceneLayout"),
785
- );
786
- const cutRect = layout?.cutRect;
787
- const width = Number(cutRect?.width);
788
- const height = Number(cutRect?.height);
789
- const left = Number(cutRect?.left);
790
- const top = Number(cutRect?.top);
791
-
792
- if (
793
- !Number.isFinite(width) ||
794
- !Number.isFinite(height) ||
795
- !Number.isFinite(left) ||
796
- !Number.isFinite(top)
797
- ) {
798
- return null;
799
- }
800
-
801
- return {
802
- width: Math.max(1, width),
803
- height: Math.max(1, height),
804
- left: left + width / 2,
805
- top: top + height / 2,
806
- };
807
- } catch {
808
- return null;
809
- }
810
- }
811
-
812
- private async fitImageToDefaultArea(id: string) {
813
- if (!this.canvasService) return;
814
- const area = await this.resolveDefaultFitArea();
815
-
816
- if (area) {
817
- await this.fitImageToArea(id, area);
818
- return;
819
- }
820
-
821
- const canvasW = Math.max(1, this.canvasService.canvas.width || 0);
822
- const canvasH = Math.max(1, this.canvasService.canvas.height || 0);
823
- await this.fitImageToArea(id, {
824
- width: canvasW,
825
- height: canvasH,
826
- left: canvasW / 2,
827
- top: canvasH / 2,
828
- });
829
- }
830
-
831
- private getImageObjects(): any[] {
832
- if (!this.canvasService) return [];
833
- return this.canvasService.canvas.getObjects().filter((obj: any) => {
834
- return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
835
- }) as any[];
836
- }
837
-
838
- private getOverlayObjects(): any[] {
839
- if (!this.canvasService) return [];
840
- return this.canvasService.getRootLayerObjects(
841
- IMAGE_OVERLAY_LAYER_ID,
842
- ) as any[];
843
- }
844
-
845
- private getImageObject(id: string): any | undefined {
846
- return this.getImageObjects().find((obj: any) => obj?.data?.id === id);
847
- }
848
-
849
- private clearRenderedImages() {
850
- if (!this.canvasService) return;
851
- const canvas = this.canvasService.canvas;
852
- this.getImageObjects().forEach((obj) => canvas.remove(obj));
853
- this.canvasService.requestRenderAll();
854
- }
855
-
856
- private purgeSourceSizeCacheForItem(item?: ImageItem) {
857
- if (!item) return;
858
- const sources = [item.url, item.sourceUrl, item.committedUrl].filter(
859
- (value): value is string => typeof value === "string" && value.length > 0,
860
- );
861
- sources.forEach((src) => this.sourceSizeBySrc.delete(src));
862
- }
863
-
864
- private rememberSourceSize(src: string, obj: any) {
865
- const width = Number(obj?.width || 0);
866
- const height = Number(obj?.height || 0);
867
- if (src && width > 0 && height > 0) {
868
- this.sourceSizeBySrc.set(src, { width, height });
869
- }
870
- }
871
-
872
- private getSourceSize(src: string, obj?: any): SourceSize {
873
- const cached = src ? this.sourceSizeBySrc.get(src) : undefined;
874
- if (cached) return cached;
875
-
876
- const width = Number(obj?.width || 0);
877
- const height = Number(obj?.height || 0);
878
- if (src && width > 0 && height > 0) {
879
- const size = { width, height };
880
- this.sourceSizeBySrc.set(src, size);
881
- return size;
882
- }
883
-
884
- return { width: 1, height: 1 };
885
- }
886
-
887
- private getCoverScale(frame: FrameRect, size: SourceSize): number {
888
- const sw = Math.max(1, size.width);
889
- const sh = Math.max(1, size.height);
890
- const fw = Math.max(1, frame.width);
891
- const fh = Math.max(1, frame.height);
892
- return Math.max(fw / sw, fh / sh);
893
- }
894
-
895
- private getFrameVisualConfig(): FrameVisualConfig {
896
- const strokeStyleRaw = (this.getConfig<string>(
897
- "image.frame.strokeStyle",
898
- "dashed",
899
- ) || "dashed") as string;
900
- const strokeStyle: "solid" | "dashed" | "hidden" =
901
- strokeStyleRaw === "dashed" || strokeStyleRaw === "hidden"
902
- ? strokeStyleRaw
903
- : "dashed";
904
-
905
- const strokeWidth = Number(
906
- this.getConfig<number>("image.frame.strokeWidth", 2) ?? 2,
907
- );
908
- const dashLength = Number(
909
- this.getConfig<number>("image.frame.dashLength", 8) ?? 8,
910
- );
911
-
912
- return {
913
- strokeColor:
914
- this.getConfig<string>("image.frame.strokeColor", "#808080") ||
915
- "#808080",
916
- strokeWidth: Number.isFinite(strokeWidth) ? Math.max(0, strokeWidth) : 2,
917
- strokeStyle,
918
- dashLength: Number.isFinite(dashLength) ? Math.max(1, dashLength) : 8,
919
- innerBackground:
920
- this.getConfig<string>(
921
- "image.frame.innerBackground",
922
- "rgba(0,0,0,0)",
923
- ) || "rgba(0,0,0,0)",
924
- outerBackground:
925
- this.getConfig<string>("image.frame.outerBackground", "#f5f5f5") ||
926
- "#f5f5f5",
927
- };
928
- }
929
-
930
- private toSceneGeometryLike(raw: any): SceneGeometryLike | null {
931
- const shape = raw?.shape;
932
- if (
933
- shape !== "rect" &&
934
- shape !== "circle" &&
935
- shape !== "ellipse" &&
936
- shape !== "custom"
937
- ) {
938
- return null;
939
- }
940
-
941
- const radius = Number(raw?.radius);
942
- const offset = Number(raw?.offset);
943
- return {
944
- shape,
945
- radius: Number.isFinite(radius) ? radius : 0,
946
- offset: Number.isFinite(offset) ? offset : 0,
947
- };
948
- }
949
-
950
- private async resolveSceneGeometryForOverlay(): Promise<SceneGeometryLike | null> {
951
- if (!this.context) return null;
952
- const commandService = this.context.services.get<any>("CommandService");
953
- if (commandService) {
954
- try {
955
- const raw = await Promise.resolve(
956
- commandService.executeCommand("getSceneGeometry"),
957
- );
958
- const geometry = this.toSceneGeometryLike(raw);
959
- if (geometry) {
960
- this.debug("overlay:sceneGeometry:command", geometry);
961
- return geometry;
962
- }
963
- this.debug("overlay:sceneGeometry:command:invalid", { raw });
964
- } catch (error) {
965
- this.debug("overlay:sceneGeometry:command:error", {
966
- error: error instanceof Error ? error.message : String(error),
967
- });
968
- }
969
- }
970
-
971
- if (!this.canvasService) return null;
972
- const configService = this.context.services.get<ConfigurationService>(
973
- "ConfigurationService",
974
- );
975
- if (!configService) return null;
976
-
977
- const sizeState = readSizeState(configService);
978
- const layout = computeSceneLayout(this.canvasService, sizeState);
979
- if (!layout) {
980
- this.debug("overlay:sceneGeometry:fallback:missing-layout");
981
- return null;
982
- }
983
-
984
- const geometry = this.toSceneGeometryLike(
985
- buildSceneGeometry(configService, layout),
986
- );
987
- if (geometry) {
988
- this.debug("overlay:sceneGeometry:fallback", geometry);
989
- }
990
- return geometry;
991
- }
992
-
993
- private resolveCutShapeRadius(
994
- geometry: SceneGeometryLike,
995
- frame: FrameRect,
996
- ): number {
997
- const visualRadius = Number.isFinite(geometry.radius)
998
- ? Math.max(0, geometry.radius)
999
- : 0;
1000
- const visualOffset = Number.isFinite(geometry.offset) ? geometry.offset : 0;
1001
- const rawCutRadius =
1002
- visualRadius === 0 ? 0 : Math.max(0, visualRadius + visualOffset);
1003
- const maxRadius = Math.max(0, Math.min(frame.width, frame.height) / 2);
1004
- return Math.max(0, Math.min(maxRadius, rawCutRadius));
1005
- }
1006
-
1007
- private getCropShapeHatchPattern(
1008
- color = "rgba(255, 0, 0, 0.6)",
1009
- ): Pattern | undefined {
1010
- if (typeof document === "undefined") return undefined;
1011
- if (
1012
- this.cropShapeHatchPattern &&
1013
- this.cropShapeHatchPatternColor === color
1014
- ) {
1015
- return this.cropShapeHatchPattern;
1016
- }
1017
-
1018
- const size = 16;
1019
- const patternCanvas = document.createElement("canvas");
1020
- patternCanvas.width = size;
1021
- patternCanvas.height = size;
1022
- const ctx = patternCanvas.getContext("2d");
1023
- if (!ctx) return undefined;
1024
-
1025
- ctx.clearRect(0, 0, size, size);
1026
- ctx.fillStyle = "rgba(255, 0, 0, 0.08)";
1027
- ctx.fillRect(0, 0, size, size);
1028
- ctx.strokeStyle = color;
1029
- ctx.lineWidth = 1.5;
1030
- ctx.beginPath();
1031
- ctx.moveTo(-size, size);
1032
- ctx.lineTo(size, -size);
1033
- ctx.moveTo(-size / 2, size + size / 2);
1034
- ctx.lineTo(size + size / 2, -size / 2);
1035
- ctx.moveTo(0, size);
1036
- ctx.lineTo(size, 0);
1037
- ctx.moveTo(size / 2, size + size / 2);
1038
- ctx.lineTo(size + size + size / 2, -size / 2);
1039
- ctx.stroke();
1040
-
1041
- const pattern = new Pattern({
1042
- source: patternCanvas,
1043
- // @ts-ignore: Fabric Pattern accepts canvas source here.
1044
- repetition: "repeat",
1045
- });
1046
- this.cropShapeHatchPattern = pattern;
1047
- this.cropShapeHatchPatternColor = color;
1048
- return pattern;
1049
- }
1050
-
1051
- private buildCropShapeOverlaySpecs(
1052
- frame: FrameRect,
1053
- sceneGeometry: SceneGeometryLike | null,
1054
- ): RenderObjectSpec[] {
1055
- if (!sceneGeometry) {
1056
- this.debug("overlay:shape:skip", { reason: "scene-geometry-missing" });
1057
- return [];
1058
- }
1059
- if (sceneGeometry.shape === "custom") {
1060
- this.debug("overlay:shape:skip", { reason: "shape-custom" });
1061
- return [];
1062
- }
1063
-
1064
- const shape = sceneGeometry.shape as ShapeOverlayShape;
1065
- const inset = 0;
1066
- const shapeWidth = Math.max(1, frame.width);
1067
- const shapeHeight = Math.max(1, frame.height);
1068
- const radius = this.resolveCutShapeRadius(sceneGeometry, frame);
1069
-
1070
- this.debug("overlay:shape:geometry", {
1071
- shape,
1072
- frameWidth: frame.width,
1073
- frameHeight: frame.height,
1074
- offset: sceneGeometry.offset,
1075
- inset,
1076
- shapeWidth,
1077
- shapeHeight,
1078
- baseRadius: sceneGeometry.radius,
1079
- radius,
1080
- });
1081
-
1082
- const isSameAsFrame =
1083
- Math.abs(shapeWidth - frame.width) <= 0.0001 &&
1084
- Math.abs(shapeHeight - frame.height) <= 0.0001;
1085
- if (shape === "rect" && radius <= 0.0001 && isSameAsFrame) {
1086
- this.debug("overlay:shape:skip", {
1087
- reason: "shape-rect-no-radius",
1088
- });
1089
- return [];
1090
- }
1091
-
1092
- const baseOptions = {
1093
- shape,
1094
- width: shapeWidth,
1095
- height: shapeHeight,
1096
- radius,
1097
- x: frame.width / 2,
1098
- y: frame.height / 2,
1099
- features: [],
1100
- canvasWidth: frame.width,
1101
- canvasHeight: frame.height,
1102
- };
1103
-
1104
- try {
1105
- const shapePathData = generateDielinePath(baseOptions);
1106
- const outerRectPathData = `M 0 0 L ${frame.width} 0 L ${frame.width} ${frame.height} L 0 ${frame.height} Z`;
1107
- const hatchPathData = `${outerRectPathData} ${shapePathData}`;
1108
- if (!shapePathData || !hatchPathData) {
1109
- this.debug("overlay:shape:skip", {
1110
- reason: "path-generation-empty",
1111
- shape,
1112
- radius,
1113
- });
1114
- return [];
1115
- }
1116
-
1117
- const patternFill = this.getCropShapeHatchPattern();
1118
- const hatchFill = patternFill || "rgba(255, 0, 0, 0.22)";
1119
- const hatchPathLength = hatchPathData.length;
1120
- const shapePathLength = shapePathData.length;
1121
- const specs: RenderObjectSpec[] = [
1122
- {
1123
- id: "image.cropShapeHatch",
1124
- type: "path",
1125
- data: { id: "image.cropShapeHatch", zIndex: 5 },
1126
- props: {
1127
- pathData: hatchPathData,
1128
- left: frame.left,
1129
- top: frame.top,
1130
- originX: "left",
1131
- originY: "top",
1132
- fill: hatchFill,
1133
- opacity: patternFill ? 1 : 0.8,
1134
- stroke: null,
1135
- fillRule: "evenodd",
1136
- selectable: false,
1137
- evented: false,
1138
- excludeFromExport: true,
1139
- objectCaching: false,
1140
- },
1141
- },
1142
- {
1143
- id: "image.cropShapePath",
1144
- type: "path",
1145
- data: { id: "image.cropShapePath", zIndex: 6 },
1146
- props: {
1147
- pathData: shapePathData,
1148
- left: frame.left,
1149
- top: frame.top,
1150
- originX: "left",
1151
- originY: "top",
1152
- fill: "rgba(0,0,0,0)",
1153
- stroke: "rgba(255, 0, 0, 0.9)",
1154
- strokeWidth: 1,
1155
- selectable: false,
1156
- evented: false,
1157
- excludeFromExport: true,
1158
- objectCaching: false,
1159
- },
1160
- },
1161
- ];
1162
- this.debug("overlay:shape:built", {
1163
- shape,
1164
- radius,
1165
- inset,
1166
- shapeWidth,
1167
- shapeHeight,
1168
- fillRule: "evenodd",
1169
- shapePathLength,
1170
- hatchPathLength,
1171
- hatchFillType:
1172
- hatchFill && typeof hatchFill === "object" ? "pattern" : "color",
1173
- ids: specs.map((spec) => spec.id),
1174
- });
1175
- return specs;
1176
- } catch (error) {
1177
- this.debug("overlay:shape:error", {
1178
- shape,
1179
- radius,
1180
- error: error instanceof Error ? error.message : String(error),
1181
- });
1182
- return [];
1183
- }
1184
- }
1185
-
1186
- private resolveRenderImageState(item: ImageItem): RenderImageState {
1187
- const active = this.isToolActive;
1188
- const sourceUrl = item.sourceUrl || item.url;
1189
- const committedUrl = item.committedUrl;
1190
-
1191
- if (!active && committedUrl) {
1192
- return {
1193
- src: committedUrl,
1194
- left: 0.5,
1195
- top: 0.5,
1196
- scale: 1,
1197
- angle: 0,
1198
- opacity: item.opacity,
1199
- };
1200
- }
1201
-
1202
- return {
1203
- src: sourceUrl || item.url,
1204
- left: Number.isFinite(item.left as any) ? (item.left as number) : 0.5,
1205
- top: Number.isFinite(item.top as any) ? (item.top as number) : 0.5,
1206
- scale: Math.max(0.05, item.scale ?? 1),
1207
- angle: Number.isFinite(item.angle as any) ? (item.angle as number) : 0,
1208
- opacity: item.opacity,
1209
- };
1210
- }
1211
-
1212
- private computeCanvasProps(
1213
- render: RenderImageState,
1214
- size: SourceSize,
1215
- frame: FrameRect,
1216
- ) {
1217
- const left = render.left;
1218
- const top = render.top;
1219
- const zoom = render.scale;
1220
- const angle = render.angle;
1221
-
1222
- const centerX = frame.left + left * frame.width;
1223
- const centerY = frame.top + top * frame.height;
1224
- const scale = this.getCoverScale(frame, size) * zoom;
1225
-
1226
- return {
1227
- left: centerX,
1228
- top: centerY,
1229
- scaleX: scale,
1230
- scaleY: scale,
1231
- angle,
1232
- originX: "center" as const,
1233
- originY: "center" as const,
1234
- uniformScaling: true,
1235
- lockScalingFlip: true,
1236
- selectable: this.isImageEditingVisible(),
1237
- evented: this.isImageEditingVisible(),
1238
- hasControls: this.isImageEditingVisible(),
1239
- hasBorders: this.isImageEditingVisible(),
1240
- opacity: render.opacity,
1241
- };
1242
- }
1243
-
1244
- private getCurrentSrc(obj: any): string | undefined {
1245
- if (!obj) return undefined;
1246
- if (typeof obj.getSrc === "function") return obj.getSrc();
1247
- return obj?._originalElement?.src;
1248
- }
1249
-
1250
- private applyImageControlVisibility(obj: any) {
1251
- if (typeof obj?.setControlsVisibility !== "function") return;
1252
- obj.setControlsVisibility({
1253
- mt: false,
1254
- mb: false,
1255
- ml: false,
1256
- mr: false,
1257
- tl: true,
1258
- tr: true,
1259
- bl: true,
1260
- br: true,
1261
- mtr: true,
1262
- });
1263
- }
1264
-
1265
- private async upsertImageObject(
1266
- item: ImageItem,
1267
- frame: FrameRect,
1268
- seq: number,
1269
- ) {
1270
- if (!this.canvasService) return;
1271
- const canvas = this.canvasService.canvas;
1272
- const render = this.resolveRenderImageState(item);
1273
- if (!render.src) return;
1274
-
1275
- let obj = this.getImageObject(item.id);
1276
- const currentSrc = this.getCurrentSrc(obj);
1277
-
1278
- if (obj && currentSrc && currentSrc !== render.src) {
1279
- canvas.remove(obj);
1280
- obj = undefined;
1281
- }
1282
-
1283
- if (!obj) {
1284
- const created = await FabricImage.fromURL(render.src, {
1285
- crossOrigin: "anonymous",
1286
- });
1287
- if (seq !== this.renderSeq) return;
1288
-
1289
- created.set({
1290
- data: {
1291
- id: item.id,
1292
- layerId: IMAGE_OBJECT_LAYER_ID,
1293
- type: "image-item",
1294
- },
1295
- } as any);
1296
- canvas.add(created as any);
1297
- obj = created as any;
1298
- }
1299
-
1300
- this.rememberSourceSize(render.src, obj);
1301
- const sourceSize = this.getSourceSize(render.src, obj);
1302
- const props = this.computeCanvasProps(render, sourceSize, frame);
1303
-
1304
- obj.set({
1305
- ...props,
1306
- data: {
1307
- ...(obj.data || {}),
1308
- id: item.id,
1309
- layerId: IMAGE_OBJECT_LAYER_ID,
1310
- type: "image-item",
1311
- },
1312
- });
1313
- this.applyImageControlVisibility(obj);
1314
- obj.setCoords();
1315
-
1316
- const resolver = this.loadResolvers.get(item.id);
1317
- if (resolver) {
1318
- resolver();
1319
- this.loadResolvers.delete(item.id);
1320
- }
1321
- }
1322
-
1323
- private syncImageZOrder(items: ImageItem[]) {
1324
- if (!this.canvasService) return;
1325
- const canvas = this.canvasService.canvas;
1326
-
1327
- const objects = canvas.getObjects();
1328
- let insertIndex = 0;
1329
-
1330
- const backgroundLayer = this.canvasService.getLayer("background");
1331
- if (backgroundLayer) {
1332
- const bgIndex = objects.indexOf(backgroundLayer as any);
1333
- if (bgIndex >= 0) insertIndex = bgIndex + 1;
1334
- }
1335
-
1336
- items.forEach((item) => {
1337
- const obj = this.getImageObject(item.id);
1338
- if (!obj) return;
1339
- canvas.moveObjectTo(obj, insertIndex);
1340
- insertIndex += 1;
1341
- });
1342
-
1343
- const overlayObjects = this.getOverlayObjects().sort((a: any, b: any) => {
1344
- const az = Number(a?.data?.zIndex ?? 0);
1345
- const bz = Number(b?.data?.zIndex ?? 0);
1346
- return az - bz;
1347
- });
1348
- overlayObjects.forEach((obj) => {
1349
- canvas.bringObjectToFront(obj);
1350
- });
1351
-
1352
- if (this.isDebugEnabled()) {
1353
- const stack = canvas
1354
- .getObjects()
1355
- .map((obj: any, index: number) => ({
1356
- index,
1357
- id: obj?.data?.id,
1358
- layerId: obj?.data?.layerId,
1359
- zIndex: obj?.data?.zIndex,
1360
- }))
1361
- .filter((item) => item.layerId === IMAGE_OVERLAY_LAYER_ID);
1362
- this.debug("overlay:stack", stack);
1363
- }
1364
- }
1365
-
1366
- private buildOverlaySpecs(
1367
- frame: FrameRect,
1368
- sceneGeometry: SceneGeometryLike | null,
1369
- ): RenderObjectSpec[] {
1370
- const visible = this.isImageEditingVisible();
1371
- if (
1372
- !visible ||
1373
- frame.width <= 0 ||
1374
- frame.height <= 0 ||
1375
- !this.canvasService
1376
- ) {
1377
- this.debug("overlay:hidden", {
1378
- visible,
1379
- frame,
1380
- isToolActive: this.isToolActive,
1381
- isImageSelectionActive: this.isImageSelectionActive,
1382
- focusedImageId: this.focusedImageId,
1383
- });
1384
- return [];
1385
- }
1386
-
1387
- const canvasW = this.canvasService.canvas.width || 0;
1388
- const canvasH = this.canvasService.canvas.height || 0;
1389
- const visual = this.getFrameVisualConfig();
1390
-
1391
- const frameLeft = Math.max(0, Math.min(canvasW, frame.left));
1392
- const frameTop = Math.max(0, Math.min(canvasH, frame.top));
1393
- const frameRight = Math.max(
1394
- frameLeft,
1395
- Math.min(canvasW, frame.left + frame.width),
1396
- );
1397
- const frameBottom = Math.max(
1398
- frameTop,
1399
- Math.min(canvasH, frame.top + frame.height),
1400
- );
1401
- const visibleFrameH = Math.max(0, frameBottom - frameTop);
1402
-
1403
- const topH = frameTop;
1404
- const bottomH = Math.max(0, canvasH - frameBottom);
1405
- const leftW = frameLeft;
1406
- const rightW = Math.max(0, canvasW - frameRight);
1407
- const shapeOverlay = this.buildCropShapeOverlaySpecs(frame, sceneGeometry);
1408
-
1409
- const mask: RenderObjectSpec[] = [
1410
- {
1411
- id: "image.cropMask.top",
1412
- type: "rect",
1413
- data: { id: "image.cropMask.top", zIndex: 1 },
1414
- props: {
1415
- left: canvasW / 2,
1416
- top: topH / 2,
1417
- width: canvasW,
1418
- height: topH,
1419
- originX: "center",
1420
- originY: "center",
1421
- fill: visual.outerBackground,
1422
- selectable: false,
1423
- evented: false,
1424
- },
1425
- },
1426
- {
1427
- id: "image.cropMask.bottom",
1428
- type: "rect",
1429
- data: { id: "image.cropMask.bottom", zIndex: 2 },
1430
- props: {
1431
- left: canvasW / 2,
1432
- top: frameBottom + bottomH / 2,
1433
- width: canvasW,
1434
- height: bottomH,
1435
- originX: "center",
1436
- originY: "center",
1437
- fill: visual.outerBackground,
1438
- selectable: false,
1439
- evented: false,
1440
- },
1441
- },
1442
- {
1443
- id: "image.cropMask.left",
1444
- type: "rect",
1445
- data: { id: "image.cropMask.left", zIndex: 3 },
1446
- props: {
1447
- left: leftW / 2,
1448
- top: frameTop + visibleFrameH / 2,
1449
- width: leftW,
1450
- height: visibleFrameH,
1451
- originX: "center",
1452
- originY: "center",
1453
- fill: visual.outerBackground,
1454
- selectable: false,
1455
- evented: false,
1456
- },
1457
- },
1458
- {
1459
- id: "image.cropMask.right",
1460
- type: "rect",
1461
- data: { id: "image.cropMask.right", zIndex: 4 },
1462
- props: {
1463
- left: frameRight + rightW / 2,
1464
- top: frameTop + visibleFrameH / 2,
1465
- width: rightW,
1466
- height: visibleFrameH,
1467
- originX: "center",
1468
- originY: "center",
1469
- fill: visual.outerBackground,
1470
- selectable: false,
1471
- evented: false,
1472
- },
1473
- },
1474
- ];
1475
-
1476
- const frameSpec: RenderObjectSpec = {
1477
- id: "image.cropFrame",
1478
- type: "rect",
1479
- data: { id: "image.cropFrame", zIndex: 7 },
1480
- props: {
1481
- left: frame.left + frame.width / 2,
1482
- top: frame.top + frame.height / 2,
1483
- width: frame.width,
1484
- height: frame.height,
1485
- originX: "center",
1486
- originY: "center",
1487
- fill: visual.innerBackground,
1488
- stroke:
1489
- visual.strokeStyle === "hidden"
1490
- ? "rgba(0,0,0,0)"
1491
- : visual.strokeColor,
1492
- strokeWidth: visual.strokeStyle === "hidden" ? 0 : visual.strokeWidth,
1493
- strokeDashArray:
1494
- visual.strokeStyle === "dashed"
1495
- ? [visual.dashLength, visual.dashLength]
1496
- : undefined,
1497
- selectable: false,
1498
- evented: false,
1499
- },
1500
- };
1501
-
1502
- const specs = [...mask, ...shapeOverlay, frameSpec];
1503
- this.debug("overlay:built", {
1504
- frame,
1505
- shape: sceneGeometry?.shape,
1506
- overlayIds: specs.map((spec) => ({
1507
- id: spec.id,
1508
- zIndex: spec.data?.zIndex,
1509
- })),
1510
- });
1511
- return specs;
1512
- }
1513
-
1514
- private updateImages() {
1515
- void this.updateImagesAsync();
1516
- }
1517
-
1518
- private async updateImagesAsync() {
1519
- if (!this.canvasService) return;
1520
- this.syncToolActiveFromWorkbench();
1521
- const seq = ++this.renderSeq;
1522
-
1523
- const renderItems = this.isToolActive ? this.workingItems : this.items;
1524
- const frame = this.getFrameRect();
1525
- const desiredIds = new Set(renderItems.map((item) => item.id));
1526
- if (this.focusedImageId && !desiredIds.has(this.focusedImageId)) {
1527
- this.setImageFocus(null, {
1528
- syncCanvasSelection: false,
1529
- skipRender: true,
1530
- });
1531
- }
1532
-
1533
- this.getImageObjects().forEach((obj: any) => {
1534
- const id = obj?.data?.id;
1535
- if (typeof id === "string" && !desiredIds.has(id)) {
1536
- this.canvasService?.canvas.remove(obj);
1537
- }
1538
- });
1539
-
1540
- for (const item of renderItems) {
1541
- if (seq !== this.renderSeq) return;
1542
- await this.upsertImageObject(item, frame, seq);
1543
- }
1544
- if (seq !== this.renderSeq) return;
1545
-
1546
- this.syncImageZOrder(renderItems);
1547
- const sceneGeometry = await this.resolveSceneGeometryForOverlay();
1548
- if (seq !== this.renderSeq) return;
1549
-
1550
- const overlaySpecs = this.buildOverlaySpecs(frame, sceneGeometry);
1551
- await this.canvasService.applyObjectSpecsToRootLayer(
1552
- IMAGE_OVERLAY_LAYER_ID,
1553
- overlaySpecs,
1554
- );
1555
- this.syncImageZOrder(renderItems);
1556
- const overlayCanvasCount = this.getOverlayObjects().length;
1557
-
1558
- this.debug("render:done", {
1559
- seq,
1560
- renderCount: renderItems.length,
1561
- overlayCount: overlaySpecs.length,
1562
- overlayCanvasCount,
1563
- isToolActive: this.isToolActive,
1564
- isImageSelectionActive: this.isImageSelectionActive,
1565
- focusedImageId: this.focusedImageId,
1566
- });
1567
- this.canvasService.requestRenderAll();
1568
- }
1569
-
1570
- private clampNormalized(value: number): number {
1571
- return Math.max(-1, Math.min(2, value));
1572
- }
1573
-
1574
- private onObjectModified = (e: any) => {
1575
- if (!this.isToolActive) return;
1576
- const target = e?.target;
1577
- const id = target?.data?.id;
1578
- const layerId = target?.data?.layerId;
1579
- if (typeof id !== "string" || layerId !== IMAGE_OBJECT_LAYER_ID) return;
1580
-
1581
- const frame = this.getFrameRect();
1582
- if (!frame.width || !frame.height) return;
1583
-
1584
- const center = target.getCenterPoint
1585
- ? target.getCenterPoint()
1586
- : new Point(target.left ?? 0, target.top ?? 0);
1587
-
1588
- const objectScale = Number.isFinite(target?.scaleX) ? target.scaleX : 1;
1589
-
1590
- const workingItem = this.workingItems.find((item) => item.id === id);
1591
- const sourceKey = workingItem?.sourceUrl || workingItem?.url || "";
1592
- const sourceSize = this.getSourceSize(sourceKey, target);
1593
- const coverScale = this.getCoverScale(frame, sourceSize);
1594
-
1595
- const updates: Partial<ImageItem> = {
1596
- left: this.clampNormalized((center.x - frame.left) / frame.width),
1597
- top: this.clampNormalized((center.y - frame.top) / frame.height),
1598
- angle: Number.isFinite(target.angle) ? target.angle : 0,
1599
- scale: Math.max(0.05, (objectScale || 1) / coverScale),
1600
- };
1601
-
1602
- this.focusedImageId = id;
1603
- this.updateImageInWorking(id, updates);
1604
- };
1605
-
1606
- private updateImageInWorking(id: string, updates: Partial<ImageItem>) {
1607
- const index = this.workingItems.findIndex((item) => item.id === id);
1608
- if (index < 0) return;
1609
-
1610
- const next = [...this.workingItems];
1611
- next[index] = this.normalizeItem({ ...next[index], ...updates });
1612
- this.workingItems = next;
1613
- this.hasWorkingChanges = true;
1614
- this.setImageFocus(id, {
1615
- syncCanvasSelection: false,
1616
- skipRender: true,
1617
- });
1618
- if (this.isToolActive) {
1619
- this.updateImages();
1620
- }
1621
- this.emitWorkingChange(id);
1622
- }
1623
-
1624
- private async updateImageInConfig(id: string, updates: Partial<ImageItem>) {
1625
- const index = this.items.findIndex((item) => item.id === id);
1626
- if (index < 0) return;
1627
-
1628
- const replacingSource =
1629
- typeof updates.url === "string" && updates.url.length > 0;
1630
- const next = [...this.items];
1631
- const base = next[index];
1632
- const replacingUrl = replacingSource ? (updates.url as string) : undefined;
1633
-
1634
- next[index] = this.normalizeItem({
1635
- ...base,
1636
- ...updates,
1637
- ...(replacingSource
1638
- ? {
1639
- url: replacingUrl,
1640
- sourceUrl: replacingUrl,
1641
- committedUrl: undefined,
1642
- scale: updates.scale ?? 1,
1643
- angle: updates.angle ?? 0,
1644
- left: updates.left ?? 0.5,
1645
- top: updates.top ?? 0.5,
1646
- }
1647
- : {}),
1648
- });
1649
-
1650
- this.updateConfig(next);
1651
-
1652
- if (replacingSource) {
1653
- this.debug("replace:image:begin", { id, replacingUrl });
1654
- this.purgeSourceSizeCacheForItem(base);
1655
- const loaded = await this.waitImageLoaded(id, true);
1656
- this.debug("replace:image:loaded", { id, loaded });
1657
- if (loaded) {
1658
- await this.refitImageToFrame(id);
1659
- this.setImageFocus(id);
1660
- }
1661
- }
1662
- }
1663
-
1664
- private waitImageLoaded(id: string, forceWait = false): Promise<boolean> {
1665
- if (!forceWait && this.getImageObject(id)) {
1666
- return Promise.resolve(true);
1667
- }
1668
-
1669
- return new Promise<boolean>((resolve) => {
1670
- const timeout = setTimeout(() => {
1671
- this.loadResolvers.delete(id);
1672
- resolve(false);
1673
- }, 4000);
1674
-
1675
- this.loadResolvers.set(id, () => {
1676
- clearTimeout(timeout);
1677
- resolve(true);
1678
- });
1679
- });
1680
- }
1681
-
1682
- private async refitImageToFrame(id: string) {
1683
- const obj = this.getImageObject(id);
1684
- if (!obj || !this.canvasService) return;
1685
- const current = this.items.find((item) => item.id === id);
1686
- if (!current) return;
1687
- const render = this.resolveRenderImageState(current);
1688
-
1689
- this.rememberSourceSize(render.src, obj);
1690
- const source = this.getSourceSize(render.src, obj);
1691
- const frame = this.getFrameRect();
1692
- const coverScale = this.getCoverScale(frame, source);
1693
-
1694
- const currentScale = obj.scaleX || 1;
1695
- const zoom = Math.max(0.05, currentScale / coverScale);
1696
-
1697
- const updated: Partial<ImageItem> = {
1698
- scale: Number.isFinite(zoom) ? zoom : 1,
1699
- angle: 0,
1700
- left: 0.5,
1701
- top: 0.5,
1702
- };
1703
-
1704
- const index = this.items.findIndex((item) => item.id === id);
1705
- if (index < 0) return;
1706
-
1707
- const next = [...this.items];
1708
- next[index] = this.normalizeItem({ ...next[index], ...updated });
1709
- this.updateConfig(next);
1710
- this.workingItems = this.cloneItems(next);
1711
- this.hasWorkingChanges = false;
1712
- this.updateImages();
1713
- this.emitWorkingChange(id);
1714
- }
1715
-
1716
- private async fitImageToArea(
1717
- id: string,
1718
- area: { width: number; height: number; left?: number; top?: number },
1719
- ) {
1720
- if (!this.canvasService) return;
1721
-
1722
- const loaded = await this.waitImageLoaded(id, false);
1723
- if (!loaded) return;
1724
-
1725
- const obj = this.getImageObject(id);
1726
- if (!obj) return;
1727
- const renderItems = this.isToolActive ? this.workingItems : this.items;
1728
- const current = renderItems.find((item) => item.id === id);
1729
- if (!current) return;
1730
- const render = this.resolveRenderImageState(current);
1731
-
1732
- this.rememberSourceSize(render.src, obj);
1733
- const source = this.getSourceSize(render.src, obj);
1734
- const frame = this.getFrameRect();
1735
- const baseCover = this.getCoverScale(frame, source);
1736
-
1737
- const desiredScale = Math.max(
1738
- Math.max(1, area.width) / Math.max(1, source.width),
1739
- Math.max(1, area.height) / Math.max(1, source.height),
1740
- );
1741
-
1742
- const canvasW = this.canvasService.canvas.width || 1;
1743
- const canvasH = this.canvasService.canvas.height || 1;
1744
-
1745
- const areaLeftInput = area.left ?? 0.5;
1746
- const areaTopInput = area.top ?? 0.5;
1747
-
1748
- const areaLeftPx =
1749
- areaLeftInput <= 1.5 ? areaLeftInput * canvasW : areaLeftInput;
1750
- const areaTopPx =
1751
- areaTopInput <= 1.5 ? areaTopInput * canvasH : areaTopInput;
1752
-
1753
- const updates: Partial<ImageItem> = {
1754
- scale: Math.max(0.05, desiredScale / baseCover),
1755
- left: this.clampNormalized(
1756
- (areaLeftPx - frame.left) / Math.max(1, frame.width),
1757
- ),
1758
- top: this.clampNormalized(
1759
- (areaTopPx - frame.top) / Math.max(1, frame.height),
1760
- ),
1761
- };
1762
-
1763
- if (this.isToolActive) {
1764
- this.updateImageInWorking(id, updates);
1765
- return;
1766
- }
1767
-
1768
- await this.updateImageInConfig(id, updates);
1769
- }
1770
-
1771
- private async commitWorkingImagesAsCropped() {
1772
- if (!this.canvasService) {
1773
- return { ok: false, reason: "canvas-not-ready" };
1774
- }
1775
-
1776
- await this.updateImagesAsync();
1777
-
1778
- const frame = this.getFrameRect();
1779
- if (!frame.width || !frame.height) {
1780
- return { ok: false, reason: "frame-not-ready" };
1781
- }
1782
-
1783
- const next: ImageItem[] = [];
1784
- for (const item of this.workingItems) {
1785
- const exported = await this.exportCroppedImageByIds([item.id], {
1786
- multiplier: 2,
1787
- format: "png",
1788
- });
1789
- const url = exported.url;
1790
-
1791
- const sourceUrl = item.sourceUrl || item.url;
1792
- const previousCommitted = item.committedUrl;
1793
- next.push(
1794
- this.normalizeItem({
1795
- ...item,
1796
- url,
1797
- // Keep original source for next image-tool session editing,
1798
- // and use committedUrl as non-image-tools render source.
1799
- sourceUrl,
1800
- committedUrl: url,
1801
- }),
1802
- );
1803
- if (previousCommitted && previousCommitted !== url) {
1804
- this.sourceSizeBySrc.delete(previousCommitted);
1805
- }
1806
- }
1807
-
1808
- this.hasWorkingChanges = false;
1809
- this.workingItems = this.cloneItems(next);
1810
- this.updateConfig(next);
1811
- this.emitWorkingChange(this.focusedImageId);
1812
- return { ok: true };
1813
- }
1814
-
1815
- private async exportCroppedImageByIds(
1816
- imageIds: string[],
1817
- options: ExportCroppedImageOptions,
1818
- ): Promise<ExportUserCroppedImageResult> {
1819
- if (!this.canvasService) {
1820
- throw new Error("CanvasService not initialized");
1821
- }
1822
-
1823
- const normalizedIds = [...new Set(imageIds)].filter(
1824
- (id): id is string => typeof id === "string" && id.length > 0,
1825
- );
1826
- if (!normalizedIds.length) {
1827
- throw new Error("image-ids-required");
1828
- }
1829
-
1830
- const frame = this.getFrameRect();
1831
- const multiplier = Math.max(1, options.multiplier ?? 2);
1832
- const format: "png" | "jpeg" = options.format === "jpeg" ? "jpeg" : "png";
1833
-
1834
- const width = Math.max(1, Math.round(frame.width * multiplier));
1835
- const height = Math.max(1, Math.round(frame.height * multiplier));
1836
-
1837
- const el = document.createElement("canvas");
1838
- const tempCanvas = new FabricCanvas(el, {
1839
- renderOnAddRemove: false,
1840
- selection: false,
1841
- enableRetinaScaling: false,
1842
- preserveObjectStacking: true,
1843
- } as any);
1844
- tempCanvas.setDimensions({ width, height });
1845
-
1846
- try {
1847
- const idSet = new Set(normalizedIds);
1848
- const sourceObjects = this.canvasService.canvas
1849
- .getObjects()
1850
- .filter((obj: any) => {
1851
- return (
1852
- obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID &&
1853
- typeof obj?.data?.id === "string" &&
1854
- idSet.has(obj.data.id)
1855
- );
1856
- });
1857
-
1858
- if (!sourceObjects.length) {
1859
- throw new Error("image-objects-not-found");
1860
- }
1861
-
1862
- for (const source of sourceObjects as any[]) {
1863
- const clone = await source.clone();
1864
- const center = source.getCenterPoint
1865
- ? source.getCenterPoint()
1866
- : new Point(source.left ?? 0, source.top ?? 0);
1867
-
1868
- clone.set({
1869
- originX: "center",
1870
- originY: "center",
1871
- left: (center.x - frame.left) * multiplier,
1872
- top: (center.y - frame.top) * multiplier,
1873
- scaleX: (source.scaleX || 1) * multiplier,
1874
- scaleY: (source.scaleY || 1) * multiplier,
1875
- angle: source.angle || 0,
1876
- selectable: false,
1877
- evented: false,
1878
- });
1879
- clone.setCoords();
1880
- tempCanvas.add(clone);
1881
- }
1882
-
1883
- tempCanvas.renderAll();
1884
- const blob = await tempCanvas.toBlob({ format, multiplier: 1 });
1885
- if (!blob) {
1886
- throw new Error("image-export-failed");
1887
- }
1888
-
1889
- return {
1890
- url: URL.createObjectURL(blob),
1891
- width,
1892
- height,
1893
- multiplier,
1894
- format,
1895
- imageIds: (sourceObjects as any[])
1896
- .map((obj: any) => obj?.data?.id)
1897
- .filter((id: any): id is string => typeof id === "string"),
1898
- };
1899
- } finally {
1900
- tempCanvas.dispose();
1901
- }
1902
- }
1903
-
1904
- private async exportUserCroppedImage(
1905
- options: ExportUserCroppedImageOptions = {},
1906
- ): Promise<ExportUserCroppedImageResult> {
1907
- if (!this.canvasService) {
1908
- throw new Error("CanvasService not initialized");
1909
- }
1910
-
1911
- await this.updateImagesAsync();
1912
- this.syncToolActiveFromWorkbench();
1913
-
1914
- const imageIds =
1915
- options.imageIds && options.imageIds.length > 0
1916
- ? options.imageIds
1917
- : (this.isToolActive ? this.workingItems : this.items).map(
1918
- (item) => item.id,
1919
- );
1920
- if (!imageIds.length) {
1921
- throw new Error("no-images-to-export");
1922
- }
1923
-
1924
- return await this.exportCroppedImageByIds(imageIds, options);
1925
- }
1926
- }
1
+ import {
2
+ Extension,
3
+ ExtensionContext,
4
+ ContributionPointIds,
5
+ CommandContribution,
6
+ ConfigurationContribution,
7
+ ConfigurationService,
8
+ ToolSessionService,
9
+ WorkbenchService,
10
+ } from "@pooder/core";
11
+ import {
12
+ Canvas as FabricCanvas,
13
+ Image as FabricImage,
14
+ Pattern,
15
+ Point,
16
+ } from "fabric";
17
+ import { CanvasService, RenderLayoutRect, RenderObjectSpec } from "../services";
18
+ import { isDielineShape, normalizeShapeStyle } from "./dielineShape";
19
+ import type { DielineShape, DielineShapeStyle } from "./dielineShape";
20
+ import { generateDielinePath, getPathBounds } from "./geometry";
21
+ import {
22
+ buildSceneGeometry,
23
+ computeSceneLayout,
24
+ readSizeState,
25
+ } from "./sceneLayoutModel";
26
+
27
+ export interface ImageItem {
28
+ id: string;
29
+ url: string;
30
+ opacity: number;
31
+ scale?: number;
32
+ angle?: number;
33
+ left?: number;
34
+ top?: number;
35
+ sourceUrl?: string;
36
+ committedUrl?: string;
37
+ }
38
+
39
+ interface FrameRect {
40
+ left: number;
41
+ top: number;
42
+ width: number;
43
+ height: number;
44
+ }
45
+
46
+ interface SourceSize {
47
+ width: number;
48
+ height: number;
49
+ }
50
+
51
+ interface RenderImageState {
52
+ src: string;
53
+ left: number;
54
+ top: number;
55
+ scale: number;
56
+ angle: number;
57
+ opacity: number;
58
+ }
59
+
60
+ interface FrameVisualConfig {
61
+ strokeColor: string;
62
+ strokeWidth: number;
63
+ strokeStyle: "solid" | "dashed" | "hidden";
64
+ dashLength: number;
65
+ innerBackground: string;
66
+ outerBackground: string;
67
+ }
68
+
69
+ type ShapeOverlayShape = Exclude<DielineShape, "custom">;
70
+
71
+ interface SceneGeometryLike {
72
+ shape: DielineShape;
73
+ shapeStyle: DielineShapeStyle;
74
+ radius: number;
75
+ offset: number;
76
+ }
77
+
78
+ interface UpsertImageOptions {
79
+ id?: string;
80
+ mode?: "replace" | "add";
81
+ addOptions?: Partial<ImageItem>;
82
+ fitOnAdd?: boolean;
83
+ }
84
+
85
+ interface DielineFitArea {
86
+ width: number;
87
+ height: number;
88
+ left: number;
89
+ top: number;
90
+ }
91
+
92
+ interface UpdateImageOptions {
93
+ target?: "auto" | "config" | "working";
94
+ }
95
+
96
+ interface ExportCroppedImageOptions {
97
+ multiplier?: number;
98
+ format?: "png" | "jpeg";
99
+ }
100
+
101
+ interface ExportUserCroppedImageOptions extends ExportCroppedImageOptions {
102
+ imageIds?: string[];
103
+ }
104
+
105
+ interface ExportUserCroppedImageResult {
106
+ url: string;
107
+ width: number;
108
+ height: number;
109
+ multiplier: number;
110
+ format: "png" | "jpeg";
111
+ imageIds: string[];
112
+ }
113
+
114
+ const IMAGE_OBJECT_LAYER_ID = "image.user";
115
+ const IMAGE_OVERLAY_LAYER_ID = "image-overlay";
116
+
117
+ export class ImageTool implements Extension {
118
+ id = "pooder.kit.image";
119
+
120
+ metadata = {
121
+ name: "ImageTool",
122
+ };
123
+
124
+ private items: ImageItem[] = [];
125
+ private workingItems: ImageItem[] = [];
126
+ private hasWorkingChanges = false;
127
+ private loadResolvers: Map<string, () => void> = new Map();
128
+ private sourceSizeBySrc: Map<string, SourceSize> = new Map();
129
+ private canvasService?: CanvasService;
130
+ private context?: ExtensionContext;
131
+ private isUpdatingConfig = false;
132
+ private isToolActive = false;
133
+ private isImageSelectionActive = false;
134
+ private focusedImageId: string | null = null;
135
+ private renderSeq = 0;
136
+ private dirtyTrackerDisposable?: { dispose(): void };
137
+ private cropShapeHatchPattern?: Pattern;
138
+ private cropShapeHatchPatternColor?: string;
139
+ private cropShapeHatchPatternKey?: string;
140
+ private overlaySpecs: RenderObjectSpec[] = [];
141
+ private renderProducerDisposable?: { dispose: () => void };
142
+
143
+ activate(context: ExtensionContext) {
144
+ this.context = context;
145
+ this.canvasService = context.services.get<CanvasService>("CanvasService");
146
+ if (!this.canvasService) {
147
+ console.warn("CanvasService not found for ImageTool");
148
+ return;
149
+ }
150
+ this.renderProducerDisposable?.dispose();
151
+ this.renderProducerDisposable = this.canvasService.registerRenderProducer(
152
+ this.id,
153
+ () => ({
154
+ rootLayerSpecs: {
155
+ [IMAGE_OVERLAY_LAYER_ID]: this.overlaySpecs,
156
+ },
157
+ }),
158
+ { priority: 300 },
159
+ );
160
+
161
+ context.eventBus.on("tool:activated", this.onToolActivated);
162
+ context.eventBus.on("object:modified", this.onObjectModified);
163
+ context.eventBus.on("selection:created", this.onSelectionChanged);
164
+ context.eventBus.on("selection:updated", this.onSelectionChanged);
165
+ context.eventBus.on("selection:cleared", this.onSelectionCleared);
166
+ context.eventBus.on("scene:layout:change", this.onSceneLayoutChanged);
167
+ context.eventBus.on("scene:geometry:change", this.onSceneGeometryChanged);
168
+
169
+ const configService = context.services.get<ConfigurationService>(
170
+ "ConfigurationService",
171
+ );
172
+ if (configService) {
173
+ this.items = this.normalizeItems(
174
+ configService.get("image.items", []) || [],
175
+ );
176
+ this.workingItems = this.cloneItems(this.items);
177
+ this.hasWorkingChanges = false;
178
+
179
+ configService.onAnyChange((e: { key: string; value: any }) => {
180
+ if (this.isUpdatingConfig) return;
181
+
182
+ if (e.key === "image.items") {
183
+ this.items = this.normalizeItems(e.value || []);
184
+ if (!this.isToolActive || !this.hasWorkingChanges) {
185
+ this.workingItems = this.cloneItems(this.items);
186
+ this.hasWorkingChanges = false;
187
+ }
188
+ this.updateImages();
189
+ return;
190
+ }
191
+
192
+ if (e.key.startsWith("size.") || e.key.startsWith("image.frame.")) {
193
+ this.updateImages();
194
+ }
195
+ });
196
+ }
197
+
198
+ const toolSessionService =
199
+ context.services.get<ToolSessionService>("ToolSessionService");
200
+ this.dirtyTrackerDisposable = toolSessionService?.registerDirtyTracker(
201
+ this.id,
202
+ () => this.hasWorkingChanges,
203
+ );
204
+
205
+ this.updateImages();
206
+ }
207
+
208
+ deactivate(context: ExtensionContext) {
209
+ context.eventBus.off("tool:activated", this.onToolActivated);
210
+ context.eventBus.off("object:modified", this.onObjectModified);
211
+ context.eventBus.off("selection:created", this.onSelectionChanged);
212
+ context.eventBus.off("selection:updated", this.onSelectionChanged);
213
+ context.eventBus.off("selection:cleared", this.onSelectionCleared);
214
+ context.eventBus.off("scene:layout:change", this.onSceneLayoutChanged);
215
+ context.eventBus.off("scene:geometry:change", this.onSceneGeometryChanged);
216
+ this.dirtyTrackerDisposable?.dispose();
217
+ this.dirtyTrackerDisposable = undefined;
218
+ this.cropShapeHatchPattern = undefined;
219
+ this.cropShapeHatchPatternColor = undefined;
220
+ this.cropShapeHatchPatternKey = undefined;
221
+ this.overlaySpecs = [];
222
+
223
+ this.clearRenderedImages();
224
+ this.renderProducerDisposable?.dispose();
225
+ this.renderProducerDisposable = undefined;
226
+ if (this.canvasService) {
227
+ void this.canvasService.flushRenderFromProducers();
228
+ this.canvasService = undefined;
229
+ }
230
+ this.context = undefined;
231
+ }
232
+
233
+ private onToolActivated = (event: {
234
+ id: string | null;
235
+ previous?: string | null;
236
+ reason?: string;
237
+ }) => {
238
+ const before = this.isToolActive;
239
+ this.syncToolActiveFromWorkbench(event.id);
240
+ if (!this.isToolActive) {
241
+ this.setImageFocus(null, {
242
+ syncCanvasSelection: true,
243
+ skipRender: true,
244
+ });
245
+ }
246
+ this.debug("tool:activated", {
247
+ id: event.id,
248
+ previous: event.previous,
249
+ reason: event.reason,
250
+ before,
251
+ isToolActive: this.isToolActive,
252
+ focusedImageId: this.focusedImageId,
253
+ });
254
+ if (!this.isToolActive && this.isDebugEnabled()) {
255
+ console.trace("[ImageTool] tool deactivated trace");
256
+ }
257
+ this.updateImages();
258
+ };
259
+
260
+ private onSelectionChanged = (e: any) => {
261
+ const list: any[] = [];
262
+ if (Array.isArray(e?.selected)) {
263
+ list.push(...e.selected);
264
+ }
265
+ if (Array.isArray(e?.target?._objects)) {
266
+ list.push(...e.target._objects);
267
+ }
268
+ if (e?.target && !Array.isArray(e?.target?._objects)) {
269
+ list.push(e.target);
270
+ }
271
+
272
+ const selectedImage = list.find(
273
+ (obj: any) => obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID,
274
+ );
275
+ this.isImageSelectionActive = !!selectedImage;
276
+ if (selectedImage?.data?.id) {
277
+ this.focusedImageId = selectedImage.data.id;
278
+ } else if (list.length > 0) {
279
+ this.focusedImageId = null;
280
+ }
281
+ this.debug("selection:changed", {
282
+ listSize: list.length,
283
+ isImageSelectionActive: this.isImageSelectionActive,
284
+ focusedImageId: this.focusedImageId,
285
+ });
286
+ this.updateImages();
287
+ };
288
+
289
+ private onSelectionCleared = () => {
290
+ this.setImageFocus(null, {
291
+ syncCanvasSelection: false,
292
+ skipRender: true,
293
+ });
294
+ this.debug("selection:cleared applied");
295
+ this.updateImages();
296
+ };
297
+
298
+ private onSceneLayoutChanged = () => {
299
+ this.updateImages();
300
+ };
301
+
302
+ private onSceneGeometryChanged = () => {
303
+ this.updateImages();
304
+ };
305
+
306
+ private syncToolActiveFromWorkbench(fallbackId?: string | null) {
307
+ const wb = this.context?.services.get<WorkbenchService>("WorkbenchService");
308
+ const activeId = wb?.activeToolId;
309
+ if (typeof activeId === "string" || activeId === null) {
310
+ this.isToolActive = activeId === this.id;
311
+ return;
312
+ }
313
+ this.isToolActive = fallbackId === this.id;
314
+ }
315
+
316
+ private isImageEditingVisible(): boolean {
317
+ return (
318
+ this.isToolActive || this.isImageSelectionActive || !!this.focusedImageId
319
+ );
320
+ }
321
+
322
+ private isDebugEnabled(): boolean {
323
+ return !!this.getConfig<boolean>("image.debug", false);
324
+ }
325
+
326
+ private debug(message: string, payload?: any) {
327
+ if (!this.isDebugEnabled()) return;
328
+ if (payload === undefined) {
329
+ console.log(`[ImageTool] ${message}`);
330
+ return;
331
+ }
332
+ console.log(`[ImageTool] ${message}`, payload);
333
+ }
334
+
335
+ contribute() {
336
+ return {
337
+ [ContributionPointIds.TOOLS]: [
338
+ {
339
+ id: this.id,
340
+ name: "Image",
341
+ interaction: "session",
342
+ commands: {
343
+ begin: "resetWorkingImages",
344
+ commit: "completeImages",
345
+ rollback: "resetWorkingImages",
346
+ },
347
+ session: {
348
+ autoBegin: true,
349
+ leavePolicy: "block",
350
+ },
351
+ },
352
+ ],
353
+ [ContributionPointIds.CONFIGURATIONS]: [
354
+ {
355
+ id: "image.items",
356
+ type: "array",
357
+ label: "Images",
358
+ default: [],
359
+ },
360
+ {
361
+ id: "image.debug",
362
+ type: "boolean",
363
+ label: "Image Debug Log",
364
+ default: false,
365
+ },
366
+ {
367
+ id: "image.frame.strokeColor",
368
+ type: "color",
369
+ label: "Image Frame Stroke Color",
370
+ default: "#808080",
371
+ },
372
+ {
373
+ id: "image.frame.strokeWidth",
374
+ type: "number",
375
+ label: "Image Frame Stroke Width",
376
+ min: 0,
377
+ max: 20,
378
+ step: 0.5,
379
+ default: 2,
380
+ },
381
+ {
382
+ id: "image.frame.strokeStyle",
383
+ type: "select",
384
+ label: "Image Frame Stroke Style",
385
+ options: ["solid", "dashed", "hidden"],
386
+ default: "dashed",
387
+ },
388
+ {
389
+ id: "image.frame.dashLength",
390
+ type: "number",
391
+ label: "Image Frame Dash Length",
392
+ min: 1,
393
+ max: 40,
394
+ step: 1,
395
+ default: 8,
396
+ },
397
+ {
398
+ id: "image.frame.innerBackground",
399
+ type: "color",
400
+ label: "Image Frame Inner Background",
401
+ default: "rgba(0,0,0,0)",
402
+ },
403
+ {
404
+ id: "image.frame.outerBackground",
405
+ type: "color",
406
+ label: "Image Frame Outer Background",
407
+ default: "#f5f5f5",
408
+ },
409
+ ] as ConfigurationContribution[],
410
+ [ContributionPointIds.COMMANDS]: [
411
+ {
412
+ command: "addImage",
413
+ title: "Add Image",
414
+ handler: async (url: string, options?: Partial<ImageItem>) => {
415
+ const result = await this.upsertImageEntry(url, {
416
+ mode: "add",
417
+ addOptions: options,
418
+ });
419
+ return result.id;
420
+ },
421
+ },
422
+ {
423
+ command: "upsertImage",
424
+ title: "Upsert Image",
425
+ handler: async (url: string, options: UpsertImageOptions = {}) => {
426
+ return await this.upsertImageEntry(url, options);
427
+ },
428
+ },
429
+ {
430
+ command: "getWorkingImages",
431
+ title: "Get Working Images",
432
+ handler: () => {
433
+ return this.cloneItems(this.workingItems);
434
+ },
435
+ },
436
+ {
437
+ command: "setWorkingImage",
438
+ title: "Set Working Image",
439
+ handler: (id: string, updates: Partial<ImageItem>) => {
440
+ this.updateImageInWorking(id, updates);
441
+ },
442
+ },
443
+ {
444
+ command: "resetWorkingImages",
445
+ title: "Reset Working Images",
446
+ handler: () => {
447
+ this.workingItems = this.cloneItems(this.items);
448
+ this.hasWorkingChanges = false;
449
+ this.updateImages();
450
+ this.emitWorkingChange();
451
+ },
452
+ },
453
+ {
454
+ command: "completeImages",
455
+ title: "Complete Images",
456
+ handler: async () => {
457
+ return await this.commitWorkingImagesAsCropped();
458
+ },
459
+ },
460
+ {
461
+ command: "exportUserCroppedImage",
462
+ title: "Export User Cropped Image",
463
+ handler: async (options: ExportUserCroppedImageOptions = {}) => {
464
+ return await this.exportUserCroppedImage(options);
465
+ },
466
+ },
467
+ {
468
+ command: "fitImageToArea",
469
+ title: "Fit Image to Area",
470
+ handler: async (
471
+ id: string,
472
+ area: {
473
+ width: number;
474
+ height: number;
475
+ left?: number;
476
+ top?: number;
477
+ },
478
+ ) => {
479
+ await this.fitImageToArea(id, area);
480
+ },
481
+ },
482
+ {
483
+ command: "fitImageToDefaultArea",
484
+ title: "Fit Image to Default Area",
485
+ handler: async (id: string) => {
486
+ await this.fitImageToDefaultArea(id);
487
+ },
488
+ },
489
+ {
490
+ command: "focusImage",
491
+ title: "Focus Image",
492
+ handler: (
493
+ id: string | null,
494
+ options: { syncCanvasSelection?: boolean } = {},
495
+ ) => {
496
+ return this.setImageFocus(id, options);
497
+ },
498
+ },
499
+ {
500
+ command: "removeImage",
501
+ title: "Remove Image",
502
+ handler: (id: string) => {
503
+ const removed = this.items.find((item) => item.id === id);
504
+ const next = this.items.filter((item) => item.id !== id);
505
+ if (next.length !== this.items.length) {
506
+ this.purgeSourceSizeCacheForItem(removed);
507
+ if (this.focusedImageId === id) {
508
+ this.setImageFocus(null, {
509
+ syncCanvasSelection: true,
510
+ skipRender: true,
511
+ });
512
+ }
513
+ this.updateConfig(next);
514
+ }
515
+ },
516
+ },
517
+ {
518
+ command: "updateImage",
519
+ title: "Update Image",
520
+ handler: async (
521
+ id: string,
522
+ updates: Partial<ImageItem>,
523
+ options: UpdateImageOptions = {},
524
+ ) => {
525
+ await this.updateImage(id, updates, options);
526
+ },
527
+ },
528
+ {
529
+ command: "clearImages",
530
+ title: "Clear Images",
531
+ handler: () => {
532
+ this.sourceSizeBySrc.clear();
533
+ this.setImageFocus(null, {
534
+ syncCanvasSelection: true,
535
+ skipRender: true,
536
+ });
537
+ this.updateConfig([]);
538
+ },
539
+ },
540
+ {
541
+ command: "bringToFront",
542
+ title: "Bring Image to Front",
543
+ handler: (id: string) => {
544
+ const index = this.items.findIndex((item) => item.id === id);
545
+ if (index !== -1 && index < this.items.length - 1) {
546
+ const next = [...this.items];
547
+ const [item] = next.splice(index, 1);
548
+ next.push(item);
549
+ this.updateConfig(next);
550
+ }
551
+ },
552
+ },
553
+ {
554
+ command: "sendToBack",
555
+ title: "Send Image to Back",
556
+ handler: (id: string) => {
557
+ const index = this.items.findIndex((item) => item.id === id);
558
+ if (index > 0) {
559
+ const next = [...this.items];
560
+ const [item] = next.splice(index, 1);
561
+ next.unshift(item);
562
+ this.updateConfig(next);
563
+ }
564
+ },
565
+ },
566
+ ] as CommandContribution[],
567
+ };
568
+ }
569
+
570
+ private normalizeItem(item: ImageItem): ImageItem {
571
+ const url = typeof item.url === "string" ? item.url : "";
572
+ const sourceUrl =
573
+ typeof item.sourceUrl === "string" && item.sourceUrl.length > 0
574
+ ? item.sourceUrl
575
+ : url;
576
+ const committedUrl =
577
+ typeof item.committedUrl === "string" && item.committedUrl.length > 0
578
+ ? item.committedUrl
579
+ : undefined;
580
+
581
+ return {
582
+ ...item,
583
+ url: url || sourceUrl,
584
+ sourceUrl,
585
+ committedUrl,
586
+ opacity: Number.isFinite(item.opacity as any) ? item.opacity : 1,
587
+ scale: Number.isFinite(item.scale as any) ? item.scale : 1,
588
+ angle: Number.isFinite(item.angle as any) ? item.angle : 0,
589
+ left: Number.isFinite(item.left as any) ? item.left : 0.5,
590
+ top: Number.isFinite(item.top as any) ? item.top : 0.5,
591
+ };
592
+ }
593
+
594
+ private normalizeItems(items: ImageItem[]): ImageItem[] {
595
+ return (items || []).map((item) => this.normalizeItem(item));
596
+ }
597
+
598
+ private cloneItems(items: ImageItem[]): ImageItem[] {
599
+ return this.normalizeItems((items || []).map((i) => ({ ...i })));
600
+ }
601
+
602
+ private emitWorkingChange(changedId: string | null = null) {
603
+ this.context?.eventBus.emit("image:working:change", {
604
+ changedId,
605
+ items: this.cloneItems(this.workingItems),
606
+ });
607
+ }
608
+
609
+ private generateId(): string {
610
+ return Math.random().toString(36).substring(2, 9);
611
+ }
612
+
613
+ private hasImageItem(id: string): boolean {
614
+ return (
615
+ this.items.some((item) => item.id === id) ||
616
+ this.workingItems.some((item) => item.id === id)
617
+ );
618
+ }
619
+
620
+ private setImageFocus(
621
+ id: string | null,
622
+ options: { syncCanvasSelection?: boolean; skipRender?: boolean } = {},
623
+ ) {
624
+ const syncCanvasSelection = options.syncCanvasSelection !== false;
625
+
626
+ if (id && !this.hasImageItem(id)) {
627
+ return { ok: false, reason: "image-not-found" as const };
628
+ }
629
+
630
+ this.focusedImageId = id;
631
+ this.isImageSelectionActive = !!id;
632
+
633
+ if (syncCanvasSelection && this.canvasService) {
634
+ const canvas = this.canvasService.canvas;
635
+ if (!id) {
636
+ canvas.discardActiveObject();
637
+ } else {
638
+ const obj = this.getImageObject(id);
639
+ if (obj) {
640
+ obj.set({
641
+ selectable: true,
642
+ evented: true,
643
+ hasControls: true,
644
+ hasBorders: true,
645
+ });
646
+ canvas.setActiveObject(obj);
647
+ }
648
+ }
649
+ this.canvasService.requestRenderAll();
650
+ }
651
+
652
+ if (!options.skipRender) {
653
+ this.updateImages();
654
+ }
655
+
656
+ return { ok: true, id };
657
+ }
658
+
659
+ private async addImageEntry(
660
+ url: string,
661
+ options?: Partial<ImageItem>,
662
+ fitOnAdd = true,
663
+ ): Promise<string> {
664
+ const id = this.generateId();
665
+ const newItem = this.normalizeItem({
666
+ id,
667
+ url,
668
+ opacity: 1,
669
+ ...options,
670
+ } as ImageItem);
671
+
672
+ const sessionDirtyBeforeAdd = this.isToolActive && this.hasWorkingChanges;
673
+ const waitLoaded = this.waitImageLoaded(id, true);
674
+ this.updateConfig([...this.items, newItem]);
675
+ this.addItemToWorkingSessionIfNeeded(newItem, sessionDirtyBeforeAdd);
676
+ const loaded = await waitLoaded;
677
+ if (loaded && fitOnAdd) {
678
+ await this.fitImageToDefaultArea(id);
679
+ }
680
+ if (loaded) {
681
+ this.setImageFocus(id);
682
+ }
683
+ return id;
684
+ }
685
+
686
+ private async upsertImageEntry(
687
+ url: string,
688
+ options: UpsertImageOptions = {},
689
+ ): Promise<{ id: string; mode: "replace" | "add" }> {
690
+ const mode = options.mode || (options.id ? "replace" : "add");
691
+ const fitOnAdd = options.fitOnAdd !== false;
692
+ if (mode === "replace") {
693
+ if (!options.id) {
694
+ throw new Error("replace-target-id-required");
695
+ }
696
+ const targetId = options.id;
697
+ if (!this.hasImageItem(targetId)) {
698
+ throw new Error("replace-target-not-found");
699
+ }
700
+ await this.updateImageInConfig(targetId, { url });
701
+ return { id: targetId, mode: "replace" };
702
+ }
703
+
704
+ const id = await this.addImageEntry(url, options.addOptions, fitOnAdd);
705
+ return { id, mode: "add" };
706
+ }
707
+
708
+ private addItemToWorkingSessionIfNeeded(
709
+ item: ImageItem,
710
+ sessionDirtyBeforeAdd: boolean,
711
+ ) {
712
+ if (!sessionDirtyBeforeAdd || !this.isToolActive) return;
713
+ if (this.workingItems.some((existing) => existing.id === item.id)) return;
714
+ this.workingItems = this.cloneItems([...this.workingItems, item]);
715
+ this.updateImages();
716
+ this.emitWorkingChange(item.id);
717
+ }
718
+
719
+ private async updateImage(
720
+ id: string,
721
+ updates: Partial<ImageItem>,
722
+ options: UpdateImageOptions = {},
723
+ ) {
724
+ this.syncToolActiveFromWorkbench();
725
+ const target = options.target || "auto";
726
+
727
+ if (target === "working" || (target === "auto" && this.isToolActive)) {
728
+ this.updateImageInWorking(id, updates);
729
+ return;
730
+ }
731
+
732
+ await this.updateImageInConfig(id, updates);
733
+ }
734
+
735
+ private getConfig<T>(key: string, fallback?: T): T | undefined {
736
+ if (!this.context) return fallback;
737
+ const configService = this.context.services.get<ConfigurationService>(
738
+ "ConfigurationService",
739
+ );
740
+ if (!configService) return fallback;
741
+ return (configService.get(key, fallback) as T) ?? fallback;
742
+ }
743
+
744
+ private updateConfig(newItems: ImageItem[], skipCanvasUpdate = false) {
745
+ if (!this.context) return;
746
+
747
+ this.isUpdatingConfig = true;
748
+ this.items = this.normalizeItems(newItems);
749
+ if (!this.isToolActive || !this.hasWorkingChanges) {
750
+ this.workingItems = this.cloneItems(this.items);
751
+ this.hasWorkingChanges = false;
752
+ }
753
+
754
+ const configService = this.context.services.get<ConfigurationService>(
755
+ "ConfigurationService",
756
+ );
757
+ configService?.update("image.items", this.items);
758
+
759
+ if (!skipCanvasUpdate) {
760
+ this.updateImages();
761
+ }
762
+
763
+ setTimeout(() => {
764
+ this.isUpdatingConfig = false;
765
+ }, 50);
766
+ }
767
+
768
+ private getFrameRect(): FrameRect {
769
+ if (!this.canvasService) {
770
+ return { left: 0, top: 0, width: 0, height: 0 };
771
+ }
772
+ const configService = this.context?.services.get<ConfigurationService>(
773
+ "ConfigurationService",
774
+ );
775
+ if (!configService) {
776
+ return { left: 0, top: 0, width: 0, height: 0 };
777
+ }
778
+
779
+ const sizeState = readSizeState(configService);
780
+ const layout = computeSceneLayout(this.canvasService, sizeState);
781
+ if (!layout) {
782
+ return { left: 0, top: 0, width: 0, height: 0 };
783
+ }
784
+
785
+ return this.canvasService.toSceneRect({
786
+ left: layout.cutRect.left,
787
+ top: layout.cutRect.top,
788
+ width: layout.cutRect.width,
789
+ height: layout.cutRect.height,
790
+ });
791
+ }
792
+
793
+ private getFrameRectScreen(frame?: FrameRect): FrameRect {
794
+ if (!this.canvasService) {
795
+ return { left: 0, top: 0, width: 0, height: 0 };
796
+ }
797
+ return this.canvasService.toScreenRect(frame || this.getFrameRect());
798
+ }
799
+
800
+ private toLayoutSceneRect(rect: FrameRect): RenderLayoutRect {
801
+ return {
802
+ left: rect.left,
803
+ top: rect.top,
804
+ width: rect.width,
805
+ height: rect.height,
806
+ space: "scene",
807
+ };
808
+ }
809
+
810
+ private async resolveDefaultFitArea(): Promise<DielineFitArea | null> {
811
+ if (!this.canvasService) return null;
812
+ const frame = this.getFrameRect();
813
+ if (frame.width <= 0 || frame.height <= 0) return null;
814
+ return {
815
+ width: Math.max(1, frame.width),
816
+ height: Math.max(1, frame.height),
817
+ left: frame.left + frame.width / 2,
818
+ top: frame.top + frame.height / 2,
819
+ };
820
+ }
821
+
822
+ private async fitImageToDefaultArea(id: string) {
823
+ if (!this.canvasService) return;
824
+ const area = await this.resolveDefaultFitArea();
825
+
826
+ if (area) {
827
+ await this.fitImageToArea(id, area);
828
+ return;
829
+ }
830
+
831
+ const viewport = this.canvasService.getSceneViewportRect();
832
+ const canvasW = Math.max(1, viewport.width || 0);
833
+ const canvasH = Math.max(1, viewport.height || 0);
834
+ await this.fitImageToArea(id, {
835
+ width: canvasW,
836
+ height: canvasH,
837
+ left: viewport.left + canvasW / 2,
838
+ top: viewport.top + canvasH / 2,
839
+ });
840
+ }
841
+
842
+ private getImageObjects(): any[] {
843
+ if (!this.canvasService) return [];
844
+ return this.canvasService.canvas.getObjects().filter((obj: any) => {
845
+ return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
846
+ }) as any[];
847
+ }
848
+
849
+ private getOverlayObjects(): any[] {
850
+ if (!this.canvasService) return [];
851
+ return this.canvasService.getRootLayerObjects(
852
+ IMAGE_OVERLAY_LAYER_ID,
853
+ ) as any[];
854
+ }
855
+
856
+ private getImageObject(id: string): any | undefined {
857
+ return this.getImageObjects().find((obj: any) => obj?.data?.id === id);
858
+ }
859
+
860
+ private clearRenderedImages() {
861
+ if (!this.canvasService) return;
862
+ const canvas = this.canvasService.canvas;
863
+ this.getImageObjects().forEach((obj) => canvas.remove(obj));
864
+ this.canvasService.requestRenderAll();
865
+ }
866
+
867
+ private purgeSourceSizeCacheForItem(item?: ImageItem) {
868
+ if (!item) return;
869
+ const sources = [item.url, item.sourceUrl, item.committedUrl].filter(
870
+ (value): value is string => typeof value === "string" && value.length > 0,
871
+ );
872
+ sources.forEach((src) => this.sourceSizeBySrc.delete(src));
873
+ }
874
+
875
+ private rememberSourceSize(src: string, obj: any) {
876
+ const width = Number(obj?.width || 0);
877
+ const height = Number(obj?.height || 0);
878
+ if (src && width > 0 && height > 0) {
879
+ this.sourceSizeBySrc.set(src, { width, height });
880
+ }
881
+ }
882
+
883
+ private getSourceSize(src: string, obj?: any): SourceSize {
884
+ const cached = src ? this.sourceSizeBySrc.get(src) : undefined;
885
+ if (cached) return cached;
886
+
887
+ const width = Number(obj?.width || 0);
888
+ const height = Number(obj?.height || 0);
889
+ if (src && width > 0 && height > 0) {
890
+ const size = { width, height };
891
+ this.sourceSizeBySrc.set(src, size);
892
+ return size;
893
+ }
894
+
895
+ return { width: 1, height: 1 };
896
+ }
897
+
898
+ private getCoverScale(frame: FrameRect, size: SourceSize): number {
899
+ const sw = Math.max(1, size.width);
900
+ const sh = Math.max(1, size.height);
901
+ const fw = Math.max(1, frame.width);
902
+ const fh = Math.max(1, frame.height);
903
+ return Math.max(fw / sw, fh / sh);
904
+ }
905
+
906
+ private getFrameVisualConfig(): FrameVisualConfig {
907
+ const strokeStyleRaw = (this.getConfig<string>(
908
+ "image.frame.strokeStyle",
909
+ "dashed",
910
+ ) || "dashed") as string;
911
+ const strokeStyle: "solid" | "dashed" | "hidden" =
912
+ strokeStyleRaw === "dashed" || strokeStyleRaw === "hidden"
913
+ ? strokeStyleRaw
914
+ : "dashed";
915
+
916
+ const strokeWidth = Number(
917
+ this.getConfig<number>("image.frame.strokeWidth", 2) ?? 2,
918
+ );
919
+ const dashLength = Number(
920
+ this.getConfig<number>("image.frame.dashLength", 8) ?? 8,
921
+ );
922
+
923
+ return {
924
+ strokeColor:
925
+ this.getConfig<string>("image.frame.strokeColor", "#808080") ||
926
+ "#808080",
927
+ strokeWidth: Number.isFinite(strokeWidth) ? Math.max(0, strokeWidth) : 2,
928
+ strokeStyle,
929
+ dashLength: Number.isFinite(dashLength) ? Math.max(1, dashLength) : 8,
930
+ innerBackground:
931
+ this.getConfig<string>(
932
+ "image.frame.innerBackground",
933
+ "rgba(0,0,0,0)",
934
+ ) || "rgba(0,0,0,0)",
935
+ outerBackground:
936
+ this.getConfig<string>("image.frame.outerBackground", "#f5f5f5") ||
937
+ "#f5f5f5",
938
+ };
939
+ }
940
+
941
+ private toSceneGeometryLike(raw: any): SceneGeometryLike | null {
942
+ const shape = raw?.shape;
943
+ if (!isDielineShape(shape)) {
944
+ return null;
945
+ }
946
+
947
+ const radiusRaw = Number(raw?.radius);
948
+ const offsetRaw = Number(raw?.offset);
949
+ const unit = typeof raw?.unit === "string" ? raw.unit : "px";
950
+ const radius =
951
+ unit === "scene" || !this.canvasService
952
+ ? radiusRaw
953
+ : this.canvasService.toSceneLength(radiusRaw);
954
+ const offset =
955
+ unit === "scene" || !this.canvasService
956
+ ? offsetRaw
957
+ : this.canvasService.toSceneLength(offsetRaw);
958
+ return {
959
+ shape,
960
+ shapeStyle: normalizeShapeStyle(raw?.shapeStyle),
961
+ radius: Number.isFinite(radius) ? radius : 0,
962
+ offset: Number.isFinite(offset) ? offset : 0,
963
+ };
964
+ }
965
+
966
+ private async resolveSceneGeometryForOverlay(): Promise<SceneGeometryLike | null> {
967
+ if (!this.context) return null;
968
+ const commandService = this.context.services.get<any>("CommandService");
969
+ if (commandService) {
970
+ try {
971
+ const raw = await Promise.resolve(
972
+ commandService.executeCommand("getSceneGeometry"),
973
+ );
974
+ const geometry = this.toSceneGeometryLike(raw);
975
+ if (geometry) {
976
+ this.debug("overlay:sceneGeometry:command", geometry);
977
+ return geometry;
978
+ }
979
+ this.debug("overlay:sceneGeometry:command:invalid", { raw });
980
+ } catch (error) {
981
+ this.debug("overlay:sceneGeometry:command:error", {
982
+ error: error instanceof Error ? error.message : String(error),
983
+ });
984
+ }
985
+ }
986
+
987
+ if (!this.canvasService) return null;
988
+ const configService = this.context.services.get<ConfigurationService>(
989
+ "ConfigurationService",
990
+ );
991
+ if (!configService) return null;
992
+
993
+ const sizeState = readSizeState(configService);
994
+ const layout = computeSceneLayout(this.canvasService, sizeState);
995
+ if (!layout) {
996
+ this.debug("overlay:sceneGeometry:fallback:missing-layout");
997
+ return null;
998
+ }
999
+
1000
+ const geometry = this.toSceneGeometryLike(
1001
+ buildSceneGeometry(configService, layout),
1002
+ );
1003
+ if (geometry) {
1004
+ this.debug("overlay:sceneGeometry:fallback", geometry);
1005
+ }
1006
+ return geometry;
1007
+ }
1008
+
1009
+ private resolveCutShapeRadius(
1010
+ geometry: SceneGeometryLike,
1011
+ frame: FrameRect,
1012
+ ): number {
1013
+ const visualRadius = Number.isFinite(geometry.radius)
1014
+ ? Math.max(0, geometry.radius)
1015
+ : 0;
1016
+ const visualOffset = Number.isFinite(geometry.offset) ? geometry.offset : 0;
1017
+ const rawCutRadius =
1018
+ visualRadius === 0 ? 0 : Math.max(0, visualRadius + visualOffset);
1019
+ const maxRadius = Math.max(0, Math.min(frame.width, frame.height) / 2);
1020
+ return Math.max(0, Math.min(maxRadius, rawCutRadius));
1021
+ }
1022
+
1023
+ private getCropShapeHatchPattern(
1024
+ color = "rgba(255, 0, 0, 0.6)",
1025
+ ): Pattern | undefined {
1026
+ if (typeof document === "undefined") return undefined;
1027
+ const sceneScale = this.canvasService?.getSceneScale() || 1;
1028
+ const cacheKey = `${color}::${sceneScale.toFixed(6)}`;
1029
+ if (
1030
+ this.cropShapeHatchPattern &&
1031
+ this.cropShapeHatchPatternColor === color &&
1032
+ this.cropShapeHatchPatternKey === cacheKey
1033
+ ) {
1034
+ return this.cropShapeHatchPattern;
1035
+ }
1036
+
1037
+ const size = 16;
1038
+ const patternCanvas = document.createElement("canvas");
1039
+ patternCanvas.width = size;
1040
+ patternCanvas.height = size;
1041
+ const ctx = patternCanvas.getContext("2d");
1042
+ if (!ctx) return undefined;
1043
+
1044
+ ctx.clearRect(0, 0, size, size);
1045
+ ctx.fillStyle = "rgba(255, 0, 0, 0.08)";
1046
+ ctx.fillRect(0, 0, size, size);
1047
+ ctx.strokeStyle = color;
1048
+ ctx.lineWidth = 1.5;
1049
+ ctx.beginPath();
1050
+ ctx.moveTo(-size, size);
1051
+ ctx.lineTo(size, -size);
1052
+ ctx.moveTo(-size / 2, size + size / 2);
1053
+ ctx.lineTo(size + size / 2, -size / 2);
1054
+ ctx.moveTo(0, size);
1055
+ ctx.lineTo(size, 0);
1056
+ ctx.moveTo(size / 2, size + size / 2);
1057
+ ctx.lineTo(size + size + size / 2, -size / 2);
1058
+ ctx.stroke();
1059
+
1060
+ const pattern = new Pattern({
1061
+ source: patternCanvas,
1062
+ // @ts-ignore: Fabric Pattern accepts canvas source here.
1063
+ repetition: "repeat",
1064
+ });
1065
+ // Scene specs are scaled to screen by CanvasService; keep hatch density in screen pixels.
1066
+ (pattern as any).patternTransform = [
1067
+ 1 / sceneScale,
1068
+ 0,
1069
+ 0,
1070
+ 1 / sceneScale,
1071
+ 0,
1072
+ 0,
1073
+ ];
1074
+ this.cropShapeHatchPattern = pattern;
1075
+ this.cropShapeHatchPatternColor = color;
1076
+ this.cropShapeHatchPatternKey = cacheKey;
1077
+ return pattern;
1078
+ }
1079
+
1080
+ private buildCropShapeOverlaySpecs(
1081
+ frame: FrameRect,
1082
+ sceneGeometry: SceneGeometryLike | null,
1083
+ ): RenderObjectSpec[] {
1084
+ if (!sceneGeometry) {
1085
+ this.debug("overlay:shape:skip", { reason: "scene-geometry-missing" });
1086
+ return [];
1087
+ }
1088
+ if (sceneGeometry.shape === "custom") {
1089
+ this.debug("overlay:shape:skip", { reason: "shape-custom" });
1090
+ return [];
1091
+ }
1092
+
1093
+ const shape = sceneGeometry.shape as ShapeOverlayShape;
1094
+ const shapeStyle = sceneGeometry.shapeStyle;
1095
+ const inset = 0;
1096
+ const shapeWidth = Math.max(1, frame.width);
1097
+ const shapeHeight = Math.max(1, frame.height);
1098
+ const radius = this.resolveCutShapeRadius(sceneGeometry, frame);
1099
+
1100
+ this.debug("overlay:shape:geometry", {
1101
+ shape,
1102
+ frameWidth: frame.width,
1103
+ frameHeight: frame.height,
1104
+ offset: sceneGeometry.offset,
1105
+ shapeStyle,
1106
+ inset,
1107
+ shapeWidth,
1108
+ shapeHeight,
1109
+ baseRadius: sceneGeometry.radius,
1110
+ radius,
1111
+ });
1112
+
1113
+ const isSameAsFrame =
1114
+ Math.abs(shapeWidth - frame.width) <= 0.0001 &&
1115
+ Math.abs(shapeHeight - frame.height) <= 0.0001;
1116
+ if (shape === "rect" && radius <= 0.0001 && isSameAsFrame) {
1117
+ this.debug("overlay:shape:skip", {
1118
+ reason: "shape-rect-no-radius",
1119
+ });
1120
+ return [];
1121
+ }
1122
+
1123
+ const baseOptions = {
1124
+ shape,
1125
+ width: shapeWidth,
1126
+ height: shapeHeight,
1127
+ radius,
1128
+ x: frame.width / 2,
1129
+ y: frame.height / 2,
1130
+ features: [],
1131
+ shapeStyle,
1132
+ canvasWidth: frame.width,
1133
+ canvasHeight: frame.height,
1134
+ };
1135
+
1136
+ try {
1137
+ const shapePathData = generateDielinePath(baseOptions);
1138
+ const outerRectPathData = `M 0 0 L ${frame.width} 0 L ${frame.width} ${frame.height} L 0 ${frame.height} Z`;
1139
+ const hatchPathData = `${outerRectPathData} ${shapePathData}`;
1140
+ if (!shapePathData || !hatchPathData) {
1141
+ this.debug("overlay:shape:skip", {
1142
+ reason: "path-generation-empty",
1143
+ shape,
1144
+ radius,
1145
+ });
1146
+ return [];
1147
+ }
1148
+
1149
+ const patternFill = this.getCropShapeHatchPattern();
1150
+ const hatchFill = patternFill || "rgba(255, 0, 0, 0.22)";
1151
+ const shapeBounds = getPathBounds(shapePathData);
1152
+ const hatchBounds = getPathBounds(hatchPathData);
1153
+ const frameRect = this.toLayoutSceneRect(frame);
1154
+ const hatchPathLength = hatchPathData.length;
1155
+ const shapePathLength = shapePathData.length;
1156
+ const specs: RenderObjectSpec[] = [
1157
+ {
1158
+ id: "image.cropShapeHatch",
1159
+ type: "path",
1160
+ data: { id: "image.cropShapeHatch", zIndex: 5 },
1161
+ layout: {
1162
+ reference: "custom",
1163
+ referenceRect: frameRect,
1164
+ alignX: "start",
1165
+ alignY: "start",
1166
+ offsetX: hatchBounds.x,
1167
+ offsetY: hatchBounds.y,
1168
+ },
1169
+ props: {
1170
+ pathData: hatchPathData,
1171
+ originX: "left",
1172
+ originY: "top",
1173
+ fill: hatchFill,
1174
+ opacity: patternFill ? 1 : 0.8,
1175
+ stroke: null,
1176
+ fillRule: "evenodd",
1177
+ selectable: false,
1178
+ evented: false,
1179
+ excludeFromExport: true,
1180
+ objectCaching: false,
1181
+ },
1182
+ },
1183
+ {
1184
+ id: "image.cropShapePath",
1185
+ type: "path",
1186
+ data: { id: "image.cropShapePath", zIndex: 6 },
1187
+ layout: {
1188
+ reference: "custom",
1189
+ referenceRect: frameRect,
1190
+ alignX: "start",
1191
+ alignY: "start",
1192
+ offsetX: shapeBounds.x,
1193
+ offsetY: shapeBounds.y,
1194
+ },
1195
+ props: {
1196
+ pathData: shapePathData,
1197
+ originX: "left",
1198
+ originY: "top",
1199
+ fill: "rgba(0,0,0,0)",
1200
+ stroke: "rgba(255, 0, 0, 0.9)",
1201
+ strokeWidth: this.canvasService?.toSceneLength(1) ?? 1,
1202
+ selectable: false,
1203
+ evented: false,
1204
+ excludeFromExport: true,
1205
+ objectCaching: false,
1206
+ },
1207
+ },
1208
+ ];
1209
+ this.debug("overlay:shape:built", {
1210
+ shape,
1211
+ radius,
1212
+ inset,
1213
+ shapeWidth,
1214
+ shapeHeight,
1215
+ fillRule: "evenodd",
1216
+ shapePathLength,
1217
+ hatchPathLength,
1218
+ shapeBounds,
1219
+ hatchBounds,
1220
+ hatchFillType:
1221
+ hatchFill && typeof hatchFill === "object" ? "pattern" : "color",
1222
+ ids: specs.map((spec) => spec.id),
1223
+ });
1224
+ return specs;
1225
+ } catch (error) {
1226
+ this.debug("overlay:shape:error", {
1227
+ shape,
1228
+ radius,
1229
+ error: error instanceof Error ? error.message : String(error),
1230
+ });
1231
+ return [];
1232
+ }
1233
+ }
1234
+
1235
+ private resolveRenderImageState(item: ImageItem): RenderImageState {
1236
+ const active = this.isToolActive;
1237
+ const sourceUrl = item.sourceUrl || item.url;
1238
+ const committedUrl = item.committedUrl;
1239
+
1240
+ if (!active && committedUrl) {
1241
+ return {
1242
+ src: committedUrl,
1243
+ left: 0.5,
1244
+ top: 0.5,
1245
+ scale: 1,
1246
+ angle: 0,
1247
+ opacity: item.opacity,
1248
+ };
1249
+ }
1250
+
1251
+ return {
1252
+ src: sourceUrl || item.url,
1253
+ left: Number.isFinite(item.left as any) ? (item.left as number) : 0.5,
1254
+ top: Number.isFinite(item.top as any) ? (item.top as number) : 0.5,
1255
+ scale: Math.max(0.05, item.scale ?? 1),
1256
+ angle: Number.isFinite(item.angle as any) ? (item.angle as number) : 0,
1257
+ opacity: item.opacity,
1258
+ };
1259
+ }
1260
+
1261
+ private computeCanvasProps(
1262
+ render: RenderImageState,
1263
+ size: SourceSize,
1264
+ frame: FrameRect,
1265
+ ) {
1266
+ const left = render.left;
1267
+ const top = render.top;
1268
+ const zoom = render.scale;
1269
+ const angle = render.angle;
1270
+
1271
+ const centerX = frame.left + left * frame.width;
1272
+ const centerY = frame.top + top * frame.height;
1273
+ const scale = this.getCoverScale(frame, size) * zoom;
1274
+
1275
+ return {
1276
+ left: centerX,
1277
+ top: centerY,
1278
+ scaleX: scale,
1279
+ scaleY: scale,
1280
+ angle,
1281
+ originX: "center" as const,
1282
+ originY: "center" as const,
1283
+ uniformScaling: true,
1284
+ lockScalingFlip: true,
1285
+ selectable: this.isImageEditingVisible(),
1286
+ evented: this.isImageEditingVisible(),
1287
+ hasControls: this.isImageEditingVisible(),
1288
+ hasBorders: this.isImageEditingVisible(),
1289
+ opacity: render.opacity,
1290
+ };
1291
+ }
1292
+
1293
+ private toScreenObjectProps(props: Record<string, any>): Record<string, any> {
1294
+ if (!this.canvasService) return props;
1295
+ const next = { ...props };
1296
+ if (Number.isFinite(next.left) || Number.isFinite(next.top)) {
1297
+ const mapped = this.canvasService.toScreenPoint({
1298
+ x: Number.isFinite(next.left) ? Number(next.left) : 0,
1299
+ y: Number.isFinite(next.top) ? Number(next.top) : 0,
1300
+ });
1301
+ if (Number.isFinite(next.left)) next.left = mapped.x;
1302
+ if (Number.isFinite(next.top)) next.top = mapped.y;
1303
+ }
1304
+ const sceneScale = this.canvasService.getSceneScale();
1305
+ const sx = Number.isFinite(next.scaleX) ? Number(next.scaleX) : 1;
1306
+ const sy = Number.isFinite(next.scaleY) ? Number(next.scaleY) : 1;
1307
+ next.scaleX = sx * sceneScale;
1308
+ next.scaleY = sy * sceneScale;
1309
+ return next;
1310
+ }
1311
+
1312
+ private toSceneObjectScale(value: number): number {
1313
+ if (!this.canvasService) return value;
1314
+ return value / this.canvasService.getSceneScale();
1315
+ }
1316
+
1317
+ private getCurrentSrc(obj: any): string | undefined {
1318
+ if (!obj) return undefined;
1319
+ if (typeof obj.getSrc === "function") return obj.getSrc();
1320
+ return obj?._originalElement?.src;
1321
+ }
1322
+
1323
+ private applyImageControlVisibility(obj: any) {
1324
+ if (typeof obj?.setControlsVisibility !== "function") return;
1325
+ obj.setControlsVisibility({
1326
+ mt: false,
1327
+ mb: false,
1328
+ ml: false,
1329
+ mr: false,
1330
+ tl: true,
1331
+ tr: true,
1332
+ bl: true,
1333
+ br: true,
1334
+ mtr: true,
1335
+ });
1336
+ }
1337
+
1338
+ private async upsertImageObject(
1339
+ item: ImageItem,
1340
+ frame: FrameRect,
1341
+ seq: number,
1342
+ ) {
1343
+ if (!this.canvasService) return;
1344
+ const canvas = this.canvasService.canvas;
1345
+ const render = this.resolveRenderImageState(item);
1346
+ if (!render.src) return;
1347
+
1348
+ let obj = this.getImageObject(item.id);
1349
+ const currentSrc = this.getCurrentSrc(obj);
1350
+
1351
+ if (obj && currentSrc && currentSrc !== render.src) {
1352
+ canvas.remove(obj);
1353
+ obj = undefined;
1354
+ }
1355
+
1356
+ if (!obj) {
1357
+ const created = await FabricImage.fromURL(render.src, {
1358
+ crossOrigin: "anonymous",
1359
+ });
1360
+ if (seq !== this.renderSeq) return;
1361
+
1362
+ created.set({
1363
+ data: {
1364
+ id: item.id,
1365
+ layerId: IMAGE_OBJECT_LAYER_ID,
1366
+ type: "image-item",
1367
+ },
1368
+ } as any);
1369
+ canvas.add(created as any);
1370
+ obj = created as any;
1371
+ }
1372
+
1373
+ this.rememberSourceSize(render.src, obj);
1374
+ const sourceSize = this.getSourceSize(render.src, obj);
1375
+ const props = this.computeCanvasProps(render, sourceSize, frame);
1376
+ const screenProps = this.toScreenObjectProps(props);
1377
+
1378
+ obj.set({
1379
+ ...screenProps,
1380
+ data: {
1381
+ ...(obj.data || {}),
1382
+ id: item.id,
1383
+ layerId: IMAGE_OBJECT_LAYER_ID,
1384
+ type: "image-item",
1385
+ },
1386
+ });
1387
+ this.applyImageControlVisibility(obj);
1388
+ obj.setCoords();
1389
+
1390
+ const resolver = this.loadResolvers.get(item.id);
1391
+ if (resolver) {
1392
+ resolver();
1393
+ this.loadResolvers.delete(item.id);
1394
+ }
1395
+ }
1396
+
1397
+ private syncImageZOrder(items: ImageItem[]) {
1398
+ if (!this.canvasService) return;
1399
+ const canvas = this.canvasService.canvas;
1400
+
1401
+ const objects = canvas.getObjects();
1402
+ let insertIndex = 0;
1403
+
1404
+ const backgroundLayer = this.canvasService.getLayer("background");
1405
+ if (backgroundLayer) {
1406
+ const bgIndex = objects.indexOf(backgroundLayer as any);
1407
+ if (bgIndex >= 0) insertIndex = bgIndex + 1;
1408
+ }
1409
+
1410
+ items.forEach((item) => {
1411
+ const obj = this.getImageObject(item.id);
1412
+ if (!obj) return;
1413
+ canvas.moveObjectTo(obj, insertIndex);
1414
+ insertIndex += 1;
1415
+ });
1416
+
1417
+ const overlayObjects = this.getOverlayObjects().sort((a: any, b: any) => {
1418
+ const az = Number(a?.data?.zIndex ?? 0);
1419
+ const bz = Number(b?.data?.zIndex ?? 0);
1420
+ return az - bz;
1421
+ });
1422
+ overlayObjects.forEach((obj) => {
1423
+ canvas.bringObjectToFront(obj);
1424
+ });
1425
+
1426
+ if (this.isDebugEnabled()) {
1427
+ const stack = canvas
1428
+ .getObjects()
1429
+ .map((obj: any, index: number) => ({
1430
+ index,
1431
+ id: obj?.data?.id,
1432
+ layerId: obj?.data?.layerId,
1433
+ zIndex: obj?.data?.zIndex,
1434
+ }))
1435
+ .filter((item) => item.layerId === IMAGE_OVERLAY_LAYER_ID);
1436
+ this.debug("overlay:stack", stack);
1437
+ }
1438
+ }
1439
+
1440
+ private buildOverlaySpecs(
1441
+ frame: FrameRect,
1442
+ sceneGeometry: SceneGeometryLike | null,
1443
+ ): RenderObjectSpec[] {
1444
+ const visible = this.isImageEditingVisible();
1445
+ if (
1446
+ !visible ||
1447
+ frame.width <= 0 ||
1448
+ frame.height <= 0 ||
1449
+ !this.canvasService
1450
+ ) {
1451
+ this.debug("overlay:hidden", {
1452
+ visible,
1453
+ frame,
1454
+ isToolActive: this.isToolActive,
1455
+ isImageSelectionActive: this.isImageSelectionActive,
1456
+ focusedImageId: this.focusedImageId,
1457
+ });
1458
+ return [];
1459
+ }
1460
+
1461
+ const viewport = this.canvasService.getSceneViewportRect();
1462
+ const canvasW = viewport.width || 0;
1463
+ const canvasH = viewport.height || 0;
1464
+ const canvasLeft = viewport.left || 0;
1465
+ const canvasTop = viewport.top || 0;
1466
+ const visual = this.getFrameVisualConfig();
1467
+ const strokeWidthScene = this.canvasService.toSceneLength(
1468
+ visual.strokeWidth,
1469
+ );
1470
+ const dashLengthScene = this.canvasService.toSceneLength(visual.dashLength);
1471
+
1472
+ const frameLeft = Math.max(
1473
+ canvasLeft,
1474
+ Math.min(canvasLeft + canvasW, frame.left),
1475
+ );
1476
+ const frameTop = Math.max(
1477
+ canvasTop,
1478
+ Math.min(canvasTop + canvasH, frame.top),
1479
+ );
1480
+ const frameRight = Math.max(
1481
+ frameLeft,
1482
+ Math.min(canvasLeft + canvasW, frame.left + frame.width),
1483
+ );
1484
+ const frameBottom = Math.max(
1485
+ frameTop,
1486
+ Math.min(canvasTop + canvasH, frame.top + frame.height),
1487
+ );
1488
+ const visibleFrameH = Math.max(0, frameBottom - frameTop);
1489
+
1490
+ const topH = Math.max(0, frameTop - canvasTop);
1491
+ const bottomH = Math.max(0, canvasTop + canvasH - frameBottom);
1492
+ const leftW = Math.max(0, frameLeft - canvasLeft);
1493
+ const rightW = Math.max(0, canvasLeft + canvasW - frameRight);
1494
+ const viewportRect = this.toLayoutSceneRect({
1495
+ left: canvasLeft,
1496
+ top: canvasTop,
1497
+ width: canvasW,
1498
+ height: canvasH,
1499
+ });
1500
+ const visibleFrameBandRect = this.toLayoutSceneRect({
1501
+ left: canvasLeft,
1502
+ top: frameTop,
1503
+ width: canvasW,
1504
+ height: visibleFrameH,
1505
+ });
1506
+ const frameRect = this.toLayoutSceneRect(frame);
1507
+ const shapeOverlay = this.buildCropShapeOverlaySpecs(frame, sceneGeometry);
1508
+
1509
+ const mask: RenderObjectSpec[] = [
1510
+ {
1511
+ id: "image.cropMask.top",
1512
+ type: "rect",
1513
+ data: { id: "image.cropMask.top", zIndex: 1 },
1514
+ layout: {
1515
+ reference: "custom",
1516
+ referenceRect: viewportRect,
1517
+ alignX: "start",
1518
+ alignY: "start",
1519
+ width: "100%",
1520
+ height: topH,
1521
+ },
1522
+ props: {
1523
+ originX: "left",
1524
+ originY: "top",
1525
+ fill: visual.outerBackground,
1526
+ selectable: false,
1527
+ evented: false,
1528
+ },
1529
+ },
1530
+ {
1531
+ id: "image.cropMask.bottom",
1532
+ type: "rect",
1533
+ data: { id: "image.cropMask.bottom", zIndex: 2 },
1534
+ layout: {
1535
+ reference: "custom",
1536
+ referenceRect: viewportRect,
1537
+ alignX: "start",
1538
+ alignY: "end",
1539
+ width: "100%",
1540
+ height: bottomH,
1541
+ },
1542
+ props: {
1543
+ originX: "left",
1544
+ originY: "top",
1545
+ fill: visual.outerBackground,
1546
+ selectable: false,
1547
+ evented: false,
1548
+ },
1549
+ },
1550
+ {
1551
+ id: "image.cropMask.left",
1552
+ type: "rect",
1553
+ data: { id: "image.cropMask.left", zIndex: 3 },
1554
+ layout: {
1555
+ reference: "custom",
1556
+ referenceRect: visibleFrameBandRect,
1557
+ alignX: "start",
1558
+ alignY: "start",
1559
+ width: leftW,
1560
+ height: "100%",
1561
+ },
1562
+ props: {
1563
+ originX: "left",
1564
+ originY: "top",
1565
+ fill: visual.outerBackground,
1566
+ selectable: false,
1567
+ evented: false,
1568
+ },
1569
+ },
1570
+ {
1571
+ id: "image.cropMask.right",
1572
+ type: "rect",
1573
+ data: { id: "image.cropMask.right", zIndex: 4 },
1574
+ layout: {
1575
+ reference: "custom",
1576
+ referenceRect: visibleFrameBandRect,
1577
+ alignX: "end",
1578
+ alignY: "start",
1579
+ width: rightW,
1580
+ height: "100%",
1581
+ },
1582
+ props: {
1583
+ originX: "left",
1584
+ originY: "top",
1585
+ fill: visual.outerBackground,
1586
+ selectable: false,
1587
+ evented: false,
1588
+ },
1589
+ },
1590
+ ];
1591
+
1592
+ const frameSpec: RenderObjectSpec = {
1593
+ id: "image.cropFrame",
1594
+ type: "rect",
1595
+ data: { id: "image.cropFrame", zIndex: 7 },
1596
+ layout: {
1597
+ reference: "custom",
1598
+ referenceRect: frameRect,
1599
+ alignX: "start",
1600
+ alignY: "start",
1601
+ width: "100%",
1602
+ height: "100%",
1603
+ },
1604
+ props: {
1605
+ originX: "left",
1606
+ originY: "top",
1607
+ fill: visual.innerBackground,
1608
+ stroke:
1609
+ visual.strokeStyle === "hidden"
1610
+ ? "rgba(0,0,0,0)"
1611
+ : visual.strokeColor,
1612
+ strokeWidth: visual.strokeStyle === "hidden" ? 0 : strokeWidthScene,
1613
+ strokeDashArray:
1614
+ visual.strokeStyle === "dashed"
1615
+ ? [dashLengthScene, dashLengthScene]
1616
+ : undefined,
1617
+ selectable: false,
1618
+ evented: false,
1619
+ },
1620
+ };
1621
+
1622
+ const specs = [...mask, ...shapeOverlay, frameSpec];
1623
+ this.debug("overlay:built", {
1624
+ frame,
1625
+ shape: sceneGeometry?.shape,
1626
+ overlayIds: specs.map((spec) => ({
1627
+ id: spec.id,
1628
+ zIndex: spec.data?.zIndex,
1629
+ })),
1630
+ });
1631
+ return specs;
1632
+ }
1633
+
1634
+ private updateImages() {
1635
+ void this.updateImagesAsync();
1636
+ }
1637
+
1638
+ private async updateImagesAsync() {
1639
+ if (!this.canvasService) return;
1640
+ this.syncToolActiveFromWorkbench();
1641
+ const seq = ++this.renderSeq;
1642
+
1643
+ const renderItems = this.isToolActive ? this.workingItems : this.items;
1644
+ const frame = this.getFrameRect();
1645
+ const desiredIds = new Set(renderItems.map((item) => item.id));
1646
+ if (this.focusedImageId && !desiredIds.has(this.focusedImageId)) {
1647
+ this.setImageFocus(null, {
1648
+ syncCanvasSelection: false,
1649
+ skipRender: true,
1650
+ });
1651
+ }
1652
+
1653
+ this.getImageObjects().forEach((obj: any) => {
1654
+ const id = obj?.data?.id;
1655
+ if (typeof id === "string" && !desiredIds.has(id)) {
1656
+ this.canvasService?.canvas.remove(obj);
1657
+ }
1658
+ });
1659
+
1660
+ for (const item of renderItems) {
1661
+ if (seq !== this.renderSeq) return;
1662
+ await this.upsertImageObject(item, frame, seq);
1663
+ }
1664
+ if (seq !== this.renderSeq) return;
1665
+
1666
+ this.syncImageZOrder(renderItems);
1667
+ const sceneGeometry = await this.resolveSceneGeometryForOverlay();
1668
+ if (seq !== this.renderSeq) return;
1669
+
1670
+ const overlaySpecs = this.buildOverlaySpecs(frame, sceneGeometry);
1671
+ this.overlaySpecs = overlaySpecs;
1672
+ await this.canvasService.flushRenderFromProducers();
1673
+ this.syncImageZOrder(renderItems);
1674
+ const overlayCanvasCount = this.getOverlayObjects().length;
1675
+
1676
+ this.debug("render:done", {
1677
+ seq,
1678
+ renderCount: renderItems.length,
1679
+ overlayCount: overlaySpecs.length,
1680
+ overlayCanvasCount,
1681
+ isToolActive: this.isToolActive,
1682
+ isImageSelectionActive: this.isImageSelectionActive,
1683
+ focusedImageId: this.focusedImageId,
1684
+ });
1685
+ this.canvasService.requestRenderAll();
1686
+ }
1687
+
1688
+ private clampNormalized(value: number): number {
1689
+ return Math.max(-1, Math.min(2, value));
1690
+ }
1691
+
1692
+ private onObjectModified = (e: any) => {
1693
+ if (!this.isToolActive) return;
1694
+ const target = e?.target;
1695
+ const id = target?.data?.id;
1696
+ const layerId = target?.data?.layerId;
1697
+ if (typeof id !== "string" || layerId !== IMAGE_OBJECT_LAYER_ID) return;
1698
+
1699
+ const frame = this.getFrameRect();
1700
+ if (!frame.width || !frame.height) return;
1701
+
1702
+ const center = target.getCenterPoint
1703
+ ? target.getCenterPoint()
1704
+ : new Point(target.left ?? 0, target.top ?? 0);
1705
+ const centerScene = this.canvasService
1706
+ ? this.canvasService.toScenePoint({ x: center.x, y: center.y })
1707
+ : { x: center.x, y: center.y };
1708
+
1709
+ const objectScale = Number.isFinite(target?.scaleX) ? target.scaleX : 1;
1710
+ const objectScaleScene = this.toSceneObjectScale(objectScale || 1);
1711
+
1712
+ const workingItem = this.workingItems.find((item) => item.id === id);
1713
+ const sourceKey = workingItem?.sourceUrl || workingItem?.url || "";
1714
+ const sourceSize = this.getSourceSize(sourceKey, target);
1715
+ const coverScale = this.getCoverScale(frame, sourceSize);
1716
+
1717
+ const updates: Partial<ImageItem> = {
1718
+ left: this.clampNormalized((centerScene.x - frame.left) / frame.width),
1719
+ top: this.clampNormalized((centerScene.y - frame.top) / frame.height),
1720
+ angle: Number.isFinite(target.angle) ? target.angle : 0,
1721
+ scale: Math.max(0.05, objectScaleScene / coverScale),
1722
+ };
1723
+
1724
+ this.focusedImageId = id;
1725
+ this.updateImageInWorking(id, updates);
1726
+ };
1727
+
1728
+ private updateImageInWorking(id: string, updates: Partial<ImageItem>) {
1729
+ const index = this.workingItems.findIndex((item) => item.id === id);
1730
+ if (index < 0) return;
1731
+
1732
+ const next = [...this.workingItems];
1733
+ next[index] = this.normalizeItem({ ...next[index], ...updates });
1734
+ this.workingItems = next;
1735
+ this.hasWorkingChanges = true;
1736
+ this.setImageFocus(id, {
1737
+ syncCanvasSelection: false,
1738
+ skipRender: true,
1739
+ });
1740
+ if (this.isToolActive) {
1741
+ this.updateImages();
1742
+ }
1743
+ this.emitWorkingChange(id);
1744
+ }
1745
+
1746
+ private async updateImageInConfig(id: string, updates: Partial<ImageItem>) {
1747
+ const index = this.items.findIndex((item) => item.id === id);
1748
+ if (index < 0) return;
1749
+
1750
+ const replacingSource =
1751
+ typeof updates.url === "string" && updates.url.length > 0;
1752
+ const next = [...this.items];
1753
+ const base = next[index];
1754
+ const replacingUrl = replacingSource ? (updates.url as string) : undefined;
1755
+
1756
+ next[index] = this.normalizeItem({
1757
+ ...base,
1758
+ ...updates,
1759
+ ...(replacingSource
1760
+ ? {
1761
+ url: replacingUrl,
1762
+ sourceUrl: replacingUrl,
1763
+ committedUrl: undefined,
1764
+ scale: updates.scale ?? 1,
1765
+ angle: updates.angle ?? 0,
1766
+ left: updates.left ?? 0.5,
1767
+ top: updates.top ?? 0.5,
1768
+ }
1769
+ : {}),
1770
+ });
1771
+
1772
+ this.updateConfig(next);
1773
+
1774
+ if (replacingSource) {
1775
+ this.debug("replace:image:begin", { id, replacingUrl });
1776
+ this.purgeSourceSizeCacheForItem(base);
1777
+ const loaded = await this.waitImageLoaded(id, true);
1778
+ this.debug("replace:image:loaded", { id, loaded });
1779
+ if (loaded) {
1780
+ await this.refitImageToFrame(id);
1781
+ this.setImageFocus(id);
1782
+ }
1783
+ }
1784
+ }
1785
+
1786
+ private waitImageLoaded(id: string, forceWait = false): Promise<boolean> {
1787
+ if (!forceWait && this.getImageObject(id)) {
1788
+ return Promise.resolve(true);
1789
+ }
1790
+
1791
+ return new Promise<boolean>((resolve) => {
1792
+ const timeout = setTimeout(() => {
1793
+ this.loadResolvers.delete(id);
1794
+ resolve(false);
1795
+ }, 4000);
1796
+
1797
+ this.loadResolvers.set(id, () => {
1798
+ clearTimeout(timeout);
1799
+ resolve(true);
1800
+ });
1801
+ });
1802
+ }
1803
+
1804
+ private async refitImageToFrame(id: string) {
1805
+ const obj = this.getImageObject(id);
1806
+ if (!obj || !this.canvasService) return;
1807
+ const current = this.items.find((item) => item.id === id);
1808
+ if (!current) return;
1809
+ const render = this.resolveRenderImageState(current);
1810
+
1811
+ this.rememberSourceSize(render.src, obj);
1812
+ const source = this.getSourceSize(render.src, obj);
1813
+ const frame = this.getFrameRect();
1814
+ const coverScale = this.getCoverScale(frame, source);
1815
+
1816
+ const currentScale = this.toSceneObjectScale(obj.scaleX || 1);
1817
+ const zoom = Math.max(0.05, currentScale / coverScale);
1818
+
1819
+ const updated: Partial<ImageItem> = {
1820
+ scale: Number.isFinite(zoom) ? zoom : 1,
1821
+ angle: 0,
1822
+ left: 0.5,
1823
+ top: 0.5,
1824
+ };
1825
+
1826
+ const index = this.items.findIndex((item) => item.id === id);
1827
+ if (index < 0) return;
1828
+
1829
+ const next = [...this.items];
1830
+ next[index] = this.normalizeItem({ ...next[index], ...updated });
1831
+ this.updateConfig(next);
1832
+ this.workingItems = this.cloneItems(next);
1833
+ this.hasWorkingChanges = false;
1834
+ this.updateImages();
1835
+ this.emitWorkingChange(id);
1836
+ }
1837
+
1838
+ private async fitImageToArea(
1839
+ id: string,
1840
+ area: { width: number; height: number; left?: number; top?: number },
1841
+ ) {
1842
+ if (!this.canvasService) return;
1843
+
1844
+ const loaded = await this.waitImageLoaded(id, false);
1845
+ if (!loaded) return;
1846
+
1847
+ const obj = this.getImageObject(id);
1848
+ if (!obj) return;
1849
+ const renderItems = this.isToolActive ? this.workingItems : this.items;
1850
+ const current = renderItems.find((item) => item.id === id);
1851
+ if (!current) return;
1852
+ const render = this.resolveRenderImageState(current);
1853
+
1854
+ this.rememberSourceSize(render.src, obj);
1855
+ const source = this.getSourceSize(render.src, obj);
1856
+ const frame = this.getFrameRect();
1857
+ const baseCover = this.getCoverScale(frame, source);
1858
+
1859
+ const desiredScale = Math.max(
1860
+ Math.max(1, area.width) / Math.max(1, source.width),
1861
+ Math.max(1, area.height) / Math.max(1, source.height),
1862
+ );
1863
+
1864
+ const viewport = this.canvasService.getSceneViewportRect();
1865
+ const canvasW = viewport.width || 1;
1866
+ const canvasH = viewport.height || 1;
1867
+
1868
+ const areaLeftInput = area.left ?? 0.5;
1869
+ const areaTopInput = area.top ?? 0.5;
1870
+
1871
+ const areaLeftPx =
1872
+ areaLeftInput <= 1.5
1873
+ ? viewport.left + areaLeftInput * canvasW
1874
+ : areaLeftInput;
1875
+ const areaTopPx =
1876
+ areaTopInput <= 1.5
1877
+ ? viewport.top + areaTopInput * canvasH
1878
+ : areaTopInput;
1879
+
1880
+ const updates: Partial<ImageItem> = {
1881
+ scale: Math.max(0.05, desiredScale / baseCover),
1882
+ left: this.clampNormalized(
1883
+ (areaLeftPx - frame.left) / Math.max(1, frame.width),
1884
+ ),
1885
+ top: this.clampNormalized(
1886
+ (areaTopPx - frame.top) / Math.max(1, frame.height),
1887
+ ),
1888
+ };
1889
+
1890
+ if (this.isToolActive) {
1891
+ this.updateImageInWorking(id, updates);
1892
+ return;
1893
+ }
1894
+
1895
+ await this.updateImageInConfig(id, updates);
1896
+ }
1897
+
1898
+ private async commitWorkingImagesAsCropped() {
1899
+ if (!this.canvasService) {
1900
+ return { ok: false, reason: "canvas-not-ready" };
1901
+ }
1902
+
1903
+ await this.updateImagesAsync();
1904
+
1905
+ const frame = this.getFrameRect();
1906
+ if (!frame.width || !frame.height) {
1907
+ return { ok: false, reason: "frame-not-ready" };
1908
+ }
1909
+
1910
+ const next: ImageItem[] = [];
1911
+ for (const item of this.workingItems) {
1912
+ const exported = await this.exportCroppedImageByIds([item.id], {
1913
+ multiplier: 2,
1914
+ format: "png",
1915
+ });
1916
+ const url = exported.url;
1917
+
1918
+ const sourceUrl = item.sourceUrl || item.url;
1919
+ const previousCommitted = item.committedUrl;
1920
+ next.push(
1921
+ this.normalizeItem({
1922
+ ...item,
1923
+ url,
1924
+ // Keep original source for next image-tool session editing,
1925
+ // and use committedUrl as non-image-tools render source.
1926
+ sourceUrl,
1927
+ committedUrl: url,
1928
+ }),
1929
+ );
1930
+ if (previousCommitted && previousCommitted !== url) {
1931
+ this.sourceSizeBySrc.delete(previousCommitted);
1932
+ }
1933
+ }
1934
+
1935
+ this.hasWorkingChanges = false;
1936
+ this.workingItems = this.cloneItems(next);
1937
+ this.updateConfig(next);
1938
+ this.emitWorkingChange(this.focusedImageId);
1939
+ return { ok: true };
1940
+ }
1941
+
1942
+ private async exportCroppedImageByIds(
1943
+ imageIds: string[],
1944
+ options: ExportCroppedImageOptions,
1945
+ ): Promise<ExportUserCroppedImageResult> {
1946
+ if (!this.canvasService) {
1947
+ throw new Error("CanvasService not initialized");
1948
+ }
1949
+
1950
+ const normalizedIds = [...new Set(imageIds)].filter(
1951
+ (id): id is string => typeof id === "string" && id.length > 0,
1952
+ );
1953
+ if (!normalizedIds.length) {
1954
+ throw new Error("image-ids-required");
1955
+ }
1956
+
1957
+ const frameScene = this.getFrameRect();
1958
+ const frame = this.getFrameRectScreen(frameScene);
1959
+ const multiplier = Math.max(1, options.multiplier ?? 2);
1960
+ const format: "png" | "jpeg" = options.format === "jpeg" ? "jpeg" : "png";
1961
+
1962
+ const width = Math.max(1, Math.round(frame.width * multiplier));
1963
+ const height = Math.max(1, Math.round(frame.height * multiplier));
1964
+
1965
+ const el = document.createElement("canvas");
1966
+ const tempCanvas = new FabricCanvas(el, {
1967
+ renderOnAddRemove: false,
1968
+ selection: false,
1969
+ enableRetinaScaling: false,
1970
+ preserveObjectStacking: true,
1971
+ } as any);
1972
+ tempCanvas.setDimensions({ width, height });
1973
+
1974
+ try {
1975
+ const idSet = new Set(normalizedIds);
1976
+ const sourceObjects = this.canvasService.canvas
1977
+ .getObjects()
1978
+ .filter((obj: any) => {
1979
+ return (
1980
+ obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID &&
1981
+ typeof obj?.data?.id === "string" &&
1982
+ idSet.has(obj.data.id)
1983
+ );
1984
+ });
1985
+
1986
+ if (!sourceObjects.length) {
1987
+ throw new Error("image-objects-not-found");
1988
+ }
1989
+
1990
+ for (const source of sourceObjects as any[]) {
1991
+ const clone = await source.clone();
1992
+ const center = source.getCenterPoint
1993
+ ? source.getCenterPoint()
1994
+ : new Point(source.left ?? 0, source.top ?? 0);
1995
+
1996
+ clone.set({
1997
+ originX: "center",
1998
+ originY: "center",
1999
+ left: (center.x - frame.left) * multiplier,
2000
+ top: (center.y - frame.top) * multiplier,
2001
+ scaleX: (source.scaleX || 1) * multiplier,
2002
+ scaleY: (source.scaleY || 1) * multiplier,
2003
+ angle: source.angle || 0,
2004
+ selectable: false,
2005
+ evented: false,
2006
+ });
2007
+ clone.setCoords();
2008
+ tempCanvas.add(clone);
2009
+ }
2010
+
2011
+ tempCanvas.renderAll();
2012
+ const blob = await tempCanvas.toBlob({ format, multiplier: 1 });
2013
+ if (!blob) {
2014
+ throw new Error("image-export-failed");
2015
+ }
2016
+
2017
+ return {
2018
+ url: URL.createObjectURL(blob),
2019
+ width,
2020
+ height,
2021
+ multiplier,
2022
+ format,
2023
+ imageIds: (sourceObjects as any[])
2024
+ .map((obj: any) => obj?.data?.id)
2025
+ .filter((id: any): id is string => typeof id === "string"),
2026
+ };
2027
+ } finally {
2028
+ tempCanvas.dispose();
2029
+ }
2030
+ }
2031
+
2032
+ private async exportUserCroppedImage(
2033
+ options: ExportUserCroppedImageOptions = {},
2034
+ ): Promise<ExportUserCroppedImageResult> {
2035
+ if (!this.canvasService) {
2036
+ throw new Error("CanvasService not initialized");
2037
+ }
2038
+
2039
+ await this.updateImagesAsync();
2040
+ this.syncToolActiveFromWorkbench();
2041
+
2042
+ const imageIds =
2043
+ options.imageIds && options.imageIds.length > 0
2044
+ ? options.imageIds
2045
+ : (this.isToolActive ? this.workingItems : this.items).map(
2046
+ (item) => item.id,
2047
+ );
2048
+ if (!imageIds.length) {
2049
+ throw new Error("no-images-to-export");
2050
+ }
2051
+
2052
+ return await this.exportCroppedImageByIds(imageIds, options);
2053
+ }
2054
+ }