@pooder/kit 5.3.0 → 5.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/.test-dist/src/CanvasService.js +249 -249
  2. package/.test-dist/src/ViewportSystem.js +75 -75
  3. package/.test-dist/src/background.js +203 -203
  4. package/.test-dist/src/bridgeSelection.js +20 -20
  5. package/.test-dist/src/constraints.js +237 -237
  6. package/.test-dist/src/dieline.js +818 -818
  7. package/.test-dist/src/edgeScale.js +12 -12
  8. package/.test-dist/src/feature.js +826 -826
  9. package/.test-dist/src/featureComplete.js +32 -32
  10. package/.test-dist/src/film.js +167 -167
  11. package/.test-dist/src/geometry.js +506 -506
  12. package/.test-dist/src/image.js +1250 -1250
  13. package/.test-dist/src/maskOps.js +270 -270
  14. package/.test-dist/src/mirror.js +104 -104
  15. package/.test-dist/src/renderSpec.js +2 -2
  16. package/.test-dist/src/ruler.js +343 -343
  17. package/.test-dist/src/sceneLayout.js +99 -99
  18. package/.test-dist/src/sceneLayoutModel.js +196 -196
  19. package/.test-dist/src/sceneView.js +40 -40
  20. package/.test-dist/src/sceneVisibility.js +42 -42
  21. package/.test-dist/src/size.js +332 -332
  22. package/.test-dist/src/tracer.js +544 -544
  23. package/.test-dist/src/white-ink.js +829 -829
  24. package/.test-dist/src/wrappedOffsets.js +33 -33
  25. package/CHANGELOG.md +6 -0
  26. package/dist/index.d.mts +6 -0
  27. package/dist/index.d.ts +6 -0
  28. package/dist/index.js +108 -20
  29. package/dist/index.mjs +108 -20
  30. package/package.json +1 -1
  31. package/src/coordinate.ts +106 -106
  32. package/src/extensions/background.ts +230 -230
  33. package/src/extensions/bridgeSelection.ts +17 -17
  34. package/src/extensions/constraints.ts +322 -322
  35. package/src/extensions/dieline.ts +46 -0
  36. package/src/extensions/edgeScale.ts +19 -19
  37. package/src/extensions/feature.ts +1021 -1021
  38. package/src/extensions/featureComplete.ts +46 -46
  39. package/src/extensions/film.ts +194 -194
  40. package/src/extensions/geometry.ts +752 -719
  41. package/src/extensions/image.ts +1926 -1924
  42. package/src/extensions/index.ts +11 -11
  43. package/src/extensions/maskOps.ts +283 -283
  44. package/src/extensions/mirror.ts +128 -128
  45. package/src/extensions/ruler.ts +451 -451
  46. package/src/extensions/sceneLayout.ts +140 -140
  47. package/src/extensions/sceneLayoutModel.ts +352 -342
  48. package/src/extensions/sceneVisibility.ts +71 -71
  49. package/src/extensions/size.ts +389 -389
  50. package/src/extensions/tracer.ts +58 -19
  51. package/src/extensions/white-ink.ts +1400 -1400
  52. package/src/extensions/wrappedOffsets.ts +33 -33
  53. package/src/index.ts +2 -2
  54. package/src/services/CanvasService.ts +300 -300
  55. package/src/services/ViewportSystem.ts +95 -95
  56. package/src/services/index.ts +3 -3
  57. package/src/services/renderSpec.ts +18 -18
  58. package/src/units.ts +27 -27
  59. package/tests/run.ts +118 -118
  60. package/tsconfig.test.json +15 -15
@@ -1,61 +1,61 @@
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
-
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
59
  interface ImagePlacementState {
60
60
  id: string;
61
61
  sourceUrl: string;
@@ -71,742 +71,742 @@ interface RenderSources {
71
71
  coverSrc: string;
72
72
  whiteScaleAdjustX: number;
73
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
-
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
810
  private getImagePlacementState(id?: string): ImagePlacementState | null {
811
811
  const rawItems = this.getConfig<any[]>("image.items", []);
812
812
  if (!Array.isArray(rawItems) || rawItems.length === 0) return null;
@@ -917,609 +917,609 @@ export class WhiteInkTool implements Extension {
917
917
  height: sourceSize.height,
918
918
  };
919
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
-
1265
- let whiteInsertIndex = imageIndexes.length
1266
- ? Math.min(...imageIndexes)
1267
- : this.resolveDefaultInsertIndex(currentObjects);
1268
-
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;
1284
-
1285
- coverObjects.forEach((obj) => {
1286
- canvas.moveObjectTo(obj, coverInsertIndex);
1287
- coverInsertIndex += 1;
1288
- });
1289
-
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;
1522
- });
1523
- }
1524
- }
1525
-
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
+
1265
+ let whiteInsertIndex = imageIndexes.length
1266
+ ? Math.min(...imageIndexes)
1267
+ : this.resolveDefaultInsertIndex(currentObjects);
1268
+
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;
1284
+
1285
+ coverObjects.forEach((obj) => {
1286
+ canvas.moveObjectTo(obj, coverInsertIndex);
1287
+ coverInsertIndex += 1;
1288
+ });
1289
+
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;
1522
+ });
1523
+ }
1524
+ }
1525
+