-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageUpload.tsx
More file actions
395 lines (354 loc) · 12 KB
/
Copy pathImageUpload.tsx
File metadata and controls
395 lines (354 loc) · 12 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
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
import { useCallback, useRef, useState, type DragEvent, type ChangeEvent } from 'react';
import { Upload, X, AlertCircle, Image as ImageIcon } from 'lucide-react';
import { Button } from './ui/button';
import { cn } from '../lib/utils';
import type { ImageAttachment } from '../../shared/types';
import {
MAX_IMAGE_SIZE,
MAX_IMAGES_PER_TASK,
ALLOWED_IMAGE_TYPES,
ALLOWED_IMAGE_TYPES_DISPLAY
} from '../../shared/constants';
interface ImageUploadProps {
images: ImageAttachment[];
onImagesChange: (images: ImageAttachment[]) => void;
disabled?: boolean;
className?: string;
}
/**
* Generate a unique ID for images
*/
export function generateImageId(): string {
return `img-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
/**
* Format file size for display
*/
export function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
/**
* Check if a file is a valid image type
*/
export function isValidImageType(file: File): boolean {
return ALLOWED_IMAGE_TYPES.includes(file.type as (typeof ALLOWED_IMAGE_TYPES)[number]);
}
/**
* Check if a MIME type is a valid image type
*/
export function isValidImageMimeType(mimeType: string): boolean {
return ALLOWED_IMAGE_TYPES.includes(mimeType as (typeof ALLOWED_IMAGE_TYPES)[number]);
}
/**
* Convert a File to base64 data URL
*/
export async function fileToBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
/**
* Convert a Blob to base64 data URL
*/
export async function blobToBase64(blob: Blob): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result as string);
reader.onerror = reject;
reader.readAsDataURL(blob);
});
}
/**
* Create a thumbnail from an image data URL
*/
export async function createThumbnail(dataUrl: string, maxSize = 200): Promise<string> {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
// Scale down to maxSize while maintaining aspect ratio
if (width > height) {
if (width > maxSize) {
height = (height * maxSize) / width;
width = maxSize;
}
} else {
if (height > maxSize) {
width = (width * maxSize) / height;
height = maxSize;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0, width, height);
resolve(canvas.toDataURL('image/jpeg', 0.8));
};
img.onerror = () => resolve(dataUrl); // Return original if thumbnail fails
img.src = dataUrl;
});
}
/**
* Resolve duplicate filenames by adding timestamp
*/
export function resolveFilename(filename: string, existingFiles: string[]): string {
if (!existingFiles.includes(filename)) {
return filename;
}
const lastDot = filename.lastIndexOf('.');
const name = lastDot !== -1 ? filename.substring(0, lastDot) : filename;
const ext = lastDot !== -1 ? filename.substring(lastDot) : '';
const timestamp = Date.now();
return `${name}-${timestamp}${ext}`;
}
export function ImageUpload({
images,
onImagesChange,
disabled = false,
className
}: ImageUploadProps) {
const [isDragOver, setIsDragOver] = useState(false);
const [error, setError] = useState<string | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
const canAddMore = images.length < MAX_IMAGES_PER_TASK;
/**
* Process files and add them to the images array
*/
const processFiles = useCallback(
async (files: FileList | File[]) => {
setError(null);
const fileArray = Array.from(files);
// Check how many more images we can add
const remainingSlots = MAX_IMAGES_PER_TASK - images.length;
if (remainingSlots <= 0) {
setError(`Maximum of ${MAX_IMAGES_PER_TASK} images allowed`);
return;
}
// Limit files to remaining slots
const filesToProcess = fileArray.slice(0, remainingSlots);
if (fileArray.length > remainingSlots) {
setError(`Only ${remainingSlots} more image(s) can be added. Some files were skipped.`);
}
const newImages: ImageAttachment[] = [];
const existingFilenames = images.map((img) => img.filename);
const errors: string[] = [];
for (const file of filesToProcess) {
// Validate file type
if (!isValidImageType(file)) {
errors.push(`"${file.name}" is not a valid image type. Allowed: ${ALLOWED_IMAGE_TYPES_DISPLAY}`);
continue;
}
// Warn about large files
if (file.size > MAX_IMAGE_SIZE) {
errors.push(`"${file.name}" is larger than 10MB. Consider compressing it for better performance.`);
// Still allow the upload, just warn
}
try {
const dataUrl = await fileToBase64(file);
const thumbnail = await createThumbnail(dataUrl);
const resolvedFilename = resolveFilename(file.name, [
...existingFilenames,
...newImages.map((img) => img.filename)
]);
newImages.push({
id: generateImageId(),
filename: resolvedFilename,
mimeType: file.type,
size: file.size,
data: dataUrl.split(',')[1], // Store base64 without data URL prefix
thumbnail
});
} catch {
errors.push(`Failed to process "${file.name}"`);
}
}
if (errors.length > 0) {
setError(errors.join(' '));
}
if (newImages.length > 0) {
onImagesChange([...images, ...newImages]);
}
},
[images, onImagesChange]
);
/**
* Handle file input change
*/
const handleFileChange = useCallback(
(e: ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (files && files.length > 0) {
processFiles(files);
}
// Reset input to allow selecting the same file again
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
},
[processFiles]
);
/**
* Handle drag events
*/
const handleDragOver = useCallback((e: DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback((e: DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
}, []);
const handleDrop = useCallback(
(e: DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
if (disabled) return;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
processFiles(files);
}
},
[disabled, processFiles]
);
/**
* Remove an image
*/
const handleRemove = useCallback(
(imageId: string) => {
onImagesChange(images.filter((img) => img.id !== imageId));
setError(null);
},
[images, onImagesChange]
);
/**
* Open file picker
*/
const handleClick = useCallback(() => {
if (!disabled && canAddMore) {
fileInputRef.current?.click();
}
}, [disabled, canAddMore]);
return (
<div className={cn('space-y-3', className)}>
{/* Drop zone */}
{/* biome-ignore lint/a11y/noNoninteractiveElementInteractions: This is a drop zone with intentional drag/click handlers */}
{/* biome-ignore lint/a11y/noStaticElementInteractions: Drop zone requires these handlers */}
{/* biome-ignore lint/a11y/useKeyWithClickEvents: The hidden file input handles keyboard accessibility */}
<div
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={handleClick}
className={cn(
'relative border-2 border-dashed rounded-lg p-6 transition-all cursor-pointer',
'flex flex-col items-center justify-center gap-2 text-center',
isDragOver && !disabled
? 'border-primary bg-primary/5'
: 'border-border hover:border-muted-foreground/50',
disabled && 'opacity-50 cursor-not-allowed',
!canAddMore && 'opacity-50 cursor-not-allowed'
)}
>
<input
ref={fileInputRef}
type="file"
accept={ALLOWED_IMAGE_TYPES.join(',')}
multiple
onChange={handleFileChange}
disabled={disabled || !canAddMore}
className="hidden"
/>
<div
className={cn(
'p-3 rounded-full transition-colors',
isDragOver && !disabled ? 'bg-primary/10' : 'bg-muted'
)}
>
<Upload className={cn('h-6 w-6', isDragOver && !disabled ? 'text-primary' : 'text-muted-foreground')} />
</div>
<div className="space-y-1">
<p className="text-sm font-medium text-foreground">
{canAddMore ? 'Drop images here or click to browse' : 'Maximum images reached'}
</p>
<p className="text-xs text-muted-foreground">
{canAddMore
? `${ALLOWED_IMAGE_TYPES_DISPLAY} up to 10MB each (${images.length}/${MAX_IMAGES_PER_TASK})`
: `${MAX_IMAGES_PER_TASK} images maximum`}
</p>
</div>
</div>
{/* Error message */}
{error && (
<div className="flex items-start gap-2 rounded-lg bg-destructive/10 border border-destructive/30 p-3 text-sm text-destructive">
<AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
<span>{error}</span>
</div>
)}
{/* Image previews */}
{images.length > 0 && (
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
{images.map((image) => (
<div
key={image.id}
className="relative group rounded-lg border border-border bg-card overflow-hidden"
>
{/* Thumbnail or placeholder */}
<div className="aspect-square flex items-center justify-center bg-muted">
{image.thumbnail ? (
<img
src={image.thumbnail}
alt={image.filename}
className="w-full h-full object-cover"
/>
) : (
<ImageIcon className="h-8 w-8 text-muted-foreground" />
)}
</div>
{/* File info overlay */}
<div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-2">
<p className="text-xs text-white font-medium truncate">{image.filename}</p>
<p className="text-[10px] text-white/70">{formatFileSize(image.size)}</p>
</div>
{/* Remove button */}
{!disabled && (
<Button
variant="destructive"
size="icon"
className={cn(
'absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity',
'rounded-full'
)}
onClick={(e) => {
e.stopPropagation();
handleRemove(image.id);
}}
>
<X className="h-3 w-3" />
</Button>
)}
{/* Large file warning indicator */}
{image.size > MAX_IMAGE_SIZE && (
<div
className="absolute top-1 left-1 p-1 rounded-full bg-warning/90"
title="Large file - consider compressing"
>
<AlertCircle className="h-3 w-3 text-warning-foreground" />
</div>
)}
</div>
))}
</div>
)}
</div>
);
}