@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
@@ -0,0 +1,1200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WhiteInkTool = void 0;
4
+ const core_1 = require("@pooder/core");
5
+ const sceneLayoutModel_1 = require("./sceneLayoutModel");
6
+ const WHITE_INK_OBJECT_LAYER_ID = "white-ink.user";
7
+ const WHITE_INK_COVER_LAYER_ID = "white-ink.cover";
8
+ const WHITE_INK_OVERLAY_LAYER_ID = "white-ink.overlay";
9
+ const IMAGE_OBJECT_LAYER_ID = "image.user";
10
+ const WHITE_INK_DEBUG_KEY = "whiteInk.debug";
11
+ const WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY = "whiteInk.previewImageVisible";
12
+ const WHITE_INK_DEFAULT_OPACITY = 0.85;
13
+ const WHITE_INK_AUTO_ITEM_ID = "white-ink-auto";
14
+ const WHITE_INK_COVER_OPACITY_FACTOR = 0.45;
15
+ const WHITE_INK_COVER_OPACITY_MIN = 0.15;
16
+ const WHITE_INK_COVER_OPACITY_MAX = 0.65;
17
+ const WHITE_MASK_TINT = { r: 255, g: 255, b: 255, key: "white" };
18
+ const COVER_MASK_TINT = { r: 52, g: 136, b: 255, key: "blue" };
19
+ class WhiteInkTool {
20
+ constructor() {
21
+ this.id = "pooder.kit.white-ink";
22
+ this.metadata = {
23
+ name: "WhiteInkTool",
24
+ };
25
+ this.items = [];
26
+ this.workingItems = [];
27
+ this.hasWorkingChanges = false;
28
+ this.sourceSizeBySrc = new Map();
29
+ this.previewMaskBySource = new Map();
30
+ this.pendingPreviewMaskBySource = new Map();
31
+ this.isUpdatingConfig = false;
32
+ this.isToolActive = false;
33
+ this.printWithWhiteInk = true;
34
+ this.previewImageVisible = true;
35
+ this.renderSeq = 0;
36
+ this.whiteSpecs = [];
37
+ this.coverSpecs = [];
38
+ this.overlaySpecs = [];
39
+ this.onToolActivated = (event) => {
40
+ const before = this.isToolActive;
41
+ this.syncToolActiveFromWorkbench(event.id);
42
+ this.debug("tool:activated", {
43
+ id: event.id,
44
+ previous: event.previous,
45
+ before,
46
+ isToolActive: this.isToolActive,
47
+ });
48
+ this.updateWhiteInks();
49
+ };
50
+ this.onSceneLayoutChanged = () => {
51
+ this.updateWhiteInks();
52
+ };
53
+ this.onObjectAdded = (e) => {
54
+ const layerId = e?.target?.data?.layerId;
55
+ if (layerId !== IMAGE_OBJECT_LAYER_ID)
56
+ return;
57
+ this.updateWhiteInks();
58
+ };
59
+ this.onObjectModified = (e) => {
60
+ const layerId = e?.target?.data?.layerId;
61
+ if (layerId !== IMAGE_OBJECT_LAYER_ID)
62
+ return;
63
+ this.updateWhiteInks();
64
+ };
65
+ this.onObjectRemoved = (e) => {
66
+ const layerId = e?.target?.data?.layerId;
67
+ if (layerId !== IMAGE_OBJECT_LAYER_ID)
68
+ return;
69
+ this.updateWhiteInks();
70
+ };
71
+ this.onImageWorkingChanged = () => {
72
+ this.updateWhiteInks();
73
+ };
74
+ }
75
+ activate(context) {
76
+ this.context = context;
77
+ this.canvasService = context.services.get("CanvasService");
78
+ if (!this.canvasService) {
79
+ console.warn("CanvasService not found for WhiteInkTool");
80
+ return;
81
+ }
82
+ this.renderProducerDisposable?.dispose();
83
+ this.renderProducerDisposable = this.canvasService.registerRenderProducer(this.id, () => ({
84
+ passes: [
85
+ {
86
+ id: WHITE_INK_COVER_LAYER_ID,
87
+ stack: 220,
88
+ order: 0,
89
+ objects: this.coverSpecs,
90
+ },
91
+ {
92
+ id: WHITE_INK_OBJECT_LAYER_ID,
93
+ stack: 221,
94
+ order: 0,
95
+ objects: this.whiteSpecs,
96
+ },
97
+ {
98
+ id: WHITE_INK_OVERLAY_LAYER_ID,
99
+ stack: 790,
100
+ order: 0,
101
+ objects: this.overlaySpecs,
102
+ },
103
+ ],
104
+ }), { priority: 260 });
105
+ context.eventBus.on("tool:activated", this.onToolActivated);
106
+ context.eventBus.on("scene:layout:change", this.onSceneLayoutChanged);
107
+ context.eventBus.on("object:added", this.onObjectAdded);
108
+ context.eventBus.on("object:modified", this.onObjectModified);
109
+ context.eventBus.on("object:removed", this.onObjectRemoved);
110
+ context.eventBus.on("image:working:change", this.onImageWorkingChanged);
111
+ const configService = context.services.get("ConfigurationService");
112
+ if (configService) {
113
+ this.items = this.normalizeItems(configService.get("whiteInk.items", []) || []);
114
+ this.workingItems = this.cloneItems(this.items);
115
+ this.hasWorkingChanges = false;
116
+ this.printWithWhiteInk = !!configService.get("whiteInk.printWithWhiteInk", true);
117
+ this.previewImageVisible = !!configService.get(WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY, true);
118
+ this.migrateLegacyConfigIfNeeded(configService);
119
+ configService.onAnyChange((e) => {
120
+ if (this.isUpdatingConfig)
121
+ return;
122
+ if (e.key === "whiteInk.items") {
123
+ this.items = this.normalizeItems(e.value || []);
124
+ if (!this.isToolActive || !this.hasWorkingChanges) {
125
+ this.workingItems = this.cloneItems(this.items);
126
+ this.hasWorkingChanges = false;
127
+ }
128
+ this.updateWhiteInks();
129
+ return;
130
+ }
131
+ if (e.key === "whiteInk.printWithWhiteInk") {
132
+ this.printWithWhiteInk = !!e.value;
133
+ this.updateWhiteInks();
134
+ return;
135
+ }
136
+ if (e.key === WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY) {
137
+ this.previewImageVisible = !!e.value;
138
+ this.updateWhiteInks();
139
+ return;
140
+ }
141
+ if (e.key === "image.items") {
142
+ this.updateWhiteInks();
143
+ return;
144
+ }
145
+ if (e.key === WHITE_INK_DEBUG_KEY) {
146
+ return;
147
+ }
148
+ if (e.key.startsWith("size.")) {
149
+ this.updateWhiteInks();
150
+ }
151
+ });
152
+ }
153
+ const toolSessionService = context.services.get("ToolSessionService");
154
+ this.dirtyTrackerDisposable = toolSessionService?.registerDirtyTracker(this.id, () => this.hasWorkingChanges);
155
+ this.updateWhiteInks();
156
+ }
157
+ deactivate(context) {
158
+ context.eventBus.off("tool:activated", this.onToolActivated);
159
+ context.eventBus.off("scene:layout:change", this.onSceneLayoutChanged);
160
+ context.eventBus.off("object:added", this.onObjectAdded);
161
+ context.eventBus.off("object:modified", this.onObjectModified);
162
+ context.eventBus.off("object:removed", this.onObjectRemoved);
163
+ context.eventBus.off("image:working:change", this.onImageWorkingChanged);
164
+ this.dirtyTrackerDisposable?.dispose();
165
+ this.dirtyTrackerDisposable = undefined;
166
+ this.clearRenderedWhiteInks();
167
+ this.renderProducerDisposable?.dispose();
168
+ this.renderProducerDisposable = undefined;
169
+ if (this.canvasService) {
170
+ void this.canvasService.flushRenderFromProducers();
171
+ }
172
+ this.canvasService = undefined;
173
+ this.context = undefined;
174
+ }
175
+ contribute() {
176
+ return {
177
+ [core_1.ContributionPointIds.TOOLS]: [
178
+ {
179
+ id: this.id,
180
+ name: "White Ink",
181
+ interaction: "session",
182
+ commands: {
183
+ begin: "resetWorkingWhiteInks",
184
+ commit: "completeWhiteInks",
185
+ rollback: "resetWorkingWhiteInks",
186
+ },
187
+ session: {
188
+ autoBegin: true,
189
+ leavePolicy: "block",
190
+ },
191
+ },
192
+ ],
193
+ [core_1.ContributionPointIds.CONFIGURATIONS]: [
194
+ {
195
+ id: "whiteInk.items",
196
+ type: "array",
197
+ label: "White Ink Images",
198
+ default: [],
199
+ },
200
+ {
201
+ id: "whiteInk.printWithWhiteInk",
202
+ type: "boolean",
203
+ label: "Preview White Ink",
204
+ default: true,
205
+ },
206
+ {
207
+ id: WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY,
208
+ type: "boolean",
209
+ label: "Show Cover During White Ink Preview",
210
+ default: true,
211
+ },
212
+ {
213
+ id: WHITE_INK_DEBUG_KEY,
214
+ type: "boolean",
215
+ label: "White Ink Debug Log",
216
+ default: false,
217
+ },
218
+ ],
219
+ [core_1.ContributionPointIds.COMMANDS]: [
220
+ {
221
+ command: "addWhiteInk",
222
+ title: "Add White Ink",
223
+ handler: async (url, options) => {
224
+ return await this.addWhiteInkEntry(url, options);
225
+ },
226
+ },
227
+ {
228
+ command: "upsertWhiteInk",
229
+ title: "Upsert White Ink",
230
+ handler: async (url, options = {}) => {
231
+ return await this.upsertWhiteInkEntry(url, options);
232
+ },
233
+ },
234
+ {
235
+ command: "getWhiteInks",
236
+ title: "Get White Inks",
237
+ handler: () => this.cloneItems(this.items),
238
+ },
239
+ {
240
+ command: "getWhiteInkSettings",
241
+ title: "Get White Ink Settings",
242
+ handler: () => {
243
+ const first = this.getEffectiveWhiteInkItem(this.items);
244
+ const primarySource = this.getPrimaryImageSource();
245
+ const sourceUrl = this.resolveSourceUrl(first) || primarySource;
246
+ return {
247
+ id: first?.id || null,
248
+ url: sourceUrl,
249
+ sourceUrl,
250
+ opacity: WHITE_INK_DEFAULT_OPACITY,
251
+ printWithWhiteInk: this.printWithWhiteInk,
252
+ previewImageVisible: this.previewImageVisible,
253
+ };
254
+ },
255
+ },
256
+ {
257
+ command: "setWhiteInkPrintEnabled",
258
+ title: "Set White Ink Preview Enabled",
259
+ handler: (enabled) => {
260
+ this.printWithWhiteInk = !!enabled;
261
+ const configService = this.context?.services.get("ConfigurationService");
262
+ configService?.update("whiteInk.printWithWhiteInk", this.printWithWhiteInk);
263
+ this.updateWhiteInks();
264
+ return { ok: true };
265
+ },
266
+ },
267
+ {
268
+ command: "setWhiteInkPreviewImageVisible",
269
+ title: "Set White Ink Cover Visible",
270
+ handler: (visible) => {
271
+ this.previewImageVisible = !!visible;
272
+ const configService = this.context?.services.get("ConfigurationService");
273
+ configService?.update(WHITE_INK_PREVIEW_IMAGE_VISIBLE_KEY, this.previewImageVisible);
274
+ this.updateWhiteInks();
275
+ return { ok: true };
276
+ },
277
+ },
278
+ {
279
+ command: "getWorkingWhiteInks",
280
+ title: "Get Working White Inks",
281
+ handler: () => this.cloneItems(this.workingItems),
282
+ },
283
+ {
284
+ command: "setWorkingWhiteInk",
285
+ title: "Set Working White Ink",
286
+ handler: (id, updates) => {
287
+ this.updateWhiteInkInWorking(id, updates);
288
+ },
289
+ },
290
+ {
291
+ command: "updateWhiteInk",
292
+ title: "Update White Ink",
293
+ handler: async (id, updates, options = {}) => {
294
+ await this.updateWhiteInkItem(id, updates, options);
295
+ },
296
+ },
297
+ {
298
+ command: "removeWhiteInk",
299
+ title: "Remove White Ink",
300
+ handler: (id) => {
301
+ this.removeWhiteInk(id);
302
+ },
303
+ },
304
+ {
305
+ command: "clearWhiteInks",
306
+ title: "Clear White Inks",
307
+ handler: () => {
308
+ this.clearWhiteInks();
309
+ },
310
+ },
311
+ {
312
+ command: "resetWorkingWhiteInks",
313
+ title: "Reset Working White Inks",
314
+ handler: () => {
315
+ this.workingItems = this.cloneItems(this.items);
316
+ this.hasWorkingChanges = false;
317
+ this.updateWhiteInks();
318
+ },
319
+ },
320
+ {
321
+ command: "completeWhiteInks",
322
+ title: "Complete White Inks",
323
+ handler: async () => {
324
+ return await this.completeWhiteInks();
325
+ },
326
+ },
327
+ {
328
+ command: "setWhiteInkImage",
329
+ title: "Set White Ink Image",
330
+ handler: async (url) => {
331
+ if (!url) {
332
+ this.clearWhiteInks();
333
+ return { ok: true };
334
+ }
335
+ const targetId = this.resolveReplaceTargetId(null);
336
+ const upsertResult = await this.upsertWhiteInkEntry(url, {
337
+ id: targetId || undefined,
338
+ mode: targetId ? "replace" : "add",
339
+ createIfMissing: true,
340
+ addOptions: {},
341
+ });
342
+ return { ok: true, id: upsertResult.id };
343
+ },
344
+ },
345
+ ],
346
+ };
347
+ }
348
+ migrateLegacyConfigIfNeeded(configService) {
349
+ if (this.items.length > 0)
350
+ return;
351
+ const legacyMask = configService.get("whiteInk.customMask", "");
352
+ if (typeof legacyMask !== "string" || legacyMask.length === 0)
353
+ return;
354
+ const item = this.normalizeItem({
355
+ id: this.generateId(),
356
+ sourceUrl: legacyMask,
357
+ opacity: WHITE_INK_DEFAULT_OPACITY,
358
+ });
359
+ this.items = [item];
360
+ this.workingItems = this.cloneItems(this.items);
361
+ this.isUpdatingConfig = true;
362
+ configService.update("whiteInk.items", this.items);
363
+ setTimeout(() => {
364
+ this.isUpdatingConfig = false;
365
+ }, 0);
366
+ }
367
+ syncToolActiveFromWorkbench(fallbackId) {
368
+ const wb = this.context?.services.get("WorkbenchService");
369
+ const activeId = wb?.activeToolId;
370
+ if (typeof activeId === "string" || activeId === null) {
371
+ this.isToolActive = activeId === this.id;
372
+ return;
373
+ }
374
+ this.isToolActive = fallbackId === this.id;
375
+ }
376
+ isPreviewActive() {
377
+ return this.isToolActive && this.printWithWhiteInk;
378
+ }
379
+ isDebugEnabled() {
380
+ return !!this.getConfig(WHITE_INK_DEBUG_KEY, false);
381
+ }
382
+ debug(message, payload) {
383
+ if (!this.isDebugEnabled())
384
+ return;
385
+ if (payload === undefined) {
386
+ console.log(`[WhiteInkTool] ${message}`);
387
+ return;
388
+ }
389
+ console.log(`[WhiteInkTool] ${message}`, payload);
390
+ }
391
+ resolveSourceUrl(item) {
392
+ if (!item)
393
+ return "";
394
+ if (typeof item.sourceUrl === "string" && item.sourceUrl.length > 0) {
395
+ return item.sourceUrl;
396
+ }
397
+ if (typeof item.url === "string" && item.url.length > 0) {
398
+ return item.url;
399
+ }
400
+ return "";
401
+ }
402
+ normalizeItem(item) {
403
+ const sourceUrl = this.resolveSourceUrl(item);
404
+ return {
405
+ id: String(item.id || this.generateId()),
406
+ sourceUrl,
407
+ url: sourceUrl,
408
+ opacity: WHITE_INK_DEFAULT_OPACITY,
409
+ };
410
+ }
411
+ normalizeItems(items) {
412
+ return (items || [])
413
+ .map((item) => this.normalizeItem(item))
414
+ .filter((item) => !!item.id);
415
+ }
416
+ cloneItems(items) {
417
+ return this.normalizeItems((items || []).map((item) => ({ ...item })));
418
+ }
419
+ getEffectiveWhiteInkItem(items) {
420
+ const normalized = this.cloneItems(items || []);
421
+ if (normalized.length > 0) {
422
+ return normalized[0];
423
+ }
424
+ if (!this.getPrimaryImageSource()) {
425
+ return null;
426
+ }
427
+ return {
428
+ id: WHITE_INK_AUTO_ITEM_ID,
429
+ opacity: WHITE_INK_DEFAULT_OPACITY,
430
+ };
431
+ }
432
+ generateId() {
433
+ return `white-ink-${Math.random().toString(36).slice(2, 9)}`;
434
+ }
435
+ getConfig(key, fallback) {
436
+ if (!this.context)
437
+ return fallback;
438
+ const configService = this.context.services.get("ConfigurationService");
439
+ if (!configService)
440
+ return fallback;
441
+ return configService.get(key, fallback) ?? fallback;
442
+ }
443
+ resolveReplaceTargetId(explicitId) {
444
+ const has = (id) => !!id && this.items.some((item) => item.id === id);
445
+ if (has(explicitId))
446
+ return explicitId;
447
+ if (this.items.length >= 1) {
448
+ return this.items[0].id;
449
+ }
450
+ return null;
451
+ }
452
+ updateConfig(newItems, skipCanvasUpdate = false) {
453
+ if (!this.context)
454
+ return;
455
+ this.isUpdatingConfig = true;
456
+ this.items = this.normalizeItems(newItems);
457
+ if (!this.isToolActive || !this.hasWorkingChanges) {
458
+ this.workingItems = this.cloneItems(this.items);
459
+ this.hasWorkingChanges = false;
460
+ }
461
+ const configService = this.context.services.get("ConfigurationService");
462
+ configService?.update("whiteInk.items", this.items);
463
+ if (!skipCanvasUpdate) {
464
+ this.updateWhiteInks();
465
+ }
466
+ setTimeout(() => {
467
+ this.isUpdatingConfig = false;
468
+ }, 50);
469
+ }
470
+ async addWhiteInkEntry(url, options) {
471
+ const id = this.generateId();
472
+ const item = this.normalizeItem({
473
+ id,
474
+ sourceUrl: url,
475
+ opacity: WHITE_INK_DEFAULT_OPACITY,
476
+ ...options,
477
+ });
478
+ const sessionDirtyBeforeAdd = this.isToolActive && this.hasWorkingChanges;
479
+ this.updateConfig([...this.items, item]);
480
+ this.addItemToWorkingSessionIfNeeded(item, sessionDirtyBeforeAdd);
481
+ return id;
482
+ }
483
+ async upsertWhiteInkEntry(url, options = {}) {
484
+ const mode = options.mode || "auto";
485
+ if (mode === "add") {
486
+ const id = await this.addWhiteInkEntry(url, options.addOptions);
487
+ return { id, mode: "add" };
488
+ }
489
+ const targetId = this.resolveReplaceTargetId(options.id ?? null);
490
+ if (targetId) {
491
+ this.updateWhiteInkInConfig(targetId, {
492
+ ...(options.addOptions || {}),
493
+ sourceUrl: url,
494
+ url,
495
+ });
496
+ return { id: targetId, mode: "replace" };
497
+ }
498
+ if (mode === "replace" || options.createIfMissing === false) {
499
+ throw new Error("replace-target-not-found");
500
+ }
501
+ const id = await this.addWhiteInkEntry(url, options.addOptions);
502
+ return { id, mode: "add" };
503
+ }
504
+ addItemToWorkingSessionIfNeeded(item, sessionDirtyBeforeAdd) {
505
+ if (!sessionDirtyBeforeAdd || !this.isToolActive)
506
+ return;
507
+ if (this.workingItems.some((existing) => existing.id === item.id))
508
+ return;
509
+ this.workingItems = this.cloneItems([...this.workingItems, item]);
510
+ this.updateWhiteInks();
511
+ }
512
+ async updateWhiteInkItem(id, updates, options = {}) {
513
+ this.syncToolActiveFromWorkbench();
514
+ const target = options.target || "auto";
515
+ if (target === "working" || (target === "auto" && this.isToolActive)) {
516
+ this.updateWhiteInkInWorking(id, updates);
517
+ return;
518
+ }
519
+ this.updateWhiteInkInConfig(id, updates);
520
+ }
521
+ updateWhiteInkInWorking(id, updates) {
522
+ let changed = false;
523
+ const next = this.workingItems.map((item) => {
524
+ if (item.id !== id)
525
+ return item;
526
+ changed = true;
527
+ return this.normalizeItem({
528
+ ...item,
529
+ ...updates,
530
+ });
531
+ });
532
+ if (!changed)
533
+ return;
534
+ this.workingItems = this.cloneItems(next);
535
+ this.hasWorkingChanges = true;
536
+ this.updateWhiteInks();
537
+ }
538
+ updateWhiteInkInConfig(id, updates) {
539
+ let changed = false;
540
+ const next = this.items.map((item) => {
541
+ if (item.id !== id)
542
+ return item;
543
+ changed = true;
544
+ const merged = this.normalizeItem({
545
+ ...item,
546
+ ...updates,
547
+ });
548
+ if (this.resolveSourceUrl(item) !== this.resolveSourceUrl(merged)) {
549
+ this.purgeSourceCaches(item);
550
+ }
551
+ return merged;
552
+ });
553
+ if (!changed)
554
+ return;
555
+ this.updateConfig(next);
556
+ }
557
+ removeWhiteInk(id) {
558
+ const removed = this.items.find((item) => item.id === id);
559
+ const next = this.items.filter((item) => item.id !== id);
560
+ if (next.length === this.items.length)
561
+ return;
562
+ this.purgeSourceCaches(removed);
563
+ this.updateConfig(next);
564
+ }
565
+ clearWhiteInks() {
566
+ this.sourceSizeBySrc.clear();
567
+ this.previewMaskBySource.clear();
568
+ this.pendingPreviewMaskBySource.clear();
569
+ this.updateConfig([]);
570
+ }
571
+ async completeWhiteInks() {
572
+ this.updateConfig(this.cloneItems(this.workingItems));
573
+ this.hasWorkingChanges = false;
574
+ return { ok: true };
575
+ }
576
+ getFrameRect() {
577
+ if (!this.canvasService) {
578
+ return { left: 0, top: 0, width: 0, height: 0 };
579
+ }
580
+ const configService = this.context?.services.get("ConfigurationService");
581
+ if (!configService) {
582
+ return { left: 0, top: 0, width: 0, height: 0 };
583
+ }
584
+ const sizeState = (0, sceneLayoutModel_1.readSizeState)(configService);
585
+ const layout = (0, sceneLayoutModel_1.computeSceneLayout)(this.canvasService, sizeState);
586
+ if (!layout) {
587
+ return { left: 0, top: 0, width: 0, height: 0 };
588
+ }
589
+ return this.canvasService.toSceneRect({
590
+ left: layout.cutRect.left,
591
+ top: layout.cutRect.top,
592
+ width: layout.cutRect.width,
593
+ height: layout.cutRect.height,
594
+ });
595
+ }
596
+ toLayoutSceneRect(rect) {
597
+ return {
598
+ left: rect.left,
599
+ top: rect.top,
600
+ width: rect.width,
601
+ height: rect.height,
602
+ space: "scene",
603
+ };
604
+ }
605
+ getImageObjects() {
606
+ if (!this.canvasService)
607
+ return [];
608
+ return this.canvasService.canvas.getObjects().filter((obj) => {
609
+ return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
610
+ });
611
+ }
612
+ getPrimaryImageObject() {
613
+ return this.getImageObjects()[0];
614
+ }
615
+ getPrimaryImageSource() {
616
+ return this.getCurrentSrc(this.getPrimaryImageObject()) || "";
617
+ }
618
+ getCurrentSrc(obj) {
619
+ if (!obj)
620
+ return undefined;
621
+ if (typeof obj.getSrc === "function")
622
+ return obj.getSrc();
623
+ return obj?._originalElement?.src;
624
+ }
625
+ getImageSnapshot(obj) {
626
+ if (!obj)
627
+ return null;
628
+ const src = this.getCurrentSrc(obj);
629
+ if (!src)
630
+ return null;
631
+ const element = this.getImageElementFromObject(obj);
632
+ const width = Number(obj?.width || 0);
633
+ const height = Number(obj?.height || 0);
634
+ this.rememberSourceSize(src, { width, height });
635
+ const sceneScale = this.canvasService?.getSceneScale() || 1;
636
+ const leftScreen = Number.isFinite(obj?.left) ? Number(obj.left) : 0;
637
+ const topScreen = Number.isFinite(obj?.top) ? Number(obj.top) : 0;
638
+ const scenePoint = this.canvasService
639
+ ? this.canvasService.toScenePoint({ x: leftScreen, y: topScreen })
640
+ : { x: leftScreen, y: topScreen };
641
+ return {
642
+ id: String(obj?.data?.id || "image"),
643
+ src,
644
+ element,
645
+ left: scenePoint.x,
646
+ top: scenePoint.y,
647
+ scaleX: (Number.isFinite(obj?.scaleX) ? Number(obj.scaleX) : 1) / sceneScale,
648
+ scaleY: (Number.isFinite(obj?.scaleY) ? Number(obj.scaleY) : 1) / sceneScale,
649
+ angle: Number.isFinite(obj?.angle) ? Number(obj.angle) : 0,
650
+ originX: typeof obj?.originX === "string" ? obj.originX : "center",
651
+ originY: typeof obj?.originY === "string" ? obj.originY : "center",
652
+ flipX: !!obj?.flipX,
653
+ flipY: !!obj?.flipY,
654
+ skewX: Number.isFinite(obj?.skewX) ? Number(obj.skewX) : 0,
655
+ skewY: Number.isFinite(obj?.skewY) ? Number(obj.skewY) : 0,
656
+ width,
657
+ height,
658
+ };
659
+ }
660
+ getImagePlacementState(id) {
661
+ const rawItems = this.getConfig("image.items", []);
662
+ if (!Array.isArray(rawItems) || rawItems.length === 0)
663
+ return null;
664
+ const matched = (id
665
+ ? rawItems.find((item) => item &&
666
+ typeof item === "object" &&
667
+ typeof item.id === "string" &&
668
+ item.id === id)
669
+ : undefined) || rawItems[0];
670
+ if (!matched || typeof matched !== "object")
671
+ return null;
672
+ const sourceUrl = typeof matched.sourceUrl === "string" && matched.sourceUrl.length > 0
673
+ ? matched.sourceUrl
674
+ : typeof matched.url === "string"
675
+ ? matched.url
676
+ : "";
677
+ const committedUrl = typeof matched.committedUrl === "string" ? matched.committedUrl : "";
678
+ return {
679
+ id: typeof matched.id === "string" && matched.id.length > 0
680
+ ? matched.id
681
+ : id || "image",
682
+ sourceUrl,
683
+ committedUrl,
684
+ left: Number.isFinite(matched.left) ? Number(matched.left) : 0.5,
685
+ top: Number.isFinite(matched.top) ? Number(matched.top) : 0.5,
686
+ scale: Number.isFinite(matched.scale) ? Math.max(0.05, matched.scale) : 1,
687
+ angle: Number.isFinite(matched.angle) ? matched.angle : 0,
688
+ };
689
+ }
690
+ shouldRestoreSnapshotToSource(snapshot, placement) {
691
+ if (!placement.sourceUrl || !placement.committedUrl)
692
+ return false;
693
+ if (placement.sourceUrl === placement.committedUrl)
694
+ return false;
695
+ return snapshot.src === placement.committedUrl;
696
+ }
697
+ getCoverScale(frame, source) {
698
+ const frameW = Math.max(1, frame.width);
699
+ const frameH = Math.max(1, frame.height);
700
+ const sourceW = Math.max(1, source.width);
701
+ const sourceH = Math.max(1, source.height);
702
+ return Math.max(frameW / sourceW, frameH / sourceH);
703
+ }
704
+ async ensureSourceSize(sourceUrl) {
705
+ if (!sourceUrl)
706
+ return null;
707
+ const cached = this.getSourceSize(sourceUrl);
708
+ if (cached)
709
+ return cached;
710
+ try {
711
+ const image = await this.loadImageElement(sourceUrl);
712
+ const size = this.getElementSize(image);
713
+ if (!size)
714
+ return null;
715
+ this.rememberSourceSize(sourceUrl, size);
716
+ return {
717
+ width: size.width,
718
+ height: size.height,
719
+ };
720
+ }
721
+ catch {
722
+ return null;
723
+ }
724
+ }
725
+ async resolveAlignedImageSnapshot(snapshot) {
726
+ const placement = this.getImagePlacementState(snapshot.id);
727
+ if (!placement)
728
+ return snapshot;
729
+ if (!this.shouldRestoreSnapshotToSource(snapshot, placement)) {
730
+ return snapshot;
731
+ }
732
+ const frame = this.getFrameRect();
733
+ if (frame.width <= 0 || frame.height <= 0) {
734
+ return snapshot;
735
+ }
736
+ const sourceSize = await this.ensureSourceSize(placement.sourceUrl);
737
+ if (!sourceSize)
738
+ return snapshot;
739
+ const coverScale = this.getCoverScale(frame, sourceSize);
740
+ return {
741
+ ...snapshot,
742
+ src: placement.sourceUrl,
743
+ element: undefined,
744
+ left: frame.left + placement.left * frame.width,
745
+ top: frame.top + placement.top * frame.height,
746
+ scaleX: coverScale * placement.scale,
747
+ scaleY: coverScale * placement.scale,
748
+ angle: placement.angle,
749
+ originX: "center",
750
+ originY: "center",
751
+ width: sourceSize.width,
752
+ height: sourceSize.height,
753
+ };
754
+ }
755
+ getImageElementFromObject(obj) {
756
+ if (!obj)
757
+ return null;
758
+ if (typeof obj.getElement === "function") {
759
+ return obj.getElement();
760
+ }
761
+ return obj?._element || obj?._originalElement || null;
762
+ }
763
+ rememberSourceSize(src, size) {
764
+ if (!src)
765
+ return;
766
+ if (!Number.isFinite(size.width) || !Number.isFinite(size.height))
767
+ return;
768
+ if (size.width <= 0 || size.height <= 0)
769
+ return;
770
+ this.sourceSizeBySrc.set(src, {
771
+ width: size.width,
772
+ height: size.height,
773
+ });
774
+ }
775
+ getSourceSize(src) {
776
+ if (!src)
777
+ return null;
778
+ const cached = this.sourceSizeBySrc.get(src);
779
+ if (!cached)
780
+ return null;
781
+ return {
782
+ width: cached.width,
783
+ height: cached.height,
784
+ };
785
+ }
786
+ computeWhiteScaleAdjust(baseSource, whiteSource) {
787
+ if (!baseSource || !whiteSource || baseSource === whiteSource) {
788
+ return { x: 1, y: 1 };
789
+ }
790
+ const baseSize = this.getSourceSize(baseSource);
791
+ const whiteSize = this.getSourceSize(whiteSource);
792
+ if (!baseSize || !whiteSize) {
793
+ return { x: 1, y: 1 };
794
+ }
795
+ if (whiteSize.width <= 0 || whiteSize.height <= 0) {
796
+ return { x: 1, y: 1 };
797
+ }
798
+ return {
799
+ x: baseSize.width / whiteSize.width,
800
+ y: baseSize.height / whiteSize.height,
801
+ };
802
+ }
803
+ computeCoverOpacity() {
804
+ const raw = WHITE_INK_DEFAULT_OPACITY * WHITE_INK_COVER_OPACITY_FACTOR;
805
+ return Math.max(WHITE_INK_COVER_OPACITY_MIN, Math.min(WHITE_INK_COVER_OPACITY_MAX, raw));
806
+ }
807
+ buildCloneImageSpec(id, snapshot, src, opacity, layerId, type, scaleAdjustX = 1, scaleAdjustY = 1) {
808
+ return {
809
+ id,
810
+ type: "image",
811
+ src,
812
+ data: {
813
+ id,
814
+ layerId,
815
+ type,
816
+ imageId: snapshot.id,
817
+ },
818
+ props: {
819
+ left: snapshot.left,
820
+ top: snapshot.top,
821
+ originX: snapshot.originX,
822
+ originY: snapshot.originY,
823
+ angle: snapshot.angle,
824
+ scaleX: snapshot.scaleX * scaleAdjustX,
825
+ scaleY: snapshot.scaleY * scaleAdjustY,
826
+ flipX: snapshot.flipX,
827
+ flipY: snapshot.flipY,
828
+ skewX: snapshot.skewX,
829
+ skewY: snapshot.skewY,
830
+ selectable: false,
831
+ evented: false,
832
+ hasControls: false,
833
+ hasBorders: false,
834
+ uniformScaling: true,
835
+ lockScalingFlip: true,
836
+ opacity: Math.max(0, Math.min(1, Number(opacity))),
837
+ excludeFromExport: true,
838
+ },
839
+ };
840
+ }
841
+ buildFrameSpecs(frame) {
842
+ if (!this.isToolActive || !this.canvasService)
843
+ return [];
844
+ if (frame.width <= 0 || frame.height <= 0)
845
+ return [];
846
+ const viewport = this.canvasService.getSceneViewportRect();
847
+ const canvasW = viewport.width || 0;
848
+ const canvasH = viewport.height || 0;
849
+ const canvasLeft = viewport.left || 0;
850
+ const canvasTop = viewport.top || 0;
851
+ const strokeColor = this.getConfig("image.frame.strokeColor", "#808080") || "#808080";
852
+ const strokeWidthRaw = Number(this.getConfig("image.frame.strokeWidth", 2) ?? 2);
853
+ const dashLengthRaw = Number(this.getConfig("image.frame.dashLength", 8) ?? 8);
854
+ const outerBackground = this.getConfig("image.frame.outerBackground", "#f5f5f5") ||
855
+ "#f5f5f5";
856
+ const innerBackground = this.getConfig("image.frame.innerBackground", "rgba(0,0,0,0)") ||
857
+ "rgba(0,0,0,0)";
858
+ const strokeWidth = Number.isFinite(strokeWidthRaw)
859
+ ? Math.max(0, strokeWidthRaw)
860
+ : 2;
861
+ const dashLength = Number.isFinite(dashLengthRaw)
862
+ ? Math.max(1, dashLengthRaw)
863
+ : 8;
864
+ const strokeWidthScene = this.canvasService.toSceneLength(strokeWidth);
865
+ const dashLengthScene = this.canvasService.toSceneLength(dashLength);
866
+ const frameLeft = Math.max(canvasLeft, Math.min(canvasLeft + canvasW, frame.left));
867
+ const frameTop = Math.max(canvasTop, Math.min(canvasTop + canvasH, frame.top));
868
+ const frameRight = Math.max(frameLeft, Math.min(canvasLeft + canvasW, frame.left + frame.width));
869
+ const frameBottom = Math.max(frameTop, Math.min(canvasTop + canvasH, frame.top + frame.height));
870
+ const visibleFrameH = Math.max(0, frameBottom - frameTop);
871
+ const topH = Math.max(0, frameTop - canvasTop);
872
+ const bottomH = Math.max(0, canvasTop + canvasH - frameBottom);
873
+ const leftW = Math.max(0, frameLeft - canvasLeft);
874
+ const rightW = Math.max(0, canvasLeft + canvasW - frameRight);
875
+ const viewportRect = this.toLayoutSceneRect({
876
+ left: canvasLeft,
877
+ top: canvasTop,
878
+ width: canvasW,
879
+ height: canvasH,
880
+ });
881
+ const visibleFrameBandRect = this.toLayoutSceneRect({
882
+ left: canvasLeft,
883
+ top: frameTop,
884
+ width: canvasW,
885
+ height: visibleFrameH,
886
+ });
887
+ const frameRect = this.toLayoutSceneRect(frame);
888
+ const maskSpecs = [
889
+ {
890
+ id: "white-ink.cropMask.top",
891
+ type: "rect",
892
+ data: {
893
+ id: "white-ink.cropMask.top",
894
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
895
+ type: "white-ink-mask",
896
+ },
897
+ layout: {
898
+ reference: "custom",
899
+ referenceRect: viewportRect,
900
+ alignX: "start",
901
+ alignY: "start",
902
+ width: "100%",
903
+ height: topH,
904
+ },
905
+ props: {
906
+ originX: "left",
907
+ originY: "top",
908
+ fill: outerBackground,
909
+ selectable: false,
910
+ evented: false,
911
+ excludeFromExport: true,
912
+ },
913
+ },
914
+ {
915
+ id: "white-ink.cropMask.bottom",
916
+ type: "rect",
917
+ data: {
918
+ id: "white-ink.cropMask.bottom",
919
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
920
+ type: "white-ink-mask",
921
+ },
922
+ layout: {
923
+ reference: "custom",
924
+ referenceRect: viewportRect,
925
+ alignX: "start",
926
+ alignY: "end",
927
+ width: "100%",
928
+ height: bottomH,
929
+ },
930
+ props: {
931
+ originX: "left",
932
+ originY: "top",
933
+ fill: outerBackground,
934
+ selectable: false,
935
+ evented: false,
936
+ excludeFromExport: true,
937
+ },
938
+ },
939
+ {
940
+ id: "white-ink.cropMask.left",
941
+ type: "rect",
942
+ data: {
943
+ id: "white-ink.cropMask.left",
944
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
945
+ type: "white-ink-mask",
946
+ },
947
+ layout: {
948
+ reference: "custom",
949
+ referenceRect: visibleFrameBandRect,
950
+ alignX: "start",
951
+ alignY: "start",
952
+ width: leftW,
953
+ height: "100%",
954
+ },
955
+ props: {
956
+ originX: "left",
957
+ originY: "top",
958
+ fill: outerBackground,
959
+ selectable: false,
960
+ evented: false,
961
+ excludeFromExport: true,
962
+ },
963
+ },
964
+ {
965
+ id: "white-ink.cropMask.right",
966
+ type: "rect",
967
+ data: {
968
+ id: "white-ink.cropMask.right",
969
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
970
+ type: "white-ink-mask",
971
+ },
972
+ layout: {
973
+ reference: "custom",
974
+ referenceRect: visibleFrameBandRect,
975
+ alignX: "end",
976
+ alignY: "start",
977
+ width: rightW,
978
+ height: "100%",
979
+ },
980
+ props: {
981
+ originX: "left",
982
+ originY: "top",
983
+ fill: outerBackground,
984
+ selectable: false,
985
+ evented: false,
986
+ excludeFromExport: true,
987
+ },
988
+ },
989
+ ];
990
+ return [
991
+ ...maskSpecs,
992
+ {
993
+ id: "white-ink.cropFrame",
994
+ type: "rect",
995
+ data: {
996
+ id: "white-ink.cropFrame",
997
+ layerId: WHITE_INK_OVERLAY_LAYER_ID,
998
+ type: "white-ink-frame",
999
+ },
1000
+ layout: {
1001
+ reference: "custom",
1002
+ referenceRect: frameRect,
1003
+ alignX: "start",
1004
+ alignY: "start",
1005
+ width: "100%",
1006
+ height: "100%",
1007
+ },
1008
+ props: {
1009
+ originX: "left",
1010
+ originY: "top",
1011
+ fill: innerBackground,
1012
+ stroke: strokeColor,
1013
+ strokeWidth: strokeWidthScene,
1014
+ strokeDashArray: [dashLengthScene, dashLengthScene],
1015
+ selectable: false,
1016
+ evented: false,
1017
+ excludeFromExport: true,
1018
+ },
1019
+ },
1020
+ ];
1021
+ }
1022
+ resolveRenderItems() {
1023
+ if (this.isToolActive) {
1024
+ return this.cloneItems(this.workingItems);
1025
+ }
1026
+ return this.cloneItems(this.items);
1027
+ }
1028
+ async resolveRenderSources(snapshot, item) {
1029
+ const imageSource = snapshot.src;
1030
+ if (!imageSource)
1031
+ return null;
1032
+ const whiteSource = this.resolveSourceUrl(item) || imageSource;
1033
+ const imageElement = snapshot.element;
1034
+ const whiteElement = whiteSource === imageSource ? imageElement : undefined;
1035
+ const [whiteMaskSrc, coverMaskSrc] = await Promise.all([
1036
+ this.getPreviewMaskSource(whiteSource, WHITE_MASK_TINT, whiteElement),
1037
+ this.getPreviewMaskSource(imageSource, COVER_MASK_TINT, imageElement),
1038
+ ]);
1039
+ const scaleAdjust = this.computeWhiteScaleAdjust(imageSource, whiteSource);
1040
+ return {
1041
+ whiteSrc: whiteMaskSrc || "",
1042
+ coverSrc: coverMaskSrc || "",
1043
+ whiteScaleAdjustX: scaleAdjust.x,
1044
+ whiteScaleAdjustY: scaleAdjust.y,
1045
+ };
1046
+ }
1047
+ clearRenderedWhiteInks() {
1048
+ if (!this.canvasService)
1049
+ return;
1050
+ this.whiteSpecs = [];
1051
+ this.coverSpecs = [];
1052
+ this.overlaySpecs = [];
1053
+ this.canvasService.requestRenderFromProducers();
1054
+ }
1055
+ purgeSourceCaches(item) {
1056
+ const sourceUrl = this.resolveSourceUrl(item);
1057
+ if (!sourceUrl)
1058
+ return;
1059
+ this.sourceSizeBySrc.delete(sourceUrl);
1060
+ const prefix = `${sourceUrl}::`;
1061
+ Array.from(this.previewMaskBySource.keys()).forEach((cacheKey) => {
1062
+ if (cacheKey.startsWith(prefix)) {
1063
+ this.previewMaskBySource.delete(cacheKey);
1064
+ }
1065
+ });
1066
+ Array.from(this.pendingPreviewMaskBySource.keys()).forEach((cacheKey) => {
1067
+ if (cacheKey.startsWith(prefix)) {
1068
+ this.pendingPreviewMaskBySource.delete(cacheKey);
1069
+ }
1070
+ });
1071
+ }
1072
+ updateWhiteInks() {
1073
+ void this.updateWhiteInksAsync();
1074
+ }
1075
+ async updateWhiteInksAsync() {
1076
+ if (!this.canvasService)
1077
+ return;
1078
+ this.syncToolActiveFromWorkbench();
1079
+ const seq = ++this.renderSeq;
1080
+ const previewActive = this.isPreviewActive();
1081
+ const frame = this.getFrameRect();
1082
+ const frameSpecs = this.buildFrameSpecs(frame);
1083
+ let whiteSpecs = [];
1084
+ let coverSpecs = [];
1085
+ if (previewActive) {
1086
+ const baseSnapshot = this.getImageSnapshot(this.getPrimaryImageObject());
1087
+ const item = this.getEffectiveWhiteInkItem(this.resolveRenderItems());
1088
+ if (baseSnapshot && item) {
1089
+ const snapshot = await this.resolveAlignedImageSnapshot(baseSnapshot);
1090
+ if (seq !== this.renderSeq)
1091
+ return;
1092
+ const sources = await this.resolveRenderSources(snapshot, item);
1093
+ if (seq !== this.renderSeq)
1094
+ return;
1095
+ if (sources?.whiteSrc) {
1096
+ whiteSpecs = [
1097
+ this.buildCloneImageSpec("white-ink.main", snapshot, sources.whiteSrc, WHITE_INK_DEFAULT_OPACITY, WHITE_INK_OBJECT_LAYER_ID, "white-ink", sources.whiteScaleAdjustX, sources.whiteScaleAdjustY),
1098
+ ];
1099
+ }
1100
+ if (this.previewImageVisible && sources?.coverSrc) {
1101
+ coverSpecs = [
1102
+ this.buildCloneImageSpec("white-ink.cover", snapshot, sources.coverSrc, this.computeCoverOpacity(), WHITE_INK_COVER_LAYER_ID, "white-ink-cover"),
1103
+ ];
1104
+ }
1105
+ }
1106
+ }
1107
+ this.whiteSpecs = whiteSpecs;
1108
+ if (seq !== this.renderSeq)
1109
+ return;
1110
+ this.coverSpecs = coverSpecs;
1111
+ if (seq !== this.renderSeq)
1112
+ return;
1113
+ this.overlaySpecs = frameSpecs;
1114
+ await this.canvasService.flushRenderFromProducers();
1115
+ if (seq !== this.renderSeq)
1116
+ return;
1117
+ this.canvasService.requestRenderAll();
1118
+ }
1119
+ getMaskCacheKey(sourceUrl, tint) {
1120
+ return `${sourceUrl}::${tint.key}`;
1121
+ }
1122
+ async getPreviewMaskSource(sourceUrl, tint = WHITE_MASK_TINT, fallbackElement) {
1123
+ if (!sourceUrl)
1124
+ return "";
1125
+ if (typeof document === "undefined" || typeof Image === "undefined") {
1126
+ return "";
1127
+ }
1128
+ const cacheKey = this.getMaskCacheKey(sourceUrl, tint);
1129
+ const cached = this.previewMaskBySource.get(cacheKey);
1130
+ if (cached)
1131
+ return cached;
1132
+ const pending = this.pendingPreviewMaskBySource.get(cacheKey);
1133
+ if (pending) {
1134
+ const loaded = await pending;
1135
+ return loaded || "";
1136
+ }
1137
+ const task = this.createOpaqueMaskSource(sourceUrl, tint, fallbackElement);
1138
+ this.pendingPreviewMaskBySource.set(cacheKey, task);
1139
+ const loaded = await task;
1140
+ this.pendingPreviewMaskBySource.delete(cacheKey);
1141
+ if (!loaded)
1142
+ return "";
1143
+ this.previewMaskBySource.set(cacheKey, loaded);
1144
+ return loaded;
1145
+ }
1146
+ getElementSize(element) {
1147
+ if (!element)
1148
+ return null;
1149
+ const width = Number(element?.naturalWidth || element?.videoWidth || element?.width || 0);
1150
+ const height = Number(element?.naturalHeight || element?.videoHeight || element?.height || 0);
1151
+ if (!Number.isFinite(width) || !Number.isFinite(height))
1152
+ return null;
1153
+ if (width <= 0 || height <= 0)
1154
+ return null;
1155
+ return { width, height };
1156
+ }
1157
+ async createOpaqueMaskSource(sourceUrl, tint = WHITE_MASK_TINT, fallbackElement) {
1158
+ try {
1159
+ const element = fallbackElement || (await this.loadImageElement(sourceUrl));
1160
+ const size = this.getElementSize(element);
1161
+ if (!size)
1162
+ return null;
1163
+ const width = Math.max(1, size.width);
1164
+ const height = Math.max(1, size.height);
1165
+ this.rememberSourceSize(sourceUrl, { width, height });
1166
+ const canvas = document.createElement("canvas");
1167
+ canvas.width = width;
1168
+ canvas.height = height;
1169
+ const ctx = canvas.getContext("2d");
1170
+ if (!ctx)
1171
+ return null;
1172
+ ctx.drawImage(element, 0, 0, width, height);
1173
+ const imageData = ctx.getImageData(0, 0, width, height);
1174
+ const data = imageData.data;
1175
+ for (let i = 0; i < data.length; i += 4) {
1176
+ const alpha = data[i + 3];
1177
+ data[i] = tint.r;
1178
+ data[i + 1] = tint.g;
1179
+ data[i + 2] = tint.b;
1180
+ data[i + 3] = alpha;
1181
+ }
1182
+ ctx.putImageData(imageData, 0, 0);
1183
+ return canvas.toDataURL("image/png");
1184
+ }
1185
+ catch (error) {
1186
+ this.debug("mask:extract:failed", { sourceUrl, tint: tint.key, error });
1187
+ return null;
1188
+ }
1189
+ }
1190
+ loadImageElement(sourceUrl) {
1191
+ return new Promise((resolve, reject) => {
1192
+ const image = new Image();
1193
+ image.crossOrigin = "anonymous";
1194
+ image.onload = () => resolve(image);
1195
+ image.onerror = () => reject(new Error("white-ink-image-load-failed"));
1196
+ image.src = sourceUrl;
1197
+ });
1198
+ }
1199
+ }
1200
+ exports.WhiteInkTool = WhiteInkTool;