@pooder/kit 1.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/dieline.ts CHANGED
@@ -1,421 +1,780 @@
1
- import { Command, Editor, EditorState, Extension, OptionSchema, Rect, Circle, Ellipse, Path, PooderLayer, Pattern } from '@pooder/core';
2
- import { generateDielinePath, generateMaskPath, generateBleedZonePath, HoleData } from './geometry';
3
-
4
- export interface DielineToolOptions {
5
- shape: 'rect' | 'circle' | 'ellipse';
6
- width: number;
7
- height: number;
8
- radius: number; // corner radius for rect
9
- position?: { x: number, y: number };
10
- borderLength?: number;
11
- offset: number;
12
- style: 'solid' | 'dashed';
13
- insideColor: string;
14
- outsideColor: string;
15
- }
16
-
17
- // Alias for compatibility if needed, or just use DielineToolOptions
18
- export type DielineConfig = DielineToolOptions;
19
-
20
- export interface DielineGeometry {
21
- shape: 'rect' | 'circle' | 'ellipse';
22
- x: number;
23
- y: number;
24
- width: number;
25
- height: number;
26
- radius: number;
27
- }
28
-
29
- export class DielineTool implements Extension<DielineToolOptions> {
30
- public name = 'DielineTool';
31
- public options: DielineToolOptions = {
32
- shape: 'rect',
33
- width: 300,
34
- height: 300,
35
- radius: 0,
36
- offset: 0,
37
- style: 'solid',
38
- insideColor: 'rgba(0,0,0,0)',
39
- outsideColor: '#ffffff'
40
- };
41
-
42
- public schema: Record<keyof DielineToolOptions, OptionSchema> = {
43
- shape: {
44
- type: 'select',
45
- options: ['rect', 'circle', 'ellipse'],
46
- label: 'Shape'
47
- },
48
- width: { type: 'number', min: 10, max: 2000, label: 'Width' },
49
- height: { type: 'number', min: 10, max: 2000, label: 'Height' },
50
- radius: { type: 'number', min: 0, max: 500, label: 'Corner Radius' },
51
- position: { type: 'string', label: 'Position' }, // Complex object, simplified for now or need custom handler
52
- borderLength: { type: 'number', min: 0, max: 500, label: 'Margin' },
53
- offset: { type: 'number', min: -100, max: 100, label: 'Bleed Offset' },
54
- style: {
55
- type: 'select',
56
- options: ['solid', 'dashed'],
57
- label: 'Line Style'
58
- },
59
- insideColor: { type: 'color', label: 'Inside Color' },
60
- outsideColor: { type: 'color', label: 'Outside Color' }
61
- };
62
-
63
- onMount(editor: Editor) {
64
- this.createLayer(editor);
65
- this.updateDieline(editor);
66
- }
67
-
68
- onUnmount(editor: Editor) {
69
- this.destroyLayer(editor);
70
- }
71
-
72
- onUpdate(editor: Editor, state: EditorState) {
73
- this.updateDieline(editor);
74
- }
75
-
76
- onDestroy(editor: Editor) {
77
- this.destroyLayer(editor);
78
- }
79
-
80
- private getLayer(editor: Editor, id: string) {
81
- return editor.canvas.getObjects().find((obj: any) => obj.data?.id === id) as PooderLayer | undefined;
82
- }
83
-
84
- private createLayer(editor: Editor) {
85
- let layer = this.getLayer(editor, 'dieline-overlay');
86
-
87
- if (!layer) {
88
- const width = editor.canvas.width || 800;
89
- const height = editor.canvas.height || 600;
90
-
91
- layer = new PooderLayer([], {
92
- width,
93
- height,
94
- selectable: false,
95
- evented: false,
96
- data: { id: 'dieline-overlay' }
97
- }as any);
98
-
99
- editor.canvas.add(layer);
100
- }
101
-
102
- editor.canvas.bringObjectToFront(layer);
103
- }
104
-
105
- private destroyLayer(editor: Editor) {
106
- const layer = this.getLayer(editor, 'dieline-overlay');
107
- if (layer) {
108
- editor.canvas.remove(layer);
109
- }
110
- }
111
-
112
- private createHatchPattern(color: string = 'rgba(0, 0, 0, 0.3)') {
113
- if (typeof document === 'undefined') {
114
- return undefined;
115
- }
116
- const size = 20;
117
- const canvas = document.createElement('canvas');
118
- canvas.width = size;
119
- canvas.height = size;
120
- const ctx = canvas.getContext('2d');
121
- if (ctx) {
122
- // Transparent background
123
- ctx.clearRect(0, 0, size, size);
124
-
125
- // Draw diagonal /
126
- ctx.strokeStyle = color;
127
- ctx.lineWidth = 1;
128
- ctx.beginPath();
129
- ctx.moveTo(0, size);
130
- ctx.lineTo(size, 0);
131
- ctx.stroke();
132
- }
133
- // @ts-ignore
134
- return new Pattern({ source: canvas, repetition: 'repeat' });
135
- }
136
-
137
- public updateDieline(editor: Editor) {
138
- const { shape, radius, offset, style, insideColor, outsideColor, position, borderLength } = this.options;
139
- let { width, height } = this.options;
140
-
141
- const canvasW = editor.canvas.width || 800;
142
- const canvasH = editor.canvas.height || 600;
143
-
144
- // Handle borderLength (Margin)
145
- if (borderLength && borderLength > 0) {
146
- width = Math.max(0, canvasW - borderLength * 2);
147
- height = Math.max(0, canvasH - borderLength * 2);
148
- }
149
-
150
- // Handle Position
151
- const cx = position?.x ?? canvasW / 2;
152
- const cy = position?.y ?? canvasH / 2;
153
-
154
- const layer = this.getLayer(editor, 'dieline-overlay');
155
- if (!layer) return;
156
-
157
- // Clear existing objects
158
- layer.remove(...layer.getObjects());
159
-
160
- // Get Hole Data
161
- const holeTool = editor.getExtension('HoleTool') as any;
162
- const holes = holeTool ? (holeTool.options.holes || []) : [];
163
- const innerRadius = holeTool ? (holeTool.options.innerRadius || 15) : 15;
164
- const outerRadius = holeTool ? (holeTool.options.outerRadius || 25) : 25;
165
-
166
- const holeData: HoleData[] = holes.map((h: any) => ({
167
- x: h.x,
168
- y: h.y,
169
- innerRadius,
170
- outerRadius
171
- }));
172
-
173
- // 1. Draw Mask (Outside)
174
- const cutW = Math.max(0, width + offset * 2);
175
- const cutH = Math.max(0, height + offset * 2);
176
- const cutR = radius === 0 ? 0 : Math.max(0, radius + offset);
177
-
178
- // Use Paper.js to generate the complex mask path
179
- const maskPathData = generateMaskPath({
180
- canvasWidth: canvasW,
181
- canvasHeight: canvasH,
182
- shape,
183
- width: cutW,
184
- height: cutH,
185
- radius: cutR,
186
- x: cx,
187
- y: cy,
188
- holes: holeData
189
- });
190
-
191
- const mask = new Path(maskPathData, {
192
- fill: outsideColor,
193
- stroke: null,
194
- selectable: false,
195
- evented: false,
196
- originX: 'left' as const,
197
- originY: 'top' as const,
198
- left: 0,
199
- top: 0
200
- });
201
- layer.add(mask);
202
-
203
- // 2. Draw Inside Fill (Dieline Shape itself, merged with holes if needed, or just the shape?)
204
- // The user wants "fusion effect" so holes should be part of the dieline visually.
205
- // If insideColor is transparent, it doesn't matter much.
206
- // If insideColor is opaque, we need to punch holes in it too.
207
- // Let's use Paper.js for this too if insideColor is not transparent.
208
-
209
- if (insideColor && insideColor !== 'transparent' && insideColor !== 'rgba(0,0,0,0)') {
210
- // Generate path for the product shape (Paper) = Dieline - Holes
211
- const productPathData = generateDielinePath({
212
- shape,
213
- width: cutW,
214
- height: cutH,
215
- radius: cutR,
216
- x: cx,
217
- y: cy,
218
- holes: holeData
219
- });
220
-
221
- const insideObj = new Path(productPathData, {
222
- fill: insideColor,
223
- stroke: null,
224
- selectable: false,
225
- evented: false,
226
- originX: 'left', // paper.js paths are absolute
227
- originY: 'top'
228
- });
229
- layer.add(insideObj);
230
- }
231
-
232
- // 3. Draw Bleed Zone (Hatch Fill) and Offset Border
233
- if (offset !== 0) {
234
- const bleedPathData = generateBleedZonePath({
235
- shape,
236
- width,
237
- height,
238
- radius,
239
- x: cx,
240
- y: cy,
241
- holes: holeData
242
- }, offset);
243
-
244
- // Use solid red for hatch lines to match dieline, background is transparent
245
- const pattern = this.createHatchPattern('red');
246
- if (pattern) {
247
- const bleedObj = new Path(bleedPathData, {
248
- fill: pattern,
249
- stroke: null,
250
- selectable: false,
251
- evented: false,
252
- objectCaching: false,
253
- originX: 'left',
254
- originY: 'top'
255
- });
256
- layer.add(bleedObj);
257
- }
258
-
259
- // Offset Dieline Border
260
- const offsetPathData = generateDielinePath({
261
- shape,
262
- width: cutW,
263
- height: cutH,
264
- radius: cutR,
265
- x: cx,
266
- y: cy,
267
- holes: holeData
268
- });
269
-
270
- const offsetBorderObj = new Path(offsetPathData, {
271
- fill: null,
272
- stroke: '#666', // Grey
273
- strokeWidth: 1,
274
- strokeDashArray: [4, 4], // Dashed
275
- selectable: false,
276
- evented: false,
277
- originX: 'left',
278
- originY: 'top'
279
- });
280
- layer.add(offsetBorderObj);
281
- }
282
-
283
- // 4. Draw Dieline (Visual Border)
284
- // This should outline the product shape AND the holes.
285
- // Paper.js `generateDielinePath` returns exactly this (Dieline - Holes).
286
-
287
- const borderPathData = generateDielinePath({
288
- shape,
289
- width: width,
290
- height: height,
291
- radius: radius,
292
- x: cx,
293
- y: cy,
294
- holes: holeData
295
- });
296
-
297
- const borderObj = new Path(borderPathData, {
298
- fill: 'transparent',
299
- stroke: 'red',
300
- strokeWidth: 1,
301
- strokeDashArray: style === 'dashed' ? [5, 5] : undefined,
302
- selectable: false,
303
- evented: false,
304
- originX: 'left',
305
- originY: 'top'
306
- });
307
-
308
- layer.add(borderObj);
309
-
310
- editor.canvas.requestRenderAll();
311
- }
312
-
313
- commands: Record<string, Command> = {
314
- reset: {
315
- execute: (editor: Editor) => {
316
- this.options = {
317
- shape: 'rect',
318
- width: 300,
319
- height: 300,
320
- radius: 0,
321
- offset: 0,
322
- style: 'solid',
323
- insideColor: 'rgba(0,0,0,0)',
324
- outsideColor: '#ffffff'
325
- };
326
- this.updateDieline(editor);
327
- return true;
328
- }
329
- },
330
- destroy: {
331
- execute: (editor: Editor) => {
332
- this.destroyLayer(editor);
333
- return true;
334
- }
335
- },
336
- setDimensions: {
337
- execute: (editor: Editor, width: number, height: number) => {
338
- if (this.options.width === width && this.options.height === height) return true;
339
- this.options.width = width;
340
- this.options.height = height;
341
- this.updateDieline(editor);
342
- return true;
343
- },
344
- schema: {
345
- width: {
346
- type: 'number',
347
- label: 'Width',
348
- min: 10,
349
- max: 2000,
350
- required: true
351
- },
352
- height: {
353
- type: 'number',
354
- label: 'Height',
355
- min: 10,
356
- max: 2000,
357
- required: true
358
- }
359
- }
360
- },
361
- setShape: {
362
- execute: (editor: Editor, shape: 'rect' | 'circle' | 'ellipse') => {
363
- if (this.options.shape === shape) return true;
364
- this.options.shape = shape;
365
- this.updateDieline(editor);
366
- return true;
367
- },
368
- schema: {
369
- shape: {
370
- type: 'string',
371
- label: 'Shape',
372
- options: ['rect', 'circle', 'ellipse'],
373
- required: true
374
- }
375
- }
376
- },
377
- setBleed: {
378
- execute: (editor: Editor, bleed: number) => {
379
- if (this.options.offset === bleed) return true;
380
- this.options.offset = bleed;
381
- this.updateDieline(editor);
382
- return true;
383
- },
384
- schema: {
385
- bleed: {
386
- type: 'number',
387
- label: 'Bleed',
388
- min: -100,
389
- max: 100,
390
- required: true
391
- }
392
- }
393
- }
394
- };
395
-
396
- public getGeometry(editor: Editor): DielineGeometry | null {
397
- const { shape, width, height, radius, position, borderLength } = this.options;
398
- const canvasW = editor.canvas.width || 800;
399
- const canvasH = editor.canvas.height || 600;
400
-
401
- let visualWidth = width;
402
- let visualHeight = height;
403
-
404
- if (borderLength && borderLength > 0) {
405
- visualWidth = Math.max(0, canvasW - borderLength * 2);
406
- visualHeight = Math.max(0, canvasH - borderLength * 2);
407
- }
408
-
409
- const cx = position?.x ?? canvasW / 2;
410
- const cy = position?.y ?? canvasH / 2;
411
-
412
- return {
413
- shape,
414
- x: cx,
415
- y: cy,
416
- width: visualWidth,
417
- height: visualHeight,
418
- radius
419
- };
420
- }
421
- }
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 { Coordinate } from "./coordinate";
12
+ import {
13
+ generateDielinePath,
14
+ generateMaskPath,
15
+ generateBleedZonePath,
16
+ getPathBounds,
17
+ HoleData,
18
+ } from "./geometry";
19
+
20
+ export interface DielineGeometry {
21
+ shape: "rect" | "circle" | "ellipse" | "custom";
22
+ x: number;
23
+ y: number;
24
+ width: number;
25
+ height: number;
26
+ radius: number;
27
+ offset: number;
28
+ borderLength?: number;
29
+ pathData?: string;
30
+ }
31
+
32
+ export class DielineTool implements Extension {
33
+ id = "pooder.kit.dieline";
34
+ public metadata = {
35
+ name: "DielineTool",
36
+ };
37
+
38
+ private shape: "rect" | "circle" | "ellipse" | "custom" = "rect";
39
+ private width: number = 500;
40
+ private height: number = 500;
41
+ private radius: number = 0;
42
+ private offset: number = 0;
43
+ private style: "solid" | "dashed" = "solid";
44
+ private insideColor: string = "rgba(0,0,0,0)";
45
+ private outsideColor: string = "#ffffff";
46
+ private showBleedLines: boolean = true;
47
+ private holes: HoleData[] = [];
48
+ // Position is stored as normalized coordinates (0-1)
49
+ private position?: { x: number; y: number };
50
+ private borderLength?: number;
51
+ private pathData?: string;
52
+
53
+ private canvasService?: CanvasService;
54
+ private context?: ExtensionContext;
55
+
56
+ constructor(
57
+ options?: Partial<{
58
+ shape: "rect" | "circle" | "ellipse" | "custom";
59
+ width: number;
60
+ height: number;
61
+ radius: number;
62
+ // Position is normalized (0-1)
63
+ position: { x: number; y: number };
64
+ borderLength: number;
65
+ offset: number;
66
+ style: "solid" | "dashed";
67
+ insideColor: string;
68
+ outsideColor: string;
69
+ showBleedLines: boolean;
70
+ holes: HoleData[];
71
+ pathData: string;
72
+ }>,
73
+ ) {
74
+ if (options) {
75
+ Object.assign(this, options);
76
+ }
77
+ }
78
+
79
+ activate(context: ExtensionContext) {
80
+ this.context = context;
81
+ this.canvasService = context.services.get<CanvasService>("CanvasService");
82
+ if (!this.canvasService) {
83
+ console.warn("CanvasService not found for DielineTool");
84
+ return;
85
+ }
86
+
87
+ const configService = context.services.get<any>("ConfigurationService");
88
+ if (configService) {
89
+ // Load initial config
90
+ this.shape = configService.get("dieline.shape", this.shape);
91
+ this.width = configService.get("dieline.width", this.width);
92
+ this.height = configService.get("dieline.height", this.height);
93
+ this.radius = configService.get("dieline.radius", this.radius);
94
+ this.borderLength = configService.get(
95
+ "dieline.borderLength",
96
+ this.borderLength,
97
+ );
98
+ this.offset = configService.get("dieline.offset", this.offset);
99
+ this.style = configService.get("dieline.style", this.style);
100
+ this.insideColor = configService.get(
101
+ "dieline.insideColor",
102
+ this.insideColor,
103
+ );
104
+ this.outsideColor = configService.get(
105
+ "dieline.outsideColor",
106
+ this.outsideColor,
107
+ );
108
+ this.showBleedLines = configService.get(
109
+ "dieline.showBleedLines",
110
+ this.showBleedLines,
111
+ );
112
+ this.holes = configService.get("dieline.holes", this.holes);
113
+ this.pathData = configService.get("dieline.pathData", this.pathData);
114
+
115
+ // Listen for changes
116
+ configService.onAnyChange((e: { key: string; value: any }) => {
117
+ if (e.key.startsWith("dieline.")) {
118
+ const prop = e.key.split(".")[1];
119
+ console.log(
120
+ `[DielineTool] Config change detected: ${e.key} -> ${e.value}`,
121
+ );
122
+ if (prop && prop in this) {
123
+ (this as any)[prop] = e.value;
124
+ this.updateDieline();
125
+ }
126
+ }
127
+ });
128
+ }
129
+
130
+ this.createLayer();
131
+ this.updateDieline();
132
+ }
133
+
134
+ deactivate(context: ExtensionContext) {
135
+ this.destroyLayer();
136
+ this.canvasService = undefined;
137
+ this.context = undefined;
138
+ }
139
+
140
+ contribute() {
141
+ return {
142
+ [ContributionPointIds.CONFIGURATIONS]: [
143
+ {
144
+ id: "dieline.shape",
145
+ type: "select",
146
+ label: "Shape",
147
+ options: ["rect", "circle", "ellipse", "custom"],
148
+ default: this.shape,
149
+ },
150
+ {
151
+ id: "dieline.width",
152
+ type: "number",
153
+ label: "Width",
154
+ min: 10,
155
+ max: 2000,
156
+ default: this.width,
157
+ },
158
+ {
159
+ id: "dieline.height",
160
+ type: "number",
161
+ label: "Height",
162
+ min: 10,
163
+ max: 2000,
164
+ default: this.height,
165
+ },
166
+ {
167
+ id: "dieline.radius",
168
+ type: "number",
169
+ label: "Corner Radius",
170
+ min: 0,
171
+ max: 500,
172
+ default: this.radius,
173
+ },
174
+ {
175
+ id: "dieline.position",
176
+ type: "json",
177
+ label: "Position (Normalized)",
178
+ default: this.position,
179
+ },
180
+ {
181
+ id: "dieline.borderLength",
182
+ type: "number",
183
+ label: "Margin",
184
+ min: 0,
185
+ max: 500,
186
+ default: this.borderLength,
187
+ },
188
+ {
189
+ id: "dieline.offset",
190
+ type: "number",
191
+ label: "Bleed Offset",
192
+ min: -100,
193
+ max: 100,
194
+ default: this.offset,
195
+ },
196
+ {
197
+ id: "dieline.showBleedLines",
198
+ type: "boolean",
199
+ label: "Show Bleed Lines",
200
+ default: this.showBleedLines,
201
+ },
202
+ {
203
+ id: "dieline.style",
204
+ type: "select",
205
+ label: "Line Style",
206
+ options: ["solid", "dashed"],
207
+ default: this.style,
208
+ },
209
+ {
210
+ id: "dieline.insideColor",
211
+ type: "color",
212
+ label: "Inside Color",
213
+ default: this.insideColor,
214
+ },
215
+ {
216
+ id: "dieline.outsideColor",
217
+ type: "color",
218
+ label: "Outside Color",
219
+ default: this.outsideColor,
220
+ },
221
+ {
222
+ id: "dieline.holes",
223
+ type: "json",
224
+ label: "Holes",
225
+ default: this.holes,
226
+ },
227
+ ] as ConfigurationContribution[],
228
+ [ContributionPointIds.COMMANDS]: [
229
+ {
230
+ command: "reset",
231
+ title: "Reset Dieline",
232
+ handler: () => {
233
+ this.shape = "rect";
234
+ this.width = 300;
235
+ this.height = 300;
236
+ this.radius = 0;
237
+ this.offset = 0;
238
+ this.style = "solid";
239
+ this.insideColor = "rgba(0,0,0,0)";
240
+ this.outsideColor = "#ffffff";
241
+ this.showBleedLines = true;
242
+ this.holes = [];
243
+ this.pathData = undefined;
244
+ this.updateDieline();
245
+ return true;
246
+ },
247
+ },
248
+ {
249
+ command: "setDimensions",
250
+ title: "Set Dimensions",
251
+ handler: (width: number, height: number) => {
252
+ if (this.width === width && this.height === height) return true;
253
+ this.width = width;
254
+ this.height = height;
255
+ this.updateDieline();
256
+ return true;
257
+ },
258
+ },
259
+ {
260
+ command: "setShape",
261
+ title: "Set Shape",
262
+ handler: (shape: "rect" | "circle" | "ellipse" | "custom") => {
263
+ if (this.shape === shape) return true;
264
+ this.shape = shape;
265
+ this.updateDieline();
266
+ return true;
267
+ },
268
+ },
269
+ {
270
+ command: "setBleed",
271
+ title: "Set Bleed",
272
+ handler: (bleed: number) => {
273
+ if (this.offset === bleed) return true;
274
+ this.offset = bleed;
275
+ this.updateDieline();
276
+ return true;
277
+ },
278
+ },
279
+ {
280
+ command: "setHoles",
281
+ title: "Set Holes",
282
+ handler: (holes: HoleData[]) => {
283
+ this.holes = holes;
284
+ this.updateDieline(false);
285
+ return true;
286
+ },
287
+ },
288
+ {
289
+ command: "getGeometry",
290
+ title: "Get Geometry",
291
+ handler: () => {
292
+ return this.getGeometry();
293
+ },
294
+ },
295
+ {
296
+ command: "exportCutImage",
297
+ title: "Export Cut Image",
298
+ handler: () => {
299
+ return this.exportCutImage();
300
+ },
301
+ },
302
+ {
303
+ command: "detectEdge",
304
+ title: "Detect Edge from Image",
305
+ handler: async (imageUrl: string, options?: any) => {
306
+ try {
307
+ // Pass current dimensions if we want to scale immediately?
308
+ // But wait, the user said "It should be scaled according to width and height".
309
+ // If the user already set width/height on the tool, we should respect it?
310
+ // Or should we set width/height based on the image aspect ratio?
311
+ // Usually for a new trace, we might want to respect the IMAGE aspect ratio but fit into current width/height?
312
+ // Or just replace width/height with image dimensions?
313
+ // Let's assume we want to keep the current "box" size but fit the shape inside?
314
+ // Or if options has width/height use that.
315
+
316
+ // Let's first trace to get the natural shape (and its aspect ratio)
317
+ // Then we can decide how to update this.width/this.height.
318
+
319
+ const pathData = await ImageTracer.trace(imageUrl, options);
320
+
321
+ // We need to set width/height from the path bounds to avoid distortion
322
+ const bounds = getPathBounds(pathData);
323
+
324
+ // If we want to scale the path to specific dimensions, we can do it via ImageTracer options.scaleToWidth/Height
325
+ // But here we got the raw path.
326
+ // Let's update the TOOL's dimensions to match the detected shape's aspect ratio,
327
+ // while keeping the size reasonable (e.g. max dimension 300 or current size).
328
+
329
+ // If current tool size is default 300x300, we might want to resize tool to match image ratio.
330
+ const currentMax = Math.max(this.width, this.height);
331
+ const scale = currentMax / Math.max(bounds.width, bounds.height);
332
+
333
+ this.width = bounds.width * scale;
334
+ this.height = bounds.height * scale;
335
+
336
+ this.shape = "custom";
337
+ this.pathData = pathData;
338
+
339
+ this.updateDieline();
340
+ return pathData;
341
+ } catch (e) {
342
+ console.error("Edge detection failed", e);
343
+ throw e;
344
+ }
345
+ },
346
+ },
347
+ ] as CommandContribution[],
348
+ };
349
+ }
350
+
351
+ private getLayer() {
352
+ return this.canvasService?.getLayer("dieline-overlay");
353
+ }
354
+
355
+ private createLayer() {
356
+ if (!this.canvasService) return;
357
+ const width = this.canvasService.canvas.width || 800;
358
+ const height = this.canvasService.canvas.height || 600;
359
+
360
+ const layer = this.canvasService.createLayer("dieline-overlay", {
361
+ width,
362
+ height,
363
+ selectable: false,
364
+ evented: false,
365
+ });
366
+
367
+ this.canvasService.canvas.bringObjectToFront(layer);
368
+
369
+ // Ensure above user layer
370
+ const userLayer = this.canvasService.getLayer("user");
371
+ if (userLayer) {
372
+ const userIndex = this.canvasService.canvas
373
+ .getObjects()
374
+ .indexOf(userLayer);
375
+ this.canvasService.canvas.moveObjectTo(layer, userIndex + 1);
376
+ }
377
+ }
378
+
379
+ private destroyLayer() {
380
+ if (!this.canvasService) return;
381
+ const layer = this.getLayer();
382
+ if (layer) {
383
+ this.canvasService.canvas.remove(layer);
384
+ }
385
+ }
386
+
387
+ private createHatchPattern(color: string = "rgba(0, 0, 0, 0.3)") {
388
+ if (typeof document === "undefined") {
389
+ return undefined;
390
+ }
391
+ const size = 20;
392
+ const canvas = document.createElement("canvas");
393
+ canvas.width = size;
394
+ canvas.height = size;
395
+ const ctx = canvas.getContext("2d");
396
+ if (ctx) {
397
+ // Transparent background
398
+ ctx.clearRect(0, 0, size, size);
399
+
400
+ // Draw diagonal /
401
+ ctx.strokeStyle = color;
402
+ ctx.lineWidth = 1;
403
+ ctx.beginPath();
404
+ ctx.moveTo(0, size);
405
+ ctx.lineTo(size, 0);
406
+ ctx.stroke();
407
+ }
408
+ // @ts-ignore
409
+ return new Pattern({ source: canvas, repetition: "repeat" });
410
+ }
411
+
412
+ public updateDieline(emitEvent: boolean = true) {
413
+ if (!this.canvasService) return;
414
+ const layer = this.getLayer();
415
+ if (!layer) return;
416
+
417
+ const {
418
+ shape,
419
+ radius,
420
+ offset,
421
+ style,
422
+ insideColor,
423
+ outsideColor,
424
+ position,
425
+ borderLength,
426
+ showBleedLines,
427
+ holes,
428
+ } = this;
429
+ let { width, height } = this;
430
+
431
+ const canvasW = this.canvasService.canvas.width || 800;
432
+ const canvasH = this.canvasService.canvas.height || 600;
433
+
434
+ // Handle borderLength (Margin)
435
+ if (borderLength && borderLength > 0) {
436
+ width = Math.max(0, canvasW - borderLength * 2);
437
+ height = Math.max(0, canvasH - borderLength * 2);
438
+ }
439
+
440
+ // Handle Position
441
+ // this.position is normalized (0-1). Default to center (0.5, 0.5).
442
+ const normalizedPos = position ?? { x: 0.5, y: 0.5 };
443
+ const cx = Coordinate.toAbsolute(normalizedPos.x, canvasW);
444
+ const cy = Coordinate.toAbsolute(normalizedPos.y, canvasH);
445
+
446
+ // Clear existing objects
447
+ layer.remove(...layer.getObjects());
448
+
449
+ // Denormalize Holes for Geometry Generation
450
+ const absoluteHoles = (holes || []).map((h) => {
451
+ const p = Coordinate.denormalizePoint(
452
+ { x: h.x, y: h.y },
453
+ { width: canvasW, height: canvasH },
454
+ );
455
+ return {
456
+ ...h,
457
+ x: p.x,
458
+ y: p.y,
459
+ };
460
+ });
461
+
462
+ // 1. Draw Mask (Outside)
463
+ const cutW = Math.max(0, width + offset * 2);
464
+ const cutH = Math.max(0, height + offset * 2);
465
+ const cutR = radius === 0 ? 0 : Math.max(0, radius + offset);
466
+
467
+ // Use Paper.js to generate the complex mask path
468
+ const maskPathData = generateMaskPath({
469
+ canvasWidth: canvasW,
470
+ canvasHeight: canvasH,
471
+ shape,
472
+ width: cutW,
473
+ height: cutH,
474
+ radius: cutR,
475
+ x: cx,
476
+ y: cy,
477
+ holes: absoluteHoles,
478
+ pathData: this.pathData,
479
+ });
480
+
481
+ const mask = new Path(maskPathData, {
482
+ fill: outsideColor,
483
+ stroke: null,
484
+ selectable: false,
485
+ evented: false,
486
+ originX: "left" as const,
487
+ originY: "top" as const,
488
+ left: 0,
489
+ top: 0,
490
+ });
491
+ layer.add(mask);
492
+
493
+ // 2. Draw Inside Fill (Dieline Shape itself, merged with holes if needed)
494
+ if (
495
+ insideColor &&
496
+ insideColor !== "transparent" &&
497
+ insideColor !== "rgba(0,0,0,0)"
498
+ ) {
499
+ // Generate path for the product shape (Paper) = Dieline - Holes
500
+ const productPathData = generateDielinePath({
501
+ shape,
502
+ width: cutW,
503
+ height: cutH,
504
+ radius: cutR,
505
+ x: cx,
506
+ y: cy,
507
+ holes: absoluteHoles,
508
+ pathData: this.pathData,
509
+ });
510
+
511
+ const insideObj = new Path(productPathData, {
512
+ fill: insideColor,
513
+ stroke: null,
514
+ selectable: false,
515
+ evented: false,
516
+ originX: "left", // paper.js paths are absolute
517
+ originY: "top",
518
+ });
519
+ layer.add(insideObj);
520
+ }
521
+
522
+ // 3. Draw Bleed Zone (Hatch Fill) and Offset Border
523
+ if (offset !== 0) {
524
+ const bleedPathData = generateBleedZonePath(
525
+ {
526
+ shape,
527
+ width,
528
+ height,
529
+ radius,
530
+ x: cx,
531
+ y: cy,
532
+ holes: absoluteHoles,
533
+ pathData: this.pathData,
534
+ },
535
+ offset,
536
+ );
537
+
538
+ // Use solid red for hatch lines to match dieline, background is transparent
539
+ if (showBleedLines !== false) {
540
+ const pattern = this.createHatchPattern("red");
541
+ if (pattern) {
542
+ const bleedObj = new Path(bleedPathData, {
543
+ fill: pattern,
544
+ stroke: null,
545
+ selectable: false,
546
+ evented: false,
547
+ objectCaching: false,
548
+ originX: "left",
549
+ originY: "top",
550
+ });
551
+ layer.add(bleedObj);
552
+ }
553
+ }
554
+
555
+ // Offset Dieline Border
556
+ const offsetPathData = generateDielinePath({
557
+ shape,
558
+ width: cutW,
559
+ height: cutH,
560
+ radius: cutR,
561
+ x: cx,
562
+ y: cy,
563
+ holes: absoluteHoles,
564
+ pathData: this.pathData,
565
+ });
566
+
567
+ const offsetBorderObj = new Path(offsetPathData, {
568
+ fill: null,
569
+ stroke: "#666", // Grey
570
+ strokeWidth: 1,
571
+ strokeDashArray: [4, 4], // Dashed
572
+ selectable: false,
573
+ evented: false,
574
+ originX: "left",
575
+ originY: "top",
576
+ });
577
+ layer.add(offsetBorderObj);
578
+ }
579
+
580
+ // 4. Draw Dieline (Visual Border)
581
+ // This should outline the product shape AND the holes.
582
+ // NOTE: We need to use absoluteHoles (denormalized) here, NOT holes (normalized 0-1)
583
+ // generateDielinePath expects holes to be in absolute coordinates (matching width/height scale)
584
+ const borderPathData = generateDielinePath({
585
+ shape,
586
+ width: width,
587
+ height: height,
588
+ radius: radius,
589
+ x: cx,
590
+ y: cy,
591
+ holes: absoluteHoles, // FIX: Use absoluteHoles instead of holes
592
+ pathData: this.pathData,
593
+ });
594
+
595
+ const borderObj = new Path(borderPathData, {
596
+ fill: "transparent",
597
+ stroke: "red",
598
+ strokeWidth: 1,
599
+ strokeDashArray: style === "dashed" ? [5, 5] : undefined,
600
+ selectable: false,
601
+ evented: false,
602
+ originX: "left",
603
+ originY: "top",
604
+ });
605
+
606
+ layer.add(borderObj);
607
+
608
+ // Enforce z-index: Dieline > User
609
+ const userLayer = this.canvasService.getLayer("user");
610
+ if (layer && userLayer) {
611
+ const layerIndex = this.canvasService.canvas.getObjects().indexOf(layer);
612
+ const userIndex = this.canvasService.canvas
613
+ .getObjects()
614
+ .indexOf(userLayer);
615
+ if (layerIndex < userIndex) {
616
+ this.canvasService.canvas.moveObjectTo(layer, userIndex + 1);
617
+ }
618
+ } else {
619
+ // If no user layer, just bring to front (safe default)
620
+ this.canvasService.canvas.bringObjectToFront(layer);
621
+ }
622
+
623
+ // Ensure Ruler is above Dieline if it exists
624
+ const rulerLayer = this.canvasService.getLayer("ruler-overlay");
625
+ if (rulerLayer) {
626
+ this.canvasService.canvas.bringObjectToFront(rulerLayer);
627
+ }
628
+
629
+ layer.dirty = true;
630
+ this.canvasService.requestRenderAll();
631
+
632
+ // Emit change event so other tools (like HoleTool) can react
633
+ // Only emit if requested (to avoid loops when updating non-geometry props like holes)
634
+ if (emitEvent && this.context) {
635
+ const geometry = this.getGeometry();
636
+ if (geometry) {
637
+ this.context.eventBus.emit("dieline:geometry:change", geometry);
638
+ }
639
+ }
640
+ }
641
+
642
+ public getGeometry(): DielineGeometry | null {
643
+ if (!this.canvasService) return null;
644
+ const { shape, width, height, radius, position, borderLength, offset } =
645
+ this;
646
+ const canvasW = this.canvasService.canvas.width || 800;
647
+ const canvasH = this.canvasService.canvas.height || 600;
648
+
649
+ let visualWidth = width;
650
+ let visualHeight = height;
651
+
652
+ if (borderLength && borderLength > 0) {
653
+ visualWidth = Math.max(0, canvasW - borderLength * 2);
654
+ visualHeight = Math.max(0, canvasH - borderLength * 2);
655
+ }
656
+
657
+ const cx = Coordinate.toAbsolute(position?.x ?? 0.5, canvasW);
658
+ const cy = Coordinate.toAbsolute(position?.y ?? 0.5, canvasH);
659
+
660
+ return {
661
+ shape,
662
+ x: cx,
663
+ y: cy,
664
+ width: visualWidth,
665
+ height: visualHeight,
666
+ radius,
667
+ offset,
668
+ borderLength,
669
+ pathData: this.pathData,
670
+ };
671
+ }
672
+
673
+ public exportCutImage() {
674
+ if (!this.canvasService) return null;
675
+ const canvas = this.canvasService.canvas;
676
+
677
+ // 1. Generate Path Data
678
+ const { shape, width, height, radius, position, holes } = this;
679
+ const canvasW = canvas.width || 800;
680
+ const canvasH = canvas.height || 600;
681
+ const cx = Coordinate.toAbsolute(position?.x ?? 0.5, canvasW);
682
+ const cy = Coordinate.toAbsolute(position?.y ?? 0.5, canvasH);
683
+
684
+ // Denormalize Holes for Export
685
+ const absoluteHoles = (holes || []).map((h) => {
686
+ const p = Coordinate.denormalizePoint(
687
+ { x: h.x, y: h.y },
688
+ { width: canvasW, height: canvasH },
689
+ );
690
+ return {
691
+ ...h,
692
+ x: p.x,
693
+ y: p.y,
694
+ };
695
+ });
696
+
697
+ const pathData = generateDielinePath({
698
+ shape,
699
+ width,
700
+ height,
701
+ radius,
702
+ x: cx,
703
+ y: cy,
704
+ holes: absoluteHoles,
705
+ pathData: this.pathData,
706
+ });
707
+
708
+ // 2. Create Clip Path
709
+ // @ts-ignore
710
+ const clipPath = new Path(pathData, {
711
+ left: 0,
712
+ top: 0,
713
+ originX: "left",
714
+ originY: "top",
715
+ absolutePositioned: true,
716
+ });
717
+
718
+ // 3. Hide UI Layers
719
+ const layer = this.getLayer();
720
+ const wasVisible = layer?.visible ?? true;
721
+ if (layer) layer.visible = false;
722
+
723
+ // Hide hole markers
724
+ const holeMarkers = canvas
725
+ .getObjects()
726
+ .filter((o: any) => o.data?.type === "hole-marker");
727
+ holeMarkers.forEach((o) => (o.visible = false));
728
+
729
+ // Hide Ruler Overlay
730
+ const rulerLayer = canvas
731
+ .getObjects()
732
+ .find((obj: any) => obj.data?.id === "ruler-overlay");
733
+ const rulerWasVisible = rulerLayer?.visible ?? true;
734
+ if (rulerLayer) rulerLayer.visible = false;
735
+
736
+ // 4. Apply Clip & Export
737
+ const originalClip = canvas.clipPath;
738
+ canvas.clipPath = clipPath;
739
+
740
+ const bbox = clipPath.getBoundingRect();
741
+
742
+ const clipPathCorrected = new Path(pathData, {
743
+ absolutePositioned: true,
744
+ left: 0,
745
+ top: 0,
746
+ });
747
+
748
+ const tempPath = new Path(pathData);
749
+ const tempBounds = tempPath.getBoundingRect();
750
+
751
+ clipPathCorrected.set({
752
+ left: tempBounds.left,
753
+ top: tempBounds.top,
754
+ originX: "left",
755
+ originY: "top",
756
+ });
757
+
758
+ // 4. Apply Clip & Export
759
+ canvas.clipPath = clipPathCorrected;
760
+
761
+ const exportBbox = clipPathCorrected.getBoundingRect();
762
+ const dataURL = canvas.toDataURL({
763
+ format: "png",
764
+ multiplier: 2,
765
+ left: exportBbox.left,
766
+ top: exportBbox.top,
767
+ width: exportBbox.width,
768
+ height: exportBbox.height,
769
+ });
770
+
771
+ // 5. Restore
772
+ canvas.clipPath = originalClip;
773
+ if (layer) layer.visible = wasVisible;
774
+ if (rulerLayer) rulerLayer.visible = rulerWasVisible;
775
+ holeMarkers.forEach((o) => (o.visible = true));
776
+ canvas.requestRenderAll();
777
+
778
+ return dataURL;
779
+ }
780
+ }