@pooder/kit 5.3.0 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/.test-dist/src/CanvasService.js +249 -249
  2. package/.test-dist/src/ViewportSystem.js +75 -75
  3. package/.test-dist/src/background.js +203 -203
  4. package/.test-dist/src/bridgeSelection.js +20 -20
  5. package/.test-dist/src/constraints.js +237 -237
  6. package/.test-dist/src/dieline.js +818 -818
  7. package/.test-dist/src/edgeScale.js +12 -12
  8. package/.test-dist/src/feature.js +826 -826
  9. package/.test-dist/src/featureComplete.js +32 -32
  10. package/.test-dist/src/film.js +167 -167
  11. package/.test-dist/src/geometry.js +506 -506
  12. package/.test-dist/src/image.js +1250 -1250
  13. package/.test-dist/src/maskOps.js +270 -270
  14. package/.test-dist/src/mirror.js +104 -104
  15. package/.test-dist/src/renderSpec.js +2 -2
  16. package/.test-dist/src/ruler.js +343 -343
  17. package/.test-dist/src/sceneLayout.js +99 -99
  18. package/.test-dist/src/sceneLayoutModel.js +196 -196
  19. package/.test-dist/src/sceneView.js +40 -40
  20. package/.test-dist/src/sceneVisibility.js +42 -42
  21. package/.test-dist/src/size.js +332 -332
  22. package/.test-dist/src/tracer.js +544 -544
  23. package/.test-dist/src/white-ink.js +829 -829
  24. package/.test-dist/src/wrappedOffsets.js +33 -33
  25. package/CHANGELOG.md +6 -0
  26. package/dist/index.d.mts +6 -0
  27. package/dist/index.d.ts +6 -0
  28. package/dist/index.js +108 -20
  29. package/dist/index.mjs +108 -20
  30. package/package.json +1 -1
  31. package/src/coordinate.ts +106 -106
  32. package/src/extensions/background.ts +230 -230
  33. package/src/extensions/bridgeSelection.ts +17 -17
  34. package/src/extensions/constraints.ts +322 -322
  35. package/src/extensions/dieline.ts +46 -0
  36. package/src/extensions/edgeScale.ts +19 -19
  37. package/src/extensions/feature.ts +1021 -1021
  38. package/src/extensions/featureComplete.ts +46 -46
  39. package/src/extensions/film.ts +194 -194
  40. package/src/extensions/geometry.ts +752 -719
  41. package/src/extensions/image.ts +1926 -1924
  42. package/src/extensions/index.ts +11 -11
  43. package/src/extensions/maskOps.ts +283 -283
  44. package/src/extensions/mirror.ts +128 -128
  45. package/src/extensions/ruler.ts +451 -451
  46. package/src/extensions/sceneLayout.ts +140 -140
  47. package/src/extensions/sceneLayoutModel.ts +352 -342
  48. package/src/extensions/sceneVisibility.ts +71 -71
  49. package/src/extensions/size.ts +389 -389
  50. package/src/extensions/tracer.ts +58 -19
  51. package/src/extensions/white-ink.ts +1400 -1400
  52. package/src/extensions/wrappedOffsets.ts +33 -33
  53. package/src/index.ts +2 -2
  54. package/src/services/CanvasService.ts +300 -300
  55. package/src/services/ViewportSystem.ts +95 -95
  56. package/src/services/index.ts +3 -3
  57. package/src/services/renderSpec.ts +18 -18
  58. package/src/units.ts +27 -27
  59. package/tests/run.ts +118 -118
  60. package/tsconfig.test.json +15 -15
