@pooder/kit 5.3.1 → 5.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.d.mts +243 -36
  3. package/dist/index.d.ts +243 -36
  4. package/dist/index.js +2278 -1041
  5. package/dist/index.mjs +2278 -1041
  6. package/package.json +1 -1
  7. package/src/coordinate.ts +106 -106
  8. package/src/extensions/background.ts +323 -230
  9. package/src/extensions/bridgeSelection.ts +17 -17
  10. package/src/extensions/constraints.ts +322 -322
  11. package/src/extensions/dieline.ts +1149 -1076
  12. package/src/extensions/dielineShape.ts +109 -0
  13. package/src/extensions/edgeScale.ts +19 -19
  14. package/src/extensions/feature.ts +1137 -1021
  15. package/src/extensions/featureComplete.ts +46 -46
  16. package/src/extensions/film.ts +266 -194
  17. package/src/extensions/geometry.ts +885 -752
  18. package/src/extensions/image.ts +2054 -1926
  19. package/src/extensions/index.ts +11 -11
  20. package/src/extensions/maskOps.ts +283 -283
  21. package/src/extensions/mirror.ts +128 -128
  22. package/src/extensions/ruler.ts +654 -451
  23. package/src/extensions/sceneLayout.ts +140 -140
  24. package/src/extensions/sceneLayoutModel.ts +364 -352
  25. package/src/extensions/sceneVisibility.ts +64 -71
  26. package/src/extensions/size.ts +389 -389
  27. package/src/extensions/tracer.ts +1019 -1019
  28. package/src/extensions/white-ink.ts +1567 -1514
  29. package/src/extensions/wrappedOffsets.ts +33 -33
  30. package/src/index.ts +2 -2
  31. package/src/services/CanvasService.ts +832 -300
  32. package/src/services/ViewportSystem.ts +95 -95
  33. package/src/services/index.ts +3 -3
  34. package/src/services/renderSpec.ts +53 -18
  35. package/src/units.ts +27 -27
  36. package/tests/run.ts +118 -118
  37. package/tsconfig.test.json +15 -15
  38. package/.test-dist/src/CanvasService.js +0 -249
  39. package/.test-dist/src/ViewportSystem.js +0 -75
  40. package/.test-dist/src/background.js +0 -203
  41. package/.test-dist/src/bridgeSelection.js +0 -20
  42. package/.test-dist/src/constraints.js +0 -237
  43. package/.test-dist/src/coordinate.js +0 -74
  44. package/.test-dist/src/dieline.js +0 -818
  45. package/.test-dist/src/edgeScale.js +0 -12
  46. package/.test-dist/src/extensions/background.js +0 -203
  47. package/.test-dist/src/extensions/bridgeSelection.js +0 -20
  48. package/.test-dist/src/extensions/constraints.js +0 -237
  49. package/.test-dist/src/extensions/dieline.js +0 -828
  50. package/.test-dist/src/extensions/edgeScale.js +0 -12
  51. package/.test-dist/src/extensions/feature.js +0 -825
  52. package/.test-dist/src/extensions/featureComplete.js +0 -32
  53. package/.test-dist/src/extensions/film.js +0 -167
  54. package/.test-dist/src/extensions/geometry.js +0 -545
  55. package/.test-dist/src/extensions/image.js +0 -1529
  56. package/.test-dist/src/extensions/index.js +0 -30
  57. package/.test-dist/src/extensions/maskOps.js +0 -279
  58. package/.test-dist/src/extensions/mirror.js +0 -104
  59. package/.test-dist/src/extensions/ruler.js +0 -345
  60. package/.test-dist/src/extensions/sceneLayout.js +0 -96
  61. package/.test-dist/src/extensions/sceneLayoutModel.js +0 -196
  62. package/.test-dist/src/extensions/sceneVisibility.js +0 -62
  63. package/.test-dist/src/extensions/size.js +0 -331
  64. package/.test-dist/src/extensions/tracer.js +0 -538
  65. package/.test-dist/src/extensions/white-ink.js +0 -1190
  66. package/.test-dist/src/extensions/wrappedOffsets.js +0 -33
  67. package/.test-dist/src/feature.js +0 -826
  68. package/.test-dist/src/featureComplete.js +0 -32
  69. package/.test-dist/src/film.js +0 -167
  70. package/.test-dist/src/geometry.js +0 -506
  71. package/.test-dist/src/image.js +0 -1250
  72. package/.test-dist/src/index.js +0 -18
  73. package/.test-dist/src/maskOps.js +0 -270
  74. package/.test-dist/src/mirror.js +0 -104
  75. package/.test-dist/src/renderSpec.js +0 -2
  76. package/.test-dist/src/ruler.js +0 -343
  77. package/.test-dist/src/sceneLayout.js +0 -99
  78. package/.test-dist/src/sceneLayoutModel.js +0 -196
  79. package/.test-dist/src/sceneView.js +0 -40
  80. package/.test-dist/src/sceneVisibility.js +0 -42
  81. package/.test-dist/src/services/CanvasService.js +0 -249
  82. package/.test-dist/src/services/ViewportSystem.js +0 -76
  83. package/.test-dist/src/services/index.js +0 -24
  84. package/.test-dist/src/services/renderSpec.js +0 -2
  85. package/.test-dist/src/size.js +0 -332
  86. package/.test-dist/src/tracer.js +0 -544
  87. package/.test-dist/src/units.js +0 -30
  88. package/.test-dist/src/white-ink.js +0 -829
  89. package/.test-dist/src/wrappedOffsets.js +0 -33
  90. package/.test-dist/tests/run.js +0 -94
