Open History to see the last commit
1import { useEffect, useRef, useState } from 'react'
2import { Upload, X } from 'lucide-react'
3
4export function SeedImageField(props: {
5 files: Array<File>
6 onChange: (files: Array<File>) => void
7 maxFiles?: number
8 required: boolean
9 disabled: boolean
10}) {
11 const inputRef = useRef<HTMLInputElement>(null)
12 const [previews, setPreviews] = useState<Array<string>>([])
13 const maxFiles = props.maxFiles ?? 1
14 const remaining = maxFiles - props.files.length
15
16 useEffect(() => {
17 const urls = props.files.map((file) => URL.createObjectURL(file))
18 setPreviews(urls)
19 return () => {
20 for (const url of urls) URL.revokeObjectURL(url)
21 }
22 }, [props.files])
23
24 const label =
25 maxFiles > 1
26 ? props.required
27 ? `Seed photos (required, max ${maxFiles})`
28 : `Seed photos (max ${maxFiles})`
29 : props.required
30 ? 'Seed image (required)'
31 : 'Seed image'
32
33 return (
34 <div className="flex flex-wrap items-center gap-2">
35 <input
36 ref={inputRef}
37 type="file"
38 accept="image/png,image/jpeg,image/webp"
39 multiple={maxFiles > 1}
40 className="hidden"
41 disabled={props.disabled || remaining <= 0}
42 onChange={(event) => {
43 const picked = Array.from(event.target.files ?? [])
44 event.target.value = ''
45 if (picked.length === 0) return
46 props.onChange([...props.files, ...picked].slice(0, maxFiles))
47 }}
48 />
49 {previews.map((src, index) => (
50 <div key={`${src}-${index}`} className="relative h-16 w-16 shrink-0">
51 <img
52 src={src}
53 alt={`Seed image ${index + 1}`}
54 className="h-16 w-16 rounded-lg object-cover"
55 />
56 <button
57 type="button"
58 onClick={() =>
59 props.onChange(props.files.filter((_, i) => i !== index))
60 }
61 disabled={props.disabled}
62 className="absolute -top-1 -right-1 rounded-full bg-gray-800 p-0.5 text-gray-300 hover:text-white disabled:opacity-50"
63 aria-label={`Remove seed image ${index + 1}`}
64 >
65 <X className="h-3 w-3" />
66 </button>
67 </div>
68 ))}
69 {remaining > 0 ? (
70 <button
71 type="button"
72 onClick={() => inputRef.current?.click()}
73 disabled={props.disabled}
74 className="flex h-16 w-28 flex-col items-center justify-center rounded-lg border-2 border-dashed border-gray-600 text-gray-400 hover:border-gray-500 hover:text-gray-300 disabled:opacity-50"
75 >
76 <Upload className="h-4 w-4" />
77 <span className="mt-0.5 px-1 text-center text-[10px] leading-tight">
78 {label}
79 </span>
80 </button>
81 ) : null}
82 </div>
83 )
84}