@@ -1,1924 +1,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, 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
- sourceUrl,
1798
- committedUrl: url,
1799
- }),
1800
- );
1801
- if (previousCommitted && previousCommitted !== url) {
1802
- this.sourceSizeBySrc.delete(previousCommitted);
1803
- }
1804
- }
1805
-
1806
- this.hasWorkingChanges = false;
1807
- this.workingItems = this.cloneItems(next);
1808
- this.updateConfig(next);
1809
- this.emitWorkingChange(this.focusedImageId);
1810
- return { ok: true };
1811
- }
1812
-
1813
- private async exportCroppedImageByIds(
1814
- imageIds: string[],
1815
- options: ExportCroppedImageOptions,
1816
- ): Promise<ExportUserCroppedImageResult> {
1817
- if (!this.canvasService) {
1818
- throw new Error("CanvasService not initialized");
1819
- }
1820
-
1821
- const normalizedIds = [...new Set(imageIds)].filter(
1822
- (id): id is string => typeof id === "string" && id.length > 0,
1823
- );
1824
- if (!normalizedIds.length) {
1825
- throw new Error("image-ids-required");
1826
- }
1827
-
1828
- const frame = this.getFrameRect();
1829
- const multiplier = Math.max(1, options.multiplier ?? 2);
1830
- const format: "png" | "jpeg" = options.format === "jpeg" ? "jpeg" : "png";
1831
-
1832
- const width = Math.max(1, Math.round(frame.width * multiplier));
1833
- const height = Math.max(1, Math.round(frame.height * multiplier));
1834
-
1835
- const el = document.createElement("canvas");
1836
- const tempCanvas = new FabricCanvas(el, {
1837
- renderOnAddRemove: false,
1838
- selection: false,
1839
- enableRetinaScaling: false,
1840
- preserveObjectStacking: true,
1841
- } as any);
1842
- tempCanvas.setDimensions({ width, height });
1843
-
1844
- try {
1845
- const idSet = new Set(normalizedIds);
1846
- const sourceObjects = this.canvasService.canvas
1847
- .getObjects()
1848
- .filter((obj: any) => {
1849
- return (
1850
- obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID &&
1851
- typeof obj?.data?.id === "string" &&
1852
- idSet.has(obj.data.id)
1853
- );
1854
- });
1855
-
1856
- if (!sourceObjects.length) {
1857
- throw new Error("image-objects-not-found");
1858
- }
1859
-
1860
- for (const source of sourceObjects as any[]) {
1861
- const clone = await source.clone();
1862
- const center = source.getCenterPoint
1863
- ? source.getCenterPoint()
1864
- : new Point(source.left ?? 0, source.top ?? 0);
1865
-
1866
- clone.set({
1867
- originX: "center",
1868
- originY: "center",
1869
- left: (center.x - frame.left) * multiplier,
1870
- top: (center.y - frame.top) * multiplier,
1871
- scaleX: (source.scaleX || 1) * multiplier,
1872
- scaleY: (source.scaleY || 1) * multiplier,
1873
- angle: source.angle || 0,
1874
- selectable: false,
1875
- evented: false,
1876
- });
1877
- clone.setCoords();
1878
- tempCanvas.add(clone);
1879
- }
1880
-
1881
- tempCanvas.renderAll();
1882
- const blob = await tempCanvas.toBlob({ format, multiplier: 1 });
1883
- if (!blob) {
1884
- throw new Error("image-export-failed");
1885
- }
1886
-
1887
- return {
1888
- url: URL.createObjectURL(blob),
1889
- width,
1890
- height,
1891
- multiplier,
1892
- format,
1893
- imageIds: (sourceObjects as any[])
1894
- .map((obj: any) => obj?.data?.id)
1895
- .filter((id: any): id is string => typeof id === "string"),
1896
- };
1897
- } finally {
1898
- tempCanvas.dispose();
1899
- }
1900
- }
1901
-
1902
- private async exportUserCroppedImage(
1903
- options: ExportUserCroppedImageOptions = {},
1904
- ): Promise<ExportUserCroppedImageResult> {
1905
- if (!this.canvasService) {
1906
- throw new Error("CanvasService not initialized");
1907
- }
1908
-
1909
- await this.updateImagesAsync();
1910
- this.syncToolActiveFromWorkbench();
1911
-
1912
- const imageIds =
1913
- options.imageIds && options.imageIds.length > 0
1914
- ? options.imageIds
1915
- : (this.isToolActive ? this.workingItems : this.items).map(
1916
- (item) => item.id,
1917
- );
1918
- if (!imageIds.length) {
1919
- throw new Error("no-images-to-export");
1920
- }
1921
-
1922
- return await this.exportCroppedImageByIds(imageIds, options);
1923
- }
1924
- }
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
+ }