@pooder/kit 5.3.1 → 5.4.0

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