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