@pooder/kit 5.4.0 → 6.0.1

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