-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
297 lines (264 loc) · 11 KB
/
App.tsx
File metadata and controls
297 lines (264 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { PlatformKey, IconAttributes, GeneratedImageData, GroupedGeneratedIcons, IOSContentsJson, IOSContentsJsonImage, PlatformOption } from './types';
import { ALL_ICON_DEFINITIONS } from './constants';
import Header from './components/Header';
import Footer from './components/Footer';
import ImageDropzone from './components/ImageDropzone';
import PlatformSelector from './components/PlatformSelector';
import GeneratedIconsDisplay from './components/GeneratedIconsDisplay';
import Button from './components/Button';
import Spinner from './components/Spinner';
import { IPhoneIcon, IPadIcon, LaptopIcon, WatchIcon, AndroidIcon, StoreIcon } from './components/PlatformIcons';
// Ensure JSZip is available (loaded from CDN)
declare var JSZip: any;
const App: React.FC = () => {
const [sourceImageFile, setSourceImageFile] = useState<File | null>(null);
const [sourceImageUrl, setSourceImageUrl] = useState<string | null>(null);
const [selectedPlatforms, setSelectedPlatforms] = useState<PlatformKey[]>(Object.values(PlatformKey)); // Select all by default
const [generatedIcons, setGeneratedIcons] = useState<GeneratedImageData[]>([]);
const [isGenerating, setIsGenerating] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
const [isDarkMode, setIsDarkMode] = useState<boolean>(() => {
const storedTheme = localStorage.getItem('theme');
if (storedTheme) {
return storedTheme === 'dark';
}
// Default to dark if prefers-color-scheme is dark or not supported well
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
});
useEffect(() => {
if (isDarkMode) {
document.documentElement.classList.add('dark');
localStorage.setItem('theme', 'dark');
} else {
document.documentElement.classList.remove('dark');
localStorage.setItem('theme', 'light');
}
}, [isDarkMode]);
const toggleTheme = () => {
setIsDarkMode(prevMode => !prevMode);
};
const PLATFORM_OPTIONS: PlatformOption[] = [
{ id: PlatformKey.iPhone, label: 'iPhone', icon: <IPhoneIcon className="w-6 h-6" /> }, // Removed mr-2, handled by parent styling
{ id: PlatformKey.iPad, label: 'iPad', icon: <IPadIcon className="w-6 h-6" /> },
{ id: PlatformKey.watchOS, label: 'Apple Watch', icon: <WatchIcon className="w-6 h-6" /> },
{ id: PlatformKey.macOS, label: 'macOS', icon: <LaptopIcon className="w-6 h-6" /> },
{ id: PlatformKey.iOSMarketing, label: 'App Store', icon: <StoreIcon className="w-6 h-6" /> },
{ id: PlatformKey.Android, label: 'Android', icon: <AndroidIcon className="w-6 h-6" /> },
];
const handleImageUpload = useCallback((file: File) => {
setSourceImageFile(file);
const reader = new FileReader();
reader.onloadend = () => {
setSourceImageUrl(reader.result as string);
};
reader.readAsDataURL(file);
setGeneratedIcons([]); // Clear previous results
setError(null);
}, []);
const handlePlatformToggle = useCallback((platform: PlatformKey, checked: boolean) => {
setSelectedPlatforms(prev =>
checked ? [...prev, platform] : prev.filter(p => p !== platform)
);
}, []);
const resizeImage = useCallback(async (imageFile: File, targetWidth: number, targetHeight: number): Promise<string> => {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
reject(new Error('Failed to get canvas context'));
return;
}
const sourceAspect = img.width / img.height;
const targetAspect = targetWidth / targetHeight;
let sx = 0, sy = 0, sWidth = img.width, sHeight = img.height;
if (sourceAspect > targetAspect) {
sWidth = img.height * targetAspect;
sx = (img.width - sWidth) / 2;
} else if (sourceAspect < targetAspect) {
sHeight = img.width / targetAspect;
sy = (img.height - sHeight) / 2;
}
ctx.drawImage(img, sx, sy, sWidth, sHeight, 0, 0, targetWidth, targetHeight);
resolve(canvas.toDataURL('image/png'));
};
img.onerror = (err) => reject(err);
img.src = URL.createObjectURL(imageFile);
});
}, []);
const handleGenerateIcons = useCallback(async () => {
if (!sourceImageFile) {
setError('Please upload an image first.');
return;
}
if (selectedPlatforms.length === 0) {
setError('Please select at least one platform.');
return;
}
setIsGenerating(true);
setError(null);
setGeneratedIcons([]);
const iconsToGenerate = ALL_ICON_DEFINITIONS.filter(def => selectedPlatforms.includes(def.platformKey));
const generated: GeneratedImageData[] = [];
try {
for (const definition of iconsToGenerate) {
const dataUrl = await resizeImage(sourceImageFile, definition.width, definition.height);
generated.push({ ...definition, dataUrl });
}
setGeneratedIcons(generated);
} catch (e: any) {
console.error('Error generating icons:', e);
setError(`Failed to generate icons: ${e.message || 'Unknown error'}`);
} finally {
setIsGenerating(false);
}
}, [sourceImageFile, selectedPlatforms, resizeImage]);
const groupedIcons = useMemo((): GroupedGeneratedIcons => {
return generatedIcons.reduce((acc, icon) => {
const key = icon.platformKey.toString();
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(icon);
return acc;
}, {} as GroupedGeneratedIcons);
}, [generatedIcons]);
const generateContentsJson = (appleIcons: GeneratedImageData[]): string | null => {
const iosImages: IOSContentsJsonImage[] = appleIcons
.filter(icon => icon.iosMeta)
.map(icon => ({
size: icon.iosMeta!.size,
idiom: icon.iosMeta!.idiom,
filename: icon.iosMeta!.filenameForContentsJson,
scale: icon.iosMeta!.scale,
...(icon.iosMeta!.role && { role: icon.iosMeta!.role }),
...(icon.iosMeta!.subtype && { subtype: icon.iosMeta!.subtype }),
}));
if (iosImages.length === 0) return null;
const contentsJson: IOSContentsJson = {
images: iosImages,
info: {
version: 1,
author: 'xcode',
},
};
return JSON.stringify(contentsJson, null, 2);
};
const handleDownloadAll = useCallback(async () => {
if (generatedIcons.length === 0) {
setError('No icons generated to download.');
return;
}
if (typeof JSZip === 'undefined') {
setError('JSZip library is not loaded. Cannot create ZIP file.');
console.error('JSZip not found!');
return;
}
setIsGenerating(true);
setError(null);
try {
const zip = new JSZip();
generatedIcons.forEach(icon => {
const base64Data = icon.dataUrl.split(',')[1];
zip.file(icon.pathInZip, base64Data, { base64: true });
});
const appleIcons = generatedIcons.filter(icon =>
[PlatformKey.iPhone, PlatformKey.iPad, PlatformKey.iOSMarketing, PlatformKey.macOS, PlatformKey.watchOS].includes(icon.platformKey)
);
if (appleIcons.length > 0) {
const contentsJsonString = generateContentsJson(appleIcons);
if (contentsJsonString) {
const contentsJsonPath = `Apple/Assets.xcassets/AppIcon.appiconset/Contents.json`;
zip.file(contentsJsonPath, contentsJsonString);
}
}
const zipBlob = await zip.generateAsync({ type: 'blob' });
const link = document.createElement('a');
link.href = URL.createObjectURL(zipBlob);
link.download = 'AppIcons.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
} catch (e: any) {
console.error('Error creating ZIP file:', e);
setError(`Failed to create ZIP file: ${e.message || 'Unknown error'}`);
} finally {
setIsGenerating(false);
}
}, [generatedIcons]);
return (
<div className="min-h-screen flex flex-col">
<Header isDarkMode={isDarkMode} toggleTheme={toggleTheme} />
<main className="flex-grow container mx-auto px-4 py-8">
<div className="max-w-5xl mx-auto">
<div className="bg-white dark:bg-brand-gray shadow-xl rounded-lg p-6 md:p-10">
<h2 className="text-3xl font-bold text-center text-slate-700 dark:text-gray-100 mb-8">
Generate Your App Icons Instantly
</h2>
<ImageDropzone onImageUpload={handleImageUpload} currentImageUrl={sourceImageUrl} />
{sourceImageFile && (
<>
<PlatformSelector
options={PLATFORM_OPTIONS}
selectedPlatforms={selectedPlatforms}
onPlatformToggle={handlePlatformToggle}
/>
<div className="mt-8 text-center">
<Button
onClick={handleGenerateIcons}
disabled={isGenerating || !sourceImageFile || selectedPlatforms.length === 0}
className="bg-brand-blue hover:bg-blue-600 text-white"
>
{isGenerating ? (
<>
<Spinner className="mr-2" /> Generating...
</>
) : (
'Generate Icons'
)}
</Button>
</div>
</>
)}
{error && (
<div
className="mt-6 border px-4 py-3 rounded-md text-center bg-red-100 border-red-400 text-red-700 dark:bg-red-900 dark:border-red-700 dark:text-red-100"
role="alert"
>
<p>{error}</p>
</div>
)}
</div>
{generatedIcons.length > 0 && !isGenerating && (
<div className="mt-12 bg-white dark:bg-brand-gray shadow-xl rounded-lg p-6 md:p-10">
<div className="flex justify-between items-center mb-6">
<h3 className="text-2xl font-semibold text-slate-700 dark:text-gray-100">Generated Icons</h3>
<Button
onClick={handleDownloadAll}
disabled={isGenerating}
className="bg-green-600 hover:bg-green-700 text-white"
>
{isGenerating && generatedIcons.length > 0 ? (
<>
<Spinner className="mr-2" /> Zipping...
</>
) : (
'Download All (.zip)'
)}
</Button>
</div>
<GeneratedIconsDisplay groupedIcons={groupedIcons} platformOptions={PLATFORM_OPTIONS} />
</div>
)}
</div>
</main>
<Footer />
</div>
);
};
export default App;