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