allisongattone commited on
Commit
a889f5f
·
verified ·
1 Parent(s): 590ef53

Upload components/CutForgeStudio.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. components/CutForgeStudio.js +407 -149
components/CutForgeStudio.js CHANGED
@@ -1,8 +1,8 @@
1
  import React, { useReducer, useState, useEffect, useRef, useCallback } from 'react';
2
- import { Upload, Download, Layers, Image as ImageIcon, Wand2, Sliders, AlertCircle, CheckCircle } from 'lucide-react';
 
3
 
4
  // --- State Management ---
5
- // States: IDLE, UPLOADING, MASKING, VECTORIZING, READY
6
  const initialState = {
7
  status: 'IDLE',
8
  imageSrc: null,
@@ -11,9 +11,15 @@ const initialState = {
11
  tolerance: 30,
12
  simplification: 0.5,
13
  colorCount: 2,
14
- bgColor: '#ffffff'
 
 
 
 
 
15
  },
16
- error: null
 
17
  };
18
 
19
  const reducer = (state, action) => {
@@ -30,66 +36,127 @@ const reducer = (state, action) => {
30
  return { ...state, error: action.payload, status: 'IDLE' };
31
  case 'RESET':
32
  return initialState;
 
 
 
 
33
  default:
34
  return state;
35
  }
36
  };
37
 
38
- // --- Engine: HEIC Mock Pattern ---
39
- const handleHeicUpload = async (file) => {
40
- // Mock pattern for heic2any integration
41
- // In a real scenario, this would be: const converted = await heic2any(file);
42
- console.log(`[Engine] Detected HEIC file: ${file.name}. Mocking conversion to JPEG...`);
43
- return new Promise((resolve) => {
44
- setTimeout(() => {
45
- // Simulate conversion delay
46
- resolve(file);
47
- }, 800);
48
- });
 
 
 
49
  };
50
 
51
- // --- Engine: Manhattan Distance Background Removal ---
52
- const removeBackground = (canvas, tolerance) => {
53
  const ctx = canvas.getContext('2d');
54
  const width = canvas.width;
55
  const height = canvas.height;
56
- const data = ctx.getImageData(0, 0, width, height);
 
57
 
58
- // Assuming top-left pixel (0,0) is the background color reference
59
- const bgR = data.data[0];
60
- const bgG = data.data[1];
61
- const bgB = data.data[2];
62
-
63
- for (let i = 0; i < data.data.length; i += 4) {
64
- const r = data.data[i];
65
- const g = data.data[i + 1];
66
- const b = data.data[i + 2];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- // Manhattan Distance: |R1 - R2| + |G1 - G2| + |B1 - B2|
69
- const distance = Math.abs(r - bgR) + Math.abs(g - bgG) + Math.abs(b - bgB);
 
 
 
 
 
 
 
70
 
71
- if (distance < tolerance) {
72
- data.data[i + 3] = 0; // Set Alpha to 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  }
74
- }
75
- ctx.putImageData(data, 0, 0);
76
  };
77
 
78
- // --- Engine: SVG Sanitizer ---
79
- const sanitizeAndInlineSvg = (svgString) => {
80
  const parser = new DOMParser();
81
  const doc = parser.parseFromString(svgString, 'image/svg+xml');
82
  const svgElement = doc.querySelector('svg');
83
 
84
  if (!svgElement) return svgString;
85
 
86
- // 1. Strip unwanted tags
87
- ['metadata', 'desc', 'style', 'image'].forEach(tag => {
88
  const elements = svgElement.querySelectorAll(tag);
89
  elements.forEach(el => el.remove());
90
  });
91
 
92
- // 2. Convert CSS styles to explicit attributes (Cricut/Silhouette compatibility)
 
 
 
 
93
  const elements = svgElement.querySelectorAll('*');
94
  elements.forEach(el => {
95
  const style = el.getAttribute('style');
@@ -100,37 +167,30 @@ const sanitizeAndInlineSvg = (svgString) => {
100
  if (prop && val) styleObj[prop.trim()] = val.trim();
101
  });
102
 
103
- // Map common CSS properties to SVG attributes
104
  if (styleObj['fill']) el.setAttribute('fill', styleObj['fill']);
105
  if (styleObj['stroke']) el.setAttribute('stroke', styleObj['stroke']);
106
  if (styleObj['stroke-width']) el.setAttribute('stroke-width', styleObj['stroke-width']);
 
107
 
108
  el.removeAttribute('style');
109
  }
 
 
 
 
 
110
  });
111
 
112
  return `<?xml version="1.0" encoding="UTF-8"?>\n${svgElement.outerHTML}`;
113
  };
114
 
