feat: add Favicon Generator app with ImageMagick WASM support

This commit is contained in:
2026-02-26 17:48:16 +01:00
parent d99c88df0e
commit 1f1b138089
16 changed files with 987 additions and 5 deletions

View File

@@ -0,0 +1,40 @@
'use client';
import * as React from 'react';
import { Copy, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { toast } from 'sonner';
interface CodeSnippetProps {
code: string;
language?: string;
}
export function CodeSnippet({ code, language }: CodeSnippetProps) {
const [copied, setCopied] = React.useState(false);
const handleCopy = () => {
navigator.clipboard.writeText(code);
setCopied(true);
toast.success('Copied to clipboard');
setTimeout(() => setCopied(false), 2000);
};
return (
<div className="relative group">
<div className="absolute right-4 top-4 opacity-0 group-hover:opacity-100 transition-opacity">
<Button
variant="secondary"
size="icon-xs"
onClick={handleCopy}
className="bg-background/50 backdrop-blur-md border border-border"
>
{copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
</Button>
</div>
<pre className="p-4 rounded-lg bg-input backdrop-blur-sm border border-border overflow-x-auto font-mono text-xs text-muted-foreground leading-relaxed">
<code>{code}</code>
</pre>
</div>
);
}

View File

@@ -0,0 +1,156 @@
'use client';
import * as React from 'react';
import { Upload, X, FileImage, HardDrive } from 'lucide-react';
import { cn } from '@/lib/utils/cn';
import { Button } from '@/components/ui/button';
export interface FaviconFileUploadProps {
onFileSelect: (file: File) => void;
onFileRemove: () => void;
selectedFile?: File | null;
disabled?: boolean;
}
export function FaviconFileUpload({
onFileSelect,
onFileRemove,
selectedFile,
disabled = false,
}: FaviconFileUploadProps) {
const [isDragging, setIsDragging] = React.useState(false);
const [dimensions, setDimensions] = React.useState<string | null>(null);
const fileInputRef = React.useRef<HTMLInputElement>(null);
React.useEffect(() => {
if (selectedFile) {
const img = new Image();
img.onload = () => {
setDimensions(`${img.width} × ${img.height}`);
URL.revokeObjectURL(img.src);
};
img.src = URL.createObjectURL(selectedFile);
} else {
setDimensions(null);
}
}, [selectedFile]);
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (!disabled) setIsDragging(true);
};
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
};
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragging(false);
if (disabled) return;
const files = Array.from(e.dataTransfer.files);
if (files.length > 0 && files[0].type.startsWith('image/')) {
onFileSelect(files[0]);
}
};
const handleFileInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
if (files.length > 0 && files[0].type.startsWith('image/')) {
onFileSelect(files[0]);
}
};
const handleClick = () => {
if (!disabled) fileInputRef.current?.click();
};
return (
<div className="w-full space-y-3">
<input
ref={fileInputRef}
type="file"
className="hidden"
accept="image/*"
onChange={handleFileInput}
disabled={disabled}
/>
{selectedFile ? (
<div className="border border-border rounded-lg p-4 bg-card/50 backdrop-blur-sm">
<div className="flex items-start gap-4">
<div className="p-2 bg-primary/10 rounded-lg">
<FileImage className="h-6 w-6 text-primary" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-start justify-between gap-2">
<p className="text-sm font-semibold text-foreground truncate" title={selectedFile.name}>
{selectedFile.name}
</p>
<Button
variant="ghost"
size="icon-xs"
onClick={onFileRemove}
disabled={disabled}
className="rounded-full hover:bg-destructive/10 hover:text-destructive"
>
<X className="h-3.5 w-3.5" />
</Button>
</div>
<div className="mt-2 flex gap-4 text-[10px] text-muted-foreground uppercase tracking-wider font-bold">
<div className="flex items-center gap-1.5">
<HardDrive className="h-3 w-3" />
<span>{(selectedFile.size / 1024).toFixed(1)} KB</span>
</div>
{dimensions && (
<div className="flex items-center gap-1.5">
<FileImage className="h-3 w-3" />
<span>{dimensions}</span>
</div>
)}
</div>
</div>
</div>
</div>
) : (
<div
onClick={handleClick}
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={cn(
'border-2 border-dashed rounded-xl p-10 text-center cursor-pointer transition-all duration-300',
'hover:border-primary/50 hover:bg-primary/5',
{
'border-primary bg-primary/10 scale-[0.98]': isDragging,
'border-border bg-muted/30': !isDragging,
'opacity-50 cursor-not-allowed': disabled,
}
)}
>
<div className="bg-primary/10 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
<Upload className="h-8 w-8 text-primary" />
</div>
<p className="text-sm font-semibold text-foreground mb-1">
Drop icon source here
</p>
<p className="text-xs text-muted-foreground">
Recommended: 512x512 PNG or SVG
</p>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,301 @@
'use client';
import * as React from 'react';
import { Download, Loader2, RefreshCw, Code2, Globe, Layout, Palette } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { FaviconFileUpload } from './FaviconFileUpload';
import { CodeSnippet } from './CodeSnippet';
import { generateFaviconSet } from '@/lib/favicon/faviconService';
import { downloadBlobsAsZip } from '@/lib/media/utils/fileUtils';
import type { FaviconSet, FaviconOptions } from '@/types/favicon';
import { toast } from 'sonner';
export function FaviconGenerator() {
const [sourceFile, setSourceFile] = React.useState<File | null>(null);
const [options, setOptions] = React.useState<FaviconOptions>({
name: 'My Awesome App',
shortName: 'App',
backgroundColor: '#ffffff',
themeColor: '#3b82f6',
});
const [isGenerating, setIsGenerating] = React.useState(false);
const [progress, setProgress] = React.useState(0);
const [result, setResult] = React.useState<FaviconSet | null>(null);
const handleGenerate = async () => {
if (!sourceFile) {
toast.error('Please upload a source image');
return;
}
setIsGenerating(true);
setProgress(0);
try {
const resultSet = await generateFaviconSet(sourceFile, options, (p) => {
setProgress(p);
});
setResult(resultSet);
toast.success('Favicon set generated successfully!');
} catch (error) {
console.error(error);
toast.error('Failed to generate favicons');
} finally {
setIsGenerating(false);
}
};
const handleDownloadAll = async () => {
if (!result) return;
const files = result.icons.map((icon) => ({
blob: icon.blob!,
filename: icon.name,
}));
// Add manifest to ZIP
const manifestBlob = new Blob([result.manifest], { type: 'application/json' });
files.push({
blob: manifestBlob,
filename: 'site.webmanifest',
});
await downloadBlobsAsZip(files, 'favicons.zip');
toast.success('Downloading favicons ZIP...');
};
const handleReset = () => {
setSourceFile(null);
setResult(null);
setProgress(0);
};
return (
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
{/* Settings Column */}
<div className="lg:col-span-4 space-y-6">
<Card className="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Layout className="h-5 w-5 text-primary" />
App Details
</CardTitle>
<CardDescription>
Configure how your app appears on devices
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="app-name">Application Name</Label>
<Input
id="app-name"
value={options.name}
onChange={(e) => setOptions({ ...options, name: e.target.value })}
placeholder="e.g. My Awesome Website"
/>
</div>
<div className="space-y-2">
<Label htmlFor="short-name">Short Name</Label>
<Input
id="short-name"
value={options.shortName}
onChange={(e) => setOptions({ ...options, shortName: e.target.value })}
placeholder="e.g. My App"
/>
<p className="text-[10px] text-muted-foreground">Used for mobile home screen labels</p>
</div>
</CardContent>
</Card>
<Card className="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Palette className="h-5 w-5 text-primary" />
Theme Colors
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="bg-color">Background</Label>
<div className="flex gap-2">
<Input
id="bg-color"
type="color"
className="w-10 p-1 h-10 shrink-0"
value={options.backgroundColor}
onChange={(e) => setOptions({ ...options, backgroundColor: e.target.value })}
/>
<Input
className="font-mono text-xs"
value={options.backgroundColor}
onChange={(e) => setOptions({ ...options, backgroundColor: e.target.value })}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="theme-color">Theme</Label>
<div className="flex gap-2">
<Input
id="theme-color"
type="color"
className="w-10 p-1 h-10 shrink-0"
value={options.themeColor}
onChange={(e) => setOptions({ ...options, themeColor: e.target.value })}
/>
<Input
className="font-mono text-xs"
value={options.themeColor}
onChange={(e) => setOptions({ ...options, themeColor: e.target.value })}
/>
</div>
</div>
</div>
</CardContent>
</Card>
<Card className="glass overflow-hidden">
<CardContent className="p-6">
<FaviconFileUpload
selectedFile={sourceFile}
onFileSelect={setSourceFile}
onFileRemove={() => setSourceFile(null)}
disabled={isGenerating}
/>
<Button
className="w-full mt-6"
size="lg"
disabled={!sourceFile || isGenerating}
onClick={handleGenerate}
>
{isGenerating ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Generating... {progress}%
</>
) : (
<>
<RefreshCw className="mr-2 h-4 w-4" />
Generate Favicons
</>
)}
</Button>
{result && (
<Button
variant="outline"
className="w-full mt-2"
onClick={handleReset}
>
Reset
</Button>
)}
</CardContent>
</Card>
</div>
{/* Results Column */}
<div className="lg:col-span-8 space-y-6">
{!result && !isGenerating ? (
<Card className="glass h-full flex flex-col items-center justify-center p-12 text-center text-muted-foreground border-dashed border-2">
<Globe className="h-12 w-12 mb-4 opacity-20" />
<h3 className="text-lg font-semibold text-foreground">Ready to generate</h3>
<p className="max-w-xs text-sm">Upload a square image (PNG or SVG recommended) and configure your app details to get started.</p>
</Card>
) : isGenerating ? (
<Card className="glass h-full flex flex-col items-center justify-center p-12 space-y-6">
<div className="relative">
<div className="h-24 w-24 rounded-full border-4 border-primary/20 animate-pulse" />
<Loader2 className="h-12 w-12 text-primary animate-spin absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2" />
</div>
<div className="w-full max-w-sm space-y-2">
<div className="flex justify-between text-xs font-bold uppercase tracking-widest text-muted-foreground">
<span>Processing Icons</span>
<span>{progress}%</span>
</div>
<Progress value={progress} className="h-1.5" />
</div>
</Card>
) : (
<div className="space-y-6 animate-fadeIn">
<div className="flex items-center justify-between gap-4">
<h2 className="text-2xl font-bold tracking-tight">Generated Assets</h2>
<Button onClick={handleDownloadAll} variant="default" className="shadow-lg shadow-primary/20">
<Download className="mr-2 h-4 w-4" />
Download All (ZIP)
</Button>
</div>
<Tabs defaultValue="icons" className="w-full">
<TabsList className="w-full">
<TabsTrigger value="icons" className="flex items-center gap-2">
<Layout className="h-4 w-4" />
Icons
</TabsTrigger>
<TabsTrigger value="html" className="flex items-center gap-2">
<Code2 className="h-4 w-4" />
HTML Code
</TabsTrigger>
<TabsTrigger value="manifest" className="flex items-center gap-2">
<Globe className="h-4 w-4" />
Manifest
</TabsTrigger>
</TabsList>
<TabsContent value="icons" className="mt-6">
<div className="grid grid-cols-2 md:grid-cols-3 gap-4">
{result?.icons.map((icon) => (
<Card key={icon.name} className="glass group overflow-hidden">
<div className="p-4 flex flex-col items-center text-center space-y-3">
<div className="relative h-20 w-20 flex items-center justify-center bg-black/20 rounded-lg p-2 border border-border group-hover:scale-110 transition-transform duration-300">
{icon.previewUrl && (
<img
src={icon.previewUrl}
alt={icon.name}
className="max-w-full max-h-full object-contain"
/>
)}
</div>
<div className="space-y-1 w-full">
<p className="text-[10px] font-bold text-foreground truncate uppercase tracking-tighter" title={icon.name}>
{icon.name}
</p>
<p className="text-[10px] text-muted-foreground">
{icon.width}x{icon.height} {(icon.size / 1024).toFixed(1)} KB
</p>
</div>
</div>
</Card>
))}
</div>
</TabsContent>
<TabsContent value="html" className="mt-6 space-y-4">
<div className="space-y-2">
<Label>Embed in your &lt;head&gt;</Label>
{result && <CodeSnippet code={result.htmlCode} />}
</div>
<div className="p-4 rounded-lg bg-info/5 border border-info/20">
<p className="text-xs text-info leading-relaxed">
<strong>Note:</strong> Make sure to place the generated files in your website&apos;s root directory or update the <code>href</code> paths accordingly.
</p>
</div>
</TabsContent>
<TabsContent value="manifest" className="mt-6">
<div className="space-y-2">
<Label>site.webmanifest</Label>
{result && <CodeSnippet code={result.manifest} />}
</div>
</TabsContent>
</Tabs>
</div>
)}
</div>
</div>
);
}