anycoder-eceaaa50 / components /CutForgeStudio.js
allisongattone's picture
Upload components/CutForgeStudio.js with huggingface_hub
a889f5f verified
Raw History Blame Contribute Delete
25 kB
import React, { useReducer, useState, useEffect, useRef, useCallback } from 'react';
import { Upload, Download, Layers, Image as ImageIcon, Wand2, Sliders, AlertCircle, CheckCircle, Trash2, ZoomIn, ZoomOut } from 'lucide-react';
import ImageTracer from 'imagetracerjs';
// --- State Management ---
const initialState = {
status: 'IDLE',
imageSrc: null,
processedSvg: null,
settings: {
tolerance: 30,
simplification: 0.5,
colorCount: 2,
bgColor: '#ffffff',
scale: 1,
ltres: 1,
qtres: 1,
pathomit: 8,
rightangleenhance: true
},
error: null,
zoom: 100
};
const reducer = (state, action) => {
switch (action.type) {
case 'SET_STATUS':
return { ...state, status: action.payload };
case 'SET_IMAGE':
return { ...state, imageSrc: action.payload, status: 'MASKING' };
case 'SET_SETTINGS':
return { ...state, settings: { ...state.settings, ...action.payload } };
case 'SET_SVG':
return { ...state, processedSvg: action.payload, status: 'READY' };
case 'SET_ERROR':
return { ...state, error: action.payload, status: 'IDLE' };
case 'RESET':
return initialState;
case 'SET_ZOOM':
return { ...state, zoom: action.payload };
case 'CLEAR_SVG':
return { ...state, processedSvg: null, status: 'MASKING' };
default:
return state;
}
};
// --- Engine: HEIC to JPEG/Blob Conversion ---
const convertHeicToBlob = async (file) => {
try {
const heic2any = (await import('heic2any')).default;
const converted = await heic2any({
blob: file,
toType: 'image/jpeg',
quality: 0.9
});
return converted;
} catch (error) {
console.error('HEIC conversion failed:', error);
return file;
}
};
// --- Engine: Advanced Background Removal ---
const removeBackgroundAdvanced = (canvas, tolerance, bgColor) => {
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
const imageData = ctx.getImageData(0, 0, width, height);
const data = imageData.data;
// Parse background color
const bgRgb = hexToRgb(bgColor);
for (let i = 0; i < data.length; i += 4) {
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];
// Calculate color distance
const distance = Math.sqrt(
Math.pow(r - bgRgb.r, 2) +
Math.pow(g - bgRgb.g, 2) +
Math.pow(b - bgRgb.b, 2)
);
// Also check if pixel is close to white/light (common background)
const brightness = (r + g + b) / 3;
const isLightBackground = brightness > 240 && distance < 50;
if (distance < tolerance || isLightBackground) {
data[i + 3] = 0; // Set alpha to 0 (transparent)
}
}
ctx.putImageData(imageData, 0, 0);
};
// Helper: Hex to RGB
const hexToRgb = (hex) => {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : { r: 255, g: 255, b: 255 };
};
// --- Engine: Real SVG Vectorization ---
const vectorizeImage = (canvas, settings) => {
return new Promise((resolve, reject) => {
try {
const tracerOptions = {
ltres: settings.ltres,
qtres: settings.qtres,
pathomit: settings.pathomit,
colorsampling: 2,
numberofcolors: settings.colorCount,
mincolorratio: 0,
colorquantcycles: 3,
scale: settings.scale,
simplify: settings.simplification,
rightangleenhance: settings.rightangleenhance,
blurradius: 0,
blurdelta: 20
};
ImageTracer.imageToSVG(
canvas.toDataURL('image/png'),
(svgString) => {
resolve(svgString);
},
tracerOptions
);
} catch (error) {
reject(error);
}
});
};
// --- Engine: SVG Sanitizer for Cutting Machines ---
const sanitizeSvgForCutting = (svgString) => {
const parser = new DOMParser();
const doc = parser.parseFromString(svgString, 'image/svg+xml');
const svgElement = doc.querySelector('svg');
if (!svgElement) return svgString;
// Remove unwanted elements
['metadata', 'desc', 'style', 'image', 'clipPath', 'mask'].forEach(tag => {
const elements = svgElement.querySelectorAll(tag);
elements.forEach(el => el.remove());
});
// Set proper viewBox and dimensions
svgElement.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svgElement.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
// Convert all styles to attributes
const elements = svgElement.querySelectorAll('*');
elements.forEach(el => {
const style = el.getAttribute('style');
if (style) {
const styleObj = {};
style.split(';').forEach(rule => {
const [prop, val] = rule.split(':');
if (prop && val) styleObj[prop.trim()] = val.trim();
});
if (styleObj['fill']) el.setAttribute('fill', styleObj['fill']);
if (styleObj['stroke']) el.setAttribute('stroke', styleObj['stroke']);
if (styleObj['stroke-width']) el.setAttribute('stroke-width', styleObj['stroke-width']);
if (styleObj['opacity']) el.setAttribute('opacity', styleObj['opacity']);
el.removeAttribute('style');
}
// Ensure paths have proper fill for cutting
if (el.tagName === 'path' && !el.getAttribute('fill')) {
el.setAttribute('fill', '#000000');
}
});
return `<?xml version="1.0" encoding="UTF-8"?>\n${svgElement.outerHTML}`;
};
// --- Main Application Component ---
export default function CutForgeStudio() {
const [state, dispatch] = useReducer(reducer, initialState);
const canvasRef = useRef(null);
const imageRef = useRef(null);
const containerRef = useRef(null);
const [previewMode, setPreviewMode] = useState('original'); // 'original', 'masked', 'vector'
// --- Handlers ---
const handleFileUpload = async (e) => {
const file = e.target.files[0];
if (!file) return;
dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' });
dispatch({ type: 'SET_ERROR', payload: null });
try {
let processedFile = file;
// Handle HEIC files
if (file.name.toLowerCase().endsWith('.heic')) {
dispatch({ type: 'SET_STATUS', payload: 'UPLOADING' });
processedFile = await convertHeicToBlob(file);
}
const url = URL.createObjectURL(processedFile);
imageRef.current.src = url;
imageRef.current.onload = () => {
dispatch({ type: 'SET_IMAGE', payload: url });
processImage(url);
};
} catch (err) {
console.error('Upload error:', err);
dispatch({ type: 'SET_ERROR', payload: 'Failed to load image. Please try again.' });
dispatch({ type: 'SET_STATUS', payload: 'IDLE' });
}
};
const processImage = useCallback((src) => {
const canvas = canvasRef.current;
const img = imageRef.current;
if (!canvas || !img) return;
// Set canvas dimensions (max 2000px for performance)
const maxSize = 2000;
let width = img.naturalWidth;
let height = img.naturalHeight;
if (width > maxSize || height > maxSize) {
const ratio = Math.min(maxSize / width, maxSize / height);
width = Math.floor(width * ratio);
height = Math.floor(height * ratio);
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
// Apply background removal
removeBackgroundAdvanced(canvas, state.settings.tolerance, state.settings.bgColor);
dispatch({ type: 'SET_STATUS', payload: 'MASKING' });
setPreviewMode('masked');
}, [state.settings.tolerance, state.settings.bgColor]);
const generateVector = useCallback(async () => {
if (!canvasRef.current) return;
dispatch({ type: 'SET_STATUS', payload: 'VECTORIZING' });
try {
const rawSvg = await vectorizeImage(canvasRef.current, state.settings);
const cleanSvg = sanitizeSvgForCutting(rawSvg);
dispatch({ type: 'SET_SVG', payload: cleanSvg });
setPreviewMode('vector');
} catch (error) {
console.error('Vectorization error:', error);
dispatch({ type: 'SET_ERROR', payload: 'Vectorization failed. Try adjusting settings.' });
dispatch({ type: 'SET_STATUS', payload: 'MASKING' });
}
}, [state.settings]);
const downloadSvg = () => {
if (!state.processedSvg) return;
const blob = new Blob([state.processedSvg], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `cutforge-${Date.now()}.svg`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
const downloadPreview = () => {
if (!canvasRef.current) return;
const link = document.createElement('a');
link.download = `cutforge-preview-${Date.now()}.png`;
link.href = canvasRef.current.toDataURL('image/png');
link.click();
};
const handleZoom = (delta) => {
const newZoom = Math.max(25, Math.min(400, state.zoom + delta));
dispatch({ type: 'SET_ZOOM', payload: newZoom });
};
const resetWorkspace = () => {
dispatch({ type: 'RESET' });
setPreviewMode('original');
if (canvasRef.current) {
const ctx = canvasRef.current.getContext('2d');
ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
}
};
// Re-process when settings change
useEffect(() => {
if (state.imageSrc && state.status === 'MASKING' || state.status === 'READY') {
const timer = setTimeout(() => {
processImage(state.imageSrc);
}, 300);
return () => clearTimeout(timer);
}
}, [state.settings.tolerance, state.settings.bgColor, state.imageSrc]);
// --- Render Helpers ---
const renderStatusBadge = () => {
const config = {
IDLE: { color: 'bg-gray-200 text-gray-600', label: 'Ready' },
UPLOADING: { color: 'bg-saffron text-ink', label: 'Uploading...' },
MASKING: { color: 'bg-forest text-white', label: 'Processing' },
VECTORIZING: { color: 'bg-forest text-white animate-pulse', label: 'Vectorizing...' },
READY: { color: 'bg-saffron text-ink', label: 'Complete' }
};
const { color, label } = config[state.status];
return (
<span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-widest ${color}`}>
{label}
</span>
);
};
return (
<div className="min-h-screen bg-bone font-sans text-ink flex flex-col overflow-hidden">
{/* Header */}
<header className="h-16 border-b border-ink/10 flex justify-between px-6 items-center sticky top-0 bg-bone/90 backdrop-blur z-10">
<div className="flex items-center gap-2">
<div className="w-8 h-8 bg-forest rounded-lg flex items-center justify-center text-white">
<Layers size={20} />
</div>
<h1 className="font-serif font-bold text-xl tracking-tight">CutForge Studio</h1>
</div>
<div className="flex items-center gap-4">
{renderStatusBadge()}
<a
href="https://huggingface.co/spaces/akhaliq/anycoder"
target="_blank"
rel="noopener noreferrer"
className="text-xs font-medium text-ink/60 hover:text-forest transition-colors underline"
>
Built with anycoder
</a>
</div>
</header>
{/* Main Grid Layout */}
<main className="flex-1 grid grid-cols-12 h-[calc(100vh - 64px)]">
{/* LEFT RAIL: Controls */}
<aside className="col-span-3 border-r border-ink/10 bg-bone p-6 flex flex-col gap-6 overflow-y-auto">
{/* Upload Section */}
<div className="space-y-4">
<h2 className="font-serif text-lg font-bold flex items-center gap-2">
<Upload size={18} /> Source Image
</h2>
<div className="relative group cursor-pointer">
<input
type="file"
accept=".png,.jpg,.jpeg,.heic,.webp"
onChange={handleFileUpload}
className="absolute inset-0 w-full h-full opacity-0 z-10 cursor-pointer"
/>
<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">
<ImageIcon className="text-ink/40 mb-2" size={32} />
<span className="text-sm font-medium">Drop Image or Click</span>
<span className="text-xs text-ink/50 mt-1">PNG, JPG, HEIC, WebP</span>
</div>
</div>
</div>
{/* Preview Mode Toggle */}
{state.imageSrc && (
<div className="space-y-3">
<h2 className="font-serif text-lg font-bold flex items-center gap-2">
<ImageIcon size={18} /> Preview Mode
</h2>
<div className="grid grid-cols-3 gap-2">
<button
onClick={() => setPreviewMode('original')}
className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
previewMode === 'original'
? 'bg-forest text-white border-forest'
: 'bg-white text-ink border-ink/20 hover:border-forest'
}`}
>
Original
</button>
<button
onClick={() => setPreviewMode('masked')}
className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
previewMode === 'masked'
? 'bg-forest text-white border-forest'
: 'bg-white text-ink border-ink/20 hover:border-forest'
}`}
>
Masked
</button>
<button
onClick={() => {
setPreviewMode('vector');
if (!state.processedSvg) generateVector();
className={`px-3 py-2 text-xs font-medium rounded-lg border transition-all ${
previewMode === 'vector'
? 'bg-forest text-white border-forest'
: 'bg-white text-ink border-ink/20 hover:border-forest'
}`}
>
Vector
</button>
</div>
</div>
)}
{/* Controls Section */}
{state.imageSrc && (
<div className="space-y-5">
<h2 className="font-serif text-lg font-bold flex items-center gap-2">
<Sliders size={18} /> Settings
</h2>
{/* Tolerance Slider */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-xs font-bold uppercase tracking-wider text-ink/70">Background Tolerance</label>
<span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.tolerance}</span>
</div>
<input
type="range"
min="0" max="150"
value={state.settings.tolerance}
onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { tolerance: parseInt(e.target.value) } })}
className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
/>
<p className="text-xs text-ink/50">Higher = more aggressive removal</p>
</div>
{/* Background Color Picker */}
<div className="space-y-2">
<label className="text-xs font-bold uppercase tracking-wider text-ink/70">Background Color</label>
<div className="flex gap-2">
<input
type="color"
value={state.settings.bgColor}
onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { bgColor: e.target.value } })}
className="w-10 h-10 rounded border border-ink/20 cursor-pointer"
/>
<input
type="text"
value={state.settings.bgColor}
onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { bgColor: e.target.value } })}
className="flex-1 bg-white border border-ink/10 rounded px-3 text-sm font-mono"
/>
</div>
</div>
{/* Color Count */}
<div className="space-y-2">
<label className="text-xs font-bold uppercase tracking-wider text-ink/70">Color Count</label>
<select
value={state.settings.colorCount}
onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { colorCount: parseInt(e.target.value) } })}
className="w-full bg-white border border-ink/10 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-forest"
>
<option value="1">1 Color (Monochrome)</option>
<option value="2">2 Colors</option>
<option value="4">4 Colors</option>
<option value="8">8 Colors</option>
<option value="16">16 Colors</option>
</select>
</div>
{/* Simplification Slider */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-xs font-bold uppercase tracking-wider text-ink/70">Path Simplification</label>
<span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.simplification}</span>
</div>
<input
type="range"
min="0" max="2" step="0.1"
value={state.settings.simplification}
onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { simplification: parseFloat(e.target.value) } })}
className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
/>
<p className="text-xs text-ink/50">Higher = smoother paths</p>
</div>
{/* Line Threshold */}
<div className="space-y-2">
<div className="flex justify-between items-center">
<label className="text-xs font-bold uppercase tracking-wider text-ink/70">Line Threshold</label>
<span className="text-xs font-mono bg-ink/10 px-2 py-1 rounded">{state.settings.ltres}</span>
</div>
<input
type="range"
min="0.1" max="5" step="0.1"
value={state.settings.ltres}
onChange={(e) => dispatch({ type: 'SET_SETTINGS', payload: { ltres: parseFloat(e.target.value) } })}
className="w-full h-2 bg-ink/10 rounded-lg appearance-none cursor-pointer accent-forest"
/>
</div>
{/* Vectorize Button */}
<button
onClick={generateVector}
disabled={state.status === 'VECTORIZING'}
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"
>
<Wand2 size={16} />
{state.status === 'VECTORIZING' ? 'Processing...' : 'Generate Vector'}
</button>
</div>
)}
{/* Actions */}
<div className="mt-auto pt-6 border-t border-ink/10 space-y-3">
{state.processedSvg && (
<button
onClick={downloadSvg}
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"
>
<Download size={16} /> Download SVG
</button>
)}
{state.imageSrc && (
<button
onClick={downloadPreview}
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"
>
<Download size={16} /> Download Preview
</button>
)}
<button
onClick={resetWorkspace}
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"
>
<Trash2 size={16} /> Reset Workspace
</button>
</div>
</aside>
{/* MAIN STAGE: Preview Area */}
<section className="col-span-9 bg-white/50 relative flex flex-col">
{/* Toolbar */}
<div className="h-12 border-b border-ink/10 flex items-center justify-between px-6 bg-white">
<div className="flex items-center gap-4">
<span className="text-xs font-mono text-ink/50">
{state.imageSrc ? `Image Loaded • ${previewMode.toUpperCase()} Mode` : 'Waiting for image...'}
</span>
{state.error && (
<span className="text-xs font-medium text-red-600 flex items-center gap-1">
<AlertCircle size={12} /> {state.error}
</span>
)}
</div>
<div className="flex items-center gap-2">
<button
onClick={() => handleZoom(-25)}
className="p-2 hover:bg-ink/5 rounded transition-colors"
title="Zoom Out"
>
<ZoomOut size={16} />
</button>
<span className="text-xs font-mono w-12 text-center">{state.zoom}%</span>
<button
onClick={() => handleZoom(25)}
className="p-2 hover:bg-ink/5 rounded transition-colors"
title="Zoom In"
>
<ZoomIn size={16} />
</button>
</div>
</div>
{/* Canvas/SVG Container */}
<div
ref={containerRef}
className="flex-1 relative overflow-auto flex items-center justify-center p-8"
>
{/* Transparency Checkerboard Background */}
<div className="absolute inset-0 bg-checkerboard bg-size-checkerboard opacity-50 pointer-events-none" />
{state.imageSrc && (
<div
className="relative shadow-2xl rounded-lg overflow-hidden bg-white transition-transform"
style={{ transform: `scale(${state.zoom / 100})` }}
>
{/* Hidden Image Ref for processing */}
<img ref={imageRef} className="hidden" alt="source" />
{/* Canvas for Masking Preview */}
<canvas
ref={canvasRef}
className="max-w-full max-h-full object-contain"
style={{ display: previewMode === 'vector' ? 'none' : 'block' }}
/>
{/* SVG Output Overlay */}
{state.processedSvg && previewMode === 'vector' && (
<div
className="w-full h-full"
dangerouslySetInnerHTML={{
__html: state.processedSvg.replace('<svg', '<svg class="w-full h-full"')
/>
)}
{/* Loading Overlay */}
{(state.status === 'UPLOADING' || state.status === 'VECTORIZING') && (
<div className="absolute inset-0 bg-bone/90 flex flex-col items-center justify-center z-20">
<Wand2 className="text-forest animate-spin mb-4" size={48} />
<p className="font-serif text-lg text-ink">Processing...</p>
<p className="text-xs font-mono text-ink/60 mt-2 uppercase tracking-widest">{state.status}</p>
</div>
)}
</div>
)}
{!state.imageSrc && (
<div className="text-center opacity-40">
<ImageIcon size={64} className="mx-auto mb-4 text-ink/20" />
<p className="font-serif text-xl">No Image Loaded</p>
<p className="text-sm text-ink/50 mt-2">Upload an image to get started</p>
</div>
)}
</div>
</section>
</main>
</div>
);
}