Image upload consolidation

This commit is contained in:
2026-05-23 15:52:07 -04:00
parent c0f4f1de0d
commit 36f23b527e
4 changed files with 113 additions and 95 deletions
@@ -1,6 +1,7 @@
import { useState, useCallback, useRef } from "react"; import { useState, useCallback, useRef } from "react";
import axios from "axios"; import axios from "axios";
import { toast } from "sonner"; import { toast } from "sonner";
import { useDropzone } from "react-dropzone";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@@ -24,6 +25,7 @@ import {
DialogTitle, DialogTitle,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { IMAGE_UPLOAD_ACCEPT, MAX_UPLOAD_BYTES, formatUploadLimitMb } from "@/config/uploads";
import { import {
DndContext, DndContext,
closestCenter, closestCenter,
@@ -222,8 +224,6 @@ export function ImageManager({
const [urlInput, setUrlInput] = useState(""); const [urlInput, setUrlInput] = useState("");
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false);
const [addOpen, setAddOpen] = useState(false); const [addOpen, setAddOpen] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const sensors = useSensors( const sensors = useSensors(
useSensor(PointerSensor, { useSensor(PointerSensor, {
@@ -296,29 +296,51 @@ export function ImageManager({
); );
const handleFileUpload = useCallback( const handleFileUpload = useCallback(
async (files: FileList | null) => { async (files: File[]) => {
if (!files || files.length === 0) return; if (files.length === 0) return;
setIsUploading(true); setIsUploading(true);
setAddOpen(false); setAddOpen(false);
try { try {
for (const file of Array.from(files)) { for (const file of files) {
try {
const formData = new FormData(); const formData = new FormData();
formData.append("image", file); formData.append("image", file);
const res = await axios.post("/api/import/upload-image", formData); const res = await axios.post("/api/import/upload-image", formData);
if (res.data?.imageUrl) { if (res.data?.imageUrl) {
addNewImage(res.data.imageUrl); addNewImage(res.data.imageUrl);
} }
} catch (err) {
const serverMessage =
(err as { response?: { data?: { error?: string } } })?.response?.data?.error;
toast.error(`Failed to upload ${file.name}${serverMessage ? `: ${serverMessage}` : ""}`);
}
} }
} catch {
toast.error("Failed to upload image");
} finally { } finally {
setIsUploading(false); setIsUploading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
} }
}, },
[addNewImage] [addNewImage]
); );
const { getRootProps, getInputProps, isDragActive, open: openFilePicker } = useDropzone({
accept: IMAGE_UPLOAD_ACCEPT,
maxSize: MAX_UPLOAD_BYTES,
multiple: true,
noClick: true,
noKeyboard: true,
disabled: isUploading,
onDrop: handleFileUpload,
onDropRejected: (rejections) => {
rejections.forEach((rejection) => {
const tooLarge = rejection.errors.some((e) => e.code === "file-too-large");
const reason = tooLarge
? `larger than ${formatUploadLimitMb()} limit`
: rejection.errors[0]?.message ?? "rejected";
toast.error(`${rejection.file.name}: ${reason}`);
});
},
});
const handleUrlAdd = useCallback(async () => { const handleUrlAdd = useCallback(async () => {
const url = urlInput.trim(); const url = urlInput.trim();
if (!url) return; if (!url) return;
@@ -404,23 +426,26 @@ export function ImageManager({
))} ))}
{/* Add button with file drop */} {/* Add button with file drop */}
<div
{...getRootProps()}
className={cn(
"rounded-md border-2 border-dashed transition-colors",
isDragActive
? "border-primary bg-primary/10"
: "border-muted-foreground/25 hover:border-muted-foreground/50"
)}
>
<input {...getInputProps()} />
<Popover open={addOpen} onOpenChange={setAddOpen}> <Popover open={addOpen} onOpenChange={setAddOpen}>
<PopoverTrigger asChild> <PopoverTrigger asChild>
<button <button
type="button" type="button"
disabled={isUploading} disabled={isUploading}
onDragOver={(e) => { e.preventDefault(); setIsDragOver(true); }}
onDragLeave={() => setIsDragOver(false)}
onDrop={(e) => {
e.preventDefault();
setIsDragOver(false);
handleFileUpload(e.dataTransfer.files);
}}
className={cn( className={cn(
"rounded-md border-2 border-dashed flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors", "w-full h-full flex items-center justify-center transition-colors",
isDragOver isDragActive
? "border-primary bg-primary/10 text-primary" ? "text-primary"
: "border-muted-foreground/25 hover:border-muted-foreground/50" : "text-muted-foreground hover:text-foreground"
)} )}
> >
{isUploading ? ( {isUploading ? (
@@ -437,7 +462,8 @@ export function ImageManager({
size="sm" size="sm"
className="w-full justify-start gap-2" className="w-full justify-start gap-2"
onClick={() => { onClick={() => {
fileInputRef.current?.click(); setAddOpen(false);
openFilePicker();
}} }}
> >
<Upload className="h-4 w-4" /> <Upload className="h-4 w-4" />
@@ -470,6 +496,7 @@ export function ImageManager({
</PopoverContent> </PopoverContent>
</Popover> </Popover>
</div> </div>
</div>
</SortableContext> </SortableContext>
<DragOverlay> <DragOverlay>
{activeImage ? ( {activeImage ? (
@@ -484,16 +511,6 @@ export function ImageManager({
</DragOverlay> </DragOverlay>
</DndContext> </DndContext>
{/* Hidden file input */}
<input
ref={fileInputRef}
type="file"
accept="image/*"
multiple
className="hidden"
onChange={(e) => handleFileUpload(e.target.files)}
/>
{/* Full-size image overlay */} {/* Full-size image overlay */}
<Dialog open={!!zoomImage} onOpenChange={(open) => !open && setZoomImage(null)}> <Dialog open={!!zoomImage} onOpenChange={(open) => !open && setZoomImage(null)}>
<DialogContent className="max-w-3xl p-2"> <DialogContent className="max-w-3xl p-2">
@@ -3,8 +3,7 @@ import { Loader2, Upload } from "lucide-react";
import { useDropzone } from "react-dropzone"; import { useDropzone } from "react-dropzone";
import { toast } from "sonner"; import { toast } from "sonner";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { IMAGE_UPLOAD_ACCEPT, MAX_UPLOAD_BYTES, formatUploadLimitMb } from "@/config/uploads";
const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
interface GenericDropzoneProps { interface GenericDropzoneProps {
processingBulk: boolean; processingBulk: boolean;
@@ -22,16 +21,14 @@ export const GenericDropzone = ({
onShowUnassigned onShowUnassigned
}: GenericDropzoneProps) => { }: GenericDropzoneProps) => {
const { getRootProps, getInputProps, isDragActive } = useDropzone({ const { getRootProps, getInputProps, isDragActive } = useDropzone({
accept: { accept: IMAGE_UPLOAD_ACCEPT,
'image/*': ['.jpeg', '.jpg', '.png', '.gif', '.webp', '.tif', '.tiff']
},
maxSize: MAX_UPLOAD_BYTES, maxSize: MAX_UPLOAD_BYTES,
onDrop, onDrop,
onDropRejected: (rejections) => { onDropRejected: (rejections) => {
rejections.forEach((rejection) => { rejections.forEach((rejection) => {
const tooLarge = rejection.errors.some((e) => e.code === 'file-too-large'); const tooLarge = rejection.errors.some((e) => e.code === 'file-too-large');
const reason = tooLarge const reason = tooLarge
? `larger than ${MAX_UPLOAD_BYTES / 1024 / 1024}MB limit` ? `larger than ${formatUploadLimitMb()} limit`
: rejection.errors[0]?.message ?? 'rejected'; : rejection.errors[0]?.message ?? 'rejected';
toast.error(`${rejection.file.name}: ${reason}`); toast.error(`${rejection.file.name}: ${reason}`);
}); });
@@ -2,8 +2,7 @@ import { Upload } from "lucide-react";
import { useDropzone } from "react-dropzone"; import { useDropzone } from "react-dropzone";
import { toast } from "sonner"; import { toast } from "sonner";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { IMAGE_UPLOAD_ACCEPT, MAX_UPLOAD_BYTES, formatUploadLimitMb } from "@/config/uploads";
const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
interface ImageDropzoneProps { interface ImageDropzoneProps {
productIndex: number; productIndex: number;
@@ -12,9 +11,7 @@ interface ImageDropzoneProps {
export const ImageDropzone = ({ onDrop }: ImageDropzoneProps) => { export const ImageDropzone = ({ onDrop }: ImageDropzoneProps) => {
const { getRootProps, getInputProps, isDragActive } = useDropzone({ const { getRootProps, getInputProps, isDragActive } = useDropzone({
accept: { accept: IMAGE_UPLOAD_ACCEPT,
'image/*': ['.jpeg', '.jpg', '.png', '.gif', '.webp', '.tif', '.tiff']
},
maxSize: MAX_UPLOAD_BYTES, maxSize: MAX_UPLOAD_BYTES,
onDrop: (acceptedFiles) => { onDrop: (acceptedFiles) => {
onDrop(acceptedFiles); onDrop(acceptedFiles);
@@ -23,7 +20,7 @@ export const ImageDropzone = ({ onDrop }: ImageDropzoneProps) => {
rejections.forEach((rejection) => { rejections.forEach((rejection) => {
const tooLarge = rejection.errors.some((e) => e.code === 'file-too-large'); const tooLarge = rejection.errors.some((e) => e.code === 'file-too-large');
const reason = tooLarge const reason = tooLarge
? `larger than ${MAX_UPLOAD_BYTES / 1024 / 1024}MB limit` ? `larger than ${formatUploadLimitMb()} limit`
: rejection.errors[0]?.message ?? 'rejected'; : rejection.errors[0]?.message ?? 'rejected';
toast.error(`${rejection.file.name}: ${reason}`); toast.error(`${rejection.file.name}: ${reason}`);
}); });
+7
View File
@@ -0,0 +1,7 @@
export const MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
export const formatUploadLimitMb = () => `${MAX_UPLOAD_BYTES / 1024 / 1024}MB`;
export const IMAGE_UPLOAD_ACCEPT: Record<string, string[]> = {
"image/*": [".jpeg", ".jpg", ".png", ".gif", ".webp", ".tif", ".tiff"],
};