115
- // --- Engine: Simple Vectorization (Mock for demo purposes) ---
116
- // A real vectorization engine is complex. Here we simulate creating SVG paths from the canvas.
117
- const generateSvgPaths = (canvas) => {
118
- // In a real app, this would use a library like 'imagetracer' or 'potrace'
119
- // For this demo, we create a bounding box SVG to represent the "processed" state
120
- const width = canvas.width;
121
- const height = canvas.height;
122
-
123
- return `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" xmlns="http://www.w3.org/2000/svg">
124
- <rect x="0" y="0" width="${width}" height="${height}" fill="none" stroke="#0a6e54" stroke-width="2"/>
125
- <text x="${width/2}" y="${height/2}" font-family="Inter" font-size="20" fill="#1a1815" text-anchor="middle">Vectorized Output</text>
126
- </svg>`;
127
- };
128
-
129
  // --- Main Application Component ---
130
  export default function CutForgeStudio() {
131
  const [state, dispatch] = useReducer(reducer, initialState);
132
  const canvasRef = useRef(null);
133
  const imageRef = useRef(null);
 
 
134
 
135
  // --- Handlers ---
136
 
@@ -139,13 +199,15 @@ export default function CutForgeStudio() {
139
  if (!file) return;
140
 
141
  dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' });
 
142
 
143
  try {
144
  let processedFile = file;
145
 
146
- // HEIC Mock Pattern
147
  if (file.name.toLowerCase().endsWith('.heic')) {
148
- processedFile = await handleHeicUpload(file);
 
149
  }
150
 
151
  const url = URL.createObjectURL(processedFile);
@@ -156,57 +218,118 @@ export default function CutForgeStudio() {
156
  processImage(url);
157
  };
158
  } catch (err) {
159
- dispatch({ type: 'SET_ERROR', payload: 'Failed to load image' });
 
 
160
  }
161
  };
162
 
163
- const processImage = (src) => {
164
  const canvas = canvasRef.current;
165
  const img = imageRef.current;
166
 
167
- // Set canvas dimensions
168
- canvas.width = img.width;
169
- canvas.height = img.height;
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
  const ctx = canvas.getContext('2d');
172
- ctx.drawImage(img, 0, 0);
 
 
 
173
 
174
- // Apply Manhattan Distance Masking
175
- removeBackground(canvas, state.settings.tolerance);
 
176
 
 
 
 
177
  dispatch({ type: 'SET_STATUS', payload: 'VECTORIZING' });
178
 
179
- // Simulate vectorization delay
180
- setTimeout(() => {
181
- const rawSvg = generateSvgPaths(canvas);
182
- const cleanSvg = sanitizeAndInlineSvg(rawSvg);
183
  dispatch({ type: 'SET_SVG', payload: cleanSvg });
184
- }, 1000);
185
- };
 
 
 
 
 
186
 
187
  const downloadSvg = () => {
188
  if (!state.processedSvg) return;
189
- const blob = new Blob([state.processedSvg], { type: 'image/svg+xml' });
190
  const url = URL.createObjectURL(blob);
191
  const a = document.createElement('a');
192
  a.href = url;
193
- a.download = 'cutforge-export.svg';
 
194
  a.click();
 
 
 
 
 
 
 
 
 
 
195
  };
196
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  // --- Render Helpers ---
198
 
199
  const renderStatusBadge = () => {
200
- const colors = {
201
- IDLE: 'bg-gray-200 text-gray-600',
202
- UPLOADING: 'bg-saffron text-ink',
203
- MASKING: 'bg-forest text-white',
204
- VECTORIZING: 'bg-forest text-white animate-pulse',
205
- READY: 'bg-saffron text-ink'
206
  };
 
207
  return (
208
- <span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-widest ${colors[state.status]}`}>
209
- {state.status}
210
  </span>
211
  );
212
  };
@@ -227,124 +350,258 @@ export default function CutForgeStudio() {
227
  href="https://huggingface.co/spaces/akhaliq/anycoder"
228
  target="_blank"
229
  rel="noopener noreferrer"
230
- className="text-xs font-medium text-ink/60 hover:text-forest transition-colors"
231
  >
232
  Built with anycoder
233
  </a>
234
  </div>
235
  </header>
236
 
237
- {/* Main Grid Layout: 12 Columns Asymmetric */}
238
  <main className="flex-1 grid grid-cols-12 h-[calc(100vh - 64px)]">
239
 
240
- {/* LEFT RAIL (Cols 1-3): Sticky Workshop */}
241
- <aside className="col-span-3 border-r border-ink/10 bg-bone p-6 flex flex-col gap-8 overflow-y-auto">
242
 
243
  {/* Upload Section */}
244
  <div className="space-y-4">
245
- <h2 className="font-serif text-lg font-bold mb-4 flex items-center gap-2">
246
- <Upload size={18} /> Source
247
  </h2>
248
  <div className="relative group cursor-pointer">
249
  <input
250
  type="file"
251
- accept=".png,.jpg,.jpeg,.heic"
252
  onChange={handleFileUpload}
253
  className="absolute inset-0 w-full h-full opacity-0 z-10 cursor-pointer"
254
  />
255
  <div className="border-2 border-dashed border-ink/20 rounded-xl p-6 flex flex-col items-center justify-center text-center hover:border-forest hover:bg-forest/5 transition-all">
256
- <ImageIcon className="text-ink/40 mb-2" />
257
  <span className="text-sm font-medium">Drop Image or Click</span>
258
- <span className="text-xs text-ink/50 mt-1">Supports HEIC (Mobile)</span>
259
  </div>
260
  </div>
261
  </div>
262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  {/* Controls Section */}
264
- <div className="space-y-6">
265
- <h2 className="font-serif text-lg font-bold mb-4 flex items-center gap-2">
266
- <Sliders size={18} /> Parameters
267
- </h2>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
- {/* Tolerance Slider */}
270
- <div className="space-y-2">
271
- <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Mask Tolerance</label>
272
- <input
273
- type="range"
274
- min="0" max="100"
275
- value={state.settings.tolerance}
276
- onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { tolerance: parseInt(e.target.value) } })}
277
- className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
278
- />
279
- <div className="text-right text-xs font-mono text-forest">{state.settings.tolerance}</div>
280
- </div>
 
 
 
 
 
 
281
 
282
- {/* Simplification Slider */}
283
- <div className="space-y-2">
284
- <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Path Simplification</label>
285
- <input
286
- type="range"
287
- min="0" max="1" step="0.1"
288
- value={state.settings.simplification}
289
- onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { simplification: parseFloat(e.target.value) } })}
290
- className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
291
- />
292
- <div className="text-right text-xs font-mono text-forest">{state.settings.simplification}</div>
293
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
- {/* Color Count */}
296
- <div className="space-y-2">
297
- <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Color Limit</label>
298
- <select
299
- value={state.settings.colorCount}
300
- onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { colorCount: parseInt(e.target.value) } })}
301
- className="w-full bg-white border border-ink/10 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-forest"
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  >
303
- <option value="1">1 Color (Monochrome)</option>
304
- <option value="2">2 Colors</option>
305
- <option value="4">4 Colors</option>
306
- <option value="8">8 Colors</option>
307
- </select>
308
  </div>
309
- </div>
310
 
311
  {/* Actions */}
312
- <div className="mt-auto pt-6 border-t border-ink/10">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
  <button
314
- onClick={() => dispatch({ type: 'RESET' })}
315
  className="w-full py-3 bg-ink/5 hover:bg-ink/10 text-ink font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
316
  >
317
- <AlertCircle size={16} /> Reset Workspace
318
  </button>
319
  </div>
320
  </aside>
321
 
322
- {/* MAIN STAGE (Cols 4-12): Preview Area */}
323
  <section className="col-span-9 bg-white/50 relative flex flex-col">
324
 
325
  {/* Toolbar */}
326
  <div className="h-12 border-b border-ink/10 flex items-center justify-between px-6 bg-white">
327
- <span className="text-xs font-mono text-ink/50">
328
- {state.imageSrc ? 'Preview Mode: Transparency Checkerboard' : 'Waiting for input...'}
329
- </span>
330
- {state.status === 'READY' && (
 
 
 
 
 
 
 
331
  <button
332
- onClick={downloadSvg}
333
- className="flex items-center gap-2 bg-forest hover:bg-forest/90 text-white px-4 py-2 rounded-md text-sm font-medium transition-colors shadow-sm"
 
334
  >
335
- <Download size={16} /> Download SVG
336
  </button>
337
- )}
 
 
 
 
 
 
 
 
338
  </div>
339
 
340
  {/* Canvas/SVG Container */}
341
- <div className="flex-1 relative overflow-hidden flex items-center justify-center p-8">
342
-
 
 
343
  {/* Transparency Checkerboard Background */}
344
  <div className="absolute inset-0 bg-checkerboard bg-size-checkerboard opacity-50 pointer-events-none" />
345
 
346
  {state.imageSrc && (
347
- <div className="relative shadow-2xl rounded-lg overflow-hidden bg-white max-w-full max-h-full">
 
 
 
348
  {/* Hidden Image Ref for processing */}
349
  <img ref={imageRef} className="hidden" alt="source" />
350
 
@@ -352,11 +609,11 @@ export default function CutForgeStudio() {
352
  <canvas
353
  ref={canvasRef}
354
  className="max-w-full max-h-full object-contain"
355
- style={{ display: state.status === 'READY' ? 'none' : 'block' }}
356
  />
357
 
358
  {/* SVG Output Overlay */}
359
- {state.processedSvg && (
360
  <div
361
  className="w-full h-full"
362
  dangerouslySetInnerHTML={{
@@ -366,10 +623,10 @@ export default function CutForgeStudio() {
366
  )}
367
 
368
  {/* Loading Overlay */}
369
- {(state.status === 'UPLOADING' || state.status === 'MASKING' || state.status === 'VECTORIZING') && (
370
- <div className="absolute inset-0 bg-bone/80 flex flex-col items-center justify-center z-20">
371
  <Wand2 className="text-forest animate-spin mb-4" size={48} />
372
- <p className="font-serif text-lg text-ink">Processing Engine...</p>
373
  <p className="text-xs font-mono text-ink/60 mt-2 uppercase tracking-widest">{state.status}</p>
374
  </div>
375
  )}
@@ -380,6 +637,7 @@ export default function CutForgeStudio() {
380
  <div className="text-center opacity-40">
381
  <ImageIcon size={64} className="mx-auto mb-4 text-ink/20" />
382
  <p className="font-serif text-xl">No Image Loaded</p>
 
383
  </div>
384
  )}
385
  </div>
 
1
  import React, { useReducer, useState, useEffect, useRef, useCallback } from 'react';
2
+ import { Upload, Download, Layers, Image as ImageIcon, Wand2, Sliders, AlertCircle, CheckCircle, Trash2, ZoomIn, ZoomOut } from 'lucide-react';
3
+ import ImageTracer from 'imagetracerjs';
4
 
5
  // --- State Management ---
 
6
  const initialState = {
7
  status: 'IDLE',
8
  imageSrc: null,
 
11
  tolerance: 30,
12
  simplification: 0.5,
13
  colorCount: 2,
14
+ bgColor: '#ffffff',
15
+ scale: 1,
16
+ ltres: 1,
17
+ qtres: 1,
18
+ pathomit: 8,
19
+ rightangleenhance: true
20
  },
21
+ error: null,
22
+ zoom: 100
23
  };
24
 
25
  const reducer = (state, action) => {
 
36
  return { ...state, error: action.payload, status: 'IDLE' };
37
  case 'RESET':
38
  return initialState;
39
+ case 'SET_ZOOM':
40
+ return { ...state, zoom: action.payload };
41
+ case 'CLEAR_SVG':
42
+ return { ...state, processedSvg: null, status: 'MASKING' };
43
  default:
44
  return state;
45
  }
46
  };
47
 
48
+ // --- Engine: HEIC to JPEG/Blob Conversion ---
49
+ const convertHeicToBlob = async (file) => {
50
+ try {
51
+ const heic2any = (await import('heic2any')).default;
52
+ const converted = await heic2any({
53
+ blob: file,
54
+ toType: 'image/jpeg',
55
+ quality: 0.9
56
+ });
57
+ return converted;
58
+ } catch (error) {
59
+ console.error('HEIC conversion failed:', error);
60
+ return file;
61
+ }
62
  };
63
 
64
+ // --- Engine: Advanced Background Removal ---
65
+ const removeBackgroundAdvanced = (canvas, tolerance, bgColor) => {
66
  const ctx = canvas.getContext('2d');
67
  const width = canvas.width;
68
  const height = canvas.height;
69
+ const imageData = ctx.getImageData(0, 0, width, height);
70
+ const data = imageData.data;
71
 
72
+ // Parse background color
73
+ const bgRgb = hexToRgb(bgColor);
74
+
75
+ for (let i = 0; i < data.length; i += 4) {
76
+ const r = data[i];
77
+ const g = data[i + 1];
78
+ const b = data[i + 2];
79
+
80
+ // Calculate color distance
81
+ const distance = Math.sqrt(
82
+ Math.pow(r - bgRgb.r, 2) +
83
+ Math.pow(g - bgRgb.g, 2) +
84
+ Math.pow(b - bgRgb.b, 2)
85
+ );
86
+
87
+ // Also check if pixel is close to white/light (common background)
88
+ const brightness = (r + g + b) / 3;
89
+ const isLightBackground = brightness > 240 && distance < 50;
90
+
91
+ if (distance < tolerance || isLightBackground) {
92
+ data[i + 3] = 0; // Set alpha to 0 (transparent)
93
+ }
94
+ }
95
+
96
+ ctx.putImageData(imageData, 0, 0);
97
+ };
98
 
99
+ // Helper: Hex to RGB
100
+ const hexToRgb = (hex) => {
101
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
102
+ return result ? {
103
+ r: parseInt(result[1], 16),
104
+ g: parseInt(result[2], 16),
105
+ b: parseInt(result[3], 16)
106
+ } : { r: 255, g: 255, b: 255 };
107
+ };
108
 
109
+ // --- Engine: Real SVG Vectorization ---
110
+ const vectorizeImage = (canvas, settings) => {
111
+ return new Promise((resolve, reject) => {
112
+ try {
113
+ const tracerOptions = {
114
+ ltres: settings.ltres,
115
+ qtres: settings.qtres,
116
+ pathomit: settings.pathomit,
117
+ colorsampling: 2,
118
+ numberofcolors: settings.colorCount,
119
+ mincolorratio: 0,
120
+ colorquantcycles: 3,
121
+ scale: settings.scale,
122
+ simplify: settings.simplification,
123
+ rightangleenhance: settings.rightangleenhance,
124
+ blurradius: 0,
125
+ blurdelta: 20
126
+ };
127
+
128
+ ImageTracer.imageToSVG(
129
+ canvas.toDataURL('image/png'),
130
+ (svgString) => {
131
+ resolve(svgString);
132
+ },
133
+ tracerOptions
134
+ );
135
+ } catch (error) {
136
+ reject(error);
137
  }
138
+ });
 
139
  };
140
 
141
+ // --- Engine: SVG Sanitizer for Cutting Machines ---
142
+ const sanitizeSvgForCutting = (svgString) => {
143
  const parser = new DOMParser();
144
  const doc = parser.parseFromString(svgString, 'image/svg+xml');
145
  const svgElement = doc.querySelector('svg');
146
 
147
  if (!svgElement) return svgString;
148
 
149
+ // Remove unwanted elements
150
+ ['metadata', 'desc', 'style', 'image', 'clipPath', 'mask'].forEach(tag => {
151
  const elements = svgElement.querySelectorAll(tag);
152
  elements.forEach(el => el.remove());
153
  });
154
 
155
+ // Set proper viewBox and dimensions
156
+ svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
157
+ svgElement.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
158
+
159
+ // Convert all styles to attributes
160
  const elements = svgElement.querySelectorAll('*');
161
  elements.forEach(el => {
162
  const style = el.getAttribute('style');
 
167
  if (prop && val) styleObj[prop.trim()] = val.trim();
168
  });
169
 
 
170
  if (styleObj['fill']) el.setAttribute('fill', styleObj['fill']);
171
  if (styleObj['stroke']) el.setAttribute('stroke', styleObj['stroke']);
172
  if (styleObj['stroke-width']) el.setAttribute('stroke-width', styleObj['stroke-width']);
173
+ if (styleObj['opacity']) el.setAttribute('opacity', styleObj['opacity']);
174
 
175
  el.removeAttribute('style');
176
  }
177
+
178
+ // Ensure paths have proper fill for cutting
179
+ if (el.tagName === 'path' && !el.getAttribute('fill')) {
180
+ el.setAttribute('fill', '#000000');
181
+ }
182
  });
183
 
184
  return `<?xml version="1.0" encoding="UTF-8"?>\n${svgElement.outerHTML}`;
185
  };
186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
  // --- Main Application Component ---
188
  export default function CutForgeStudio() {
189
  const [state, dispatch] = useReducer(reducer, initialState);
190
  const canvasRef = useRef(null);
191
  const imageRef = useRef(null);
192
+ const containerRef = useRef(null);
193
+ const [previewMode, setPreviewMode] = useState('original'); // 'original', 'masked', 'vector'
194
 
195
  // --- Handlers ---
196
 
 
199
  if (!file) return;
200
 
201
  dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' });
202
+ dispatch({ type: 'SET_ERROR', payload: null });
203
 
204
  try {
205
  let processedFile = file;
206
 
207
+ // Handle HEIC files
208
  if (file.name.toLowerCase().endsWith('.heic')) {
209
+ dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' });
210
+ processedFile = await convertHeicToBlob(file);
211
  }
212
 
213
  const url = URL.createObjectURL(processedFile);
 
218
  processImage(url);
219
  };
220
  } catch (err) {
221
+ console.error('Upload error:', err);
222
+ dispatch({ type: 'SET_ERROR', payload: 'Failed to load image. Please try again.' });
223
+ dispatch({ type: 'SET_STATUS', payload: 'IDLE' });
224
  }
225
  };
226
 
227
+ const processImage = useCallback((src) => {
228
  const canvas = canvasRef.current;
229
  const img = imageRef.current;
230
 
231
+ if (!canvas || !img) return;
232
+
233
+ // Set canvas dimensions (max 2000px for performance)
234
+ const maxSize = 2000;
235
+ let width = img.naturalWidth;
236
+ let height = img.naturalHeight;
237
+
238
+ if (width > maxSize || height > maxSize) {
239
+ const ratio = Math.min(maxSize / width, maxSize / height);
240
+ width = Math.floor(width * ratio);
241
+ height = Math.floor(height * ratio);
242
+ }
243
+
244
+ canvas.width = width;
245
+ canvas.height = height;
246
 
247
  const ctx = canvas.getContext('2d');
248
+ ctx.drawImage(img, 0, 0, width, height);
249
+
250
+ // Apply background removal
251
+ removeBackgroundAdvanced(canvas, state.settings.tolerance, state.settings.bgColor);
252
 
253
+ dispatch({ type: 'SET_STATUS', payload: 'MASKING' });
254
+ setPreviewMode('masked');
255
+ }, [state.settings.tolerance, state.settings.bgColor]);
256
 
257
+ const generateVector = useCallback(async () => {
258
+ if (!canvasRef.current) return;
259
+
260
  dispatch({ type: 'SET_STATUS', payload: 'VECTORIZING' });
261
 
262
+ try {
263
+ const rawSvg = await vectorizeImage(canvasRef.current, state.settings);
264
+ const cleanSvg = sanitizeSvgForCutting(rawSvg);
 
265
  dispatch({ type: 'SET_SVG', payload: cleanSvg });
266
+ setPreviewMode('vector');
267
+ } catch (error) {
268
+ console.error('Vectorization error:', error);
269
+ dispatch({ type: 'SET_ERROR', payload: 'Vectorization failed. Try adjusting settings.' });
270
+ dispatch({ type: 'SET_STATUS', payload: 'MASKING' });
271
+ }
272
+ }, [state.settings]);
273
 
274
  const downloadSvg = () => {
275
  if (!state.processedSvg) return;
276
+ const blob = new Blob([state.processedSvg], { type: 'image/svg+xml;charset=utf-8' });
277
  const url = URL.createObjectURL(blob);
278
  const a = document.createElement('a');
279
  a.href = url;
280
+ a.download = `cutforge-${Date.now()}.svg`;
281
+ document.body.appendChild(a);
282
  a.click();
283
+ document.body.removeChild(a);
284
+ URL.revokeObjectURL(url);
285
+ };
286
+
287
+ const downloadPreview = () => {
288
+ if (!canvasRef.current) return;
289
+ const link = document.createElement('a');
290
+ link.download = `cutforge-preview-${Date.now()}.png`;
291
+ link.href = canvasRef.current.toDataURL('image/png');
292
+ link.click();
293
  };
294
 
295
+ const handleZoom = (delta) => {
296
+ const newZoom = Math.max(25, Math.min(400, state.zoom + delta));
297
+ dispatch({ type: 'SET_ZOOM', payload: newZoom });
298
+ };
299
+
300
+ const resetWorkspace = () => {
301
+ dispatch({ type: 'RESET' });
302
+ setPreviewMode('original');
303
+ if (canvasRef.current) {
304
+ const ctx = canvasRef.current.getContext('2d');
305
+ ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
306
+ }
307
+ };
308
+
309
+ // Re-process when settings change
310
+ useEffect(() => {
311
+ if (state.imageSrc && state.status === 'MASKING' || state.status === 'READY') {
312
+ const timer = setTimeout(() => {
313
+ processImage(state.imageSrc);
314
+ }, 300);
315
+ return () => clearTimeout(timer);
316
+ }
317
+ }, [state.settings.tolerance, state.settings.bgColor, state.imageSrc]);
318
+
319
  // --- Render Helpers ---
320
 
321
  const renderStatusBadge = () => {
322
+ const config = {
323
+ IDLE: { color: 'bg-gray-200 text-gray-600', label: 'Ready' },
324
+ UPLOADING: { color: 'bg-saffron text-ink', label: 'Uploading...' },
325
+ MASKING: { color: 'bg-forest text-white', label: 'Processing' },
326
+ VECTORIZING: { color: 'bg-forest text-white animate-pulse', label: 'Vectorizing...' },
327
+ READY: { color: 'bg-saffron text-ink', label: 'Complete' }
328
  };
329
+ const { color, label } = config[state.status];
330
  return (
331
+ <span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-widest ${color}`}>
332
+ {label}
333
  </span>
334
  );
335
  };
 
