allisongattone commited on
Commit
4bf234c
·
verified ·
1 Parent(s): bc93c56

Upload components/CutForgeStudio.js with huggingface_hub

Browse files
Files changed (1) hide show
  1. components/CutForgeStudio.js +390 -0
components/CutForgeStudio.js ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
9
+ processedSvg: null,
10
+ settings: {
11
+ tolerance: 30,
12
+ simplification: 0.5,
13
+ colorCount: 2,
14
+ bgColor: '#ffffff'
15
+ },
16
+ error: null
17
+ };
18
+
19
+ const reducer = (state, action) => {
20
+ switch (action.type) {
21
+ case 'SET_STATUS':
22
+ return { ...state, status: action.payload };
23
+ case 'SET_IMAGE':
24
+ return { ...state, imageSrc: action.payload, status: 'MASKING' };
25
+ case 'SET_SETTINGS':
26
+ return { ...state, settings: { ...state.settings, ...action.payload } };
27
+ case 'SET_SVG':
28
+ return { ...state, processedSvg: action.payload, status: 'READY' };
29
+ case 'SET_ERROR':
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');
96
+ if (style) {
97
+ const styleObj = {};
98
+ style.split(';').forEach(rule => {
99
+ const [prop, val] = rule.split(':');
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
+
137
+ const handleFileUpload = async (e) => {
138
+ const file = e.target.files[0];
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);
152
+ imageRef.current.src = url;
153
+
154
+ imageRef.current.onload = () => {
155
+ dispatch({ type: 'SET_IMAGE', payload: url });
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
+ };
213
+
214
+ return (
215
+ <div className="min-h-screen bg-bone font-sans text-ink flex flex-col overflow-hidden">
216
+ {/* Header */
217
+ <header className="h-16 border-b border-ink/10 flex items-between px-6 justify-between items-center sticky top-0 bg-bone/90 backdrop-blur z-10">
218
+ <div className="flex items-center gap-2">
219
+ <div className="w-8 h-8 bg-forest rounded-lg flex items-center justify-center text-white">
220
+ <Layers size={20} />
221
+ </div>
222
+ <h1 className="font-serif font-bold text-xl tracking-tight">CutForge Studio</h1>
223
+ </div>
224
+ <div className="flex items-center gap-4">
225
+ {renderStatusBadge()}
226
+ <a
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
+
351
+ {/* Canvas for Masking Preview */}
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={{
363
+ __html: state.processedSvg.replace('<svg', '<svg class="w-full h-full"')
364
+
365
+ />
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
+ )}
376
+ </div>
377
+ )}
378
+
379
+ {!state.imageSrc && (
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>
386
+ </section>
387
+ </main>
388
+ </div>
389
+ );
390
+ }