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