350
  href="https://huggingface.co/spaces/akhaliq/anycoder"
351
  target="_blank"
352
  rel="noopener noreferrer"
353
+ className="text-xs font-medium text-ink/60 hover:text-forest transition-colors underline"
354
  >
355
  Built with anycoder
356
  </a>
357
  </div>
358
  </header>
359
 
360
+ {/* Main Grid Layout */}
361
  <main className="flex-1 grid grid-cols-12 h-[calc(100vh - 64px)]">
362
 
363
+ {/* LEFT RAIL: Controls */}
364
+ <aside className="col-span-3 border-r border-ink/10 bg-bone p-6 flex flex-col gap-6 overflow-y-auto">
365
 
366
  {/* Upload Section */}
367
  <div className="space-y-4">
368
+ <h2 className="font-serif text-lg font-bold flex items-center gap-2">
369
+ <Upload size={18} /> Source Image
370
  </h2>
371
  <div className="relative group cursor-pointer">
372
  <input
373
  type="file"
374
+ accept=".png,.jpg,.jpeg,.heic,.webp"
375
  onChange={handleFileUpload}
376
  className="absolute inset-0 w-full h-full opacity-0 z-10 cursor-pointer"
377
  />
378
  <div className="border-2 border-dashed border-ink/20 rounded-xl p-6 flex flex-col items-center justify-center text-center hover:border-forest hover:bg-forest/5 transition-all">
