import React, { useState, useCallback } from 'react'; import { useDropzone } from 'react-dropzone'; import { Upload, Trash2, Settings2, Download, Grid3X3, CheckCircle2, HelpCircle, X, Image as ImageIcon, Save, FolderOpen, Sparkles, ChevronLeft, Copy, Check, Info, Lightbulb, ListOrdered, AlertTriangle, Mail, Github, Star } from 'lucide-react'; import { generateHoverOutlines, generateSpriteSheet } from './utils/canvasProcessor'; import { useLanguage } from './context/LanguageContext'; import { ThemeToggle, LanguageToggle } from './components/Toggles'; import ContactPage from './pages/ContactPage'; import pixelBindLogo from './assets/PixelBind.png'; const GRID_RESOLUTIONS = [16, 32, 48, 64]; const CONTACT_EMAIL = 'baltacimustafa@outlook.com'; const CONTACT_HASH = '#contact'; const REPO_URL = 'https://github.com/mustafabaltaci/PixelBind'; const PROMPTS_URL = 'https://script.google.com/macros/s/AKfycbxK6N5RGTE_rtCE5uMemIw03mH9ZiN8RvUFxN91uXxX6SvBKETW09WDZmlb0Cao8ZXn7w/exec'; const createAssetId = () => globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2, 11); const revokeObjectUrl = (url) => { if (typeof url === 'string' && url.startsWith('blob:')) { URL.revokeObjectURL(url); } }; const revokeAssetPreviews = (assetList) => { assetList.forEach((asset) => revokeObjectUrl(asset.preview)); }; const canvasToBlob = (canvas, type) => new Promise((resolve, reject) => { canvas.toBlob((blob) => { if (!blob) { reject(new Error('Canvas export failed')); return; } resolve(blob); }, type); }); // Mirror the hash-based view state so the contact page can be linked directly. const getActiveViewFromHash = () => { if (typeof window === 'undefined') return 'generator'; return window.location.hash === CONTACT_HASH ? 'contact' : 'generator'; }; export default function App() { const { t } = useLanguage(); const [activeView, setActiveView] = useState(getActiveViewFromHash); const [packageName, setPackageName] = useState('MySpriteSheet'); const [baseResolution, setBaseResolution] = useState(32); const [customGridW, setCustomGridW] = useState(64); const [customGridH, setCustomGridH] = useState(64); const [generateOutlines, setGenerateOutlines] = useState(false); const [assets, setAssets] = useState([]); const [isGenerating, setIsGenerating] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false); const [isPreviewOpen, setIsPreviewOpen] = useState(false); const [previewData, setPreviewData] = useState(null); // Prompt helper UI state lives here because the modal is driven from the top-level layout. const [isPromptModalOpen, setIsPromptModalOpen] = useState(false); const [promptsData, setPromptsData] = useState([]); const [selectedPrompt, setSelectedPrompt] = useState(null); const [isLoadingPrompts, setIsLoadingPrompts] = useState(false); const [isCopied, setIsCopied] = useState(false); const [showPromptGuide, setShowPromptGuide] = useState(false); const assetsRef = React.useRef(assets); const previewUrlRef = React.useRef(null); const copyResetTimeoutRef = React.useRef(null); React.useEffect(() => { assetsRef.current = assets; }, [assets]); React.useEffect(() => { previewUrlRef.current = previewData?.previewUrl ?? null; }, [previewData]); React.useEffect(() => { // Lazy-load prompt templates only when the modal is opened for the first time. if (!isPromptModalOpen || promptsData.length > 0) { return undefined; } const controller = new AbortController(); setIsLoadingPrompts(true); fetch(PROMPTS_URL, { signal: controller.signal }) .then((response) => { if (!response.ok) { throw new Error(`Prompt request failed with ${response.status}`); } return response.json(); }) .then((data) => { setPromptsData(Array.isArray(data) ? data : []); }) .catch((error) => { if (error.name !== 'AbortError') { console.error('Failed to fetch prompts:', error); } }) .finally(() => { if (!controller.signal.aborted) { setIsLoadingPrompts(false); } }); return () => controller.abort(); }, [isPromptModalOpen, promptsData.length]); React.useEffect(() => () => { revokeAssetPreviews(assetsRef.current); revokeObjectUrl(previewUrlRef.current); if (copyResetTimeoutRef.current) { window.clearTimeout(copyResetTimeoutRef.current); } }, []); const handleCopyPrompt = async (text) => { try { await navigator.clipboard.writeText(text); setIsCopied(true); if (copyResetTimeoutRef.current) { window.clearTimeout(copyResetTimeoutRef.current); } copyResetTimeoutRef.current = window.setTimeout(() => { setIsCopied(false); copyResetTimeoutRef.current = null; }, 2000); } catch (error) { console.error('Failed to copy prompt:', error); } }; React.useEffect(() => { // Keep browser navigation and direct links aligned with the rendered view. const syncViewFromHash = () => { setActiveView(getActiveViewFromHash()); }; window.addEventListener('hashchange', syncViewFromHash); return () => window.removeEventListener('hashchange', syncViewFromHash); }, []); const openContactPage = () => { // Close generator-specific overlays before switching to the contact view. setIsModalOpen(false); closePreview(); setIsPromptModalOpen(false); setSelectedPrompt(null); setActiveView('contact'); window.location.hash = CONTACT_HASH; window.scrollTo({ top: 0, behavior: 'smooth' }); }; const openGeneratorPage = () => { setActiveView('generator'); // Remove the contact hash so refreshes land back on the generator. window.history.replaceState(null, '', `${window.location.pathname}${window.location.search}`); window.scrollTo({ top: 0, behavior: 'smooth' }); }; const onDrop = useCallback(async (acceptedFiles) => { // Support both image uploads and saved workspace files in the same drop target. const projectFile = acceptedFiles.find(file => file.name.endsWith('.spack') || file.name.endsWith('.json')); if (projectFile) { const reader = new FileReader(); reader.onload = async (e) => { try { const data = JSON.parse(e.target.result); if (!data || !data.assets || !data.packageName) { throw new Error('Invalid project structure'); } setPackageName(data.packageName); if (data.baseResolution) setBaseResolution(data.baseResolution); if (data.customGridW) setCustomGridW(data.customGridW); if (data.customGridH) setCustomGridH(data.customGridH); if (data.generateOutlines !== undefined) setGenerateOutlines(data.generateOutlines); // Rehydrate the serialized asset payload back into File objects and blob URLs. const restoredAssets = await Promise.all(data.assets.map(async (asset) => { const res = await fetch(asset.base64Data); const blob = await res.blob(); const file = new File([blob], asset.fileName, { type: asset.fileType }); return { id: asset.id || createAssetId(), customName: asset.customName || asset.fileName, file, preview: URL.createObjectURL(file), gridSpan: asset.gridSpan || { w: 1, h: 1 }, padding: asset.padding || { x: 0, y: 0 }, removeBg: asset.removeBg || false, tolerance: asset.tolerance || 15, cleanInnerWhites: asset.cleanInnerWhites || false }; })); setAssets((prev) => { revokeAssetPreviews(prev); return restoredAssets; }); } catch (error) { console.error("Failed to load project:", error); alert(t('invalidProject')); } }; reader.readAsText(projectFile); return; } // Plain image uploads are normalized into the internal asset shape with sane defaults. const imageFiles = acceptedFiles.filter(file => file.type.startsWith('image/')); const newAssets = imageFiles.map(file => { const lastDotIndex = file.name.lastIndexOf('.'); const customName = lastDotIndex !== -1 ? file.name.substring(0, lastDotIndex) : file.name; return { id: createAssetId(), file, customName, preview: URL.createObjectURL(file), gridSpan: { w: 1, h: 1 }, padding: { x: 0, y: 0 }, removeBg: true, tolerance: 15, cleanInnerWhites: false }; }); setAssets(prev => [...prev, ...newAssets]); }, [t]); // react-dropzone handles click-to-upload and drag-and-drop with the same configuration. const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop, accept: { 'image/png': ['.png'], 'image/jpeg': ['.jpg', '.jpeg'], 'application/json': ['.json', '.spack'], 'application/x-spritepacker': ['.spack'] } }); // Small state updaters keep the JSX readable when editing per-asset options. const removeAsset = (id) => { setAssets((prev) => { const assetToRemove = prev.find((asset) => asset.id === id); revokeObjectUrl(assetToRemove?.preview); return prev.filter((asset) => asset.id !== id); }); }; const handleClearAll = () => { if (assets.length === 0) return; if (window.confirm(t('confirmClear'))) { setAssets((prev) => { revokeAssetPreviews(prev); return []; }); } }; const updateAssetSetting = (id, setting, value) => { setAssets(prev => prev.map(a => a.id === id ? { ...a, [setting]: value } : a )); }; const updateGridSpan = (id, axis, value) => { setAssets(prev => prev.map(a => a.id === id ? { ...a, gridSpan: { ...a.gridSpan, [axis]: parseInt(value) || 1 } } : a )); }; const updatePadding = (id, axis, value) => { setAssets(prev => prev.map(a => a.id === id ? { ...a, padding: { ...a.padding, [axis]: parseInt(value) || 0 } } : a )); }; // Trigger a browser download without leaving the page or needing a backend. const downloadFile = (blob, fileName) => { const link = document.createElement('a'); const objectUrl = URL.createObjectURL(blob); link.download = fileName; link.href = objectUrl; document.body.appendChild(link); link.click(); link.remove(); revokeObjectUrl(objectUrl); }; const closePreview = useCallback(() => { setIsPreviewOpen(false); setPreviewData((prev) => { revokeObjectUrl(prev?.previewUrl); return null; }); }, []); const handleSaveProject = async () => { try { // Inline file data into the workspace export so projects are fully portable. const serializedAssets = await Promise.all( assets.map(async (asset) => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { resolve({ id: asset.id, customName: asset.customName, gridSpan: asset.gridSpan, padding: asset.padding, removeBg: asset.removeBg, tolerance: asset.tolerance, cleanInnerWhites: asset.cleanInnerWhites, fileName: asset.file.name, fileType: asset.file.type, base64Data: reader.result }); }; reader.onerror = reject; reader.readAsDataURL(asset.file); }); }) ); const projectData = { version: 1, packageName, baseResolution, customGridW, customGridH, generateOutlines, assets: serializedAssets }; const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(projectData)); const downloadAnchorNode = document.createElement('a'); downloadAnchorNode.setAttribute("href", dataStr); downloadAnchorNode.setAttribute("download", `${packageName}_workspace.spack`); document.body.appendChild(downloadAnchorNode); downloadAnchorNode.click(); downloadAnchorNode.remove(); } catch (error) { console.error('Failed to save project:', error); alert(t('failedToSave')); } }; const handleConfirmDownload = () => { // The preview modal batches every generated artifact into one confirmation step. if (!previewData) return; downloadFile(previewData.mainImage, `${packageName}.png`); const tsxBlob = new Blob([previewData.tsxContent], { type: 'text/xml' }); downloadFile(tsxBlob, `${packageName}.tsx`); if (previewData.outlinesImage) { downloadFile(previewData.outlinesImage, `${packageName}_outlines.png`); } closePreview(); }; const handleGenerate = async () => { if (assets.length === 0) return; setIsGenerating(true); // Custom mode allows non-square cells while presets stay square. const activeGridW = baseResolution === 'custom' ? (parseInt(customGridW, 10) || 32) : (parseInt(baseResolution, 10) || 32); const activeGridH = baseResolution === 'custom' ? (parseInt(customGridH, 10) || 32) : (parseInt(baseResolution, 10) || 32); try { const { canvas, packing } = await generateSpriteSheet(assets, { w: activeGridW, h: activeGridH }, { generateOutlines }); const mainImageBlob = await canvasToBlob(canvas); // TSX metadata lets Tiled consume the exported sheet without extra manual setup. const tileCount = packing.placements.length; const columns = Math.floor(packing.width / activeGridW); const tsxContent = `\n\n \n`; let outlinesImageBlob = null; if (generateOutlines) { const outlineCanvas = generateHoverOutlines(canvas); outlinesImageBlob = await canvasToBlob(outlineCanvas); } setPreviewData((prev) => { revokeObjectUrl(prev?.previewUrl); return { mainImage: mainImageBlob, outlinesImage: outlinesImageBlob, tsxContent, previewUrl: URL.createObjectURL(mainImageBlob) }; }); setIsPreviewOpen(true); } catch (error) { console.error(t('generationFailed'), error); } finally { setIsGenerating(false); } }; // Reuse the same glassmorphism tokens across panels and modals for visual consistency. const liquidGlassClass = "backdrop-blur-3xl bg-white/75 dark:bg-gray-950/40 border border-slate-200/80 dark:border-white/10 shadow-[0_25px_50px_-12px_rgba(15,23,42,0.18),_inset_0_1px_1px_rgba(255,255,255,0.7)] dark:shadow-[0_25px_50px_-12px_rgba(0,0,0,0.5),_inset_0_1px_1px_rgba(255,255,255,0.1)] transition-all duration-500"; const nestedGlassClass = "bg-white/80 dark:bg-white/5 border border-slate-200/80 dark:border-white/10 shadow-[inset_0_1px_1px_rgba(255,255,255,0.45)] dark:shadow-[inset_0_1px_1px_rgba(255,255,255,0.05)] rounded-2xl transition-all duration-300"; return (
{/* Background accents for depth */}
{/* Liquid Glass Header */}
PixelBind logo