@@ -1,1076 +1,1149 @@
1
- import {
2
- Extension,
3
- ExtensionContext,
4
- ContributionPointIds,
5
- CommandContribution,
6
- ConfigurationContribution,
7
- ConfigurationService,
8
- } from "@pooder/core";
9
- import { Canvas as FabricCanvas, Path, Pattern } from "fabric";
10
- import { CanvasService } from "../services";
11
- import { ImageTracer } from "./tracer";
12
- import { Unit } from "../coordinate";
13
- import { parseLengthToMm } from "../units";
14
- import {
15
- generateDielinePath,
16
- generateMaskPath,
17
- generateBleedZonePath,
18
- DielineFeature,
19
- } from "./geometry";
20
- import {
21
- buildSceneGeometry,
22
- computeSceneLayout,
23
- readSizeState,
24
- } from "./sceneLayoutModel";
25
-
26
- export interface DielineGeometry {
27
- shape: "rect" | "circle" | "ellipse" | "custom";
28
- unit: "mm";
29
- displayUnit: Unit;
30
- x: number;
31
- y: number;
32
- width: number;
33
- height: number;
34
- radius: number;
35
- offset: number;
36
- borderLength?: number;
37
- scale?: number;
38
- strokeWidth?: number;
39
- pathData?: string;
40
- customSourceWidthPx?: number;
41
- customSourceHeightPx?: number;
42
- }
43
-
44
- export interface LineStyle {
45
- width: number;
46
- color: string;
47
- dashLength: number;
48
- style: "solid" | "dashed" | "hidden";
49
- }
50
-
51
- export interface DielineState {
52
- displayUnit: Unit;
53
- shape: "rect" | "circle" | "ellipse" | "custom";
54
- width: number;
55
- height: number;
56
- radius: number;
57
- offset: number;
58
- padding: number | string;
59
- mainLine: LineStyle;
60
- offsetLine: LineStyle;
61
- insideColor: string;
62
- outsideColor: string;
63
- showBleedLines: boolean;
64
- features: DielineFeature[];
65
- pathData?: string;
66
- customSourceWidthPx?: number;
67
- customSourceHeightPx?: number;
68
- }
69
-
70
- const IMAGE_OBJECT_LAYER_ID = "image.user";
71
-
72
- export class DielineTool implements Extension {
73
- id = "pooder.kit.dieline";
74
- public metadata = {
75
- name: "DielineTool",
76
- };
77
-
78
- private state: DielineState = {
79
- displayUnit: "mm",
80
- shape: "rect",
81
- width: 500,
82
- height: 500,
83
- radius: 0,
84
- offset: 0,
85
- padding: 140,
86
- mainLine: {
87
- width: 2.7,
88
- color: "#FF0000",
89
- dashLength: 5,
90
- style: "solid",
91
- },
92
- offsetLine: {
93
- width: 2.7,
94
- color: "#FF0000",
95
- dashLength: 5,
96
- style: "solid",
97
- },
98
- insideColor: "rgba(0,0,0,0)",
99
- outsideColor: "#ffffff",
100
- showBleedLines: true,
101
- features: [],
102
- };
103
-
104
- private canvasService?: CanvasService;
105
- private context?: ExtensionContext;
106
- private onCanvasResized = () => {
107
- this.updateDieline();
108
- };
109
-
110
- constructor(options?: Partial<DielineState>) {
111
- if (options) {
112
- // Deep merge for styles to avoid overwriting defaults with partial objects
113
- if (options.mainLine) {
114
- Object.assign(this.state.mainLine, options.mainLine);
115
- delete options.mainLine;
116
- }
117
- if (options.offsetLine) {
118
- Object.assign(this.state.offsetLine, options.offsetLine);
119
- delete options.offsetLine;
120
- }
121
- Object.assign(this.state, options);
122
- }
123
- }
124
-
125
- activate(context: ExtensionContext) {
126
- this.context = context;
127
- this.canvasService = context.services.get<CanvasService>("CanvasService");
128
- if (!this.canvasService) {
129
- console.warn("CanvasService not found for DielineTool");
130
- return;
131
- }
132
-
133
- const configService = context.services.get<ConfigurationService>(
134
- "ConfigurationService",
135
- );
136
- if (configService) {
137
- // Load initial config
138
- const s = this.state;
139
- const sizeState = readSizeState(configService);
140
- s.displayUnit = sizeState.unit;
141
- s.shape = configService.get("dieline.shape", s.shape);
142
- s.width = sizeState.actualWidthMm;
143
- s.height = sizeState.actualHeightMm;
144
- s.radius = parseLengthToMm(
145
- configService.get("dieline.radius", s.radius),
146
- "mm",
147
- );
148
- s.padding = sizeState.viewPadding;
149
- s.offset =
150
- sizeState.cutMode === "outset"
151
- ? sizeState.cutMarginMm
152
- : sizeState.cutMode === "inset"
153
- ? -sizeState.cutMarginMm
154
- : 0;
155
-
156
- // Main Line
157
- s.mainLine.width = configService.get(
158
- "dieline.strokeWidth",
159
- s.mainLine.width,
160
- );
161
- s.mainLine.color = configService.get(
162
- "dieline.strokeColor",
163
- s.mainLine.color,
164
- );
165
- s.mainLine.dashLength = configService.get(
166
- "dieline.dashLength",
167
- s.mainLine.dashLength,
168
- );
169
- s.mainLine.style = configService.get("dieline.style", s.mainLine.style);
170
-
171
- // Offset Line
172
- s.offsetLine.width = configService.get(
173
- "dieline.offsetStrokeWidth",
174
- s.offsetLine.width,
175
- );
176
- s.offsetLine.color = configService.get(
177
- "dieline.offsetStrokeColor",
178
- s.offsetLine.color,
179
- );
180
- s.offsetLine.dashLength = configService.get(
181
- "dieline.offsetDashLength",
182
- s.offsetLine.dashLength,
183
- );
184
- s.offsetLine.style = configService.get(
185
- "dieline.offsetStyle",
186
- s.offsetLine.style,
187
- );
188
-
189
- s.insideColor = configService.get("dieline.insideColor", s.insideColor);
190
- s.outsideColor = configService.get(
191
- "dieline.outsideColor",
192
- s.outsideColor,
193
- );
194
- s.showBleedLines = configService.get(
195
- "dieline.showBleedLines",
196
- s.showBleedLines,
197
- );
198
- s.features = configService.get("dieline.features", s.features);
199
- s.pathData = configService.get("dieline.pathData", s.pathData);
200
- const sourceWidth = Number(
201
- configService.get("dieline.customSourceWidthPx", 0),
202
- );
203
- const sourceHeight = Number(
204
- configService.get("dieline.customSourceHeightPx", 0),
205
- );
206
- s.customSourceWidthPx =
207
- Number.isFinite(sourceWidth) && sourceWidth > 0
208
- ? sourceWidth
209
- : undefined;
210
- s.customSourceHeightPx =
211
- Number.isFinite(sourceHeight) && sourceHeight > 0
212
- ? sourceHeight
213
- : undefined;
214
-
215
- // Listen for changes
216
- configService.onAnyChange((e: { key: string; value: any }) => {
217
- if (e.key.startsWith("size.")) {
218
- const nextSize = readSizeState(configService);
219
- s.displayUnit = nextSize.unit;
220
- s.width = nextSize.actualWidthMm;
221
- s.height = nextSize.actualHeightMm;
222
- s.padding = nextSize.viewPadding;
223
- s.offset =
224
- nextSize.cutMode === "outset"
225
- ? nextSize.cutMarginMm
226
- : nextSize.cutMode === "inset"
227
- ? -nextSize.cutMarginMm
228
- : 0;
229
- this.updateDieline();
230
- return;
231
- }
232
-
233
- if (e.key.startsWith("dieline.")) {
234
- switch (e.key) {
235
- case "dieline.shape":
236
- s.shape = e.value;
237
- break;
238
- case "dieline.radius":
239
- s.radius = parseLengthToMm(e.value, "mm");
240
- break;
241
-
242
- case "dieline.strokeWidth":
243
- s.mainLine.width = e.value;
244
- break;
245
- case "dieline.strokeColor":
246
- s.mainLine.color = e.value;
247
- break;
248
- case "dieline.dashLength":
249
- s.mainLine.dashLength = e.value;
250
- break;
251
- case "dieline.style":
252
- s.mainLine.style = e.value;
253
- break;
254
-
255
- case "dieline.offsetStrokeWidth":
256
- s.offsetLine.width = e.value;
257
- break;
258
- case "dieline.offsetStrokeColor":
259
- s.offsetLine.color = e.value;
260
- break;
261
- case "dieline.offsetDashLength":
262
- s.offsetLine.dashLength = e.value;
263
- break;
264
- case "dieline.offsetStyle":
265
- s.offsetLine.style = e.value;
266
- break;
267
-
268
- case "dieline.insideColor":
269
- s.insideColor = e.value;
270
- break;
271
- case "dieline.outsideColor":
272
- s.outsideColor = e.value;
273
- break;
274
- case "dieline.showBleedLines":
275
- s.showBleedLines = e.value;
276
- break;
277
- case "dieline.features":
278
- s.features = e.value;
279
- break;
280
- case "dieline.pathData":
281
- s.pathData = e.value;
282
- break;
283
- case "dieline.customSourceWidthPx":
284
- s.customSourceWidthPx =
285
- Number.isFinite(Number(e.value)) && Number(e.value) > 0
286
- ? Number(e.value)
287
- : undefined;
288
- break;
289
- case "dieline.customSourceHeightPx":
290
- s.customSourceHeightPx =
291
- Number.isFinite(Number(e.value)) && Number(e.value) > 0
292
- ? Number(e.value)
293
- : undefined;
294
- break;
295
- }
296
- this.updateDieline();
297
- }
298
- });
299
- }
300
-
301
- context.eventBus.on("canvas:resized", this.onCanvasResized);
302
- this.createLayer();
303
- this.updateDieline();
304
- }
305
-
306
- deactivate(context: ExtensionContext) {
307
- context.eventBus.off("canvas:resized", this.onCanvasResized);
308
- this.destroyLayer();
309
- this.canvasService = undefined;
310
- this.context = undefined;
311
- }
312
-
313
- contribute() {
314
- const s = this.state;
315
- return {
316
- [ContributionPointIds.TOOLS]: [
317
- {
318
- id: this.id,
319
- name: "Dieline",
320
- interaction: "session",
321
- session: {
322
- autoBegin: false,
323
- leavePolicy: "block",
324
- },
325
- },
326
- ],
327
- [ContributionPointIds.CONFIGURATIONS]: [
328
- {
329
- id: "dieline.shape",
330
- type: "select",
331
- label: "Shape",
332
- options: ["rect", "circle", "ellipse", "custom"],
333
- default: s.shape,
334
- },
335
- {
336
- id: "dieline.radius",
337
- type: "number",
338
- label: "Corner Radius (mm)",
339
- min: 0,
340
- max: 500,
341
- default: s.radius,
342
- },
343
- {
344
- id: "dieline.showBleedLines",
345
- type: "boolean",
346
- label: "Show Bleed Lines",
347
- default: s.showBleedLines,
348
- },
349
- {
350
- id: "dieline.strokeWidth",
351
- type: "number",
352
- label: "Line Width",
353
- min: 0.1,
354
- max: 10,
355
- step: 0.1,
356
- default: s.mainLine.width,
357
- },
358
- {
359
- id: "dieline.strokeColor",
360
- type: "color",
361
- label: "Line Color",
362
- default: s.mainLine.color,
363
- },
364
- {
365
- id: "dieline.dashLength",
366
- type: "number",
367
- label: "Dash Length",
368
- min: 1,
369
- max: 50,
370
- default: s.mainLine.dashLength,
371
- },
372
- {
373
- id: "dieline.style",
374
- type: "select",
375
- label: "Line Style",
376
- options: ["solid", "dashed", "hidden"],
377
- default: s.mainLine.style,
378
- },
379
- {
380
- id: "dieline.offsetStrokeWidth",
381
- type: "number",
382
- label: "Offset Line Width",
383
- min: 0.1,
384
- max: 10,
385
- step: 0.1,
386
- default: s.offsetLine.width,
387
- },
388
- {
389
- id: "dieline.offsetStrokeColor",
390
- type: "color",
391
- label: "Offset Line Color",
392
- default: s.offsetLine.color,
393
- },
394
- {
395
- id: "dieline.offsetDashLength",
396
- type: "number",
397
- label: "Offset Dash Length",
398
- min: 1,
399
- max: 50,
400
- default: s.offsetLine.dashLength,
401
- },
402
- {
403
- id: "dieline.offsetStyle",
404
- type: "select",
405
- label: "Offset Line Style",
406
- options: ["solid", "dashed", "hidden"],
407
- default: s.offsetLine.style,
408
- },
409
- {
410
- id: "dieline.insideColor",
411
- type: "color",
412
- label: "Inside Color",
413
- default: s.insideColor,
414
- },
415
- {
416
- id: "dieline.outsideColor",
417
- type: "color",
418
- label: "Outside Color",
419
- default: s.outsideColor,
420
- },
421
- {
422
- id: "dieline.features",
423
- type: "json",
424
- label: "Edge Features",
425
- default: s.features,
426
- },
427
- ] as ConfigurationContribution[],
428
- [ContributionPointIds.COMMANDS]: [
429
- {
430
- command: "updateFeaturePosition",
431
- title: "Update Feature Position",
432
- handler: (groupId: string, x: number, y: number) => {
433
- const configService = this.context?.services.get<any>(
434
- "ConfigurationService",
435
- );
436
- if (!configService) return;
437
-
438
- const features = configService.get("dieline.features") || [];
439
-
440
- let changed = false;
441
- const newFeatures = features.map((f: any) => {
442
- if (f.groupId === groupId) {
443
- if (f.x !== x || f.y !== y) {
444
- changed = true;
445
- return { ...f, x, y };
446
- }
447
- }
448
- return f;
449
- });
450
-
451
- if (changed) {
452
- configService.update("dieline.features", newFeatures);
453
- }
454
- },
455
- },
456
- {
457
- command: "exportCutImage",
458
- title: "Export Cut Image",
459
- handler: (options?: { debug?: boolean }) => {
460
- return this.exportCutImage(options);
461
- },
462
- },
463
- {
464
- command: "detectEdge",
465
- title: "Detect Edge from Image",
466
- handler: async (
467
- imageUrl: string,
468
- options?: {
469
- expand?: number;
470
- smoothing?: boolean;
471
- simplifyTolerance?: number;
472
- threshold?: number;
473
- debug?: boolean;
474
- },
475
- ) => {
476
- try {
477
- const detectOptions = options || {};
478
- const debug = detectOptions.debug === true;
479
- const tracerOptions = {
480
- expand: detectOptions.expand ?? 0,
481
- smoothing: detectOptions.smoothing ?? true,
482
- simplifyTolerance: detectOptions.simplifyTolerance ?? 2,
483
- threshold: detectOptions.threshold,
484
- debug,
485
- };
486
-
487
- // Helper to get image dimensions
488
- const loadImage = (url: string): Promise<HTMLImageElement> => {
489
- return new Promise((resolve, reject) => {
490
- const img = new Image();
491
- img.crossOrigin = "Anonymous";
492
- img.onload = () => resolve(img);
493
- img.onerror = (e) => reject(e);
494
- img.src = url;
495
- });
496
- };
497
-
498
- const [img, traced] = await Promise.all([
499
- loadImage(imageUrl),
500
- ImageTracer.traceWithBounds(imageUrl, tracerOptions),
501
- ]);
502
- const { pathData, baseBounds, bounds } = traced;
503
-
504
- if (debug) {
505
- console.info("[DielineTool] detectEdge", {
506
- imageWidth: img.width,
507
- imageHeight: img.height,
508
- baseBounds,
509
- expandedBounds: bounds,
510
- currentDielineWidth: s.width,
511
- currentDielineHeight: s.height,
512
- options: tracerOptions,
513
- strategy: "single-connected-silhouette",
514
- });
515
- }
516
-
517
- return {
518
- pathData,
519
- rawBounds: bounds,
520
- baseBounds,
521
- imageWidth: img.width,
522
- imageHeight: img.height,
523
- };
524
- } catch (e) {
525
- console.error("Edge detection failed", e);
526
- throw e;
527
- }
528
- },
529
- },
530
- ] as CommandContribution[],
531
- };
532
- }
533
-
534
- private getLayer() {
535
- return this.canvasService?.getLayer("dieline-overlay");
536
- }
537
-
538
- private createLayer() {
539
- if (!this.canvasService) return;
540
- const width = this.canvasService.canvas.width || 800;
541
- const height = this.canvasService.canvas.height || 600;
542
-
543
- const layer = this.canvasService.createLayer("dieline-overlay", {
544
- width,
545
- height,
546
- selectable: false,
547
- evented: false,
548
- });
549
-
550
- this.canvasService.canvas.bringObjectToFront(layer);
551
-
552
- // Ensure above user layer
553
- const userLayer = this.canvasService.getLayer("user");
554
- if (userLayer) {
555
- const userIndex = this.canvasService.canvas
556
- .getObjects()
557
- .indexOf(userLayer);
558
- this.canvasService.canvas.moveObjectTo(layer, userIndex + 1);
559
- }
560
- }
561
-
562
- private destroyLayer() {
563
- if (!this.canvasService) return;
564
- const layer = this.getLayer();
565
- if (layer) {
566
- this.canvasService.canvas.remove(layer);
567
- }
568
- }
569
-
570
- private createHatchPattern(color: string = "rgba(0, 0, 0, 0.3)") {
571
- if (typeof document === "undefined") {
572
- return undefined;
573
- }
574
- const size = 20;
575
- const canvas = document.createElement("canvas");
576
- canvas.width = size;
577
- canvas.height = size;
578
- const ctx = canvas.getContext("2d");
579
- if (ctx) {
580
- // Transparent background
581
- ctx.clearRect(0, 0, size, size);
582
-
583
- // Draw diagonal /
584
- ctx.strokeStyle = color;
585
- ctx.lineWidth = 1;
586
- ctx.beginPath();
587
- ctx.moveTo(0, size);
588
- ctx.lineTo(size, 0);
589
- ctx.stroke();
590
- }
591
- // @ts-ignore
592
- return new Pattern({ source: canvas, repetition: "repeat" });
593
- }
594
-
595
- private getConfigService(): ConfigurationService | undefined {
596
- return this.context?.services.get<ConfigurationService>(
597
- "ConfigurationService",
598
- );
599
- }
600
-
601
- private syncSizeState(configService: ConfigurationService) {
602
- const sizeState = readSizeState(configService);
603
- this.state.displayUnit = sizeState.unit;
604
- this.state.width = sizeState.actualWidthMm;
605
- this.state.height = sizeState.actualHeightMm;
606
- this.state.padding = sizeState.viewPadding;
607
- this.state.offset =
608
- sizeState.cutMode === "outset"
609
- ? sizeState.cutMarginMm
610
- : sizeState.cutMode === "inset"
611
- ? -sizeState.cutMarginMm
612
- : 0;
613
- }
614
-
615
- private bringFeatureMarkersToFront() {
616
- if (!this.canvasService) return;
617
- const canvas = this.canvasService.canvas;
618
- canvas
619
- .getObjects()
620
- .filter((obj: any) => obj?.data?.type === "feature-marker")
621
- .forEach((obj: any) => canvas.bringObjectToFront(obj));
622
- }
623
-
624
- public updateDieline(_emitEvent: boolean = true) {
625
- if (!this.canvasService) return;
626
- const layer = this.getLayer();
627
- if (!layer) return;
628
- const configService = this.getConfigService();
629
- if (!configService) return;
630
-
631
- this.syncSizeState(configService);
632
- const sceneLayout = computeSceneLayout(
633
- this.canvasService,
634
- readSizeState(configService),
635
- );
636
- if (!sceneLayout) return;
637
-
638
- const {
639
- shape,
640
- radius,
641
- mainLine,
642
- offsetLine,
643
- insideColor,
644
- outsideColor,
645
- showBleedLines,
646
- features,
647
- } = this.state;
648
-
649
- const canvasW =
650
- sceneLayout.canvasWidth || this.canvasService.canvas.width || 800;
651
- const canvasH =
652
- sceneLayout.canvasHeight || this.canvasService.canvas.height || 600;
653
- const scale = sceneLayout.scale;
654
- const cx = sceneLayout.trimRect.centerX;
655
- const cy = sceneLayout.trimRect.centerY;
656
-
657
- const visualWidth = sceneLayout.trimRect.width;
658
- const visualHeight = sceneLayout.trimRect.height;
659
- const visualRadius = radius * scale;
660
- const cutW = sceneLayout.cutRect.width;
661
- const cutH = sceneLayout.cutRect.height;
662
- const visualOffset = (cutW - visualWidth) / 2;
663
- const cutR =
664
- visualRadius === 0 ? 0 : Math.max(0, visualRadius + visualOffset);
665
-
666
- layer.remove(...layer.getObjects());
667
-
668
- const absoluteFeatures = (features || []).map((f) => ({
669
- ...f,
670
- x: f.x,
671
- y: f.y,
672
- width: (f.width || 0) * scale,
673
- height: (f.height || 0) * scale,
674
- radius: (f.radius || 0) * scale,
675
- }));
676
- const cutFeatures = absoluteFeatures.filter((f) => !f.skipCut);
677
-
678
- const maskPathData = generateMaskPath({
679
- canvasWidth: canvasW,
680
- canvasHeight: canvasH,
681
- shape,
682
- width: cutW,
683
- height: cutH,
684
- radius: cutR,
685
- x: cx,
686
- y: cy,
687
- features: cutFeatures,
688
- pathData: this.state.pathData,
689
- customSourceWidthPx: this.state.customSourceWidthPx,
690
- customSourceHeightPx: this.state.customSourceHeightPx,
691
- });
692
- const mask = new Path(maskPathData, {
693
- fill: outsideColor,
694
- stroke: null,
695
- selectable: false,
696
- evented: false,
697
- originX: "left" as const,
698
- originY: "top" as const,
699
- left: 0,
700
- top: 0,
701
- });
702
- layer.add(mask);
703
-
704
- if (
705
- insideColor &&
706
- insideColor !== "transparent" &&
707
- insideColor !== "rgba(0,0,0,0)"
708
- ) {
709
- const productPathData = generateDielinePath({
710
- shape,
711
- width: cutW,
712
- height: cutH,
713
- radius: cutR,
714
- x: cx,
715
- y: cy,
716
- features: cutFeatures,
717
- pathData: this.state.pathData,
718
- customSourceWidthPx: this.state.customSourceWidthPx,
719
- customSourceHeightPx: this.state.customSourceHeightPx,
720
- canvasWidth: canvasW,
721
- canvasHeight: canvasH,
722
- });
723
-
724
- const insideObj = new Path(productPathData, {
725
- fill: insideColor,
726
- stroke: null,
727
- selectable: false,
728
- evented: false,
729
- originX: "left",
730
- originY: "top",
731
- });
732
- layer.add(insideObj);
733
- }
734
-
735
- if (Math.abs(visualOffset) > 0.0001) {
736
- const bleedPathData = generateBleedZonePath(
737
- {
738
- shape,
739
- width: visualWidth,
740
- height: visualHeight,
741
- radius: visualRadius,
742
- x: cx,
743
- y: cy,
744
- features: cutFeatures,
745
- pathData: this.state.pathData,
746
- customSourceWidthPx: this.state.customSourceWidthPx,
747
- customSourceHeightPx: this.state.customSourceHeightPx,
748
- canvasWidth: canvasW,
749
- canvasHeight: canvasH,
750
- },
751
- {
752
- shape,
753
- width: cutW,
754
- height: cutH,
755
- radius: cutR,
756
- x: cx,
757
- y: cy,
758
- features: cutFeatures,
759
- pathData: this.state.pathData,
760
- customSourceWidthPx: this.state.customSourceWidthPx,
761
- customSourceHeightPx: this.state.customSourceHeightPx,
762
- canvasWidth: canvasW,
763
- canvasHeight: canvasH,
764
- },
765
- visualOffset,
766
- );
767
-
768
- if (showBleedLines !== false) {
769
- const pattern = this.createHatchPattern(mainLine.color);
770
- if (pattern) {
771
- const bleedObj = new Path(bleedPathData, {
772
- fill: pattern,
773
- stroke: null,
774
- selectable: false,
775
- evented: false,
776
- objectCaching: false,
777
- originX: "left",
778
- originY: "top",
779
- });
780
- layer.add(bleedObj);
781
- }
782
- }
783
-
784
- const offsetPathData = generateDielinePath({
785
- shape,
786
- width: cutW,
787
- height: cutH,
788
- radius: cutR,
789
- x: cx,
790
- y: cy,
791
- features: cutFeatures,
792
- pathData: this.state.pathData,
793
- customSourceWidthPx: this.state.customSourceWidthPx,
794
- customSourceHeightPx: this.state.customSourceHeightPx,
795
- canvasWidth: canvasW,
796
- canvasHeight: canvasH,
797
- });
798
-
799
- const offsetBorderObj = new Path(offsetPathData, {
800
- fill: null,
801
- stroke: offsetLine.style === "hidden" ? null : offsetLine.color,
802
- strokeWidth: offsetLine.width,
803
- strokeDashArray:
804
- offsetLine.style === "dashed"
805
- ? [offsetLine.dashLength, offsetLine.dashLength]
806
- : undefined,
807
- selectable: false,
808
- evented: false,
809
- originX: "left",
810
- originY: "top",
811
- });
812
- layer.add(offsetBorderObj);
813
- }
814
-
815
- const borderPathData = generateDielinePath({
816
- shape,
817
- width: visualWidth,
818
- height: visualHeight,
819
- radius: visualRadius,
820
- x: cx,
821
- y: cy,
822
- features: absoluteFeatures,
823
- pathData: this.state.pathData,
824
- customSourceWidthPx: this.state.customSourceWidthPx,
825
- customSourceHeightPx: this.state.customSourceHeightPx,
826
- canvasWidth: canvasW,
827
- canvasHeight: canvasH,
828
- });
829
- const borderObj = new Path(borderPathData, {
830
- fill: "transparent",
831
- stroke: mainLine.style === "hidden" ? null : mainLine.color,
832
- strokeWidth: mainLine.width,
833
- strokeDashArray:
834
- mainLine.style === "dashed"
835
- ? [mainLine.dashLength, mainLine.dashLength]
836
- : undefined,
837
- selectable: false,
838
- evented: false,
839
- originX: "left",
840
- originY: "top",
841
- });
842
- layer.add(borderObj);
843
-
844
- const userLayer = this.canvasService.getLayer("user");
845
- if (layer && userLayer) {
846
- const layerIndex = this.canvasService.canvas.getObjects().indexOf(layer);
847
- const userIndex = this.canvasService.canvas
848
- .getObjects()
849
- .indexOf(userLayer);
850
- if (layerIndex < userIndex) {
851
- this.canvasService.canvas.moveObjectTo(layer, userIndex + 1);
852
- }
853
- } else {
854
- this.canvasService.canvas.bringObjectToFront(layer);
855
- }
856
-
857
- // Feature tool markers can extend outside trim. Keep them above dieline mask.
858
- this.bringFeatureMarkersToFront();
859
-
860
- const rulerLayer = this.canvasService.getLayer("ruler-overlay");
861
- if (rulerLayer) {
862
- this.canvasService.canvas.bringObjectToFront(rulerLayer);
863
- }
864
-
865
- layer.dirty = true;
866
- this.canvasService.requestRenderAll();
867
- }
868
-
869
- public getGeometry(): DielineGeometry | null {
870
- if (!this.canvasService) return null;
871
- const configService = this.getConfigService();
872
- if (!configService) return null;
873
- const sceneLayout = computeSceneLayout(
874
- this.canvasService,
875
- readSizeState(configService),
876
- );
877
- if (!sceneLayout) return null;
878
- const sceneGeometry = buildSceneGeometry(configService, sceneLayout);
879
- return {
880
- ...sceneGeometry,
881
- strokeWidth: this.state.mainLine.width,
882
- pathData: this.state.pathData,
883
- customSourceWidthPx: this.state.customSourceWidthPx,
884
- customSourceHeightPx: this.state.customSourceHeightPx,
885
- } as DielineGeometry;
886
- }
887
-
888
- public async exportCutImage(options?: { debug?: boolean }) {
889
- const debug = options?.debug === true;
890
-
891
- if (!this.canvasService) {
892
- console.warn(
893
- "[DielineTool] exportCutImage returned null: canvas-not-ready",
894
- );
895
- return null;
896
- }
897
- const configService = this.getConfigService();
898
- if (!configService) {
899
- console.warn(
900
- "[DielineTool] exportCutImage returned null: config-service-not-ready",
901
- );
902
- return null;
903
- }
904
-
905
- this.syncSizeState(configService);
906
- const sceneLayout = computeSceneLayout(
907
- this.canvasService,
908
- readSizeState(configService),
909
- );
910
- if (!sceneLayout) {
911
- console.warn(
912
- "[DielineTool] exportCutImage returned null: scene-layout-null",
913
- );
914
- return null;
915
- }
916
-
917
- const { shape, radius, features, pathData } = this.state;
918
- const canvasW =
919
- sceneLayout.canvasWidth || this.canvasService.canvas.width || 800;
920
- const canvasH =
921
- sceneLayout.canvasHeight || this.canvasService.canvas.height || 600;
922
- const scale = sceneLayout.scale;
923
- const cx = sceneLayout.trimRect.centerX;
924
- const cy = sceneLayout.trimRect.centerY;
925
- const cutW = sceneLayout.cutRect.width;
926
- const cutH = sceneLayout.cutRect.height;
927
- const visualRadius = radius * scale;
928
- const visualOffset = (cutW - sceneLayout.trimRect.width) / 2;
929
- const cutR =
930
- visualRadius === 0 ? 0 : Math.max(0, visualRadius + visualOffset);
931
-
932
- const absoluteFeatures = (features || []).map((f) => ({
933
- ...f,
934
- x: f.x,
935
- y: f.y,
936
- width: (f.width || 0) * scale,
937
- height: (f.height || 0) * scale,
938
- radius: (f.radius || 0) * scale,
939
- }));
940
- const cutFeatures = absoluteFeatures.filter((f) => !f.skipCut);
941
-
942
- const generatedPathData = generateDielinePath({
943
- shape,
944
- width: cutW,
945
- height: cutH,
946
- radius: cutR,
947
- x: cx,
948
- y: cy,
949
- features: cutFeatures,
950
- pathData,
951
- customSourceWidthPx: this.state.customSourceWidthPx,
952
- customSourceHeightPx: this.state.customSourceHeightPx,
953
- canvasWidth: canvasW,
954
- canvasHeight: canvasH,
955
- });
956
-
957
- const clipPath = new Path(generatedPathData, {
958
- originX: "center",
959
- originY: "center",
960
- left: cx,
961
- top: cy,
962
- absolutePositioned: true,
963
- });
964
- const pathOffsetX = Number((clipPath as any)?.pathOffset?.x);
965
- const pathOffsetY = Number((clipPath as any)?.pathOffset?.y);
966
- const centerX = Number.isFinite(pathOffsetX) ? pathOffsetX : cx;
967
- const centerY = Number.isFinite(pathOffsetY) ? pathOffsetY : cy;
968
- clipPath.set({
969
- originX: "center",
970
- originY: "center",
971
- left: centerX,
972
- top: centerY,
973
- absolutePositioned: true,
974
- });
975
- clipPath.setCoords();
976
-
977
- const pathBounds = clipPath.getBoundingRect();
978
- if (
979
- !Number.isFinite(pathBounds.left) ||
980
- !Number.isFinite(pathBounds.top) ||
981
- !Number.isFinite(pathBounds.width) ||
982
- !Number.isFinite(pathBounds.height) ||
983
- pathBounds.width <= 0 ||
984
- pathBounds.height <= 0
985
- ) {
986
- console.warn(
987
- "[DielineTool] exportCutImage returned null: invalid-cut-bounds",
988
- {
989
- bounds: pathBounds,
990
- },
991
- );
992
- return null;
993
- }
994
- const exportBounds = pathBounds;
995
-
996
- const sourceImages = this.canvasService.canvas
997
- .getObjects()
998
- .filter((obj: any) => {
999
- return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
1000
- });
1001
- if (!sourceImages.length) {
1002
- console.warn(
1003
- "[DielineTool] exportCutImage returned null: no-image-objects-on-canvas",
1004
- );
1005
- return null;
1006
- }
1007
-
1008
- const sourceCanvasWidth = Number(
1009
- this.canvasService.canvas.width || sceneLayout.canvasWidth || canvasW,
1010
- );
1011
- const sourceCanvasHeight = Number(
1012
- this.canvasService.canvas.height || sceneLayout.canvasHeight || canvasH,
1013
- );
1014
-
1015
- const el = document.createElement("canvas");
1016
- const exportCanvas = new FabricCanvas(el, {
1017
- renderOnAddRemove: false,
1018
- selection: false,
1019
- enableRetinaScaling: false,
1020
- preserveObjectStacking: true,
1021
- } as any);
1022
- exportCanvas.setDimensions({
1023
- width: Math.max(1, sourceCanvasWidth),
1024
- height: Math.max(1, sourceCanvasHeight),
1025
- });
1026
-
1027
- try {
1028
- for (const source of sourceImages as any[]) {
1029
- const clone = await source.clone();
1030
- clone.set({
1031
- selectable: false,
1032
- evented: false,
1033
- });
1034
- clone.setCoords();
1035
- exportCanvas.add(clone);
1036
- }
1037
-
1038
- exportCanvas.clipPath = clipPath;
1039
- exportCanvas.renderAll();
1040
-
1041
- const dataUrl = exportCanvas.toDataURL({
1042
- format: "png",
1043
- multiplier: 2,
1044
- left: exportBounds.left,
1045
- top: exportBounds.top,
1046
- width: exportBounds.width,
1047
- height: exportBounds.height,
1048
- });
1049
-
1050
- if (debug) {
1051
- console.info("[DielineTool] exportCutImage success", {
1052
- sourceCount: sourceImages.length,
1053
- bounds: exportBounds,
1054
- rawPathBounds: pathBounds,
1055
- pathOffset: {
1056
- x: Number.isFinite(pathOffsetX) ? pathOffsetX : null,
1057
- y: Number.isFinite(pathOffsetY) ? pathOffsetY : null,
1058
- },
1059
- clipPathCenter: {
1060
- x: centerX,
1061
- y: centerY,
1062
- },
1063
- cutRect: sceneLayout.cutRect,
1064
- canvasSize: {
1065
- width: Math.max(1, sourceCanvasWidth),
1066
- height: Math.max(1, sourceCanvasHeight),
1067
- },
1068
- });
1069
- }
1070
-
1071
- return dataUrl;
1072
- } finally {
1073
- exportCanvas.dispose();
1074
- }
1075
- }
1076
- }
1
+ import {
2
+ Extension,
3
+ ExtensionContext,
4
+ ContributionPointIds,
5
+ CommandContribution,
6
+ ConfigurationContribution,
7
+ ConfigurationService,
8
+ } from "@pooder/core";
9
+ import { Canvas as FabricCanvas, Path, Pattern } from "fabric";
10
+ import { CanvasService, RenderObjectSpec } from "../services";
11
+ import { ImageTracer } from "./tracer";
12
+ import { parseLengthToMm } from "../units";
13
+ import {
14
+ DEFAULT_DIELINE_SHAPE,
15
+ DEFAULT_DIELINE_SHAPE_STYLE,
16
+ DIELINE_SHAPES,
17
+ normalizeShapeStyle,
18
+ normalizeDielineShape,
19
+ } from "./dielineShape";
20
+ import type { DielineShape, DielineShapeStyle } from "./dielineShape";
21
+ import {
22
+ generateDielinePath,
23
+ generateMaskPath,
24
+ generateBleedZonePath,
25
+ DielineFeature,
26
+ } from "./geometry";
27
+ import {
28
+ buildSceneGeometry,
29
+ computeSceneLayout,
30
+ readSizeState,
31
+ } from "./sceneLayoutModel";
32
+
33
+ export interface DielineGeometry {
34
+ shape: DielineShape;
35
+ shapeStyle: DielineShapeStyle;
36
+ unit: "px";
37
+ x: number;
38
+ y: number;
39
+ width: number;
40
+ height: number;
41
+ radius: number;
42
+ offset: number;
43
+ borderLength?: number;
44
+ scale?: number;
45
+ strokeWidth?: number;
46
+ pathData?: string;
47
+ customSourceWidthPx?: number;
48
+ customSourceHeightPx?: number;
49
+ }
50
+
51
+ export interface LineStyle {
52
+ width: number;
53
+ color: string;
54
+ dashLength: number;
55
+ style: "solid" | "dashed" | "hidden";
56
+ }
57
+
58
+ export interface DielineState {
59
+ shape: DielineShape;
60
+ shapeStyle: DielineShapeStyle;
61
+ width: number;
62
+ height: number;
63
+ radius: number;
64
+ offset: number;
65
+ padding: number | string;
66
+ mainLine: LineStyle;
67
+ offsetLine: LineStyle;
68
+ insideColor: string;
69
+ outsideColor: string;
70
+ showBleedLines: boolean;
71
+ features: DielineFeature[];
72
+ pathData?: string;
73
+ customSourceWidthPx?: number;
74
+ customSourceHeightPx?: number;
75
+ }
76
+
77
+ const IMAGE_OBJECT_LAYER_ID = "image.user";
78
+ const DIELINE_LAYER_ID = "dieline-overlay";
79
+
80
+ export class DielineTool implements Extension {
81
+ id = "pooder.kit.dieline";
82
+ public metadata = {
83
+ name: "DielineTool",
84
+ };
85
+
86
+ private state: DielineState = {
87
+ shape: DEFAULT_DIELINE_SHAPE,
88
+ shapeStyle: { ...DEFAULT_DIELINE_SHAPE_STYLE },
89
+ width: 500,
90
+ height: 500,
91
+ radius: 0,
92
+ offset: 0,
93
+ padding: 140,
94
+ mainLine: {
95
+ width: 2.7,
96
+ color: "#FF0000",
97
+ dashLength: 5,
98
+ style: "solid",
99
+ },
100
+ offsetLine: {
101
+ width: 2.7,
102
+ color: "#FF0000",
103
+ dashLength: 5,
104
+ style: "solid",
105
+ },
106
+ insideColor: "rgba(0,0,0,0)",
107
+ outsideColor: "#ffffff",
108
+ showBleedLines: true,
109
+ features: [],
110
+ };
111
+
112
+ private canvasService?: CanvasService;
113
+ private context?: ExtensionContext;
114
+ private specs: RenderObjectSpec[] = [];
115
+ private renderSeq = 0;
116
+ private renderProducerDisposable?: { dispose: () => void };
117
+ private onCanvasResized = () => {
118
+ this.updateDieline();
119
+ };
120
+
121
+ constructor(options?: Partial<DielineState>) {
122
+ if (options) {
123
+ // Deep merge for styles to avoid overwriting defaults with partial objects
124
+ if (options.mainLine) {
125
+ Object.assign(this.state.mainLine, options.mainLine);
126
+ delete options.mainLine;
127
+ }
128
+ if (options.offsetLine) {
129
+ Object.assign(this.state.offsetLine, options.offsetLine);
130
+ delete options.offsetLine;
131
+ }
132
+ if (options.shapeStyle) {
133
+ this.state.shapeStyle = normalizeShapeStyle(
134
+ options.shapeStyle,
135
+ this.state.shapeStyle,
136
+ );
137
+ delete options.shapeStyle;
138
+ }
139
+ Object.assign(this.state, options);
140
+ this.state.shape = normalizeDielineShape(options.shape, this.state.shape);
141
+ }
142
+ }
143
+
144
+ activate(context: ExtensionContext) {
145
+ this.context = context;
146
+ this.canvasService = context.services.get<CanvasService>("CanvasService");
147
+ if (!this.canvasService) {
148
+ console.warn("CanvasService not found for DielineTool");
149
+ return;
150
+ }
151
+ this.renderProducerDisposable?.dispose();
152
+ this.renderProducerDisposable = this.canvasService.registerRenderProducer(
153
+ this.id,
154
+ () => ({
155
+ layerSpecs: {
156
+ [DIELINE_LAYER_ID]: this.specs,
157
+ },
158
+ replaceLayerIds: [DIELINE_LAYER_ID],
159
+ }),
160
+ { priority: 250 },
161
+ );
162
+
163
+ const configService = context.services.get<ConfigurationService>(
164
+ "ConfigurationService",
165
+ );
166
+ if (configService) {
167
+ // Load initial config
168
+ const s = this.state;
169
+ const sizeState = readSizeState(configService);
170
+ s.shape = normalizeDielineShape(
171
+ configService.get("dieline.shape", s.shape),
172
+ s.shape,
173
+ );
174
+ s.shapeStyle = normalizeShapeStyle(
175
+ configService.get("dieline.shapeStyle", s.shapeStyle),
176
+ s.shapeStyle,
177
+ );
178
+ s.width = sizeState.actualWidthMm;
179
+ s.height = sizeState.actualHeightMm;
180
+ s.radius = parseLengthToMm(
181
+ configService.get("dieline.radius", s.radius),
182
+ "mm",
183
+ );
184
+ s.padding = sizeState.viewPadding;
185
+ s.offset =
186
+ sizeState.cutMode === "outset"
187
+ ? sizeState.cutMarginMm
188
+ : sizeState.cutMode === "inset"
189
+ ? -sizeState.cutMarginMm
190
+ : 0;
191
+
192
+ // Main Line
193
+ s.mainLine.width = configService.get(
194
+ "dieline.strokeWidth",
195
+ s.mainLine.width,
196
+ );
197
+ s.mainLine.color = configService.get(
198
+ "dieline.strokeColor",
199
+ s.mainLine.color,
200
+ );
201
+ s.mainLine.dashLength = configService.get(
202
+ "dieline.dashLength",
203
+ s.mainLine.dashLength,
204
+ );
205
+ s.mainLine.style = configService.get("dieline.style", s.mainLine.style);
206
+
207
+ // Offset Line
208
+ s.offsetLine.width = configService.get(
209
+ "dieline.offsetStrokeWidth",
210
+ s.offsetLine.width,
211
+ );
212
+ s.offsetLine.color = configService.get(
213
+ "dieline.offsetStrokeColor",
214
+ s.offsetLine.color,
215
+ );
216
+ s.offsetLine.dashLength = configService.get(
217
+ "dieline.offsetDashLength",
218
+ s.offsetLine.dashLength,
219
+ );
220
+ s.offsetLine.style = configService.get(
221
+ "dieline.offsetStyle",
222
+ s.offsetLine.style,
223
+ );
224
+
225
+ s.insideColor = configService.get("dieline.insideColor", s.insideColor);
226
+ s.outsideColor = configService.get(
227
+ "dieline.outsideColor",
228
+ s.outsideColor,
229
+ );
230
+ s.showBleedLines = configService.get(
231
+ "dieline.showBleedLines",
232
+ s.showBleedLines,
233
+ );
234
+ s.features = configService.get("dieline.features", s.features);
235
+ s.pathData = configService.get("dieline.pathData", s.pathData);
236
+ const sourceWidth = Number(
237
+ configService.get("dieline.customSourceWidthPx", 0),
238
+ );
239
+ const sourceHeight = Number(
240
+ configService.get("dieline.customSourceHeightPx", 0),
241
+ );
242
+ s.customSourceWidthPx =
243
+ Number.isFinite(sourceWidth) && sourceWidth > 0
244
+ ? sourceWidth
245
+ : undefined;
246
+ s.customSourceHeightPx =
247
+ Number.isFinite(sourceHeight) && sourceHeight > 0
248
+ ? sourceHeight
249
+ : undefined;
250
+
251
+ // Listen for changes
252
+ configService.onAnyChange((e: { key: string; value: any }) => {
253
+ if (e.key.startsWith("size.")) {
254
+ const nextSize = readSizeState(configService);
255
+ s.width = nextSize.actualWidthMm;
256
+ s.height = nextSize.actualHeightMm;
257
+ s.padding = nextSize.viewPadding;
258
+ s.offset =
259
+ nextSize.cutMode === "outset"
260
+ ? nextSize.cutMarginMm
261
+ : nextSize.cutMode === "inset"
262
+ ? -nextSize.cutMarginMm
263
+ : 0;
264
+ this.updateDieline();
265
+ return;
266
+ }
267
+
268
+ if (e.key.startsWith("dieline.")) {
269
+ switch (e.key) {
270
+ case "dieline.shape":
271
+ s.shape = normalizeDielineShape(e.value, s.shape);
272
+ break;
273
+ case "dieline.shapeStyle":
274
+ s.shapeStyle = normalizeShapeStyle(e.value, s.shapeStyle);
275
+ break;
276
+ case "dieline.radius":
277
+ s.radius = parseLengthToMm(e.value, "mm");
278
+ break;
279
+
280
+ case "dieline.strokeWidth":
281
+ s.mainLine.width = e.value;
282
+ break;
283
+ case "dieline.strokeColor":
284
+ s.mainLine.color = e.value;
285
+ break;
286
+ case "dieline.dashLength":
287
+ s.mainLine.dashLength = e.value;
288
+ break;
289
+ case "dieline.style":
290
+ s.mainLine.style = e.value;
291
+ break;
292
+
293
+ case "dieline.offsetStrokeWidth":
294
+ s.offsetLine.width = e.value;
295
+ break;
296
+ case "dieline.offsetStrokeColor":
297
+ s.offsetLine.color = e.value;
298
+ break;
299
+ case "dieline.offsetDashLength":
300
+ s.offsetLine.dashLength = e.value;
301
+ break;
302
+ case "dieline.offsetStyle":
303
+ s.offsetLine.style = e.value;
304
+ break;
305
+
306
+ case "dieline.insideColor":
307
+ s.insideColor = e.value;
308
+ break;
309
+ case "dieline.outsideColor":
310
+ s.outsideColor = e.value;
311
+ break;
312
+ case "dieline.showBleedLines":
313
+ s.showBleedLines = e.value;
314
+ break;
315
+ case "dieline.features":
316
+ s.features = e.value;
317
+ break;
318
+ case "dieline.pathData":
319
+ s.pathData = e.value;
320
+ break;
321
+ case "dieline.customSourceWidthPx":
322
+ s.customSourceWidthPx =
323
+ Number.isFinite(Number(e.value)) && Number(e.value) > 0
324
+ ? Number(e.value)
325
+ : undefined;
326
+ break;
327
+ case "dieline.customSourceHeightPx":
328
+ s.customSourceHeightPx =
329
+ Number.isFinite(Number(e.value)) && Number(e.value) > 0
330
+ ? Number(e.value)
331
+ : undefined;
332
+ break;
333
+ }
334
+ this.updateDieline();
335
+ }
336
+ });
337
+ }
338
+
339
+ context.eventBus.on("canvas:resized", this.onCanvasResized);
340
+ this.updateDieline();
341
+ }
342
+
343
+ deactivate(context: ExtensionContext) {
344
+ context.eventBus.off("canvas:resized", this.onCanvasResized);
345
+ this.renderSeq += 1;
346
+ this.specs = [];
347
+ this.renderProducerDisposable?.dispose();
348
+ this.renderProducerDisposable = undefined;
349
+ if (this.canvasService) {
350
+ void this.canvasService.flushRenderFromProducers();
351
+ }
352
+ this.canvasService = undefined;
353
+ this.context = undefined;
354
+ }
355
+
356
+ contribute() {
357
+ const s = this.state;
358
+ return {
359
+ [ContributionPointIds.TOOLS]: [
360
+ {
361
+ id: this.id,
362
+ name: "Dieline",
363
+ interaction: "session",
364
+ session: {
365
+ autoBegin: false,
366
+ leavePolicy: "block",
367
+ },
368
+ },
369
+ ],
370
+ [ContributionPointIds.CONFIGURATIONS]: [
371
+ {
372
+ id: "dieline.shape",
373
+ type: "select",
374
+ label: "Shape",
375
+ options: Array.from(DIELINE_SHAPES),
376
+ default: s.shape,
377
+ },
378
+ {
379
+ id: "dieline.radius",
380
+ type: "number",
381
+ label: "Corner Radius (mm)",
382
+ min: 0,
383
+ max: 500,
384
+ default: s.radius,
385
+ },
386
+ {
387
+ id: "dieline.shapeStyle",
388
+ type: "json",
389
+ label: "Shape Style",
390
+ default: s.shapeStyle,
391
+ },
392
+ {
393
+ id: "dieline.showBleedLines",
394
+ type: "boolean",
395
+ label: "Show Bleed Lines",
396
+ default: s.showBleedLines,
397
+ },
398
+ {
399
+ id: "dieline.strokeWidth",
400
+ type: "number",
401
+ label: "Line Width",
402
+ min: 0.1,
403
+ max: 10,
404
+ step: 0.1,
405
+ default: s.mainLine.width,
406
+ },
407
+ {
408
+ id: "dieline.strokeColor",
409
+ type: "color",
410
+ label: "Line Color",
411
+ default: s.mainLine.color,
412
+ },
413
+ {
414
+ id: "dieline.dashLength",
415
+ type: "number",
416
+ label: "Dash Length",
417
+ min: 1,
418
+ max: 50,
419
+ default: s.mainLine.dashLength,
420
+ },
421
+ {
422
+ id: "dieline.style",
423
+ type: "select",
424
+ label: "Line Style",
425
+ options: ["solid", "dashed", "hidden"],
426
+ default: s.mainLine.style,
427
+ },
428
+ {
429
+ id: "dieline.offsetStrokeWidth",
430
+ type: "number",
431
+ label: "Offset Line Width",
432
+ min: 0.1,
433
+ max: 10,
434
+ step: 0.1,
435
+ default: s.offsetLine.width,
436
+ },
437
+ {
438
+ id: "dieline.offsetStrokeColor",
439
+ type: "color",
440
+ label: "Offset Line Color",
441
+ default: s.offsetLine.color,
442
+ },
443
+ {
444
+ id: "dieline.offsetDashLength",
445
+ type: "number",
446
+ label: "Offset Dash Length",
447
+ min: 1,
448
+ max: 50,
449
+ default: s.offsetLine.dashLength,
450
+ },
451
+ {
452
+ id: "dieline.offsetStyle",
453
+ type: "select",
454
+ label: "Offset Line Style",
455
+ options: ["solid", "dashed", "hidden"],
456
+ default: s.offsetLine.style,
457
+ },
458
+ {
459
+ id: "dieline.insideColor",
460
+ type: "color",
461
+ label: "Inside Color",
462
+ default: s.insideColor,
463
+ },
464
+ {
465
+ id: "dieline.outsideColor",
466
+ type: "color",
467
+ label: "Outside Color",
468
+ default: s.outsideColor,
469
+ },
470
+ {
471
+ id: "dieline.features",
472
+ type: "json",
473
+ label: "Edge Features",
474
+ default: s.features,
475
+ },
476
+ ] as ConfigurationContribution[],
477
+ [ContributionPointIds.COMMANDS]: [
478
+ {
479
+ command: "updateFeaturePosition",
480
+ title: "Update Feature Position",
481
+ handler: (groupId: string, x: number, y: number) => {
482
+ const configService = this.context?.services.get<any>(
483
+ "ConfigurationService",
484
+ );
485
+ if (!configService) return;
486
+
487
+ const features = configService.get("dieline.features") || [];
488
+
489
+ let changed = false;
490
+ const newFeatures = features.map((f: any) => {
491
+ if (f.groupId === groupId) {
492
+ if (f.x !== x || f.y !== y) {
493
+ changed = true;
494
+ return { ...f, x, y };
495
+ }
496
+ }
497
+ return f;
498
+ });
499
+
500
+ if (changed) {
501
+ configService.update("dieline.features", newFeatures);
502
+ }
503
+ },
504
+ },
505
+ {
506
+ command: "exportCutImage",
507
+ title: "Export Cut Image",
508
+ handler: (options?: { debug?: boolean }) => {
509
+ return this.exportCutImage(options);
510
+ },
511
+ },
512
+ {
513
+ command: "detectEdge",
514
+ title: "Detect Edge from Image",
515
+ handler: async (
516
+ imageUrl: string,
517
+ options?: {
518
+ expand?: number;
519
+ smoothing?: boolean;
520
+ simplifyTolerance?: number;
521
+ threshold?: number;
522
+ debug?: boolean;
523
+ },
524
+ ) => {
525
+ try {
526
+ const detectOptions = options || {};
527
+ const debug = detectOptions.debug === true;
528
+ const tracerOptions = {
529
+ expand: detectOptions.expand ?? 0,
530
+ smoothing: detectOptions.smoothing ?? true,
531
+ simplifyTolerance: detectOptions.simplifyTolerance ?? 2,
532
+ threshold: detectOptions.threshold,
533
+ debug,
534
+ };
535
+
536
+ // Helper to get image dimensions
537
+ const loadImage = (url: string): Promise<HTMLImageElement> => {
538
+ return new Promise((resolve, reject) => {
539
+ const img = new Image();
540
+ img.crossOrigin = "Anonymous";
541
+ img.onload = () => resolve(img);
542
+ img.onerror = (e) => reject(e);
543
+ img.src = url;
544
+ });
545
+ };
546
+
547
+ const [img, traced] = await Promise.all([
548
+ loadImage(imageUrl),
549
+ ImageTracer.traceWithBounds(imageUrl, tracerOptions),
550
+ ]);
551
+ const { pathData, baseBounds, bounds } = traced;
552
+
553
+ if (debug) {
554
+ console.info("[DielineTool] detectEdge", {
555
+ imageWidth: img.width,
556
+ imageHeight: img.height,
557
+ baseBounds,
558
+ expandedBounds: bounds,
559
+ currentDielineWidth: s.width,
560
+ currentDielineHeight: s.height,
561
+ options: tracerOptions,
562
+ strategy: "single-connected-silhouette",
563
+ });
564
+ }
565
+
566
+ return {
567
+ pathData,
568
+ rawBounds: bounds,
569
+ baseBounds,
570
+ imageWidth: img.width,
571
+ imageHeight: img.height,
572
+ };
573
+ } catch (e) {
574
+ console.error("Edge detection failed", e);
575
+ throw e;
576
+ }
577
+ },
578
+ },
579
+ ] as CommandContribution[],
580
+ };
581
+ }
582
+
583
+ private createHatchPattern(color: string = "rgba(0, 0, 0, 0.3)") {
584
+ if (typeof document === "undefined") {
585
+ return undefined;
586
+ }
587
+ const size = 20;
588
+ const canvas = document.createElement("canvas");
589
+ canvas.width = size;
590
+ canvas.height = size;
591
+ const ctx = canvas.getContext("2d");
592
+ if (ctx) {
593
+ // Transparent background
594
+ ctx.clearRect(0, 0, size, size);
595
+
596
+ // Draw diagonal /
597
+ ctx.strokeStyle = color;
598
+ ctx.lineWidth = 1;
599
+ ctx.beginPath();
600
+ ctx.moveTo(0, size);
601
+ ctx.lineTo(size, 0);
602
+ ctx.stroke();
603
+ }
604
+ // @ts-ignore
605
+ return new Pattern({ source: canvas, repetition: "repeat" });
606
+ }
607
+
608
+ private getConfigService(): ConfigurationService | undefined {
609
+ return this.context?.services.get<ConfigurationService>(
610
+ "ConfigurationService",
611
+ );
612
+ }
613
+
614
+ private syncSizeState(configService: ConfigurationService) {
615
+ const sizeState = readSizeState(configService);
616
+ this.state.width = sizeState.actualWidthMm;
617
+ this.state.height = sizeState.actualHeightMm;
618
+ this.state.padding = sizeState.viewPadding;
619
+ this.state.offset =
620
+ sizeState.cutMode === "outset"
621
+ ? sizeState.cutMarginMm
622
+ : sizeState.cutMode === "inset"
623
+ ? -sizeState.cutMarginMm
624
+ : 0;
625
+ }
626
+
627
+ private bringFeatureMarkersToFront() {
628
+ if (!this.canvasService) return;
629
+ const canvas = this.canvasService.canvas;
630
+ canvas
631
+ .getObjects()
632
+ .filter((obj: any) => obj?.data?.type === "feature-marker")
633
+ .forEach((obj: any) => canvas.bringObjectToFront(obj));
634
+ }
635
+
636
+ private ensureLayerStacking() {
637
+ if (!this.canvasService) return;
638
+ const layer = this.canvasService.getLayer(DIELINE_LAYER_ID);
639
+ if (!layer) return;
640
+ const userLayer = this.canvasService.getLayer("user");
641
+ if (userLayer) {
642
+ const layerIndex = this.canvasService.canvas.getObjects().indexOf(layer);
643
+ const userIndex = this.canvasService.canvas
644
+ .getObjects()
645
+ .indexOf(userLayer);
646
+ if (layerIndex < userIndex) {
647
+ this.canvasService.canvas.moveObjectTo(layer, userIndex + 1);
648
+ }
649
+ return;
650
+ }
651
+ this.canvasService.canvas.bringObjectToFront(layer);
652
+ }
653
+
654
+ private buildDielineSpecs(
655
+ sceneLayout: NonNullable<ReturnType<typeof computeSceneLayout>>,
656
+ ): RenderObjectSpec[] {
657
+ const {
658
+ shape,
659
+ shapeStyle,
660
+ radius,
661
+ mainLine,
662
+ offsetLine,
663
+ insideColor,
664
+ outsideColor,
665
+ showBleedLines,
666
+ features,
667
+ } = this.state;
668
+
669
+ const canvasW =
670
+ sceneLayout.canvasWidth || this.canvasService?.canvas.width || 800;
671
+ const canvasH =
672
+ sceneLayout.canvasHeight || this.canvasService?.canvas.height || 600;
673
+ const scale = sceneLayout.scale;
674
+ const cx = sceneLayout.trimRect.centerX;
675
+ const cy = sceneLayout.trimRect.centerY;
676
+
677
+ const visualWidth = sceneLayout.trimRect.width;
678
+ const visualHeight = sceneLayout.trimRect.height;
679
+ const visualRadius = radius * scale;
680
+ const cutW = sceneLayout.cutRect.width;
681
+ const cutH = sceneLayout.cutRect.height;
682
+ const visualOffset = (cutW - visualWidth) / 2;
683
+ const cutR =
684
+ visualRadius === 0 ? 0 : Math.max(0, visualRadius + visualOffset);
685
+
686
+ const absoluteFeatures = (features || []).map((f) => ({
687
+ ...f,
688
+ x: f.x,
689
+ y: f.y,
690
+ width: (f.width || 0) * scale,
691
+ height: (f.height || 0) * scale,
692
+ radius: (f.radius || 0) * scale,
693
+ }));
694
+ const cutFeatures = absoluteFeatures.filter((f) => !f.skipCut);
695
+
696
+ const maskPathData = generateMaskPath({
697
+ canvasWidth: canvasW,
698
+ canvasHeight: canvasH,
699
+ shape,
700
+ width: cutW,
701
+ height: cutH,
702
+ radius: cutR,
703
+ x: cx,
704
+ y: cy,
705
+ features: cutFeatures,
706
+ shapeStyle,
707
+ pathData: this.state.pathData,
708
+ customSourceWidthPx: this.state.customSourceWidthPx,
709
+ customSourceHeightPx: this.state.customSourceHeightPx,
710
+ });
711
+
712
+ const specs: RenderObjectSpec[] = [
713
+ {
714
+ id: "dieline.mask",
715
+ type: "path",
716
+ space: "screen",
717
+ data: { id: "dieline.mask", type: "dieline" },
718
+ props: {
719
+ pathData: maskPathData,
720
+ fill: outsideColor,
721
+ stroke: null,
722
+ selectable: false,
723
+ evented: false,
724
+ originX: "left",
725
+ originY: "top",
726
+ left: 0,
727
+ top: 0,
728
+ },
729
+ },
730
+ ];
731
+
732
+ if (
733
+ insideColor &&
734
+ insideColor !== "transparent" &&
735
+ insideColor !== "rgba(0,0,0,0)"
736
+ ) {
737
+ const productPathData = generateDielinePath({
738
+ shape,
739
+ width: cutW,
740
+ height: cutH,
741
+ radius: cutR,
742
+ x: cx,
743
+ y: cy,
744
+ features: cutFeatures,
745
+ shapeStyle,
746
+ pathData: this.state.pathData,
747
+ customSourceWidthPx: this.state.customSourceWidthPx,
748
+ customSourceHeightPx: this.state.customSourceHeightPx,
749
+ canvasWidth: canvasW,
750
+ canvasHeight: canvasH,
751
+ });
752
+
753
+ specs.push({
754
+ id: "dieline.inside",
755
+ type: "path",
756
+ space: "screen",
757
+ data: { id: "dieline.inside", type: "dieline" },
758
+ props: {
759
+ pathData: productPathData,
760
+ fill: insideColor,
761
+ stroke: null,
762
+ selectable: false,
763
+ evented: false,
764
+ originX: "left",
765
+ originY: "top",
766
+ },
767
+ });
768
+ }
769
+
770
+ if (Math.abs(visualOffset) > 0.0001) {
771
+ const bleedPathData = generateBleedZonePath(
772
+ {
773
+ shape,
774
+ width: visualWidth,
775
+ height: visualHeight,
776
+ radius: visualRadius,
777
+ x: cx,
778
+ y: cy,
779
+ features: cutFeatures,
780
+ shapeStyle,
781
+ pathData: this.state.pathData,
782
+ customSourceWidthPx: this.state.customSourceWidthPx,
783
+ customSourceHeightPx: this.state.customSourceHeightPx,
784
+ canvasWidth: canvasW,
785
+ canvasHeight: canvasH,
786
+ },
787
+ {
788
+ shape,
789
+ width: cutW,
790
+ height: cutH,
791
+ radius: cutR,
792
+ x: cx,
793
+ y: cy,
794
+ features: cutFeatures,
795
+ shapeStyle,
796
+ pathData: this.state.pathData,
797
+ customSourceWidthPx: this.state.customSourceWidthPx,
798
+ customSourceHeightPx: this.state.customSourceHeightPx,
799
+ canvasWidth: canvasW,
800
+ canvasHeight: canvasH,
801
+ },
802
+ visualOffset,
803
+ );
804
+
805
+ if (showBleedLines !== false) {
806
+ const pattern = this.createHatchPattern(mainLine.color);
807
+ if (pattern) {
808
+ specs.push({
809
+ id: "dieline.bleed-zone",
810
+ type: "path",
811
+ space: "screen",
812
+ data: { id: "dieline.bleed-zone", type: "dieline" },
813
+ props: {
814
+ pathData: bleedPathData,
815
+ fill: pattern,
816
+ stroke: null,
817
+ selectable: false,
818
+ evented: false,
819
+ objectCaching: false,
820
+ originX: "left",
821
+ originY: "top",
822
+ },
823
+ });
824
+ }
825
+ }
826
+
827
+ const offsetPathData = generateDielinePath({
828
+ shape,
829
+ width: cutW,
830
+ height: cutH,
831
+ radius: cutR,
832
+ x: cx,
833
+ y: cy,
834
+ features: cutFeatures,
835
+ shapeStyle,
836
+ pathData: this.state.pathData,
837
+ customSourceWidthPx: this.state.customSourceWidthPx,
838
+ customSourceHeightPx: this.state.customSourceHeightPx,
839
+ canvasWidth: canvasW,
840
+ canvasHeight: canvasH,
841
+ });
842
+
843
+ specs.push({
844
+ id: "dieline.offset-border",
845
+ type: "path",
846
+ space: "screen",
847
+ data: { id: "dieline.offset-border", type: "dieline" },
848
+ props: {
849
+ pathData: offsetPathData,
850
+ fill: null,
851
+ stroke: offsetLine.style === "hidden" ? null : offsetLine.color,
852
+ strokeWidth: offsetLine.width,
853
+ strokeDashArray:
854
+ offsetLine.style === "dashed"
855
+ ? [offsetLine.dashLength, offsetLine.dashLength]
856
+ : undefined,
857
+ selectable: false,
858
+ evented: false,
859
+ originX: "left",
860
+ originY: "top",
861
+ },
862
+ });
863
+ }
864
+
865
+ const borderPathData = generateDielinePath({
866
+ shape,
867
+ width: visualWidth,
868
+ height: visualHeight,
869
+ radius: visualRadius,
870
+ x: cx,
871
+ y: cy,
872
+ features: absoluteFeatures,
873
+ shapeStyle,
874
+ pathData: this.state.pathData,
875
+ customSourceWidthPx: this.state.customSourceWidthPx,
876
+ customSourceHeightPx: this.state.customSourceHeightPx,
877
+ canvasWidth: canvasW,
878
+ canvasHeight: canvasH,
879
+ });
880
+
881
+ specs.push({
882
+ id: "dieline.border",
883
+ type: "path",
884
+ space: "screen",
885
+ data: { id: "dieline.border", type: "dieline" },
886
+ props: {
887
+ pathData: borderPathData,
888
+ fill: "transparent",
889
+ stroke: mainLine.style === "hidden" ? null : mainLine.color,
890
+ strokeWidth: mainLine.width,
891
+ strokeDashArray:
892
+ mainLine.style === "dashed"
893
+ ? [mainLine.dashLength, mainLine.dashLength]
894
+ : undefined,
895
+ selectable: false,
896
+ evented: false,
897
+ originX: "left",
898
+ originY: "top",
899
+ },
900
+ });
901
+
902
+ return specs;
903
+ }
904
+
905
+ public updateDieline(_emitEvent: boolean = true) {
906
+ void this.updateDielineAsync();
907
+ }
908
+
909
+ private async updateDielineAsync() {
910
+ if (!this.canvasService) return;
911
+ const configService = this.getConfigService();
912
+ if (!configService) return;
913
+ const seq = ++this.renderSeq;
914
+
915
+ this.syncSizeState(configService);
916
+ const sceneLayout = computeSceneLayout(
917
+ this.canvasService,
918
+ readSizeState(configService),
919
+ );
920
+ if (!sceneLayout) {
921
+ if (seq !== this.renderSeq) return;
922
+ this.specs = [];
923
+ await this.canvasService.flushRenderFromProducers();
924
+ return;
925
+ }
926
+
927
+ const nextSpecs = this.buildDielineSpecs(sceneLayout);
928
+ if (seq !== this.renderSeq) return;
929
+ this.specs = nextSpecs;
930
+ await this.canvasService.flushRenderFromProducers();
931
+ if (seq !== this.renderSeq) return;
932
+
933
+ this.ensureLayerStacking();
934
+
935
+ // Feature tool markers can extend outside trim. Keep them above dieline mask.
936
+ this.bringFeatureMarkersToFront();
937
+ this.canvasService.bringLayerToFront("ruler-overlay");
938
+ this.canvasService.requestRenderAll();
939
+ }
940
+
941
+ public getGeometry(): DielineGeometry | null {
942
+ if (!this.canvasService) return null;
943
+ const configService = this.getConfigService();
944
+ if (!configService) return null;
945
+ const sceneLayout = computeSceneLayout(
946
+ this.canvasService,
947
+ readSizeState(configService),
948
+ );
949
+ if (!sceneLayout) return null;
950
+ const sceneGeometry = buildSceneGeometry(configService, sceneLayout);
951
+ return {
952
+ ...sceneGeometry,
953
+ strokeWidth: this.state.mainLine.width,
954
+ pathData: this.state.pathData,
955
+ customSourceWidthPx: this.state.customSourceWidthPx,
956
+ customSourceHeightPx: this.state.customSourceHeightPx,
957
+ } as DielineGeometry;
958
+ }
959
+
960
+ public async exportCutImage(options?: { debug?: boolean }) {
961
+ const debug = options?.debug === true;
962
+
963
+ if (!this.canvasService) {
964
+ console.warn(
965
+ "[DielineTool] exportCutImage returned null: canvas-not-ready",
966
+ );
967
+ return null;
968
+ }
969
+ const configService = this.getConfigService();
970
+ if (!configService) {
971
+ console.warn(
972
+ "[DielineTool] exportCutImage returned null: config-service-not-ready",
973
+ );
974
+ return null;
975
+ }
976
+
977
+ this.syncSizeState(configService);
978
+ const sceneLayout = computeSceneLayout(
979
+ this.canvasService,
980
+ readSizeState(configService),
981
+ );
982
+ if (!sceneLayout) {
983
+ console.warn(
984
+ "[DielineTool] exportCutImage returned null: scene-layout-null",
985
+ );
986
+ return null;
987
+ }
988
+
989
+ const { shape, shapeStyle, radius, features, pathData } = this.state;
990
+ const canvasW =
991
+ sceneLayout.canvasWidth || this.canvasService.canvas.width || 800;
992
+ const canvasH =
993
+ sceneLayout.canvasHeight || this.canvasService.canvas.height || 600;
994
+ const scale = sceneLayout.scale;
995
+ const cx = sceneLayout.trimRect.centerX;
996
+ const cy = sceneLayout.trimRect.centerY;
997
+ const cutW = sceneLayout.cutRect.width;
998
+ const cutH = sceneLayout.cutRect.height;
999
+ const visualRadius = radius * scale;
1000
+ const visualOffset = (cutW - sceneLayout.trimRect.width) / 2;
1001
+ const cutR =
1002
+ visualRadius === 0 ? 0 : Math.max(0, visualRadius + visualOffset);
1003
+
1004
+ const absoluteFeatures = (features || []).map((f) => ({
1005
+ ...f,
1006
+ x: f.x,
1007
+ y: f.y,
1008
+ width: (f.width || 0) * scale,
1009
+ height: (f.height || 0) * scale,
1010
+ radius: (f.radius || 0) * scale,
1011
+ }));
1012
+ const cutFeatures = absoluteFeatures.filter((f) => !f.skipCut);
1013
+
1014
+ const generatedPathData = generateDielinePath({
1015
+ shape,
1016
+ width: cutW,
1017
+ height: cutH,
1018
+ radius: cutR,
1019
+ x: cx,
1020
+ y: cy,
1021
+ features: cutFeatures,
1022
+ shapeStyle,
1023
+ pathData,
1024
+ customSourceWidthPx: this.state.customSourceWidthPx,
1025
+ customSourceHeightPx: this.state.customSourceHeightPx,
1026
+ canvasWidth: canvasW,
1027
+ canvasHeight: canvasH,
1028
+ });
1029
+
1030
+ const clipPath = new Path(generatedPathData, {
1031
+ originX: "center",
1032
+ originY: "center",
1033
+ left: cx,
1034
+ top: cy,
1035
+ absolutePositioned: true,
1036
+ });
1037
+ const pathOffsetX = Number((clipPath as any)?.pathOffset?.x);
1038
+ const pathOffsetY = Number((clipPath as any)?.pathOffset?.y);
1039
+ const centerX = Number.isFinite(pathOffsetX) ? pathOffsetX : cx;
1040
+ const centerY = Number.isFinite(pathOffsetY) ? pathOffsetY : cy;
1041
+ clipPath.set({
1042
+ originX: "center",
1043
+ originY: "center",
1044
+ left: centerX,
1045
+ top: centerY,
1046
+ absolutePositioned: true,
1047
+ });
1048
+ clipPath.setCoords();
1049
+
1050
+ const pathBounds = clipPath.getBoundingRect();
1051
+ if (
1052
+ !Number.isFinite(pathBounds.left) ||
1053
+ !Number.isFinite(pathBounds.top) ||
1054
+ !Number.isFinite(pathBounds.width) ||
1055
+ !Number.isFinite(pathBounds.height) ||
1056
+ pathBounds.width <= 0 ||
1057
+ pathBounds.height <= 0
1058
+ ) {
1059
+ console.warn(
1060
+ "[DielineTool] exportCutImage returned null: invalid-cut-bounds",
1061
+ {
1062
+ bounds: pathBounds,
1063
+ },
1064
+ );
1065
+ return null;
1066
+ }
1067
+ const exportBounds = pathBounds;
1068
+
1069
+ const sourceImages = this.canvasService.canvas
1070
+ .getObjects()
1071
+ .filter((obj: any) => {
1072
+ return obj?.data?.layerId === IMAGE_OBJECT_LAYER_ID;
1073
+ });
1074
+ if (!sourceImages.length) {
1075
+ console.warn(
1076
+ "[DielineTool] exportCutImage returned null: no-image-objects-on-canvas",
1077
+ );
1078
+ return null;
1079
+ }
1080
+
1081
+ const sourceCanvasWidth = Number(
1082
+ this.canvasService.canvas.width || sceneLayout.canvasWidth || canvasW,
1083
+ );
1084
+ const sourceCanvasHeight = Number(
1085
+ this.canvasService.canvas.height || sceneLayout.canvasHeight || canvasH,
1086
+ );
1087
+
1088
+ const el = document.createElement("canvas");
1089
+ const exportCanvas = new FabricCanvas(el, {
1090
+ renderOnAddRemove: false,
1091
+ selection: false,
1092
+ enableRetinaScaling: false,
1093
+ preserveObjectStacking: true,
1094
+ } as any);
1095
+ exportCanvas.setDimensions({
1096
+ width: Math.max(1, sourceCanvasWidth),
1097
+ height: Math.max(1, sourceCanvasHeight),
1098
+ });
1099
+
1100
+ try {
1101
+ for (const source of sourceImages as any[]) {
1102
+ const clone = await source.clone();
1103
+ clone.set({
1104
+ selectable: false,
1105
+ evented: false,
1106
+ });
1107
+ clone.setCoords();
1108
+ exportCanvas.add(clone);
1109
+ }
1110
+
1111
+ exportCanvas.clipPath = clipPath;
1112
+ exportCanvas.renderAll();
1113
+
1114
+ const dataUrl = exportCanvas.toDataURL({
1115
+ format: "png",
1116
+ multiplier: 2,
1117
+ left: exportBounds.left,
1118
+ top: exportBounds.top,
1119
+ width: exportBounds.width,
1120
+ height: exportBounds.height,
1121
+ });
1122
+
1123
+ if (debug) {
1124
+ console.info("[DielineTool] exportCutImage success", {
1125
+ sourceCount: sourceImages.length,
1126
+ bounds: exportBounds,
1127
+ rawPathBounds: pathBounds,
1128
+ pathOffset: {
1129
+ x: Number.isFinite(pathOffsetX) ? pathOffsetX : null,
1130
+ y: Number.isFinite(pathOffsetY) ? pathOffsetY : null,
1131
+ },
1132
+ clipPathCenter: {
1133
+ x: centerX,
1134
+ y: centerY,
1135
+ },
1136
+ cutRect: sceneLayout.cutRect,
1137
+ canvasSize: {
1138
+ width: Math.max(1, sourceCanvasWidth),
1139
+ height: Math.max(1, sourceCanvasHeight),
1140
+ },
1141
+ });
1142
+ }
1143
+
1144
+ return dataUrl;
1145
+ } finally {
1146
+ exportCanvas.dispose();
1147
+ }
1148
+ }
1149
+ }