379
+ <ImageIcon className="text-ink/40 mb-2" size={32} />
380
  <span className="text-sm font-medium">Drop Image or Click</span>
381
+ <span className="text-xs text-ink/50 mt-1">PNG, JPG, HEIC, WebP</span>
382
  </div>
383
  </div>
384
  </div>
385
 
386
+ {/* Preview Mode Toggle */}
387
+ {state.imageSrc && (
388
+ <div className="space-y-3">
389
+ <h2 className="font-serif text-lg font-bold flex items-center gap-2">
390
+ <ImageIcon size={18} /> Preview Mode
391
+ </h2>
392
+ <div className="grid grid-cols-3 gap-2">
393
+ <button
394
+ onClick={() => setPreviewMode('original')}
395
+ className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
396
+ previewMode === 'original'
397
+ ? 'bg-forest text-white border-forest'
398
+ : 'bg-white text-ink border-ink/20 hover:border-forest'
399
+ }`}
400
+ >
401
+ Original
402
+ </button>
403
+ <button
404
+ onClick={() => setPreviewMode('masked')}
405
+ className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
406
+ previewMode === 'masked'
407
+ ? 'bg-forest text-white border-forest'
408
+ : 'bg-white text-ink border-ink/20 hover:border-forest'
409
+ }`}
410
+ >
411
+ Masked
412
+ </button>
413
+ <button
414
+ onClick={() => {
415
+ setPreviewMode('vector');
416
+ if (!state.processedSvg) generateVector();
417
+
418
+ className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
419
+ previewMode === 'vector'
420
+ ? 'bg-forest text-white border-forest'
421
+ : 'bg-white text-ink border-ink/20 hover:border-forest'
422
+ }`}
423
+ >
424
+ Vector
425
+ </button>
426
+ </div>
427
+ </div>
428
+ )}
429
+
430
  {/* Controls Section */}
431
+ {state.imageSrc && (
432
+ <div className="space-y-5">
433
+ <h2 className="font-serif text-lg font-bold flex items-center gap-2">
434
+ <Sliders size={18} /> Settings
435
+ </h2>
436
+
437
+ {/* Tolerance Slider */}
438
+ <div className="space-y-2">
439
+ <div className="flex justify-between items-center">
440
+ <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Background Tolerance</label>
441
+ <span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.tolerance}</span>
442
+ </div>
443
+ <input
444
+ type="range"
445
+ min="0" max="150"
446
+ value={state.settings.tolerance}
447
+ onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { tolerance: parseInt(e.target.value) } })}
448
+ className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
449
+ />
450
+ <p className="text-xs text-ink/50">Higher = more aggressive removal</p>
451
+ </div>
452
 
453
+ {/* Background Color Picker */}
454
+ <div className="space-y-2">
455
+ <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Background Color</label>
456
+ <div className="flex gap-2">
457
+ <input
458
+ type="color"
459
+ value={state.settings.bgColor}
460
+ onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { bgColor: e.target.value } })}
461
+ className="w-10 h-10 rounded border border-ink/20 cursor-pointer"
462
+ />
463
+ <input
464
+ type="text"
465
+ value={state.settings.bgColor}
466
+ onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { bgColor: e.target.value } })}
467
+ className="flex-1 bg-white border border-ink/10 rounded px-3 text-sm font-mono"
468
+ />
469
+ </div>
470
+ </div>
471
 
472
+ {/* Color Count */}
473
+ <div className="space-y-2">
474
+ <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Color Count</label>
475
+ <select
476
+ value={state.settings.colorCount}
477
+ onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { colorCount: parseInt(e.target.value) } })}
478
+ className="w-full bg-white border border-ink/10 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-forest"
479
+ >
480
+ <option value="1">1 Color (Monochrome)</option>
481
+ <option value="2">2 Colors</option>
482
+ <option value="4">4 Colors</option>
483
+ <option value="8">8 Colors</option>
484
+ <option value="16">16 Colors</option>
485
+ </select>
486
+ </div>
487
+
488
+ {/* Simplification Slider */}
489
+ <div className="space-y-2">
490
+ <div className="flex justify-between items-center">
491
+ <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Path Simplification</label>
492
+ <span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.simplification}</span>
493
+ </div>
494
+ <input
495
+ type="range"
496
+ min="0" max="2" step="0.1"
497
+ value={state.settings.simplification}
498
+ onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { simplification: parseFloat(e.target.value) } })}
499
+ className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
500
+ />
501
+ <p className="text-xs text-ink/50">Higher = smoother paths</p>
502
+ </div>
503
 
504
+ {/* Line Threshold */}
505
+ <div className="space-y-2">
506
+ <div className="flex justify-between items-center">
507
+ <label className="text-xs font-bold uppercase tracking-wider text-ink/70">Line Threshold</label>
508
+ <span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.ltres}</span>
509
+ </div>
510
+ <input
511
+ type="range"
512
+ min="0.1" max="5" step="0.1"
513
+ value={state.settings.ltres}
514
+ onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { ltres: parseFloat(e.target.value) } })}
515
+ className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
516
+ />
517
+ </div>
518
+
519
+ {/* Vectorize Button */}
520
+ <button
521
+ onClick={generateVector}
522
+ disabled={state.status === 'VECTORIZING'}
523
+ className="w-full py-3 bg-forest hover:bg-forest/90 disabled:bg-ink/30 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
524
  >
525
+ <Wand2 size={16} />
526
+ {state.status === 'VECTORIZING' ? 'Processing...' : 'Generate Vector'}
527
+ </button>
 
 
528
  </div>
529
+ )}
530
 
531
  {/* Actions */}
532
+ <div className="mt-auto pt-6 border-t border-ink/10 space-y-3">
533
+ {state.processedSvg && (
534
+ <button
535
+ onClick={downloadSvg}
536
+ className="w-full py-3 bg-ink hover:bg-ink/90 text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
537
+ >
538
+ <Download size={16} /> Download SVG
539
+ </button>
540
+ )}
541
+ {state.imageSrc && (
542
+ <button
543
+ onClick={downloadPreview}
544
+ className="w-full py-3 bg-white border border-ink/20 hover:bg-ink/5 text-ink font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
545
+ >
546
+ <Download size={16} /> Download Preview
547
+ </button>
548
+ )}
549
  <button
550
+ onClick={resetWorkspace}
551
  className="w-full py-3 bg-ink/5 hover:bg-ink/10 text-ink font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
552
  >
553
+ <Trash2 size={16} /> Reset Workspace
554
  </button>
555
  </div>
556
  </aside>
557
 
558
+ {/* MAIN STAGE: Preview Area */}
559
  <section className="col-span-9 bg-white/50 relative flex flex-col">
560
 
561
  {/* Toolbar */}
562
  <div className="h-12 border-b border-ink/10 flex items-center justify-between px-6 bg-white">
563
+ <div className="flex items-center gap-4">
564
+ <span className="text-xs font-mono text-ink/50">
565
+ {state.imageSrc ? `Image Loaded • ${previewMode.toUpperCase()} Mode` : 'Waiting for image...'}
566
+ </span>
567
+ {state.error && (
568
+ <span className="text-xs font-medium text-red-600 flex items-center gap-1">
569
+ <AlertCircle size={12} /> {state.error}
570
+ </span>
571
+ )}
572
+ </div>
573
+ <div className="flex items-center gap-2">
574
  <button
575
+ onClick={() => handleZoom(-25)}
576
+ className="p-2 hover:bg-ink/5 rounded transition-colors"
577
+ title="Zoom Out"
578
  >
579
+ <ZoomOut size={16} />
580
  </button>
581
+ <span className="text-xs font-mono w-12 text-center">{state.zoom}%</span>
582
+ <button
583
+ onClick={() => handleZoom(25)}
584
+ className="p-2 hover:bg-ink/5 rounded transition-colors"
585
+ title="Zoom In"
586
+ >
587
+ <ZoomIn size={16} />
588
+ </button>
589
+ </div>
590
  </div>
591
 
592
  {/* Canvas/SVG Container */}
593
+ <div
594
+ ref={containerRef}
595
+ className="flex-1 relative overflow-auto flex items-center justify-center p-8"
596
+ >
597
  {/* Transparency Checkerboard Background */}
598
  <div className="absolute inset-0 bg-checkerboard bg-size-checkerboard opacity-50 pointer-events-none" />
599
 
600
  {state.imageSrc && (
601
+ <div
602
+ className="relative shadow-2xl rounded-lg overflow-hidden bg-white transition-transform"
603
+ style={{ transform: `scale(${state.zoom / 100})` }}
604
+ >
605
  {/* Hidden Image Ref for processing */}
606
  <img ref={imageRef} className="hidden" alt="source" />
607
 
 
609
  <canvas
610
  ref={canvasRef}
611
  className="max-w-full max-h-full object-contain"
612
+ style={{ display: previewMode === 'vector' ? 'none' : 'block' }}
613
  />
614
 
615
  {/* SVG Output Overlay */}
616
+ {state.processedSvg && previewMode === 'vector' && (
617
  <div
618
  className="w-full h-full"
619
  dangerouslySetInnerHTML={{
 
623
  )}
624
 
625
  {/* Loading Overlay */}
626
+ {(state.status === 'UPLOADING' || state.status === 'VECTORIZING') && (
627
+ <div className="absolute inset-0 bg-bone/90 flex flex-col items-center justify-center z-20">
628
  <Wand2 className="text-forest animate-spin mb-4" size={48} />
629
+ <p className="font-serif text-lg text-ink">Processing...</p>
630
  <p className="text-xs font-mono text-ink/60 mt-2 uppercase tracking-widest">{state.status}</p>
631
  </div>
632
  )}
 
637
  <div className="text-center opacity-40">
638
  <ImageIcon size={64} className="mx-auto mb-4 text-ink/20" />
639
  <p className="font-serif text-xl">No Image Loaded</p>
640
+ <p className="text-sm text-ink/50 mt-2">Upload an image to get started</p>
641
  </div>
642
  )}
643
  </div>