{t('title')}

{activeView === 'generator' ? ( <> ) : ( )}

{t('description')}

{activeView === 'generator' && ( <>
setPackageName(e.target.value)} className="bg-white/10 dark:bg-black/20 border border-white/10 rounded-xl px-4 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent outline-none transition-all w-48 font-bold text-gray-800 dark:text-white" placeholder={t('packNamePlaceholder')} />
{baseResolution === 'custom' && (
setCustomGridW(parseInt(e.target.value) || '')} className="bg-white/10 dark:bg-black/20 border border-white/10 rounded-xl pl-2 pr-2 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none transition-all w-20 font-bold text-gray-800 dark:text-white text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" min="1" placeholder="W" /> w
×
setCustomGridH(parseInt(e.target.value) || '')} className="bg-white/10 dark:bg-black/20 border border-white/10 rounded-xl pl-2 pr-2 py-2 text-sm focus:ring-2 focus:ring-indigo-500 outline-none transition-all w-20 font-bold text-gray-800 dark:text-white text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" min="1" placeholder="H" /> h
)}
)}
{activeView === 'contact' ? ( ) : (
{/* Liquid Glass Dropzone */}

{isDragActive ? t('dropActive') : t('dropInactive')}

{t('dropSupport')}

{/* Asset Tiles */}
{assets.map((asset) => (
preview
updateAssetSetting(asset.id, 'customName', e.target.value)} className="text-sm font-black text-gray-900 dark:text-white bg-transparent border border-transparent hover:bg-white/10 hover:border-white/10 focus:bg-black/20 focus:border-indigo-500 rounded-lg px-2 py-1 -ml-2 outline-none w-full truncate transition-all shadow-none" title={t('renameAsset')} />
{['W', 'H'].map((dim, i) => (
{dim} i === 0 ? updateGridSpan(asset.id, 'w', e.target.value) : updateGridSpan(asset.id, 'h', e.target.value)} className="w-8 bg-transparent text-xs font-bold outline-none text-gray-800 dark:text-white" />
))} {['PX', 'PY'].map((pad, i) => (
{pad} i === 0 ? updatePadding(asset.id, 'x', e.target.value) : updatePadding(asset.id, 'y', e.target.value)} className="w-8 bg-transparent text-xs font-bold outline-none text-indigo-700 dark:text-indigo-300" />
))}
{asset.removeBg && (
{t('tolerance')} {asset.tolerance} updateAssetSetting(asset.id, 'tolerance', parseInt(e.target.value))} className="flex-1 h-1.5 bg-black/30 rounded-full appearance-none cursor-pointer accent-indigo-500 ring-1 ring-white/5" />
)}
))}
{/* Liquid Glass Configuration Panel */}

