@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,1525 +1,1578 @@
1
- import {
2
- Extension,
3
- ExtensionContext,
4
- ContributionPointIds,
5
- CommandContribution,
6
- ConfigurationContribution,
7
- ConfigurationService,
8
- ToolSessionService,
9
- WorkbenchService,
10
- } from "@pooder/core";
11
- import { CanvasService, RenderObjectSpec } from "../services";
12
- import { computeSceneLayout, readSizeState } from "./sceneLayoutModel";
13
-
14
- export interface WhiteInkItem {
15
- id: string;
16
- sourceUrl?: string;
17
- url?: string;
18
- opacity: number;
19
- }
20
-
21
- interface SourceSize {
22
- width: number;
23
- height: number;
24
- }
25
-
26
- interface MaskTint {
27
- r: number;
28
- g: number;
29
- b: number;
30
- key: string;
31
- }
32
-
33
- interface FrameRect {
34
- left: number;
35
- top: number;
36
- width: number;
37
- height: number;
38
- }
39
-
40
- interface ImageSnapshot {
41
- id: string;
42
- src: string;
43
- element: any;
44
- left: number;
45
- top: number;
46
- scaleX: number;
47
- scaleY: number;
48
- angle: number;
49
- originX: string;
50
- originY: string;
51
- flipX: boolean;
52
- flipY: boolean;
53
- skewX: number;
54
- skewY: number;
55
- width: number;
56
- height: number;
57
- }
58
-
59
- interface ImagePlacementState {
60
- id: string;
61
- sourceUrl: string;
62
- committedUrl: string;
63
- left: number;
64
- top: number;
65
- scale: number;
66
- angle: number;
67
- }
68
-
69
- interface RenderSources {
70
- whiteSrc: string;
71
- coverSrc: string;
72
- whiteScaleAdjustX: number;
73
- whiteScaleAdjustY: number;
74
- }
75
-
76
- interface UpsertWhiteInkOptions {
77
- id?: string;
78
- mode?: "auto" | "replace" | "add";
79
- createIfMissing?: boolean;
80
- addOptions?: Partial<WhiteInkItem>;
81
- }
82
-
83
- interface UpdateWhiteInkOptions {
84
- target?: "auto" | "config" | "working";
85
- }
86
-
87
- const WHITE_INK_OBJECT_LAYER_ID = "white-ink.user";
88
- const WHITE_INK_COVER_LAYER_ID = "white-ink.cover";
89
- const WHITE_INK_OVERLAY_LAYER_ID = "white-ink.overlay";
90
- const IMAGE_OBJECT_LAYER_ID = "image.user";
91
- const IMAGE_OVERLAY_LAYER_ID = "image-overlay";
92
-
93
- const WHITE_INK_DEBUG_KEY = "whiteInk.debug";
94
- const WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY = "whiteInk.previewImageVisible";
95
- const WHITE_INK_DEFAULT_OPACITY = 0.85;
96
- const WHITE_INK_AUTO_ITEM_ID = "white-ink-auto";
97
-
98
- const WHITE_INK_COVER_OPACITY_FACTOR = 0.45;
99
- const WHITE_INK_COVER_OPACITY_MIN = 0.15;
100
- const WHITE_INK_COVER_OPACITY_MAX = 0.65;
101
- const WHITE_MASK_TINT: MaskTint = { r: 255, g: 255, b: 255, key: "white" };
102
- const COVER_MASK_TINT: MaskTint = { r: 52, g: 136, b: 255, key: "blue" };
103
-
104
- export class WhiteInkTool implements Extension {
105
- id = "pooder.kit.white-ink";
106
-
107
- metadata = {
108
- name: "WhiteInkTool",
109
- };
110
-
111
- private items: WhiteInkItem[] = [];
112
- private workingItems: WhiteInkItem[] = [];
113
- private hasWorkingChanges = false;
114
-
115
- private sourceSizeBySrc: Map<string, SourceSize> = new Map();
116
- private previewMaskBySource: Map<string, string> = new Map();
117
- private pendingPreviewMaskBySource: Map<string, Promise<string | null>> =
118
- new Map();
119
-
120
- private canvasService?: CanvasService;
121
- private context?: ExtensionContext;
122
- private isUpdatingConfig = false;
123
- private isToolActive = false;
124
- private printWithWhiteInk = true;
125
- private previewImageVisible = true;
126
- private renderSeq = 0;
127
- private dirtyTrackerDisposable?: { dispose(): void };
128
-
129
- activate(context: ExtensionContext) {
130
- this.context = context;
131
- this.canvasService = context.services.get<CanvasService>("CanvasService");
132
- if (!this.canvasService) {
133
- console.warn("CanvasService not found for WhiteInkTool");
134
- return;
135
- }
136
-
137
- context.eventBus.on("tool:activated", this.onToolActivated);
138
- context.eventBus.on("scene:layout:change", this.onSceneLayoutChanged);
139
- context.eventBus.on("object:added", this.onObjectAdded);
140
- context.eventBus.on("object:modified", this.onObjectModified);
141
- context.eventBus.on("object:removed", this.onObjectRemoved);
142
- context.eventBus.on("image:working:change", this.onImageWorkingChanged);
143
-
144
- const configService = context.services.get<ConfigurationService>(
145
- "ConfigurationService",
146
- );
147
- if (configService) {
148
- this.items = this.normalizeItems(
149
- configService.get("whiteInk.items", []) || [],
150
- );
151
- this.workingItems = this.cloneItems(this.items);
152
- this.hasWorkingChanges = false;
153
- this.printWithWhiteInk = !!configService.get(
154
- "whiteInk.printWithWhiteInk",
155
- true,
156
- );
157
- this.previewImageVisible = !!configService.get(
158
- WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY,
159
- true,
160
- );
161
-
162
- this.migrateLegacyConfigIfNeeded(configService);
163
-
164
- configService.onAnyChange((e: { key: string; value: any }) => {
165
- if (this.isUpdatingConfig) return;
166
-
167
- if (e.key === "whiteInk.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.updateWhiteInks();
174
- return;
175
- }
176
-
177
- if (e.key === "whiteInk.printWithWhiteInk") {
178
- this.printWithWhiteInk = !!e.value;
179
- this.updateWhiteInks();
180
- return;
181
- }
182
-
183
- if (e.key === WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY) {
184
- this.previewImageVisible = !!e.value;
185
- this.updateWhiteInks();
186
- return;
187
- }
188
-
189
- if (e.key === "image.items") {
190
- this.updateWhiteInks();
191
- return;
192
- }
193
-
194
- if (e.key === WHITE_INK_DEBUG_KEY) {
195
- return;
196
- }
197
-
198
- if (e.key.startsWith("size.")) {
199
- this.updateWhiteInks();
200
- }
201
- });
202
- }
203
-
204
- const toolSessionService =
205
- context.services.get<ToolSessionService>("ToolSessionService");
206
- this.dirtyTrackerDisposable = toolSessionService?.registerDirtyTracker(
207
- this.id,
208
- () => this.hasWorkingChanges,
209
- );
210
-
211
- this.updateWhiteInks();
212
- }
213
-
214
- deactivate(context: ExtensionContext) {
215
- context.eventBus.off("tool:activated", this.onToolActivated);
216
- context.eventBus.off("scene:layout:change", this.onSceneLayoutChanged);
217
- context.eventBus.off("object:added", this.onObjectAdded);
218
- context.eventBus.off("object:modified", this.onObjectModified);
219
- context.eventBus.off("object:removed", this.onObjectRemoved);
220
- context.eventBus.off("image:working:change", this.onImageWorkingChanged);
221
-
222
- this.dirtyTrackerDisposable?.dispose();
223
- this.dirtyTrackerDisposable = undefined;
224
- this.clearRenderedWhiteInks();
225
- this.applyImageVisibilityForWhiteInk(false);
226
-
227
- this.canvasService = undefined;
228
- this.context = undefined;
229
- }
230
-
231
- contribute() {
232
- return {
233
- [ContributionPointIds.TOOLS]: [
234
- {
235
- id: this.id,
236
- name: "White Ink",
237
- interaction: "session",
238
- commands: {
239
- begin: "resetWorkingWhiteInks",
240
- commit: "completeWhiteInks",
241
- rollback: "resetWorkingWhiteInks",
242
- },
243
- session: {
244
- autoBegin: true,
245
- leavePolicy: "block",
246
- },
247
- },
248
- ],
249
- [ContributionPointIds.CONFIGURATIONS]: [
250
- {
251
- id: "whiteInk.items",
252
- type: "array",
253
- label: "White Ink Images",
254
- default: [],
255
- },
256
- {
257
- id: "whiteInk.printWithWhiteInk",
258
- type: "boolean",
259
- label: "Preview White Ink",
260
- default: true,
261
- },
262
- {
263
- id: WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY,
264
- type: "boolean",
265
- label: "Show Cover During White Ink Preview",
266
- default: true,
267
- },
268
- {
269
- id: WHITE_INK_DEBUG_KEY,
270
- type: "boolean",
271
- label: "White Ink Debug Log",
272
- default: false,
273
- },
274
- ] as ConfigurationContribution[],
275
- [ContributionPointIds.COMMANDS]: [
276
- {
277
- command: "addWhiteInk",
278
- title: "Add White Ink",
279
- handler: async (url: string, options?: Partial<WhiteInkItem>) => {
280
- return await this.addWhiteInkEntry(url, options);
281
- },
282
- },
283
- {
284
- command: "upsertWhiteInk",
285
- title: "Upsert White Ink",
286
- handler: async (url: string, options: UpsertWhiteInkOptions = {}) => {
287
- return await this.upsertWhiteInkEntry(url, options);
288
- },
289
- },
290
- {
291
- command: "getWhiteInks",
292
- title: "Get White Inks",
293
- handler: () => this.cloneItems(this.items),
294
- },
295
- {
296
- command: "getWhiteInkSettings",
297
- title: "Get White Ink Settings",
298
- handler: () => {
299
- const first = this.getEffectiveWhiteInkItem(this.items);
300
- const primarySource = this.getPrimaryImageSource();
301
- const sourceUrl = this.resolveSourceUrl(first) || primarySource;
302
-
303
- return {
304
- id: first?.id || null,
305
- url: sourceUrl,
306
- sourceUrl,
307
- opacity: WHITE_INK_DEFAULT_OPACITY,
308
- printWithWhiteInk: this.printWithWhiteInk,
309
- previewImageVisible: this.previewImageVisible,
310
- };
311
- },
312
- },
313
- {
314
- command: "setWhiteInkPrintEnabled",
315
- title: "Set White Ink Preview Enabled",
316
- handler: (enabled: boolean) => {
317
- this.printWithWhiteInk = !!enabled;
318
- const configService =
319
- this.context?.services.get<ConfigurationService>(
320
- "ConfigurationService",
321
- );
322
- configService?.update(
323
- "whiteInk.printWithWhiteInk",
324
- this.printWithWhiteInk,
325
- );
326
- this.updateWhiteInks();
327
- return { ok: true };
328
- },
329
- },
330
- {
331
- command: "setWhiteInkPreviewImageVisible",
332
- title: "Set White Ink Cover Visible",
333
- handler: (visible: boolean) => {
334
- this.previewImageVisible = !!visible;
335
- const configService =
336
- this.context?.services.get<ConfigurationService>(
337
- "ConfigurationService",
338
- );
339
- configService?.update(
340
- WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY,
341
- this.previewImageVisible,
342
- );
343
- this.updateWhiteInks();
344
- return { ok: true };
345
- },
346
- },
347
- {
348
- command: "getWorkingWhiteInks",
349
- title: "Get Working White Inks",
350
- handler: () => this.cloneItems(this.workingItems),
351
- },
352
- {
353
- command: "setWorkingWhiteInk",
354
- title: "Set Working White Ink",
355
- handler: (id: string, updates: Partial<WhiteInkItem>) => {
356
- this.updateWhiteInkInWorking(id, updates);
357
- },
358
- },
359
- {
360
- command: "updateWhiteInk",
361
- title: "Update White Ink",
362
- handler: async (
363
- id: string,
364
- updates: Partial<WhiteInkItem>,
365
- options: UpdateWhiteInkOptions = {},
366
- ) => {
367
- await this.updateWhiteInkItem(id, updates, options);
368
- },
369
- },
370
- {
371
- command: "removeWhiteInk",
372
- title: "Remove White Ink",
373
- handler: (id: string) => {
374
- this.removeWhiteInk(id);
375
- },
376
- },
377
- {
378
- command: "clearWhiteInks",
379
- title: "Clear White Inks",
380
- handler: () => {
381
- this.clearWhiteInks();
382
- },
383
- },
384
- {
385
- command: "resetWorkingWhiteInks",
386
- title: "Reset Working White Inks",
387
- handler: () => {
388
- this.workingItems = this.cloneItems(this.items);
389
- this.hasWorkingChanges = false;
390
- this.updateWhiteInks();
391
- },
392
- },
393
- {
394
- command: "completeWhiteInks",
395
- title: "Complete White Inks",
396
- handler: async () => {
397
- return await this.completeWhiteInks();
398
- },
399
- },
400
- {
401
- command: "setWhiteInkImage",
402
- title: "Set White Ink Image",
403
- handler: async (url: string) => {
404
- if (!url) {
405
- this.clearWhiteInks();
406
- return { ok: true };
407
- }
408
-
409
- const targetId = this.resolveReplaceTargetId(null);
410
- const upsertResult = await this.upsertWhiteInkEntry(url, {
411
- id: targetId || undefined,
412
- mode: targetId ? "replace" : "add",
413
- createIfMissing: true,
414
- addOptions: {},
415
- });
416
- return { ok: true, id: upsertResult.id };
417
- },
418
- },
419
- ] as CommandContribution[],
420
- };
421
- }
422
-
423
- private onToolActivated = (event: {
424
- id: string | null;
425
- previous?: string | null;
426
- }) => {
427
- const before = this.isToolActive;
428
- this.syncToolActiveFromWorkbench(event.id);
429
- this.debug("tool:activated", {
430
- id: event.id,
431
- previous: event.previous,
432
- before,
433
- isToolActive: this.isToolActive,
434
- });
435
- this.updateWhiteInks();
436
- };
437
-
438
- private onSceneLayoutChanged = () => {
439
- this.updateWhiteInks();
440
- };
441
-
442
- private onObjectAdded = (e: any) => {
443
- const layerId = e?.target?.data?.layerId;
444
- if (layerId !== IMAGE_OBJECT_LAYER_ID) return;
445
- this.updateWhiteInks();
446
- };
447
-
448
- private onObjectModified = (e: any) => {
449
- const layerId = e?.target?.data?.layerId;
450
- if (layerId !== IMAGE_OBJECT_LAYER_ID) return;
451
- this.updateWhiteInks();
452
- };
453
-
454
- private onObjectRemoved = (e: any) => {
455
- const layerId = e?.target?.data?.layerId;
456
- if (layerId !== IMAGE_OBJECT_LAYER_ID) return;
457
- this.updateWhiteInks();
458
- };
459
-
460
- private onImageWorkingChanged = () => {
461
- this.updateWhiteInks();
462
- };
463
-
464
- private migrateLegacyConfigIfNeeded(configService: ConfigurationService) {
465
- if (this.items.length > 0) return;
466
- const legacyMask = configService.get("whiteInk.customMask", "");
467
- if (typeof legacyMask !== "string" || legacyMask.length === 0) return;
468
-
469
- const item = this.normalizeItem({
470
- id: this.generateId(),
471
- sourceUrl: legacyMask,
472
- opacity: WHITE_INK_DEFAULT_OPACITY,
473
- });
474
-
475
- this.items = [item];
476
- this.workingItems = this.cloneItems(this.items);
477
- this.isUpdatingConfig = true;
478
- configService.update("whiteInk.items", this.items);
479
- setTimeout(() => {
480
- this.isUpdatingConfig = false;
481
- }, 0);
482
- }
483
-
484
- private syncToolActiveFromWorkbench(fallbackId?: string | null) {
485
- const wb = this.context?.services.get<WorkbenchService>("WorkbenchService");
486
- const activeId = wb?.activeToolId;
487
- if (typeof activeId === "string" || activeId === null) {
488
- this.isToolActive = activeId === this.id;
489
- return;
490
- }
491
- this.isToolActive = fallbackId === this.id;
492
- }
493
-
494
- private isPreviewActive(): boolean {
495
- return this.isToolActive && this.printWithWhiteInk;
496
- }
497
-
498
- private isDebugEnabled(): boolean {
499
- return !!this.getConfig<boolean>(WHITE_INK_DEBUG_KEY, false);
500
- }
501
-
502
- private debug(message: string, payload?: any) {
503
- if (!this.isDebugEnabled()) return;
504
- if (payload === undefined) {
505
- console.log(`[WhiteInkTool] ${message}`);
506
- return;
507
- }
508
- console.log(`[WhiteInkTool] ${message}`, payload);
509
- }
510
-
511
- private resolveSourceUrl(item?: Partial<WhiteInkItem> | null): string {
512
- if (!item) return "";
513
- if (typeof item.sourceUrl === "string" && item.sourceUrl.length > 0) {
514
- return item.sourceUrl;
515
- }
516
- if (typeof item.url === "string" && item.url.length > 0) {
517
- return item.url;
518
- }
519
- return "";
520
- }
521
-
522
- private normalizeItem(item: Partial<WhiteInkItem>): WhiteInkItem {
523
- const sourceUrl = this.resolveSourceUrl(item);
524
- return {
525
- id: String(item.id || this.generateId()),
526
- sourceUrl,
527
- url: sourceUrl,
528
- opacity: WHITE_INK_DEFAULT_OPACITY,
529
- };
530
- }
531
-
532
- private normalizeItems(items: WhiteInkItem[]): WhiteInkItem[] {
533
- return (items || [])
534
- .map((item) => this.normalizeItem(item))
535
- .filter((item) => !!item.id);
536
- }
537
-
538
- private cloneItems(items: WhiteInkItem[]): WhiteInkItem[] {
539
- return this.normalizeItems((items || []).map((item) => ({ ...item })));
540
- }
541
-
542
- private getEffectiveWhiteInkItem(items: WhiteInkItem[]): WhiteInkItem | null {
543
- const normalized = this.cloneItems(items || []);
544
- if (normalized.length > 0) {
545
- return normalized[0];
546
- }
547
-
548
- if (!this.getPrimaryImageSource()) {
549
- return null;
550
- }
551
-
552
- return {
553
- id: WHITE_INK_AUTO_ITEM_ID,
554
- opacity: WHITE_INK_DEFAULT_OPACITY,
555
- };
556
- }
557
-
558
- private generateId(): string {
559
- return `white-ink-${Math.random().toString(36).slice(2, 9)}`;
560
- }
561
-
562
- private getConfig<T>(key: string, fallback?: T): T | undefined {
563
- if (!this.context) return fallback;
564
- const configService = this.context.services.get<ConfigurationService>(
565
- "ConfigurationService",
566
- );
567
- if (!configService) return fallback;
568
- return (configService.get(key, fallback) as T) ?? fallback;
569
- }
570
-
571
- private resolveReplaceTargetId(explicitId?: string | null): string | null {
572
- const has = (id: string | null | undefined) =>
573
- !!id && this.items.some((item) => item.id === id);
574
- if (has(explicitId)) return explicitId as string;
575
- if (this.items.length >= 1) {
576
- return this.items[0].id;
577
- }
578
- return null;
579
- }
580
-
581
- private updateConfig(newItems: WhiteInkItem[], skipCanvasUpdate = false) {
582
- if (!this.context) return;
583
-
584
- this.isUpdatingConfig = true;
585
- this.items = this.normalizeItems(newItems);
586
- if (!this.isToolActive || !this.hasWorkingChanges) {
587
- this.workingItems = this.cloneItems(this.items);
588
- this.hasWorkingChanges = false;
589
- }
590
-
591
- const configService = this.context.services.get<ConfigurationService>(
592
- "ConfigurationService",
593
- );
594
- configService?.update("whiteInk.items", this.items);
595
-
596
- if (!skipCanvasUpdate) {
597
- this.updateWhiteInks();
598
- }
599
-
600
- setTimeout(() => {
601
- this.isUpdatingConfig = false;
602
- }, 50);
603
- }
604
-
605
- private async addWhiteInkEntry(
606
- url: string,
607
- options?: Partial<WhiteInkItem>,
608
- ): Promise<string> {
609
- const id = this.generateId();
610
- const item = this.normalizeItem({
611
- id,
612
- sourceUrl: url,
613
- opacity: WHITE_INK_DEFAULT_OPACITY,
614
- ...options,
615
- });
616
-
617
- const sessionDirtyBeforeAdd = this.isToolActive && this.hasWorkingChanges;
618
- this.updateConfig([...this.items, item]);
619
- this.addItemToWorkingSessionIfNeeded(item, sessionDirtyBeforeAdd);
620
- return id;
621
- }
622
-
623
- private async upsertWhiteInkEntry(
624
- url: string,
625
- options: UpsertWhiteInkOptions = {},
626
- ): Promise<{ id: string; mode: "replace" | "add" }> {
627
- const mode = options.mode || "auto";
628
- if (mode === "add") {
629
- const id = await this.addWhiteInkEntry(url, options.addOptions);
630
- return { id, mode: "add" };
631
- }
632
-
633
- const targetId = this.resolveReplaceTargetId(options.id ?? null);
634
- if (targetId) {
635
- this.updateWhiteInkInConfig(targetId, {
636
- ...(options.addOptions || {}),
637
- sourceUrl: url,
638
- url,
639
- });
640
- return { id: targetId, mode: "replace" };
641
- }
642
-
643
- if (mode === "replace" || options.createIfMissing === false) {
644
- throw new Error("replace-target-not-found");
645
- }
646
-
647
- const id = await this.addWhiteInkEntry(url, options.addOptions);
648
- return { id, mode: "add" };
649
- }
650
-
651
- private addItemToWorkingSessionIfNeeded(
652
- item: WhiteInkItem,
653
- sessionDirtyBeforeAdd: boolean,
654
- ) {
655
- if (!sessionDirtyBeforeAdd || !this.isToolActive) return;
656
- if (this.workingItems.some((existing) => existing.id === item.id)) return;
657
- this.workingItems = this.cloneItems([...this.workingItems, item]);
658
- this.updateWhiteInks();
659
- }
660
-
661
- private async updateWhiteInkItem(
662
- id: string,
663
- updates: Partial<WhiteInkItem>,
664
- options: UpdateWhiteInkOptions = {},
665
- ) {
666
- this.syncToolActiveFromWorkbench();
667
- const target = options.target || "auto";
668
- if (target === "working" || (target === "auto" && this.isToolActive)) {
669
- this.updateWhiteInkInWorking(id, updates);
670
- return;
671
- }
672
-
673
- this.updateWhiteInkInConfig(id, updates);
674
- }
675
-
676
- private updateWhiteInkInWorking(id: string, updates: Partial<WhiteInkItem>) {
677
- let changed = false;
678
- const next = this.workingItems.map((item) => {
679
- if (item.id !== id) return item;
680
- changed = true;
681
- return this.normalizeItem({
682
- ...item,
683
- ...updates,
684
- });
685
- });
686
- if (!changed) return;
687
-
688
- this.workingItems = this.cloneItems(next);
689
- this.hasWorkingChanges = true;
690
- this.updateWhiteInks();
691
- }
692
-
693
- private updateWhiteInkInConfig(id: string, updates: Partial<WhiteInkItem>) {
694
- let changed = false;
695
- const next = this.items.map((item) => {
696
- if (item.id !== id) return item;
697
- changed = true;
698
- const merged = this.normalizeItem({
699
- ...item,
700
- ...updates,
701
- });
702
- if (this.resolveSourceUrl(item) !== this.resolveSourceUrl(merged)) {
703
- this.purgeSourceCaches(item);
704
- }
705
- return merged;
706
- });
707
- if (!changed) return;
708
-
709
- this.updateConfig(next);
710
- }
711
-
712
- private removeWhiteInk(id: string) {
713
- const removed = this.items.find((item) => item.id === id);
714
- const next = this.items.filter((item) => item.id !== id);
715
- if (next.length === this.items.length) return;
716
-
717
- this.purgeSourceCaches(removed);
718
- this.updateConfig(next);
719
- }
720
-
721
- private clearWhiteInks() {
722
- this.sourceSizeBySrc.clear();
723
- this.previewMaskBySource.clear();
724
- this.pendingPreviewMaskBySource.clear();
725
- this.updateConfig([]);
726
- }
727
-
728
- private async completeWhiteInks() {
729
- this.updateConfig(this.cloneItems(this.workingItems));
730
- this.hasWorkingChanges = false;
731
- return { ok: true };
732
- }
733
-
734
- private getFrameRect(): FrameRect {
735
- if (!this.canvasService) {
736
- return { left: 0, top: 0, width: 0, height: 0 };
737
- }
738
- const configService = this.context?.services.get<ConfigurationService>(
739
- "ConfigurationService",
740
- );
741
- if (!configService) {
742
- return { left: 0, top: 0, width: 0, height: 0 };
743
- }
744
- const sizeState = readSizeState(configService);
745
- const layout = computeSceneLayout(this.canvasService, sizeState);
746
- if (!layout) {
747
- return { left: 0, top: 0, width: 0, height: 0 };
748
- }
749
-
750
- return {
751
- left: layout.cutRect.left,
752
- top: layout.cutRect.top,
753
- width: layout.cutRect.width,
754
- height: layout.cutRect.height,
755
- };
756
- }
757
-
758
- private getImageObjects(): any[] {
759
- if (!this.canvasService) return [];
760
- return this.canvasService.canvas.getObjects().filter((obj: any) => {
761
- return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
762
- }) as any[];
763
- }
764
-
765
- private getPrimaryImageObject(): any | undefined {
766
- return this.getImageObjects()[0];
767
- }
768
-
769
- private getPrimaryImageSource(): string {
770
- return this.getCurrentSrc(this.getPrimaryImageObject()) || "";
771
- }
772
-
773
- private getCurrentSrc(obj: any): string | undefined {
774
- if (!obj) return undefined;
775
- if (typeof obj.getSrc === "function") return obj.getSrc();
776
- return obj?._originalElement?.src;
777
- }
778
-
779
- private getImageSnapshot(obj: any): ImageSnapshot | null {
780
- if (!obj) return null;
781
-
782
- const src = this.getCurrentSrc(obj);
783
- if (!src) return null;
784
-
785
- const element = this.getImageElementFromObject(obj);
786
- const width = Number(obj?.width || 0);
787
- const height = Number(obj?.height || 0);
788
- this.rememberSourceSize(src, { width, height });
789
-
790
- return {
791
- id: String(obj?.data?.id || "image"),
792
- src,
793
- element,
794
- left: Number.isFinite(obj?.left) ? Number(obj.left) : 0,
795
- top: Number.isFinite(obj?.top) ? Number(obj.top) : 0,
796
- scaleX: Number.isFinite(obj?.scaleX) ? Number(obj.scaleX) : 1,
797
- scaleY: Number.isFinite(obj?.scaleY) ? Number(obj.scaleY) : 1,
798
- angle: Number.isFinite(obj?.angle) ? Number(obj.angle) : 0,
799
- originX: typeof obj?.originX === "string" ? obj.originX : "center",
800
- originY: typeof obj?.originY === "string" ? obj.originY : "center",
801
- flipX: !!obj?.flipX,
802
- flipY: !!obj?.flipY,
803
- skewX: Number.isFinite(obj?.skewX) ? Number(obj.skewX) : 0,
804
- skewY: Number.isFinite(obj?.skewY) ? Number(obj.skewY) : 0,
805
- width,
806
- height,
807
- };
808
- }
809
-
810
- private getImagePlacementState(id?: string): ImagePlacementState | null {
811
- const rawItems = this.getConfig<any[]>("image.items", []);
812
- if (!Array.isArray(rawItems) || rawItems.length === 0) return null;
813
-
814
- const matched =
815
- (id
816
- ? rawItems.find(
817
- (item: any) =>
818
- item &&
819
- typeof item === "object" &&
820
- typeof item.id === "string" &&
821
- item.id === id,
822
- )
823
- : undefined) || rawItems[0];
824
-
825
- if (!matched || typeof matched !== "object") return null;
826
-
827
- const sourceUrl =
828
- typeof matched.sourceUrl === "string" && matched.sourceUrl.length > 0
829
- ? matched.sourceUrl
830
- : typeof matched.url === "string"
831
- ? matched.url
832
- : "";
833
- const committedUrl =
834
- typeof matched.committedUrl === "string" ? matched.committedUrl : "";
835
-
836
- return {
837
- id:
838
- typeof matched.id === "string" && matched.id.length > 0
839
- ? matched.id
840
- : id || "image",
841
- sourceUrl,
842
- committedUrl,
843
- left: Number.isFinite(matched.left) ? Number(matched.left) : 0.5,
844
- top: Number.isFinite(matched.top) ? Number(matched.top) : 0.5,
845
- scale: Number.isFinite(matched.scale) ? Math.max(0.05, matched.scale) : 1,
846
- angle: Number.isFinite(matched.angle) ? matched.angle : 0,
847
- };
848
- }
849
-
850
- private shouldRestoreSnapshotToSource(
851
- snapshot: ImageSnapshot,
852
- placement: ImagePlacementState,
853
- ): boolean {
854
- if (!placement.sourceUrl || !placement.committedUrl) return false;
855
- if (placement.sourceUrl === placement.committedUrl) return false;
856
- return snapshot.src === placement.committedUrl;
857
- }
858
-
859
- private getCoverScale(frame: FrameRect, source: SourceSize): number {
860
- const frameW = Math.max(1, frame.width);
861
- const frameH = Math.max(1, frame.height);
862
- const sourceW = Math.max(1, source.width);
863
- const sourceH = Math.max(1, source.height);
864
- return Math.max(frameW / sourceW, frameH / sourceH);
865
- }
866
-
867
- private async ensureSourceSize(sourceUrl: string): Promise<SourceSize | null> {
868
- if (!sourceUrl) return null;
869
- const cached = this.getSourceSize(sourceUrl);
870
- if (cached) return cached;
871
-
872
- try {
873
- const image = await this.loadImageElement(sourceUrl);
874
- const size = this.getElementSize(image);
875
- if (!size) return null;
876
- this.rememberSourceSize(sourceUrl, size);
877
- return {
878
- width: size.width,
879
- height: size.height,
880
- };
881
- } catch {
882
- return null;
883
- }
884
- }
885
-
886
- private async resolveAlignedImageSnapshot(
887
- snapshot: ImageSnapshot,
888
- ): Promise<ImageSnapshot> {
889
- const placement = this.getImagePlacementState(snapshot.id);
890
- if (!placement) return snapshot;
891
- if (!this.shouldRestoreSnapshotToSource(snapshot, placement)) {
892
- return snapshot;
893
- }
894
-
895
- const frame = this.getFrameRect();
896
- if (frame.width <= 0 || frame.height <= 0) {
897
- return snapshot;
898
- }
899
-
900
- const sourceSize = await this.ensureSourceSize(placement.sourceUrl);
901
- if (!sourceSize) return snapshot;
902
-
903
- const coverScale = this.getCoverScale(frame, sourceSize);
904
-
905
- return {
906
- ...snapshot,
907
- src: placement.sourceUrl,
908
- element: undefined,
909
- left: frame.left + placement.left * frame.width,
910
- top: frame.top + placement.top * frame.height,
911
- scaleX: coverScale * placement.scale,
912
- scaleY: coverScale * placement.scale,
913
- angle: placement.angle,
914
- originX: "center",
915
- originY: "center",
916
- width: sourceSize.width,
917
- height: sourceSize.height,
918
- };
919
- }
920
- private getImageElementFromObject(obj: any): any {
921
- if (!obj) return null;
922
- if (typeof obj.getElement === "function") {
923
- return obj.getElement();
924
- }
925
- return obj?._element || obj?._originalElement || null;
926
- }
927
-
928
- private rememberSourceSize(src: string, size: SourceSize) {
929
- if (!src) return;
930
- if (!Number.isFinite(size.width) || !Number.isFinite(size.height)) return;
931
- if (size.width <= 0 || size.height <= 0) return;
932
- this.sourceSizeBySrc.set(src, {
933
- width: size.width,
934
- height: size.height,
935
- });
936
- }
937
-
938
- private getSourceSize(src: string): SourceSize | null {
939
- if (!src) return null;
940
- const cached = this.sourceSizeBySrc.get(src);
941
- if (!cached) return null;
942
- return {
943
- width: cached.width,
944
- height: cached.height,
945
- };
946
- }
947
-
948
- private computeWhiteScaleAdjust(
949
- baseSource: string,
950
- whiteSource: string,
951
- ): { x: number; y: number } {
952
- if (!baseSource || !whiteSource || baseSource === whiteSource) {
953
- return { x: 1, y: 1 };
954
- }
955
-
956
- const baseSize = this.getSourceSize(baseSource);
957
- const whiteSize = this.getSourceSize(whiteSource);
958
- if (!baseSize || !whiteSize) {
959
- return { x: 1, y: 1 };
960
- }
961
-
962
- if (whiteSize.width <= 0 || whiteSize.height <= 0) {
963
- return { x: 1, y: 1 };
964
- }
965
-
966
- return {
967
- x: baseSize.width / whiteSize.width,
968
- y: baseSize.height / whiteSize.height,
969
- };
970
- }
971
-
972
- private computeCoverOpacity(): number {
973
- const raw = WHITE_INK_DEFAULT_OPACITY * WHITE_INK_COVER_OPACITY_FACTOR;
974
- return Math.max(
975
- WHITE_INK_COVER_OPACITY_MIN,
976
- Math.min(WHITE_INK_COVER_OPACITY_MAX, raw),
977
- );
978
- }
979
-
980
- private buildCloneImageSpec(
981
- id: string,
982
- snapshot: ImageSnapshot,
983
- src: string,
984
- opacity: number,
985
- layerId: string,
986
- type: "white-ink" | "white-ink-cover",
987
- scaleAdjustX = 1,
988
- scaleAdjustY = 1,
989
- ): RenderObjectSpec {
990
- return {
991
- id,
992
- type: "image",
993
- src,
994
- data: {
995
- id,
996
- layerId,
997
- type,
998
- imageId: snapshot.id,
999
- },
1000
- props: {
1001
- left: snapshot.left,
1002
- top: snapshot.top,
1003
- originX: snapshot.originX,
1004
- originY: snapshot.originY,
1005
- angle: snapshot.angle,
1006
- scaleX: snapshot.scaleX * scaleAdjustX,
1007
- scaleY: snapshot.scaleY * scaleAdjustY,
1008
- flipX: snapshot.flipX,
1009
- flipY: snapshot.flipY,
1010
- skewX: snapshot.skewX,
1011
- skewY: snapshot.skewY,
1012
- selectable: false,
1013
- evented: false,
1014
- hasControls: false,
1015
- hasBorders: false,
1016
- uniformScaling: true,
1017
- lockScalingFlip: true,
1018
- opacity: Math.max(0, Math.min(1, Number(opacity))),
1019
- excludeFromExport: true,
1020
- },
1021
- };
1022
- }
1023
-
1024
- private buildFrameSpecs(frame: FrameRect): RenderObjectSpec[] {
1025
- if (!this.isToolActive || !this.canvasService) return [];
1026
- if (frame.width <= 0 || frame.height <= 0) return [];
1027
-
1028
- const canvasW = this.canvasService.canvas.width || 0;
1029
- const canvasH = this.canvasService.canvas.height || 0;
1030
- const strokeColor =
1031
- this.getConfig<string>("image.frame.strokeColor", "#808080") || "#808080";
1032
- const strokeWidthRaw = Number(
1033
- this.getConfig<number>("image.frame.strokeWidth", 2) ?? 2,
1034
- );
1035
- const dashLengthRaw = Number(
1036
- this.getConfig<number>("image.frame.dashLength", 8) ?? 8,
1037
- );
1038
- const outerBackground =
1039
- this.getConfig<string>("image.frame.outerBackground", "#f5f5f5") ||
1040
- "#f5f5f5";
1041
- const innerBackground =
1042
- this.getConfig<string>("image.frame.innerBackground", "rgba(0,0,0,0)") ||
1043
- "rgba(0,0,0,0)";
1044
-
1045
- const strokeWidth = Number.isFinite(strokeWidthRaw)
1046
- ? Math.max(0, strokeWidthRaw)
1047
- : 2;
1048
- const dashLength = Number.isFinite(dashLengthRaw)
1049
- ? Math.max(1, dashLengthRaw)
1050
- : 8;
1051
-
1052
- const frameLeft = Math.max(0, Math.min(canvasW, frame.left));
1053
- const frameTop = Math.max(0, Math.min(canvasH, frame.top));
1054
- const frameRight = Math.max(
1055
- frameLeft,
1056
- Math.min(canvasW, frame.left + frame.width),
1057
- );
1058
- const frameBottom = Math.max(
1059
- frameTop,
1060
- Math.min(canvasH, frame.top + frame.height),
1061
- );
1062
- const visibleFrameH = Math.max(0, frameBottom - frameTop);
1063
-
1064
- const topH = frameTop;
1065
- const bottomH = Math.max(0, canvasH - frameBottom);
1066
- const leftW = frameLeft;
1067
- const rightW = Math.max(0, canvasW - frameRight);
1068
-
1069
- const maskSpecs: RenderObjectSpec[] = [
1070
- {
1071
- id: "white-ink.cropMask.top",
1072
- type: "rect",
1073
- data: {
1074
- id: "white-ink.cropMask.top",
1075
- layerId: WHITE_INK_OVERLAY_LAYER_ID,
1076
- type: "white-ink-mask",
1077
- },
1078
- props: {
1079
- left: canvasW / 2,
1080
- top: topH / 2,
1081
- width: canvasW,
1082
- height: topH,
1083
- originX: "center",
1084
- originY: "center",
1085
- fill: outerBackground,
1086
- selectable: false,
1087
- evented: false,
1088
- excludeFromExport: true,
1089
- },
1090
- },
1091
- {
1092
- id: "white-ink.cropMask.bottom",
1093
- type: "rect",
1094
- data: {
1095
- id: "white-ink.cropMask.bottom",
1096
- layerId: WHITE_INK_OVERLAY_LAYER_ID,
1097
- type: "white-ink-mask",
1098
- },
1099
- props: {
1100
- left: canvasW / 2,
1101
- top: frameBottom + bottomH / 2,
1102
- width: canvasW,
1103
- height: bottomH,
1104
- originX: "center",
1105
- originY: "center",
1106
- fill: outerBackground,
1107
- selectable: false,
1108
- evented: false,
1109
- excludeFromExport: true,
1110
- },
1111
- },
1112
- {
1113
- id: "white-ink.cropMask.left",
1114
- type: "rect",
1115
- data: {
1116
- id: "white-ink.cropMask.left",
1117
- layerId: WHITE_INK_OVERLAY_LAYER_ID,
1118
- type: "white-ink-mask",
1119
- },
1120
- props: {
1121
- left: leftW / 2,
1122
- top: frameTop + visibleFrameH / 2,
1123
- width: leftW,
1124
- height: visibleFrameH,
1125
- originX: "center",
1126
- originY: "center",
1127
- fill: outerBackground,
1128
- selectable: false,
1129
- evented: false,
1130
- excludeFromExport: true,
1131
- },
1132
- },
1133
- {
1134
- id: "white-ink.cropMask.right",
1135
- type: "rect",
1136
- data: {
1137
- id: "white-ink.cropMask.right",
1138
- layerId: WHITE_INK_OVERLAY_LAYER_ID,
1139
- type: "white-ink-mask",
1140
- },
1141
- props: {
1142
- left: frameRight + rightW / 2,
1143
- top: frameTop + visibleFrameH / 2,
1144
- width: rightW,
1145
- height: visibleFrameH,
1146
- originX: "center",
1147
- originY: "center",
1148
- fill: outerBackground,
1149
- selectable: false,
1150
- evented: false,
1151
- excludeFromExport: true,
1152
- },
1153
- },
1154
- ];
1155
-
1156
- return [
1157
- ...maskSpecs,
1158
- {
1159
- id: "white-ink.cropFrame",
1160
- type: "rect",
1161
- data: {
1162
- id: "white-ink.cropFrame",
1163
- layerId: WHITE_INK_OVERLAY_LAYER_ID,
1164
- type: "white-ink-frame",
1165
- },
1166
- props: {
1167
- left: frame.left + frame.width / 2,
1168
- top: frame.top + frame.height / 2,
1169
- width: frame.width,
1170
- height: frame.height,
1171
- originX: "center",
1172
- originY: "center",
1173
- fill: innerBackground,
1174
- stroke: strokeColor,
1175
- strokeWidth,
1176
- strokeDashArray: [dashLength, dashLength],
1177
- selectable: false,
1178
- evented: false,
1179
- excludeFromExport: true,
1180
- },
1181
- },
1182
- ];
1183
- }
1184
-
1185
- private applyImageVisibilityForWhiteInk(previewActive: boolean) {
1186
- if (!this.canvasService) return;
1187
- const visible = !previewActive;
1188
- let changed = false;
1189
-
1190
- this.canvasService.canvas.getObjects().forEach((obj: any) => {
1191
- if (obj?.data?.layerId !== IMAGE_OBJECT_LAYER_ID) return;
1192
- if (obj.visible === visible) return;
1193
- obj.set({ visible });
1194
- obj.setCoords?.();
1195
- changed = true;
1196
- });
1197
-
1198
- if (changed) {
1199
- this.canvasService.requestRenderAll();
1200
- }
1201
- }
1202
-
1203
- private resolveRenderItems(): WhiteInkItem[] {
1204
- if (this.isToolActive) {
1205
- return this.cloneItems(this.workingItems);
1206
- }
1207
- return this.cloneItems(this.items);
1208
- }
1209
-
1210
- private async resolveRenderSources(
1211
- snapshot: ImageSnapshot,
1212
- item: WhiteInkItem,
1213
- ): Promise<RenderSources | null> {
1214
- const imageSource = snapshot.src;
1215
- if (!imageSource) return null;
1216
-
1217
- const whiteSource = this.resolveSourceUrl(item) || imageSource;
1218
- const imageElement = snapshot.element;
1219
- const whiteElement = whiteSource === imageSource ? imageElement : undefined;
1220
- const [whiteMaskSrc, coverMaskSrc] = await Promise.all([
1221
- this.getPreviewMaskSource(whiteSource, WHITE_MASK_TINT, whiteElement),
1222
- this.getPreviewMaskSource(imageSource, COVER_MASK_TINT, imageElement),
1223
- ]);
1224
-
1225
- const scaleAdjust = this.computeWhiteScaleAdjust(imageSource, whiteSource);
1226
-
1227
- return {
1228
- whiteSrc: whiteMaskSrc || "",
1229
- coverSrc: coverMaskSrc || "",
1230
- whiteScaleAdjustX: scaleAdjust.x,
1231
- whiteScaleAdjustY: scaleAdjust.y,
1232
- };
1233
- }
1234
-
1235
- private resolveDefaultInsertIndex(objects: any[]): number {
1236
- if (!this.canvasService) return 0;
1237
- const backgroundLayer = this.canvasService.getLayer("background");
1238
- if (!backgroundLayer) return 0;
1239
- const bgIndex = objects.indexOf(backgroundLayer as any);
1240
- if (bgIndex < 0) return 0;
1241
- return bgIndex + 1;
1242
- }
1243
-
1244
- private syncZOrder() {
1245
- if (!this.canvasService) return;
1246
- const canvas = this.canvasService.canvas;
1247
-
1248
- const whiteObjects = this.canvasService.getRootLayerObjects(
1249
- WHITE_INK_OBJECT_LAYER_ID,
1250
- ) as any[];
1251
- const coverObjects = this.canvasService.getRootLayerObjects(
1252
- WHITE_INK_COVER_LAYER_ID,
1253
- ) as any[];
1254
- const frameObjects = this.canvasService.getRootLayerObjects(
1255
- WHITE_INK_OVERLAY_LAYER_ID,
1256
- ) as any[];
1257
-
1258
- const currentObjects = canvas.getObjects();
1259
- const imageIndexes = currentObjects
1260
- .map((obj: any, index: number) =>
1261
- obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID ? index : -1,
1262
- )
1263
- .filter((index: number) => index >= 0);
1264
-
1
+ import {
2
+ Extension,
3
+ ExtensionContext,
4
+ ContributionPointIds,
5
+ CommandContribution,
6
+ ConfigurationContribution,
7
+ ConfigurationService,
8
+ ToolSessionService,
9
+ WorkbenchService,
10
+ } from "@pooder/core";
11
+ import { CanvasService, RenderLayoutRect, RenderObjectSpec } from "../services";
12
+ import { computeSceneLayout, readSizeState } from "./sceneLayoutModel";
13
+
14
+ export interface WhiteInkItem {
15
+ id: string;
16
+ sourceUrl?: string;
17
+ url?: string;
18
+ opacity: number;
19
+ }
20
+
21
+ interface SourceSize {
22
+ width: number;
23
+ height: number;
24
+ }
25
+
26
+ interface MaskTint {
27
+ r: number;
28
+ g: number;
29
+ b: number;
30
+ key: string;
31
+ }
32
+
33
+ interface FrameRect {
34
+ left: number;
35
+ top: number;
36
+ width: number;
37
+ height: number;
38
+ }
39
+
40
+ interface ImageSnapshot {
41
+ id: string;
42
+ src: string;
43
+ element: any;
44
+ left: number;
45
+ top: number;
46
+ scaleX: number;
47
+ scaleY: number;
48
+ angle: number;
49
+ originX: string;
50
+ originY: string;
51
+ flipX: boolean;
52
+ flipY: boolean;
53
+ skewX: number;
54
+ skewY: number;
55
+ width: number;
56
+ height: number;
57
+ }
58
+
59
+ interface ImagePlacementState {
60
+ id: string;
61
+ sourceUrl: string;
62
+ committedUrl: string;
63
+ left: number;
64
+ top: number;
65
+ scale: number;
66
+ angle: number;
67
+ }
68
+
69
+ interface RenderSources {
70
+ whiteSrc: string;
71
+ coverSrc: string;
72
+ whiteScaleAdjustX: number;
73
+ whiteScaleAdjustY: number;
74
+ }
75
+
76
+ interface UpsertWhiteInkOptions {
77
+ id?: string;
78
+ mode?: "auto" | "replace" | "add";
79
+ createIfMissing?: boolean;
80
+ addOptions?: Partial<WhiteInkItem>;
81
+ }
82
+
83
+ interface UpdateWhiteInkOptions {
84
+ target?: "auto" | "config" | "working";
85
+ }
86
+
87
+ const WHITE_INK_OBJECT_LAYER_ID = "white-ink.user";
88
+ const WHITE_INK_COVER_LAYER_ID = "white-ink.cover";
89
+ const WHITE_INK_OVERLAY_LAYER_ID = "white-ink.overlay";
90
+ const IMAGE_OBJECT_LAYER_ID = "image.user";
91
+ const IMAGE_OVERLAY_LAYER_ID = "image-overlay";
92
+
93
+ const WHITE_INK_DEBUG_KEY = "whiteInk.debug";
94
+ const WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY = "whiteInk.previewImageVisible";
95
+ const WHITE_INK_DEFAULT_OPACITY = 0.85;
96
+ const WHITE_INK_AUTO_ITEM_ID = "white-ink-auto";
97
+
98
+ const WHITE_INK_COVER_OPACITY_FACTOR = 0.45;
99
+ const WHITE_INK_COVER_OPACITY_MIN = 0.15;
100
+ const WHITE_INK_COVER_OPACITY_MAX = 0.65;
101
+ const WHITE_MASK_TINT: MaskTint = { r: 255, g: 255, b: 255, key: "white" };
102
+ const COVER_MASK_TINT: MaskTint = { r: 52, g: 136, b: 255, key: "blue" };
103
+
104
+ export class WhiteInkTool implements Extension {
105
+ id = "pooder.kit.white-ink";
106
+
107
+ metadata = {
108
+ name: "WhiteInkTool",
109
+ };
110
+
111
+ private items: WhiteInkItem[] = [];
112
+ private workingItems: WhiteInkItem[] = [];
113
+ private hasWorkingChanges = false;
114
+
115
+ private sourceSizeBySrc: Map<string, SourceSize> = new Map();
116
+ private previewMaskBySource: Map<string, string> = new Map();
117
+ private pendingPreviewMaskBySource: Map<string, Promise<string | null>> =
118
+ new Map();
119
+
120
+ private canvasService?: CanvasService;
121
+ private context?: ExtensionContext;
122
+ private isUpdatingConfig = false;
123
+ private isToolActive = false;
124
+ private printWithWhiteInk = true;
125
+ private previewImageVisible = true;
126
+ private renderSeq = 0;
127
+ private dirtyTrackerDisposable?: { dispose(): void };
128
+ private whiteSpecs: RenderObjectSpec[] = [];
129
+ private coverSpecs: RenderObjectSpec[] = [];
130
+ private overlaySpecs: RenderObjectSpec[] = [];
131
+ private renderProducerDisposable?: { dispose: () => void };
132
+
133
+ activate(context: ExtensionContext) {
134
+ this.context = context;
135
+ this.canvasService = context.services.get<CanvasService>("CanvasService");
136
+ if (!this.canvasService) {
137
+ console.warn("CanvasService not found for WhiteInkTool");
138
+ return;
139
+ }
140
+ this.renderProducerDisposable?.dispose();
141
+ this.renderProducerDisposable = this.canvasService.registerRenderProducer(
142
+ this.id,
143
+ () => ({
144
+ rootLayerSpecs: {
145
+ [WHITE_INK_OBJECT_LAYER_ID]: this.whiteSpecs,
146
+ [WHITE_INK_COVER_LAYER_ID]: this.coverSpecs,
147
+ [WHITE_INK_OVERLAY_LAYER_ID]: this.overlaySpecs,
148
+ },
149
+ }),
150
+ { priority: 260 },
151
+ );
152
+
153
+ context.eventBus.on("tool:activated", this.onToolActivated);
154
+ context.eventBus.on("scene:layout:change", this.onSceneLayoutChanged);
155
+ context.eventBus.on("object:added", this.onObjectAdded);
156
+ context.eventBus.on("object:modified", this.onObjectModified);
157
+ context.eventBus.on("object:removed", this.onObjectRemoved);
158
+ context.eventBus.on("image:working:change", this.onImageWorkingChanged);
159
+
160
+ const configService = context.services.get<ConfigurationService>(
161
+ "ConfigurationService",
162
+ );
163
+ if (configService) {
164
+ this.items = this.normalizeItems(
165
+ configService.get("whiteInk.items", []) || [],
166
+ );
167
+ this.workingItems = this.cloneItems(this.items);
168
+ this.hasWorkingChanges = false;
169
+ this.printWithWhiteInk = !!configService.get(
170
+ "whiteInk.printWithWhiteInk",
171
+ true,
172
+ );
173
+ this.previewImageVisible = !!configService.get(
174
+ WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY,
175
+ true,
176
+ );
177
+
178
+ this.migrateLegacyConfigIfNeeded(configService);
179
+
180
+ configService.onAnyChange((e: { key: string; value: any }) => {
181
+ if (this.isUpdatingConfig) return;
182
+
183
+ if (e.key === "whiteInk.items") {
184
+ this.items = this.normalizeItems(e.value || []);
185
+ if (!this.isToolActive || !this.hasWorkingChanges) {
186
+ this.workingItems = this.cloneItems(this.items);
187
+ this.hasWorkingChanges = false;
188
+ }
189
+ this.updateWhiteInks();
190
+ return;
191
+ }
192
+
193
+ if (e.key === "whiteInk.printWithWhiteInk") {
194
+ this.printWithWhiteInk = !!e.value;
195
+ this.updateWhiteInks();
196
+ return;
197
+ }
198
+
199
+ if (e.key === WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY) {
200
+ this.previewImageVisible = !!e.value;
201
+ this.updateWhiteInks();
202
+ return;
203
+ }
204
+
205
+ if (e.key === "image.items") {
206
+ this.updateWhiteInks();
207
+ return;
208
+ }
209
+
210
+ if (e.key === WHITE_INK_DEBUG_KEY) {
211
+ return;
212
+ }
213
+
214
+ if (e.key.startsWith("size.")) {
215
+ this.updateWhiteInks();
216
+ }
217
+ });
218
+ }
219
+
220
+ const toolSessionService =
221
+ context.services.get<ToolSessionService>("ToolSessionService");
222
+ this.dirtyTrackerDisposable = toolSessionService?.registerDirtyTracker(
223
+ this.id,
224
+ () => this.hasWorkingChanges,
225
+ );
226
+
227
+ this.updateWhiteInks();
228
+ }
229
+
230
+ deactivate(context: ExtensionContext) {
231
+ context.eventBus.off("tool:activated", this.onToolActivated);
232
+ context.eventBus.off("scene:layout:change", this.onSceneLayoutChanged);
233
+ context.eventBus.off("object:added", this.onObjectAdded);
234
+ context.eventBus.off("object:modified", this.onObjectModified);
235
+ context.eventBus.off("object:removed", this.onObjectRemoved);
236
+ context.eventBus.off("image:working:change", this.onImageWorkingChanged);
237
+
238
+ this.dirtyTrackerDisposable?.dispose();
239
+ this.dirtyTrackerDisposable = undefined;
240
+ this.clearRenderedWhiteInks();
241
+ this.applyImageVisibilityForWhiteInk(false);
242
+ this.renderProducerDisposable?.dispose();
243
+ this.renderProducerDisposable = undefined;
244
+ if (this.canvasService) {
245
+ void this.canvasService.flushRenderFromProducers();
246
+ }
247
+
248
+ this.canvasService = undefined;
249
+ this.context = undefined;
250
+ }
251
+
252
+ contribute() {
253
+ return {
254
+ [ContributionPointIds.TOOLS]: [
255
+ {
256
+ id: this.id,
257
+ name: "White Ink",
258
+ interaction: "session",
259
+ commands: {
260
+ begin: "resetWorkingWhiteInks",
261
+ commit: "completeWhiteInks",
262
+ rollback: "resetWorkingWhiteInks",
263
+ },
264
+ session: {
265
+ autoBegin: true,
266
+ leavePolicy: "block",
267
+ },
268
+ },
269
+ ],
270
+ [ContributionPointIds.CONFIGURATIONS]: [
271
+ {
272
+ id: "whiteInk.items",
273
+ type: "array",
274
+ label: "White Ink Images",
275
+ default: [],
276
+ },
277
+ {
278
+ id: "whiteInk.printWithWhiteInk",
279
+ type: "boolean",
280
+ label: "Preview White Ink",
281
+ default: true,
282
+ },
283
+ {
284
+ id: WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY,
285
+ type: "boolean",
286
+ label: "Show Cover During White Ink Preview",
287
+ default: true,
288
+ },
289
+ {
290
+ id: WHITE_INK_DEBUG_KEY,
291
+ type: "boolean",
292
+ label: "White Ink Debug Log",
293
+ default: false,
294
+ },
295
+ ] as ConfigurationContribution[],
296
+ [ContributionPointIds.COMMANDS]: [
297
+ {
298
+ command: "addWhiteInk",
299
+ title: "Add White Ink",
300
+ handler: async (url: string, options?: Partial<WhiteInkItem>) => {
301
+ return await this.addWhiteInkEntry(url, options);
302
+ },
303
+ },
304
+ {
305
+ command: "upsertWhiteInk",
306
+ title: "Upsert White Ink",
307
+ handler: async (url: string, options: UpsertWhiteInkOptions = {}) => {
308
+ return await this.upsertWhiteInkEntry(url, options);
309
+ },
310
+ },
311
+ {
312
+ command: "getWhiteInks",
313
+ title: "Get White Inks",
314
+ handler: () => this.cloneItems(this.items),
315
+ },
316
+ {
317
+ command: "getWhiteInkSettings",
318
+ title: "Get White Ink Settings",
319
+ handler: () => {
320
+ const first = this.getEffectiveWhiteInkItem(this.items);
321
+ const primarySource = this.getPrimaryImageSource();
322
+ const sourceUrl = this.resolveSourceUrl(first) || primarySource;
323
+
324
+ return {
325
+ id: first?.id || null,
326
+ url: sourceUrl,
327
+ sourceUrl,
328
+ opacity: WHITE_INK_DEFAULT_OPACITY,
329
+ printWithWhiteInk: this.printWithWhiteInk,
330
+ previewImageVisible: this.previewImageVisible,
331
+ };
332
+ },
333
+ },
334
+ {
335
+ command: "setWhiteInkPrintEnabled",
336
+ title: "Set White Ink Preview Enabled",
337
+ handler: (enabled: boolean) => {
338
+ this.printWithWhiteInk = !!enabled;
339
+ const configService =
340
+ this.context?.services.get<ConfigurationService>(
341
+ "ConfigurationService",
342
+ );
343
+ configService?.update(
344
+ "whiteInk.printWithWhiteInk",
345
+ this.printWithWhiteInk,
346
+ );
347
+ this.updateWhiteInks();
348
+ return { ok: true };
349
+ },
350
+ },
351
+ {
352
+ command: "setWhiteInkPreviewImageVisible",
353
+ title: "Set White Ink Cover Visible",
354
+ handler: (visible: boolean) => {
355
+ this.previewImageVisible = !!visible;
356
+ const configService =
357
+ this.context?.services.get<ConfigurationService>(
358
+ "ConfigurationService",
359
+ );
360
+ configService?.update(
361
+ WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY,
362
+ this.previewImageVisible,
363
+ );
364
+ this.updateWhiteInks();
365
+ return { ok: true };
366
+ },
367
+ },
368
+ {
369
+ command: "getWorkingWhiteInks",
370
+ title: "Get Working White Inks",
371
+ handler: () => this.cloneItems(this.workingItems),
372
+ },
373
+ {
374
+ command: "setWorkingWhiteInk",
375
+ title: "Set Working White Ink",
376
+ handler: (id: string, updates: Partial<WhiteInkItem>) => {
377
+ this.updateWhiteInkInWorking(id, updates);
378
+ },
379
+ },
380
+ {
381
+ command: "updateWhiteInk",
382
+ title: "Update White Ink",
383
+ handler: async (
384
+ id: string,
385
+ updates: Partial<WhiteInkItem>,
386
+ options: UpdateWhiteInkOptions = {},
387
+ ) => {
388
+ await this.updateWhiteInkItem(id, updates, options);
389
+ },
390
+ },
391
+ {
392
+ command: "removeWhiteInk",
393
+ title: "Remove White Ink",
394
+ handler: (id: string) => {
395
+ this.removeWhiteInk(id);
396
+ },
397
+ },
398
+ {
399
+ command: "clearWhiteInks",
400
+ title: "Clear White Inks",
401
+ handler: () => {
402
+ this.clearWhiteInks();
403
+ },
404
+ },
405
+ {
406
+ command: "resetWorkingWhiteInks",
407
+ title: "Reset Working White Inks",
408
+ handler: () => {
409
+ this.workingItems = this.cloneItems(this.items);
410
+ this.hasWorkingChanges = false;
411
+ this.updateWhiteInks();
412
+ },
413
+ },
414
+ {
415
+ command: "completeWhiteInks",
416
+ title: "Complete White Inks",
417
+ handler: async () => {
418
+ return await this.completeWhiteInks();
419
+ },
420
+ },
421
+ {
422
+ command: "setWhiteInkImage",
423
+ title: "Set White Ink Image",
424
+ handler: async (url: string) => {
425
+ if (!url) {
426
+ this.clearWhiteInks();
427
+ return { ok: true };
428
+ }
429
+
430
+ const targetId = this.resolveReplaceTargetId(null);
431
+ const upsertResult = await this.upsertWhiteInkEntry(url, {
432
+ id: targetId || undefined,
433
+ mode: targetId ? "replace" : "add",
434
+ createIfMissing: true,
435
+ addOptions: {},
436
+ });
437
+ return { ok: true, id: upsertResult.id };
438
+ },
439
+ },
440
+ ] as CommandContribution[],
441
+ };
442
+ }
443
+
444
+ private onToolActivated = (event: {
445
+ id: string | null;
446
+ previous?: string | null;
447
+ }) => {
448
+ const before = this.isToolActive;
449
+ this.syncToolActiveFromWorkbench(event.id);
450
+ this.debug("tool:activated", {
451
+ id: event.id,
452
+ previous: event.previous,
453
+ before,
454
+ isToolActive: this.isToolActive,
455
+ });
456
+ this.updateWhiteInks();
457
+ };
458
+
459
+ private onSceneLayoutChanged = () => {
460
+ this.updateWhiteInks();
461
+ };
462
+
463
+ private onObjectAdded = (e: any) => {
464
+ const layerId = e?.target?.data?.layerId;
465
+ if (layerId !== IMAGE_OBJECT_LAYER_ID) return;
466
+ this.updateWhiteInks();
467
+ };
468
+
469
+ private onObjectModified = (e: any) => {
470
+ const layerId = e?.target?.data?.layerId;
471
+ if (layerId !== IMAGE_OBJECT_LAYER_ID) return;
472
+ this.updateWhiteInks();
473
+ };
474
+
475
+ private onObjectRemoved = (e: any) => {
476
+ const layerId = e?.target?.data?.layerId;
477
+ if (layerId !== IMAGE_OBJECT_LAYER_ID) return;
478
+ this.updateWhiteInks();
479
+ };
480
+
481
+ private onImageWorkingChanged = () => {
482
+ this.updateWhiteInks();
483
+ };
484
+
485
+ private migrateLegacyConfigIfNeeded(configService: ConfigurationService) {
486
+ if (this.items.length > 0) return;
487
+ const legacyMask = configService.get("whiteInk.customMask", "");
488
+ if (typeof legacyMask !== "string" || legacyMask.length === 0) return;
489
+
490
+ const item = this.normalizeItem({
491
+ id: this.generateId(),
492
+ sourceUrl: legacyMask,
493
+ opacity: WHITE_INK_DEFAULT_OPACITY,
494
+ });
495
+
496
+ this.items = [item];
497
+ this.workingItems = this.cloneItems(this.items);
498
+ this.isUpdatingConfig = true;
499
+ configService.update("whiteInk.items", this.items);
500
+ setTimeout(() => {
501
+ this.isUpdatingConfig = false;
502
+ }, 0);
503
+ }
504
+
505
+ private syncToolActiveFromWorkbench(fallbackId?: string | null) {
506
+ const wb = this.context?.services.get<WorkbenchService>("WorkbenchService");
507
+ const activeId = wb?.activeToolId;
508
+ if (typeof activeId === "string" || activeId === null) {
509
+ this.isToolActive = activeId === this.id;
510
+ return;
511
+ }
512
+ this.isToolActive = fallbackId === this.id;
513
+ }
514
+
515
+ private isPreviewActive(): boolean {
516
+ return this.isToolActive && this.printWithWhiteInk;
517
+ }
518
+
519
+ private isDebugEnabled(): boolean {
520
+ return !!this.getConfig<boolean>(WHITE_INK_DEBUG_KEY, false);
521
+ }
522
+
523
+ private debug(message: string, payload?: any) {
524
+ if (!this.isDebugEnabled()) return;
525
+ if (payload === undefined) {
526
+ console.log(`[WhiteInkTool] ${message}`);
527
+ return;
528
+ }
529
+ console.log(`[WhiteInkTool] ${message}`, payload);
530
+ }
531
+
532
+ private resolveSourceUrl(item?: Partial<WhiteInkItem> | null): string {
533
+ if (!item) return "";
534
+ if (typeof item.sourceUrl === "string" && item.sourceUrl.length > 0) {
535
+ return item.sourceUrl;
536
+ }
537
+ if (typeof item.url === "string" && item.url.length > 0) {
538
+ return item.url;
539
+ }
540
+ return "";
541
+ }
542
+
543
+ private normalizeItem(item: Partial<WhiteInkItem>): WhiteInkItem {
544
+ const sourceUrl = this.resolveSourceUrl(item);
545
+ return {
546
+ id: String(item.id || this.generateId()),
547
+ sourceUrl,
548
+ url: sourceUrl,
549
+ opacity: WHITE_INK_DEFAULT_OPACITY,
550
+ };
551
+ }
552
+
553
+ private normalizeItems(items: WhiteInkItem[]): WhiteInkItem[] {
554
+ return (items || [])
555
+ .map((item) => this.normalizeItem(item))
556
+ .filter((item) => !!item.id);
557
+ }
558
+
559
+ private cloneItems(items: WhiteInkItem[]): WhiteInkItem[] {
560
+ return this.normalizeItems((items || []).map((item) => ({ ...item })));
561
+ }
562
+
563
+ private getEffectiveWhiteInkItem(items: WhiteInkItem[]): WhiteInkItem | null {
564
+ const normalized = this.cloneItems(items || []);
565
+ if (normalized.length > 0) {
566
+ return normalized[0];
567
+ }
568
+
569
+ if (!this.getPrimaryImageSource()) {
570
+ return null;
571
+ }
572
+
573
+ return {
574
+ id: WHITE_INK_AUTO_ITEM_ID,
575
+ opacity: WHITE_INK_DEFAULT_OPACITY,
576
+ };
577
+ }
578
+
579
+ private generateId(): string {
580
+ return `white-ink-${Math.random().toString(36).slice(2, 9)}`;
581
+ }
582
+
583
+ private getConfig<T>(key: string, fallback?: T): T | undefined {
584
+ if (!this.context) return fallback;
585
+ const configService = this.context.services.get<ConfigurationService>(
586
+ "ConfigurationService",
587
+ );
588
+ if (!configService) return fallback;
589
+ return (configService.get(key, fallback) as T) ?? fallback;
590
+ }
591
+
592
+ private resolveReplaceTargetId(explicitId?: string | null): string | null {
593
+ const has = (id: string | null | undefined) =>
594
+ !!id && this.items.some((item) => item.id === id);
595
+ if (has(explicitId)) return explicitId as string;
596
+ if (this.items.length >= 1) {
597
+ return this.items[0].id;
598
+ }
599
+ return null;
600
+ }
601
+
602
+ private updateConfig(newItems: WhiteInkItem[], skipCanvasUpdate = false) {
603
+ if (!this.context) return;
604
+
605
+ this.isUpdatingConfig = true;
606
+ this.items = this.normalizeItems(newItems);
607
+ if (!this.isToolActive || !this.hasWorkingChanges) {
608
+ this.workingItems = this.cloneItems(this.items);
609
+ this.hasWorkingChanges = false;
610
+ }
611
+
612
+ const configService = this.context.services.get<ConfigurationService>(
613
+ "ConfigurationService",
614
+ );
615
+ configService?.update("whiteInk.items", this.items);
616
+
617
+ if (!skipCanvasUpdate) {
618
+ this.updateWhiteInks();
619
+ }
620
+
621
+ setTimeout(() => {
622
+ this.isUpdatingConfig = false;
623
+ }, 50);
624
+ }
625
+
626
+ private async addWhiteInkEntry(
627
+ url: string,
628
+ options?: Partial<WhiteInkItem>,
629
+ ): Promise<string> {
630
+ const id = this.generateId();
631
+ const item = this.normalizeItem({
632
+ id,
633
+ sourceUrl: url,
634
+ opacity: WHITE_INK_DEFAULT_OPACITY,
635
+ ...options,
636
+ });
637
+
638
+ const sessionDirtyBeforeAdd = this.isToolActive && this.hasWorkingChanges;
639
+ this.updateConfig([...this.items, item]);
640
+ this.addItemToWorkingSessionIfNeeded(item, sessionDirtyBeforeAdd);
641
+ return id;
642
+ }
643
+
644
+ private async upsertWhiteInkEntry(
645
+ url: string,
646
+ options: UpsertWhiteInkOptions = {},
647
+ ): Promise<{ id: string; mode: "replace" | "add" }> {
648
+ const mode = options.mode || "auto";
649
+ if (mode === "add") {
650
+ const id = await this.addWhiteInkEntry(url, options.addOptions);
651
+ return { id, mode: "add" };
652
+ }
653
+
654
+ const targetId = this.resolveReplaceTargetId(options.id ?? null);
655
+ if (targetId) {
656
+ this.updateWhiteInkInConfig(targetId, {
657
+ ...(options.addOptions || {}),
658
+ sourceUrl: url,
659
+ url,
660
+ });
661
+ return { id: targetId, mode: "replace" };
662
+ }
663
+
664
+ if (mode === "replace" || options.createIfMissing === false) {
665
+ throw new Error("replace-target-not-found");
666
+ }
667
+
668
+ const id = await this.addWhiteInkEntry(url, options.addOptions);
669
+ return { id, mode: "add" };
670
+ }
671
+
672
+ private addItemToWorkingSessionIfNeeded(
673
+ item: WhiteInkItem,
674
+ sessionDirtyBeforeAdd: boolean,
675
+ ) {
676
+ if (!sessionDirtyBeforeAdd || !this.isToolActive) return;
677
+ if (this.workingItems.some((existing) => existing.id === item.id)) return;
678
+ this.workingItems = this.cloneItems([...this.workingItems, item]);
679
+ this.updateWhiteInks();
680
+ }
681
+
682
+ private async updateWhiteInkItem(
683
+ id: string,
684
+ updates: Partial<WhiteInkItem>,
685
+ options: UpdateWhiteInkOptions = {},
686
+ ) {
687
+ this.syncToolActiveFromWorkbench();
688
+ const target = options.target || "auto";
689
+ if (target === "working" || (target === "auto" && this.isToolActive)) {
690
+ this.updateWhiteInkInWorking(id, updates);
691
+ return;
692
+ }
693
+
694
+ this.updateWhiteInkInConfig(id, updates);
695
+ }
696
+
697
+ private updateWhiteInkInWorking(id: string, updates: Partial<WhiteInkItem>) {
698
+ let changed = false;
699
+ const next = this.workingItems.map((item) => {
700
+ if (item.id !== id) return item;
701
+ changed = true;
702
+ return this.normalizeItem({
703
+ ...item,
704
+ ...updates,
705
+ });
706
+ });
707
+ if (!changed) return;
708
+
709
+ this.workingItems = this.cloneItems(next);
710
+ this.hasWorkingChanges = true;
711
+ this.updateWhiteInks();
712
+ }
713
+
714
+ private updateWhiteInkInConfig(id: string, updates: Partial<WhiteInkItem>) {
715
+ let changed = false;
716
+ const next = this.items.map((item) => {
717
+ if (item.id !== id) return item;
718
+ changed = true;
719
+ const merged = this.normalizeItem({
720
+ ...item,
721
+ ...updates,
722
+ });
723
+ if (this.resolveSourceUrl(item) !== this.resolveSourceUrl(merged)) {
724
+ this.purgeSourceCaches(item);
725
+ }
726
+ return merged;
727
+ });
728
+ if (!changed) return;
729
+
730
+ this.updateConfig(next);
731
+ }
732
+
733
+ private removeWhiteInk(id: string) {
734
+ const removed = this.items.find((item) => item.id === id);
735
+ const next = this.items.filter((item) => item.id !== id);
736
+ if (next.length === this.items.length) return;
737
+
738
+ this.purgeSourceCaches(removed);
739
+ this.updateConfig(next);
740
+ }
741
+
742
+ private clearWhiteInks() {
743
+ this.sourceSizeBySrc.clear();
744
+ this.previewMaskBySource.clear();
745
+ this.pendingPreviewMaskBySource.clear();
746
+ this.updateConfig([]);
747
+ }
748
+
749
+ private async completeWhiteInks() {
750
+ this.updateConfig(this.cloneItems(this.workingItems));
751
+ this.hasWorkingChanges = false;
752
+ return { ok: true };
753
+ }
754
+
755
+ private getFrameRect(): FrameRect {
756
+ if (!this.canvasService) {
757
+ return { left: 0, top: 0, width: 0, height: 0 };
758
+ }
759
+ const configService = this.context?.services.get<ConfigurationService>(
760
+ "ConfigurationService",
761
+ );
762
+ if (!configService) {
763
+ return { left: 0, top: 0, width: 0, height: 0 };
764
+ }
765
+ const sizeState = readSizeState(configService);
766
+ const layout = computeSceneLayout(this.canvasService, sizeState);
767
+ if (!layout) {
768
+ return { left: 0, top: 0, width: 0, height: 0 };
769
+ }
770
+
771
+ return this.canvasService.toSceneRect({
772
+ left: layout.cutRect.left,
773
+ top: layout.cutRect.top,
774
+ width: layout.cutRect.width,
775
+ height: layout.cutRect.height,
776
+ });
777
+ }
778
+
779
+ private toLayoutSceneRect(rect: FrameRect): RenderLayoutRect {
780
+ return {
781
+ left: rect.left,
782
+ top: rect.top,
783
+ width: rect.width,
784
+ height: rect.height,
785
+ space: "scene",
786
+ };
787
+ }
788
+
789
+ private getImageObjects(): any[] {
790
+ if (!this.canvasService) return [];
791
+ return this.canvasService.canvas.getObjects().filter((obj: any) => {
792
+ return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
793
+ }) as any[];
794
+ }
795
+
796
+ private getPrimaryImageObject(): any | undefined {
797
+ return this.getImageObjects()[0];
798
+ }
799
+
800
+ private getPrimaryImageSource(): string {
801
+ return this.getCurrentSrc(this.getPrimaryImageObject()) || "";
802
+ }
803
+
804
+ private getCurrentSrc(obj: any): string | undefined {
805
+ if (!obj) return undefined;
806
+ if (typeof obj.getSrc === "function") return obj.getSrc();
807
+ return obj?._originalElement?.src;
808
+ }
809
+
810
+ private getImageSnapshot(obj: any): ImageSnapshot | null {
811
+ if (!obj) return null;
812
+
813
+ const src = this.getCurrentSrc(obj);
814
+ if (!src) return null;
815
+
816
+ const element = this.getImageElementFromObject(obj);
817
+ const width = Number(obj?.width || 0);
818
+ const height = Number(obj?.height || 0);
819
+ this.rememberSourceSize(src, { width, height });
820
+ const sceneScale = this.canvasService?.getSceneScale() || 1;
821
+ const leftScreen = Number.isFinite(obj?.left) ? Number(obj.left) : 0;
822
+ const topScreen = Number.isFinite(obj?.top) ? Number(obj.top) : 0;
823
+ const scenePoint = this.canvasService
824
+ ? this.canvasService.toScenePoint({ x: leftScreen, y: topScreen })
825
+ : { x: leftScreen, y: topScreen };
826
+
827
+ return {
828
+ id: String(obj?.data?.id || "image"),
829
+ src,
830
+ element,
831
+ left: scenePoint.x,
832
+ top: scenePoint.y,
833
+ scaleX:
834
+ (Number.isFinite(obj?.scaleX) ? Number(obj.scaleX) : 1) / sceneScale,
835
+ scaleY:
836
+ (Number.isFinite(obj?.scaleY) ? Number(obj.scaleY) : 1) / sceneScale,
837
+ angle: Number.isFinite(obj?.angle) ? Number(obj.angle) : 0,
838
+ originX: typeof obj?.originX === "string" ? obj.originX : "center",
839
+ originY: typeof obj?.originY === "string" ? obj.originY : "center",
840
+ flipX: !!obj?.flipX,
841
+ flipY: !!obj?.flipY,
842
+ skewX: Number.isFinite(obj?.skewX) ? Number(obj.skewX) : 0,
843
+ skewY: Number.isFinite(obj?.skewY) ? Number(obj.skewY) : 0,
844
+ width,
845
+ height,
846
+ };
847
+ }
848
+
849
+ private getImagePlacementState(id?: string): ImagePlacementState | null {
850
+ const rawItems = this.getConfig<any[]>("image.items", []);
851
+ if (!Array.isArray(rawItems) || rawItems.length === 0) return null;
852
+
853
+ const matched =
854
+ (id
855
+ ? rawItems.find(
856
+ (item: any) =>
857
+ item &&
858
+ typeof item === "object" &&
859
+ typeof item.id === "string" &&
860
+ item.id === id,
861
+ )
862
+ : undefined) || rawItems[0];
863
+
864
+ if (!matched || typeof matched !== "object") return null;
865
+
866
+ const sourceUrl =
867
+ typeof matched.sourceUrl === "string" && matched.sourceUrl.length > 0
868
+ ? matched.sourceUrl
869
+ : typeof matched.url === "string"
870
+ ? matched.url
871
+ : "";
872
+ const committedUrl =
873
+ typeof matched.committedUrl === "string" ? matched.committedUrl : "";
874
+
875
+ return {
876
+ id:
877
+ typeof matched.id === "string" && matched.id.length > 0
878
+ ? matched.id
879
+ : id || "image",
880
+ sourceUrl,
881
+ committedUrl,
882
+ left: Number.isFinite(matched.left) ? Number(matched.left) : 0.5,
883
+ top: Number.isFinite(matched.top) ? Number(matched.top) : 0.5,
884
+ scale: Number.isFinite(matched.scale) ? Math.max(0.05, matched.scale) : 1,
885
+ angle: Number.isFinite(matched.angle) ? matched.angle : 0,
886
+ };
887
+ }
888
+
889
+ private shouldRestoreSnapshotToSource(
890
+ snapshot: ImageSnapshot,
891
+ placement: ImagePlacementState,
892
+ ): boolean {
893
+ if (!placement.sourceUrl || !placement.committedUrl) return false;
894
+ if (placement.sourceUrl === placement.committedUrl) return false;
895
+ return snapshot.src === placement.committedUrl;
896
+ }
897
+
898
+ private getCoverScale(frame: FrameRect, source: SourceSize): number {
899
+ const frameW = Math.max(1, frame.width);
900
+ const frameH = Math.max(1, frame.height);
901
+ const sourceW = Math.max(1, source.width);
902
+ const sourceH = Math.max(1, source.height);
903
+ return Math.max(frameW / sourceW, frameH / sourceH);
904
+ }
905
+
906
+ private async ensureSourceSize(
907
+ sourceUrl: string,
908
+ ): Promise<SourceSize | null> {
909
+ if (!sourceUrl) return null;
910
+ const cached = this.getSourceSize(sourceUrl);
911
+ if (cached) return cached;
912
+
913
+ try {
914
+ const image = await this.loadImageElement(sourceUrl);
915
+ const size = this.getElementSize(image);
916
+ if (!size) return null;
917
+ this.rememberSourceSize(sourceUrl, size);
918
+ return {
919
+ width: size.width,
920
+ height: size.height,
921
+ };
922
+ } catch {
923
+ return null;
924
+ }
925
+ }
926
+
927
+ private async resolveAlignedImageSnapshot(
928
+ snapshot: ImageSnapshot,
929
+ ): Promise<ImageSnapshot> {
930
+ const placement = this.getImagePlacementState(snapshot.id);
931
+ if (!placement) return snapshot;
932
+ if (!this.shouldRestoreSnapshotToSource(snapshot, placement)) {
933
+ return snapshot;
934
+ }
935
+
936
+ const frame = this.getFrameRect();
937
+ if (frame.width <= 0 || frame.height <= 0) {
938
+ return snapshot;
939
+ }
940
+
941
+ const sourceSize = await this.ensureSourceSize(placement.sourceUrl);
942
+ if (!sourceSize) return snapshot;
943
+
944
+ const coverScale = this.getCoverScale(frame, sourceSize);
945
+
946
+ return {
947
+ ...snapshot,
948
+ src: placement.sourceUrl,
949
+ element: undefined,
950
+ left: frame.left + placement.left * frame.width,
951
+ top: frame.top + placement.top * frame.height,
952
+ scaleX: coverScale * placement.scale,
953
+ scaleY: coverScale * placement.scale,
954
+ angle: placement.angle,
955
+ originX: "center",
956
+ originY: "center",
957
+ width: sourceSize.width,
958
+ height: sourceSize.height,
959
+ };
960
+ }
961
+ private getImageElementFromObject(obj: any): any {
962
+ if (!obj) return null;
963
+ if (typeof obj.getElement === "function") {
964
+ return obj.getElement();
965
+ }
966
+ return obj?._element || obj?._originalElement || null;
967
+ }
968
+
969
+ private rememberSourceSize(src: string, size: SourceSize) {
970
+ if (!src) return;
971
+ if (!Number.isFinite(size.width) || !Number.isFinite(size.height)) return;
972
+ if (size.width <= 0 || size.height <= 0) return;
973
+ this.sourceSizeBySrc.set(src, {
974
+ width: size.width,
975
+ height: size.height,
976
+ });
977
+ }
978
+
979
+ private getSourceSize(src: string): SourceSize | null {
980
+ if (!src) return null;
981
+ const cached = this.sourceSizeBySrc.get(src);
982
+ if (!cached) return null;
983
+ return {
984
+ width: cached.width,
985
+ height: cached.height,
986
+ };
987
+ }
988
+
989
+ private computeWhiteScaleAdjust(
990
+ baseSource: string,
991
+ whiteSource: string,
992
+ ): { x: number; y: number } {
993
+ if (!baseSource || !whiteSource || baseSource === whiteSource) {
994
+ return { x: 1, y: 1 };
995
+ }
996
+
997
+ const baseSize = this.getSourceSize(baseSource);
998
+ const whiteSize = this.getSourceSize(whiteSource);
999
+ if (!baseSize || !whiteSize) {
1000
+ return { x: 1, y: 1 };
1001
+ }
1002
+
1003
+ if (whiteSize.width <= 0 || whiteSize.height <= 0) {
1004
+ return { x: 1, y: 1 };
1005
+ }
1006
+
1007
+ return {
1008
+ x: baseSize.width / whiteSize.width,
1009
+ y: baseSize.height / whiteSize.height,
1010
+ };
1011
+ }
1012
+
1013
+ private computeCoverOpacity(): number {
1014
+ const raw = WHITE_INK_DEFAULT_OPACITY * WHITE_INK_COVER_OPACITY_FACTOR;
1015
+ return Math.max(
1016
+ WHITE_INK_COVER_OPACITY_MIN,
1017
+ Math.min(WHITE_INK_COVER_OPACITY_MAX, raw),
1018
+ );
1019
+ }
1020
+
1021
+ private buildCloneImageSpec(
1022
+ id: string,
1023
+ snapshot: ImageSnapshot,
1024
+ src: string,
1025
+ opacity: number,
1026
+ layerId: string,
1027
+ type: "white-ink" | "white-ink-cover",
1028
+ scaleAdjustX = 1,
1029
+ scaleAdjustY = 1,
1030
+ ): RenderObjectSpec {
1031
+ return {
1032
+ id,
1033
+ type: "image",
1034
+ src,
1035
+ data: {
1036
+ id,
1037
+ layerId,
1038
+ type,
1039
+ imageId: snapshot.id,
1040
+ },
1041
+ props: {
1042
+ left: snapshot.left,
1043
+ top: snapshot.top,
1044
+ originX: snapshot.originX,
1045
+ originY: snapshot.originY,
1046
+ angle: snapshot.angle,
1047
+ scaleX: snapshot.scaleX * scaleAdjustX,
1048
+ scaleY: snapshot.scaleY * scaleAdjustY,
1049
+ flipX: snapshot.flipX,
1050
+ flipY: snapshot.flipY,
1051
+ skewX: snapshot.skewX,
1052
+ skewY: snapshot.skewY,
1053
+ selectable: false,
1054
+ evented: false,
1055
+ hasControls: false,
1056
+ hasBorders: false,
1057
+ uniformScaling: true,
1058
+ lockScalingFlip: true,
1059
+ opacity: Math.max(0, Math.min(1, Number(opacity))),
1060
+ excludeFromExport: true,
1061
+ },
1062
+ };
1063
+ }
1064
+
1065
+ private buildFrameSpecs(frame: FrameRect): RenderObjectSpec[] {
1066
+ if (!this.isToolActive || !this.canvasService) return [];
1067
+ if (frame.width <= 0 || frame.height <= 0) return [];
1068
+
1069
+ const viewport = this.canvasService.getSceneViewportRect();
1070
+ const canvasW = viewport.width || 0;
1071
+ const canvasH = viewport.height || 0;
1072
+ const canvasLeft = viewport.left || 0;
1073
+ const canvasTop = viewport.top || 0;
1074
+ const strokeColor =
1075
+ this.getConfig<string>("image.frame.strokeColor", "#808080") || "#808080";
1076
+ const strokeWidthRaw = Number(
1077
+ this.getConfig<number>("image.frame.strokeWidth", 2) ?? 2,
1078
+ );
1079
+ const dashLengthRaw = Number(
1080
+ this.getConfig<number>("image.frame.dashLength", 8) ?? 8,
1081
+ );
1082
+ const outerBackground =
1083
+ this.getConfig<string>("image.frame.outerBackground", "#f5f5f5") ||
1084
+ "#f5f5f5";
1085
+ const innerBackground =
1086
+ this.getConfig<string>("image.frame.innerBackground", "rgba(0,0,0,0)") ||
1087
+ "rgba(0,0,0,0)";
1088
+
1089
+ const strokeWidth = Number.isFinite(strokeWidthRaw)
1090
+ ? Math.max(0, strokeWidthRaw)
1091
+ : 2;
1092
+ const dashLength = Number.isFinite(dashLengthRaw)
1093
+ ? Math.max(1, dashLengthRaw)
1094
+ : 8;
1095
+ const strokeWidthScene = this.canvasService.toSceneLength(strokeWidth);
1096
+ const dashLengthScene = this.canvasService.toSceneLength(dashLength);
1097
+
1098
+ const frameLeft = Math.max(
1099
+ canvasLeft,
1100
+ Math.min(canvasLeft + canvasW, frame.left),
1101
+ );
1102
+ const frameTop = Math.max(
1103
+ canvasTop,
1104
+ Math.min(canvasTop + canvasH, frame.top),
1105
+ );
1106
+ const frameRight = Math.max(
1107
+ frameLeft,
1108
+ Math.min(canvasLeft + canvasW, frame.left + frame.width),
1109
+ );
1110
+ const frameBottom = Math.max(
1111
+ frameTop,
1112
+ Math.min(canvasTop + canvasH, frame.top + frame.height),
1113
+ );
1114
+ const visibleFrameH = Math.max(0, frameBottom - frameTop);
1115
+
1116
+ const topH = Math.max(0, frameTop - canvasTop);
1117
+ const bottomH = Math.max(0, canvasTop + canvasH - frameBottom);
1118
+ const leftW = Math.max(0, frameLeft - canvasLeft);
1119
+ const rightW = Math.max(0, canvasLeft + canvasW - frameRight);
1120
+ const viewportRect = this.toLayoutSceneRect({
1121
+ left: canvasLeft,
1122
+ top: canvasTop,
1123
+ width: canvasW,
1124
+ height: canvasH,
1125
+ });
1126
+ const visibleFrameBandRect = this.toLayoutSceneRect({
1127
+ left: canvasLeft,
1128
+ top: frameTop,
1129
+ width: canvasW,
1130
+ height: visibleFrameH,
1131
+ });
1132
+ const frameRect = this.toLayoutSceneRect(frame);
1133
+
1134
+ const maskSpecs: RenderObjectSpec[] = [
1135
+ {
1136
+ id: "white-ink.cropMask.top",
1137
+ type: "rect",
1138
+ data: {
1139
+ id: "white-ink.cropMask.top",
1140
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
1141
+ type: "white-ink-mask",
1142
+ },
1143
+ layout: {
1144
+ reference: "custom",
1145
+ referenceRect: viewportRect,
1146
+ alignX: "start",
1147
+ alignY: "start",
1148
+ width: "100%",
1149
+ height: topH,
1150
+ },
1151
+ props: {
1152
+ originX: "left",
1153
+ originY: "top",
1154
+ fill: outerBackground,
1155
+ selectable: false,
1156
+ evented: false,
1157
+ excludeFromExport: true,
1158
+ },
1159
+ },
1160
+ {
1161
+ id: "white-ink.cropMask.bottom",
1162
+ type: "rect",
1163
+ data: {
1164
+ id: "white-ink.cropMask.bottom",
1165
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
1166
+ type: "white-ink-mask",
1167
+ },
1168
+ layout: {
1169
+ reference: "custom",
1170
+ referenceRect: viewportRect,
1171
+ alignX: "start",
1172
+ alignY: "end",
1173
+ width: "100%",
1174
+ height: bottomH,
1175
+ },
1176
+ props: {
1177
+ originX: "left",
1178
+ originY: "top",
1179
+ fill: outerBackground,
1180
+ selectable: false,
1181
+ evented: false,
1182
+ excludeFromExport: true,
1183
+ },
1184
+ },
1185
+ {
1186
+ id: "white-ink.cropMask.left",
1187
+ type: "rect",
1188
+ data: {
1189
+ id: "white-ink.cropMask.left",
1190
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
1191
+ type: "white-ink-mask",
1192
+ },
1193
+ layout: {
1194
+ reference: "custom",
1195
+ referenceRect: visibleFrameBandRect,
1196
+ alignX: "start",
1197
+ alignY: "start",
1198
+ width: leftW,
1199
+ height: "100%",
1200
+ },
1201
+ props: {
1202
+ originX: "left",
1203
+ originY: "top",
1204
+ fill: outerBackground,
1205
+ selectable: false,
1206
+ evented: false,
1207
+ excludeFromExport: true,
1208
+ },
1209
+ },
1210
+ {
1211
+ id: "white-ink.cropMask.right",
1212
+ type: "rect",
1213
+ data: {
1214
+ id: "white-ink.cropMask.right",
1215
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
1216
+ type: "white-ink-mask",
1217
+ },
1218
+ layout: {
1219
+ reference: "custom",
1220
+ referenceRect: visibleFrameBandRect,
1221
+ alignX: "end",
1222
+ alignY: "start",
1223
+ width: rightW,
1224
+ height: "100%",
1225
+ },
1226
+ props: {
1227
+ originX: "left",
1228
+ originY: "top",
1229
+ fill: outerBackground,
1230
+ selectable: false,
1231
+ evented: false,
1232
+ excludeFromExport: true,
1233
+ },
1234
+ },
1235
+ ];
1236
+
1237
+ return [
1238
+ ...maskSpecs,
1239
+ {
1240
+ id: "white-ink.cropFrame",
1241
+ type: "rect",
1242
+ data: {
1243
+ id: "white-ink.cropFrame",
1244
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
1245
+ type: "white-ink-frame",
1246
+ },
1247
+ layout: {
1248
+ reference: "custom",
1249
+ referenceRect: frameRect,
1250
+ alignX: "start",
1251
+ alignY: "start",
1252
+ width: "100%",
1253
+ height: "100%",
1254
+ },
1255
+ props: {
1256
+ originX: "left",
1257
+ originY: "top",
1258
+ fill: innerBackground,
1259
+ stroke: strokeColor,
1260
+ strokeWidth: strokeWidthScene,
1261
+ strokeDashArray: [dashLengthScene, dashLengthScene],
1262
+ selectable: false,
1263
+ evented: false,
1264
+ excludeFromExport: true,
1265
+ },
1266
+ },
1267
+ ];
1268
+ }
1269
+
1270
+ private applyImageVisibilityForWhiteInk(previewActive: boolean) {
1271
+ if (!this.canvasService) return;
1272
+ const visible = !previewActive;
1273
+ let changed = false;
1274
+
1275
+ this.canvasService.canvas.getObjects().forEach((obj: any) => {
1276
+ if (obj?.data?.layerId !== IMAGE_OBJECT_LAYER_ID) return;
1277
+ if (obj.visible === visible) return;
1278
+ obj.set({ visible });
1279
+ obj.setCoords?.();
1280
+ changed = true;
1281
+ });
1282
+
1283
+ if (changed) {
1284
+ this.canvasService.requestRenderAll();
1285
+ }
1286
+ }
1287
+
1288
+ private resolveRenderItems(): WhiteInkItem[] {
1289
+ if (this.isToolActive) {
1290
+ return this.cloneItems(this.workingItems);
1291
+ }
1292
+ return this.cloneItems(this.items);
1293
+ }
1294
+
1295
+ private async resolveRenderSources(
1296
+ snapshot: ImageSnapshot,
1297
+ item: WhiteInkItem,
1298
+ ): Promise<RenderSources | null> {
1299
+ const imageSource = snapshot.src;
1300
+ if (!imageSource) return null;
1301
+
1302
+ const whiteSource = this.resolveSourceUrl(item) || imageSource;
1303
+ const imageElement = snapshot.element;
1304
+ const whiteElement = whiteSource === imageSource ? imageElement : undefined;
1305
+ const [whiteMaskSrc, coverMaskSrc] = await Promise.all([
1306
+ this.getPreviewMaskSource(whiteSource, WHITE_MASK_TINT, whiteElement),
1307
+ this.getPreviewMaskSource(imageSource, COVER_MASK_TINT, imageElement),
1308
+ ]);
1309
+
1310
+ const scaleAdjust = this.computeWhiteScaleAdjust(imageSource, whiteSource);
1311
+
1312
+ return {
1313
+ whiteSrc: whiteMaskSrc || "",
1314
+ coverSrc: coverMaskSrc || "",
1315
+ whiteScaleAdjustX: scaleAdjust.x,
1316
+ whiteScaleAdjustY: scaleAdjust.y,
1317
+ };
1318
+ }
1319
+
1320
+ private resolveDefaultInsertIndex(objects: any[]): number {
1321
+ if (!this.canvasService) return 0;
1322
+ const backgroundLayer = this.canvasService.getLayer("background");
1323
+ if (!backgroundLayer) return 0;
1324
+ const bgIndex = objects.indexOf(backgroundLayer as any);
1325
+ if (bgIndex < 0) return 0;
1326
+ return bgIndex + 1;
1327
+ }
1328
+
1329
+ private syncZOrder() {
1330
+ if (!this.canvasService) return;
1331
+ const canvas = this.canvasService.canvas;
1332
+
1333
+ const whiteObjects = this.canvasService.getRootLayerObjects(
1334
+ WHITE_INK_OBJECT_LAYER_ID,
1335
+ ) as any[];
1336
+ const coverObjects = this.canvasService.getRootLayerObjects(
1337
+ WHITE_INK_COVER_LAYER_ID,
1338
+ ) as any[];
1339
+ const frameObjects = this.canvasService.getRootLayerObjects(
1340
+ WHITE_INK_OVERLAY_LAYER_ID,
1341
+ ) as any[];
1342
+
1343
+ const currentObjects = canvas.getObjects();
1344
+ const imageIndexes = currentObjects
1345
+ .map((obj: any, index: number) =>
1346
+ obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID ? index : -1,
1347
+ )
1348
+ .filter((index: number) => index >= 0);
1349
+
1265
1350
  let whiteInsertIndex = imageIndexes.length
1266
1351
  ? Math.min(...imageIndexes)
1267
1352
  : this.resolveDefaultInsertIndex(currentObjects);
1268
1353
 
1269
- whiteObjects.forEach((obj) => {
1270
- canvas.moveObjectTo(obj, whiteInsertIndex);
1271
- whiteInsertIndex += 1;
1272
- });
1273
-
1274
- const afterWhiteObjects = canvas.getObjects();
1275
- const afterImageIndexes = afterWhiteObjects
1276
- .map((obj: any, index: number) =>
1277
- obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID ? index : -1,
1278
- )
1279
- .filter((index: number) => index >= 0);
1280
-
1281
- let coverInsertIndex = afterImageIndexes.length
1282
- ? Math.max(...afterImageIndexes) + 1
1283
- : whiteInsertIndex;
1354
+ let coverInsertIndex = whiteInsertIndex;
1284
1355
 
1285
1356
  coverObjects.forEach((obj) => {
1286
1357
  canvas.moveObjectTo(obj, coverInsertIndex);
1287
1358
  coverInsertIndex += 1;
1288
1359
  });
1289
1360
 
1290
- frameObjects.forEach((obj) => canvas.bringObjectToFront(obj));
1291
-
1292
- canvas
1293
- .getObjects()
1294
- .filter((obj: any) => obj?.data?.layerId === IMAGE_OVERLAY_LAYER_ID)
1295
- .forEach((obj: any) => canvas.bringObjectToFront(obj));
1296
-
1297
- const dielineOverlay = this.canvasService.getLayer("dieline-overlay");
1298
- if (dielineOverlay) {
1299
- canvas.bringObjectToFront(dielineOverlay as any);
1300
- }
1301
-
1302
- const rulerOverlay = this.canvasService.getLayer("ruler-overlay");
1303
- if (rulerOverlay) {
1304
- canvas.bringObjectToFront(rulerOverlay as any);
1305
- }
1306
- }
1307
-
1308
- private clearRenderedWhiteInks() {
1309
- if (!this.canvasService) return;
1310
- void this.canvasService.applyObjectSpecsToRootLayer(
1311
- WHITE_INK_OBJECT_LAYER_ID,
1312
- [],
1313
- );
1314
- void this.canvasService.applyObjectSpecsToRootLayer(
1315
- WHITE_INK_COVER_LAYER_ID,
1316
- [],
1317
- );
1318
- void this.canvasService.applyObjectSpecsToRootLayer(
1319
- WHITE_INK_OVERLAY_LAYER_ID,
1320
- [],
1321
- );
1322
- }
1323
-
1324
- private purgeSourceCaches(item?: WhiteInkItem) {
1325
- const sourceUrl = this.resolveSourceUrl(item);
1326
- if (!sourceUrl) return;
1327
- this.sourceSizeBySrc.delete(sourceUrl);
1328
- const prefix = `${sourceUrl}::`;
1329
- Array.from(this.previewMaskBySource.keys()).forEach((cacheKey) => {
1330
- if (cacheKey.startsWith(prefix)) {
1331
- this.previewMaskBySource.delete(cacheKey);
1332
- }
1333
- });
1334
- Array.from(this.pendingPreviewMaskBySource.keys()).forEach((cacheKey) => {
1335
- if (cacheKey.startsWith(prefix)) {
1336
- this.pendingPreviewMaskBySource.delete(cacheKey);
1337
- }
1338
- });
1339
- }
1340
-
1341
- private updateWhiteInks() {
1342
- void this.updateWhiteInksAsync();
1343
- }
1344
-
1345
- private async updateWhiteInksAsync() {
1346
- if (!this.canvasService) return;
1347
-
1348
- this.syncToolActiveFromWorkbench();
1349
- const seq = ++this.renderSeq;
1350
-
1351
- const previewActive = this.isPreviewActive();
1352
- this.applyImageVisibilityForWhiteInk(previewActive);
1353
-
1354
- const frame = this.getFrameRect();
1355
- const frameSpecs = this.buildFrameSpecs(frame);
1356
-
1357
- let whiteSpecs: RenderObjectSpec[] = [];
1358
- let coverSpecs: RenderObjectSpec[] = [];
1359
-
1360
- if (previewActive) {
1361
- const baseSnapshot = this.getImageSnapshot(this.getPrimaryImageObject());
1362
- const item = this.getEffectiveWhiteInkItem(this.resolveRenderItems());
1363
-
1364
- if (baseSnapshot && item) {
1365
- const snapshot = await this.resolveAlignedImageSnapshot(baseSnapshot);
1366
- if (seq !== this.renderSeq) return;
1367
- const sources = await this.resolveRenderSources(snapshot, item);
1368
- if (seq !== this.renderSeq) return;
1369
-
1370
- if (sources?.whiteSrc) {
1371
- whiteSpecs = [
1372
- this.buildCloneImageSpec(
1373
- "white-ink.main",
1374
- snapshot,
1375
- sources.whiteSrc,
1376
- WHITE_INK_DEFAULT_OPACITY,
1377
- WHITE_INK_OBJECT_LAYER_ID,
1378
- "white-ink",
1379
- sources.whiteScaleAdjustX,
1380
- sources.whiteScaleAdjustY,
1381
- ),
1382
- ];
1383
- }
1384
-
1385
- if (this.previewImageVisible && sources?.coverSrc) {
1386
- coverSpecs = [
1387
- this.buildCloneImageSpec(
1388
- "white-ink.cover",
1389
- snapshot,
1390
- sources.coverSrc,
1391
- this.computeCoverOpacity(),
1392
- WHITE_INK_COVER_LAYER_ID,
1393
- "white-ink-cover",
1394
- ),
1395
- ];
1396
- }
1397
- }
1398
- }
1399
-
1400
- await this.canvasService.applyObjectSpecsToRootLayer(
1401
- WHITE_INK_OBJECT_LAYER_ID,
1402
- whiteSpecs,
1403
- );
1404
- if (seq !== this.renderSeq) return;
1405
-
1406
- await this.canvasService.applyObjectSpecsToRootLayer(
1407
- WHITE_INK_COVER_LAYER_ID,
1408
- coverSpecs,
1409
- );
1410
- if (seq !== this.renderSeq) return;
1411
-
1412
- await this.canvasService.applyObjectSpecsToRootLayer(
1413
- WHITE_INK_OVERLAY_LAYER_ID,
1414
- frameSpecs,
1415
- );
1416
- if (seq !== this.renderSeq) return;
1417
-
1418
- this.syncZOrder();
1419
- this.canvasService.requestRenderAll();
1420
- }
1421
-
1422
- private getMaskCacheKey(sourceUrl: string, tint: MaskTint): string {
1423
- return `${sourceUrl}::${tint.key}`;
1424
- }
1425
-
1426
- private async getPreviewMaskSource(
1427
- sourceUrl: string,
1428
- tint: MaskTint = WHITE_MASK_TINT,
1429
- fallbackElement?: any,
1430
- ): Promise<string> {
1431
- if (!sourceUrl) return "";
1432
- if (typeof document === "undefined" || typeof Image === "undefined") {
1433
- return "";
1434
- }
1435
-
1436
- const cacheKey = this.getMaskCacheKey(sourceUrl, tint);
1437
- const cached = this.previewMaskBySource.get(cacheKey);
1438
- if (cached) return cached;
1439
-
1440
- const pending = this.pendingPreviewMaskBySource.get(cacheKey);
1441
- if (pending) {
1442
- const loaded = await pending;
1443
- return loaded || "";
1444
- }
1445
-
1446
- const task = this.createOpaqueMaskSource(sourceUrl, tint, fallbackElement);
1447
- this.pendingPreviewMaskBySource.set(cacheKey, task);
1448
- const loaded = await task;
1449
- this.pendingPreviewMaskBySource.delete(cacheKey);
1450
-
1451
- if (!loaded) return "";
1452
- this.previewMaskBySource.set(cacheKey, loaded);
1453
- return loaded;
1454
- }
1455
-
1456
- private getElementSize(
1457
- element: any,
1458
- ): { width: number; height: number } | null {
1459
- if (!element) return null;
1460
-
1461
- const width = Number(
1462
- element?.naturalWidth || element?.videoWidth || element?.width || 0,
1463
- );
1464
- const height = Number(
1465
- element?.naturalHeight || element?.videoHeight || element?.height || 0,
1466
- );
1467
-
1468
- if (!Number.isFinite(width) || !Number.isFinite(height)) return null;
1469
- if (width <= 0 || height <= 0) return null;
1470
-
1471
- return { width, height };
1472
- }
1473
-
1474
- private async createOpaqueMaskSource(
1475
- sourceUrl: string,
1476
- tint: MaskTint = WHITE_MASK_TINT,
1477
- fallbackElement?: any,
1478
- ): Promise<string | null> {
1479
- try {
1480
- const element =
1481
- fallbackElement || (await this.loadImageElement(sourceUrl));
1482
- const size = this.getElementSize(element);
1483
- if (!size) return null;
1484
- const width = Math.max(1, size.width);
1485
- const height = Math.max(1, size.height);
1486
-
1487
- this.rememberSourceSize(sourceUrl, { width, height });
1488
-
1489
- const canvas = document.createElement("canvas");
1490
- canvas.width = width;
1491
- canvas.height = height;
1492
- const ctx = canvas.getContext("2d");
1493
- if (!ctx) return null;
1494
-
1495
- ctx.drawImage(element, 0, 0, width, height);
1496
- const imageData = ctx.getImageData(0, 0, width, height);
1497
- const data = imageData.data;
1498
-
1499
- for (let i = 0; i < data.length; i += 4) {
1500
- const alpha = data[i + 3];
1501
- data[i] = tint.r;
1502
- data[i + 1] = tint.g;
1503
- data[i + 2] = tint.b;
1504
- data[i + 3] = alpha;
1505
- }
1506
-
1507
- ctx.putImageData(imageData, 0, 0);
1508
- return canvas.toDataURL("image/png");
1509
- } catch (error) {
1510
- this.debug("mask:extract:failed", { sourceUrl, tint: tint.key, error });
1511
- return null;
1512
- }
1513
- }
1514
-
1515
- private loadImageElement(sourceUrl: string): Promise<HTMLImageElement> {
1516
- return new Promise((resolve, reject) => {
1517
- const image = new Image();
1518
- image.crossOrigin = "anonymous";
1519
- image.onload = () => resolve(image);
1520
- image.onerror = () => reject(new Error("white-ink-image-load-failed"));
1521
- image.src = sourceUrl;
1361
+ whiteInsertIndex = coverInsertIndex;
1362
+ whiteObjects.forEach((obj) => {
1363
+ canvas.moveObjectTo(obj, whiteInsertIndex);
1364
+ whiteInsertIndex += 1;
1522
1365
  });
1523
- }
1524
- }
1525
-
1366
+
1367
+ frameObjects.forEach((obj) => canvas.bringObjectToFront(obj));
1368
+
1369
+ canvas
1370
+ .getObjects()
1371
+ .filter((obj: any) => obj?.data?.layerId === IMAGE_OVERLAY_LAYER_ID)
1372
+ .forEach((obj: any) => canvas.bringObjectToFront(obj));
1373
+
1374
+ this.canvasService.bringLayerToFront("dieline-overlay");
1375
+ this.canvasService.bringLayerToFront("ruler-overlay");
1376
+ }
1377
+
1378
+ private clearRenderedWhiteInks() {
1379
+ if (!this.canvasService) return;
1380
+ this.whiteSpecs = [];
1381
+ this.coverSpecs = [];
1382
+ this.overlaySpecs = [];
1383
+ this.canvasService.requestRenderFromProducers();
1384
+ }
1385
+
1386
+ private purgeSourceCaches(item?: WhiteInkItem) {
1387
+ const sourceUrl = this.resolveSourceUrl(item);
1388
+ if (!sourceUrl) return;
1389
+ this.sourceSizeBySrc.delete(sourceUrl);
1390
+ const prefix = `${sourceUrl}::`;
1391
+ Array.from(this.previewMaskBySource.keys()).forEach((cacheKey) => {
1392
+ if (cacheKey.startsWith(prefix)) {
1393
+ this.previewMaskBySource.delete(cacheKey);
1394
+ }
1395
+ });
1396
+ Array.from(this.pendingPreviewMaskBySource.keys()).forEach((cacheKey) => {
1397
+ if (cacheKey.startsWith(prefix)) {
1398
+ this.pendingPreviewMaskBySource.delete(cacheKey);
1399
+ }
1400
+ });
1401
+ }
1402
+
1403
+ private updateWhiteInks() {
1404
+ void this.updateWhiteInksAsync();
1405
+ }
1406
+
1407
+ private async updateWhiteInksAsync() {
1408
+ if (!this.canvasService) return;
1409
+
1410
+ this.syncToolActiveFromWorkbench();
1411
+ const seq = ++this.renderSeq;
1412
+
1413
+ const previewActive = this.isPreviewActive();
1414
+ this.applyImageVisibilityForWhiteInk(previewActive);
1415
+
1416
+ const frame = this.getFrameRect();
1417
+ const frameSpecs = this.buildFrameSpecs(frame);
1418
+
1419
+ let whiteSpecs: RenderObjectSpec[] = [];
1420
+ let coverSpecs: RenderObjectSpec[] = [];
1421
+
1422
+ if (previewActive) {
1423
+ const baseSnapshot = this.getImageSnapshot(this.getPrimaryImageObject());
1424
+ const item = this.getEffectiveWhiteInkItem(this.resolveRenderItems());
1425
+
1426
+ if (baseSnapshot && item) {
1427
+ const snapshot = await this.resolveAlignedImageSnapshot(baseSnapshot);
1428
+ if (seq !== this.renderSeq) return;
1429
+ const sources = await this.resolveRenderSources(snapshot, item);
1430
+ if (seq !== this.renderSeq) return;
1431
+
1432
+ if (sources?.whiteSrc) {
1433
+ whiteSpecs = [
1434
+ this.buildCloneImageSpec(
1435
+ "white-ink.main",
1436
+ snapshot,
1437
+ sources.whiteSrc,
1438
+ WHITE_INK_DEFAULT_OPACITY,
1439
+ WHITE_INK_OBJECT_LAYER_ID,
1440
+ "white-ink",
1441
+ sources.whiteScaleAdjustX,
1442
+ sources.whiteScaleAdjustY,
1443
+ ),
1444
+ ];
1445
+ }
1446
+
1447
+ if (this.previewImageVisible && sources?.coverSrc) {
1448
+ coverSpecs = [
1449
+ this.buildCloneImageSpec(
1450
+ "white-ink.cover",
1451
+ snapshot,
1452
+ sources.coverSrc,
1453
+ this.computeCoverOpacity(),
1454
+ WHITE_INK_COVER_LAYER_ID,
1455
+ "white-ink-cover",
1456
+ ),
1457
+ ];
1458
+ }
1459
+ }
1460
+ }
1461
+
1462
+ this.whiteSpecs = whiteSpecs;
1463
+ if (seq !== this.renderSeq) return;
1464
+
1465
+ this.coverSpecs = coverSpecs;
1466
+ if (seq !== this.renderSeq) return;
1467
+
1468
+ this.overlaySpecs = frameSpecs;
1469
+ await this.canvasService.flushRenderFromProducers();
1470
+ if (seq !== this.renderSeq) return;
1471
+
1472
+ this.syncZOrder();
1473
+ this.canvasService.requestRenderAll();
1474
+ }
1475
+
1476
+ private getMaskCacheKey(sourceUrl: string, tint: MaskTint): string {
1477
+ return `${sourceUrl}::${tint.key}`;
1478
+ }
1479
+
1480
+ private async getPreviewMaskSource(
1481
+ sourceUrl: string,
1482
+ tint: MaskTint = WHITE_MASK_TINT,
1483
+ fallbackElement?: any,
1484
+ ): Promise<string> {
1485
+ if (!sourceUrl) return "";
1486
+ if (typeof document === "undefined" || typeof Image === "undefined") {
1487
+ return "";
1488
+ }
1489
+
1490
+ const cacheKey = this.getMaskCacheKey(sourceUrl, tint);
1491
+ const cached = this.previewMaskBySource.get(cacheKey);
1492
+ if (cached) return cached;
1493
+
1494
+ const pending = this.pendingPreviewMaskBySource.get(cacheKey);
1495
+ if (pending) {
1496
+ const loaded = await pending;
1497
+ return loaded || "";
1498
+ }
1499
+
1500
+ const task = this.createOpaqueMaskSource(sourceUrl, tint, fallbackElement);
1501
+ this.pendingPreviewMaskBySource.set(cacheKey, task);
1502
+ const loaded = await task;
1503
+ this.pendingPreviewMaskBySource.delete(cacheKey);
1504
+
1505
+ if (!loaded) return "";
1506
+ this.previewMaskBySource.set(cacheKey, loaded);
1507
+ return loaded;
1508
+ }
1509
+
1510
+ private getElementSize(
1511
+ element: any,
1512
+ ): { width: number; height: number } | null {
1513
+ if (!element) return null;
1514
+
1515
+ const width = Number(
1516
+ element?.naturalWidth || element?.videoWidth || element?.width || 0,
1517
+ );
1518
+ const height = Number(
1519
+ element?.naturalHeight || element?.videoHeight || element?.height || 0,
1520
+ );
1521
+
1522
+ if (!Number.isFinite(width) || !Number.isFinite(height)) return null;
1523
+ if (width <= 0 || height <= 0) return null;
1524
+
1525
+ return { width, height };
1526
+ }
1527
+
1528
+ private async createOpaqueMaskSource(
1529
+ sourceUrl: string,
1530
+ tint: MaskTint = WHITE_MASK_TINT,
1531
+ fallbackElement?: any,
1532
+ ): Promise<string | null> {
1533
+ try {
1534
+ const element =
1535
+ fallbackElement || (await this.loadImageElement(sourceUrl));
1536
+ const size = this.getElementSize(element);
1537
+ if (!size) return null;
1538
+ const width = Math.max(1, size.width);
1539
+ const height = Math.max(1, size.height);
1540
+
1541
+ this.rememberSourceSize(sourceUrl, { width, height });
1542
+
1543
+ const canvas = document.createElement("canvas");
1544
+ canvas.width = width;
1545
+ canvas.height = height;
1546
+ const ctx = canvas.getContext("2d");
1547
+ if (!ctx) return null;
1548
+
1549
+ ctx.drawImage(element, 0, 0, width, height);
1550
+ const imageData = ctx.getImageData(0, 0, width, height);
1551
+ const data = imageData.data;
1552
+
1553
+ for (let i = 0; i < data.length; i += 4) {
1554
+ const alpha = data[i + 3];
1555
+ data[i] = tint.r;
1556
+ data[i + 1] = tint.g;
1557
+ data[i + 2] = tint.b;
1558
+ data[i + 3] = alpha;
1559
+ }
1560
+
1561
+ ctx.putImageData(imageData, 0, 0);
1562
+ return canvas.toDataURL("image/png");
1563
+ } catch (error) {
1564
+ this.debug("mask:extract:failed", { sourceUrl, tint: tint.key, error });
1565
+ return null;
1566
+ }
1567
+ }
1568
+
1569
+ private loadImageElement(sourceUrl: string): Promise<HTMLImageElement> {
1570
+ return new Promise((resolve, reject) => {
1571
+ const image = new Image();
1572
+ image.crossOrigin = "anonymous";
1573
+ image.onload = () => resolve(image);
1574
+ image.onerror = () => reject(new Error("white-ink-image-load-failed"));
1575
+ image.src = sourceUrl;
1576
+ });
1577
+ }
1578
+ }