Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | 'use client';
/**
* ImageUploader Component
*
* Drag-and-drop image upload component with preview, progress tracking,
* and Cloudinary integration.
*/
import { useState, useCallback, useEffect } from 'react';
import { clientLogger } from '@/lib/logging/clientLogger';
import { useDropzone, FileRejection, Accept } from 'react-dropzone';
import { cn } from '@/lib/core';
import { Icon } from '@/components/ui/icons';
import { Button } from '@/components/ui/Button';
interface UploadedImage {
/** Unique identifier */
id: string;
/** File object (for pending uploads) */
file?: File;
/** Preview URL (blob URL for pending, actual URL for uploaded) */
previewUrl: string;
/** Cloudinary public ID (after upload) */
publicId?: string;
/** Final URL (after upload) */
url?: string;
/** Upload progress (0-100) */
progress: number;
/** Upload status */
status: 'pending' | 'uploading' | 'success' | 'error';
/** Error message if failed */
error?: string;
}
interface ImageUploaderProps {
/** Callback when images are uploaded successfully */
onUpload?: (images: UploadedImage[]) => void;
/** Callback when an image is removed */
onRemove?: (imageId: string) => void;
/** Callback when upload status changes */
onStatusChange?: (images: UploadedImage[]) => void;
/** Maximum number of files */
maxFiles?: number;
/** Maximum file size in bytes */
maxSize?: number;
/** Accepted file types */
accept?: Accept;
/** Upload endpoint */
uploadEndpoint?: string;
/** Whether to auto-upload on drop */
autoUpload?: boolean;
/** Initial images (already uploaded) */
initialImages?: UploadedImage[];
/** Whether multiple files are allowed */
multiple?: boolean;
/** Whether the uploader is disabled */
disabled?: boolean;
/** Additional class name */
className?: string;
/** Folder path for Cloudinary */
folder?: string;
/** Show image previews */
showPreviews?: boolean;
/** Compact mode (smaller UI) */
compact?: boolean;
}
const defaultAccept: Accept = {
'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif'],
};
function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function generateId(): string {
return `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}
export function ImageUploader({
onUpload,
onRemove,
onStatusChange,
maxFiles = 10,
maxSize = 10 * 1024 * 1024, // 10MB default
accept = defaultAccept,
uploadEndpoint = '/api/images/upload',
autoUpload = true,
initialImages = [],
multiple = true,
disabled = false,
className,
folder = 'uploads',
showPreviews = true,
compact = false,
}: ImageUploaderProps) {
const [images, setImages] = useState<UploadedImage[]>(initialImages);
// Clean up blob URLs on unmount
useEffect(() => {
return () => {
images.forEach((img) => {
if (img.previewUrl.startsWith('blob:')) {
URL.revokeObjectURL(img.previewUrl);
}
});
};
}, [images]);
// Notify parent of status changes
useEffect(() => {
onStatusChange?.(images);
}, [images, onStatusChange]);
const uploadImage = useCallback(
async (image: UploadedImage) => {
if (!image.file) return;
setImages((prev) =>
prev.map((img) =>
img.id === image.id ? { ...img, status: 'uploading' as const } : img
)
);
try {
const formData = new FormData();
formData.append('file', image.file);
formData.append('folder', folder);
const response = await fetch(uploadEndpoint, {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('Upload failed');
}
const result = await response.json();
setImages((prev) => {
const updated = prev.map((img) =>
img.id === image.id
? {
...img,
status: 'success' as const,
progress: 100,
publicId: result.publicId,
url: result.secureUrl || result.url,
}
: img
);
// Notify parent of successful uploads
const successfulImages = updated.filter(
(img) => img.status === 'success'
);
onUpload?.(successfulImages);
return updated;
});
} catch (error) {
setImages((prev) =>
prev.map((img) =>
img.id === image.id
? {
...img,
status: 'error' as const,
error: error instanceof Error ? error.message : 'Upload failed',
}
: img
)
);
}
},
[folder, uploadEndpoint, onUpload]
);
const onDrop = useCallback(
(acceptedFiles: File[], rejectedFiles: FileRejection[]) => {
// Handle rejected files
if (rejectedFiles.length > 0) {
clientLogger.warn('Rejected files', { rejectedFiles });
}
// Create image objects for accepted files
const newImages: UploadedImage[] = acceptedFiles.map((file) => ({
id: generateId(),
file,
previewUrl: URL.createObjectURL(file),
progress: 0,
status: 'pending' as const,
}));
setImages((prev) => {
const combined = [...prev, ...newImages];
// Limit to maxFiles
return combined.slice(0, maxFiles);
});
// Auto-upload if enabled
if (autoUpload) {
newImages.forEach((image) => uploadImage(image));
}
},
[maxFiles, autoUpload, uploadImage]
);
const { getRootProps, getInputProps, isDragActive, isDragReject } =
useDropzone({
onDrop,
accept,
maxSize,
maxFiles: multiple ? maxFiles - images.length : 1,
multiple,
disabled: disabled || images.length >= maxFiles,
});
const handleRemove = useCallback(
(imageId: string) => {
setImages((prev) => {
const image = prev.find((img) => img.id === imageId);
if (image?.previewUrl.startsWith('blob:')) {
URL.revokeObjectURL(image.previewUrl);
}
return prev.filter((img) => img.id !== imageId);
});
onRemove?.(imageId);
},
[onRemove]
);
const handleRetry = useCallback(
(imageId: string) => {
const image = images.find((img) => img.id === imageId);
if (image) {
uploadImage(image);
}
},
[images, uploadImage]
);
const handleUploadAll = useCallback(() => {
const pendingImages = images.filter((img) => img.status === 'pending');
pendingImages.forEach((image) => uploadImage(image));
}, [images, uploadImage]);
const pendingCount = images.filter((img) => img.status === 'pending').length;
return (
<div className={cn('space-y-4', className)}>
{/* Dropzone */}
<div
{...getRootProps()}
className={cn(
'relative border-2 border-dashed rounded-lg transition-colors cursor-pointer',
compact ? 'p-4' : 'p-8',
isDragActive && !isDragReject && 'border-primary-500 bg-primary-50 dark:bg-primary-900/20',
isDragReject && 'border-red-500 bg-red-50 dark:bg-red-900/20',
!isDragActive && 'border-gray-300 dark:border-gray-600 hover:border-gray-400 dark:hover:border-gray-500',
(disabled || images.length >= maxFiles) && 'opacity-50 cursor-not-allowed'
)}
>
<input {...getInputProps()} />
<div className="flex flex-col items-center justify-center text-center">
<Icon
name="upload-cloud"
className={cn(
'text-gray-400 dark:text-gray-500',
compact ? 'w-8 h-8 mb-2' : 'w-12 h-12 mb-4'
)}
/>
{isDragActive && !isDragReject ? (
<p className="text-primary-600 dark:text-primary-400 font-medium">
Drop the images here...
</p>
) : isDragReject ? (
<p className="text-red-600 dark:text-red-400 font-medium">
Some files are not allowed
</p>
) : (
<>
<p className="text-gray-600 dark:text-gray-300 font-medium">
{compact ? 'Click or drag to upload' : 'Drag & drop images here, or click to select'}
</p>
{!compact && (
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
Max {maxFiles} files, up to {formatFileSize(maxSize)} each
</p>
)}
</>
)}
</div>
</div>
{/* Upload all button (when autoUpload is disabled) */}
{!autoUpload && pendingCount > 0 && (
<div className="flex justify-end">
<Button onClick={handleUploadAll} variant="primary" size="sm">
Upload {pendingCount} {pendingCount === 1 ? 'image' : 'images'}
</Button>
</div>
)}
{/* Image previews */}
{showPreviews && images.length > 0 && (
<div
className={cn(
'grid gap-4',
compact ? 'grid-cols-4 sm:grid-cols-6' : 'grid-cols-2 sm:grid-cols-3 md:grid-cols-4'
)}
>
{images.map((image) => (
<div
key={image.id}
className={cn(
'relative group rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-800',
compact ? 'aspect-square' : 'aspect-[4/3]'
)}
>
{/* Image preview - using img tag because sources are dynamic blob URLs from file uploads
which cannot be optimized by Next.js Image component */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={image.url || image.previewUrl}
alt="Upload preview"
className="w-full h-full object-cover"
/>
{/* Status overlay */}
{image.status === 'uploading' && (
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
<div className="w-3/4">
<div className="bg-gray-200 dark:bg-gray-700 rounded-full h-2">
<div
className="bg-primary-500 h-2 rounded-full transition-all duration-300"
style={{ width: `${image.progress}%` }}
/>
</div>
</div>
</div>
)}
{image.status === 'error' && (
<div className="absolute inset-0 bg-red-500/80 flex flex-col items-center justify-center p-2">
<Icon name="alert-circle" className="w-6 h-6 text-white mb-1" />
<p className="text-white text-xs text-center truncate w-full">
{image.error || 'Failed'}
</p>
<button
onClick={() => handleRetry(image.id)}
className="mt-1 text-white text-xs underline hover:no-underline"
>
Retry
</button>
</div>
)}
{image.status === 'success' && (
<div className="absolute top-1 right-1">
<Icon
name="check-circle"
className="w-5 h-5 text-green-500 bg-white rounded-full"
/>
</div>
)}
{/* Remove button */}
<button
onClick={() => handleRemove(image.id)}
className={cn(
'absolute top-1 left-1 p-1 bg-black/60 rounded-full',
'opacity-0 group-hover:opacity-100 transition-opacity',
'hover:bg-black/80 focus:opacity-100 focus:outline-none focus:ring-2 focus:ring-white'
)}
aria-label="Remove image"
>
<Icon name="x" className="w-4 h-4 text-white" />
</button>
</div>
))}
</div>
)}
</div>
);
}
export default ImageUploader;
|