{t('configuration')}

{t('logicInfo')}

{t('totalAssets')} {assets.length > 0 && ( )}
{assets.length}
{t('targetGrid')} {baseResolution === 'custom' ? `${customGridW || 32}x${customGridH || 32}` : `${baseResolution}x${baseResolution}`}
{assets.length > 0 && (
{t('readyToGenerate')}
)}
)}
{/* Liquid Glass Modal */} {activeView === 'generator' && isModalOpen && (
setIsModalOpen(false)} />

{t('modalTitle')}

{t('modalSubtitle')}

{[1,2,3,4,5,6].map((i) => (
{i}

{t(`step${i}Title`)}

{t(`step${i}Text`)}

))}
)} {/* Liquid Glass Preview Modal */} {activeView === 'generator' && isPreviewOpen && previewData && (

{t('previewTitle')}

Sprite Sheet Preview
)} {/* Prompt Ideas Modal */} {activeView === 'generator' && isPromptModalOpen && (
{ setIsPromptModalOpen(false); setSelectedPrompt(null); }} />

{t('promptIdeas')}

{!selectedPrompt && ( )} {selectedPrompt && ( )}
{isLoadingPrompts ? (

{t('loading')}

) : selectedPrompt ? (

{selectedPrompt.title}

{selectedPrompt.prompt}
) : (
{showPromptGuide && (

{t('howToUsePrompts')}

{t('promptsIntro')}

{t('promptsRecommendation')}

{t('configuration')}

{[1,2,3,4,5,6].map(i => (
{i}

{t(`promptStep${i}Title`)}

{t(`promptStep${i}Text`)}

))}

{t('importantNotes')}

    {[1,2,3].map(i => (
  • {t(`note${i}`)}
  • ))}
)}
{promptsData.map((item, idx) => ( ))}
)}
)} {/* Footer */}
); }