From 6902c9467f8ffe0bde225024e73384652ff8d66f Mon Sep 17 00:00:00 2001
From: MohamedBassem <me@mbassem.com>
Date: Sat, 30 Mar 2024 02:02:41 +0000
Subject: feature(web): Allow support for multiple asset upload at the same
 time. Fixes: #36

---
 apps/web/components/dashboard/UploadDropzone.tsx | 86 +++++++++++++++++++-----
 1 file changed, 70 insertions(+), 16 deletions(-)

(limited to 'apps/web/components/dashboard/UploadDropzone.tsx')

diff --git a/apps/web/components/dashboard/UploadDropzone.tsx b/apps/web/components/dashboard/UploadDropzone.tsx
index b08ac0a6..70e6483a 100644
--- a/apps/web/components/dashboard/UploadDropzone.tsx
+++ b/apps/web/components/dashboard/UploadDropzone.tsx
@@ -4,6 +4,7 @@ import React, { useState } from "react";
 import { api } from "@/lib/trpc";
 import { cn } from "@/lib/utils";
 import { useMutation } from "@tanstack/react-query";
+import { TRPCClientError } from "@trpc/client";
 import DropZone from "react-dropzone";
 
 import {
@@ -14,26 +15,23 @@ import {
 import LoadingSpinner from "../ui/spinner";
 import { toast } from "../ui/use-toast";
 
-export default function UploadDropzone({
-  children,
-}: {
-  children: React.ReactNode;
-}) {
+function useUploadAsset({ onComplete }: { onComplete: () => void }) {
   const invalidateAllBookmarks =
     api.useUtils().bookmarks.getBookmarks.invalidate;
 
-  const { mutate: createBookmark, isPending: isCreating } =
+  const { mutateAsync: createBookmark } =
     api.bookmarks.createBookmark.useMutation({
       onSuccess: () => {
         toast({ description: "Bookmark uploaded" });
         invalidateAllBookmarks();
+        onComplete();
       },
       onError: () => {
         toast({ description: "Something went wrong", variant: "destructive" });
       },
     });
 
-  const { mutate: uploadAsset, isPending: isUploading } = useMutation({
+  const { mutateAsync: runUpload } = useMutation({
     mutationFn: async (file: File) => {
       const formData = new FormData();
       formData.append("image", file);
@@ -48,24 +46,78 @@ export default function UploadDropzone({
     },
     onSuccess: async (resp) => {
       const assetId = resp.assetId;
-      createBookmark({ type: "asset", assetId, assetType: "image" });
+      return createBookmark({ type: "asset", assetId, assetType: "image" });
     },
-    onError: (error) => {
+    onError: (error, req) => {
       const err = zUploadErrorSchema.parse(JSON.parse(error.message));
-      toast({ description: err.error, variant: "destructive" });
+      toast({
+        description: `${req.name}: ${err.error}`,
+        variant: "destructive",
+      });
+    },
+  });
+
+  return runUpload;
+}
+
+function useUploadAssets({
+  onFileUpload,
+  onFileError,
+  onAllUploaded,
+}: {
+  onFileUpload: () => void;
+  onFileError: (name: string, e: Error) => void;
+  onAllUploaded: () => void;
+}) {
+  const runUpload = useUploadAsset({ onComplete: onFileUpload });
+
+  return async (files: File[]) => {
+    if (files.length == 0) {
+      return;
+    }
+    for (const file of files) {
+      try {
+        await runUpload(file);
+      } catch (e) {
+        if (e instanceof TRPCClientError || e instanceof Error) {
+          onFileError(file.name, e);
+        }
+      }
+    }
+    onAllUploaded();
+  };
+}
+
+export default function UploadDropzone({
+  children,
+}: {
+  children: React.ReactNode;
+}) {
+  const [numUploading, setNumUploading] = useState(0);
+  const [numUploaded, setNumUploaded] = useState(0);
+  const uploadAssets = useUploadAssets({
+    onFileUpload: () => {
+      setNumUploaded((c) => c + 1);
+    },
+    onFileError: () => {
+      setNumUploaded((c) => c + 1);
+    },
+    onAllUploaded: () => {
+      setNumUploading(0);
+      setNumUploaded(0);
+      return;
     },
   });
 
   const [isDragging, setDragging] = useState(false);
   const onDrop = (acceptedFiles: File[]) => {
-    const file = acceptedFiles[0];
+    uploadAssets(acceptedFiles);
+    setNumUploading(acceptedFiles.length);
     setDragging(false);
-    uploadAsset(file);
   };
 
   return (
     <DropZone
-      multiple={false}
       noClick
       onDrop={onDrop}
       onDragEnter={() => setDragging(true)}
@@ -77,12 +129,14 @@ export default function UploadDropzone({
           <div
             className={cn(
               "fixed inset-0 z-50 flex h-full w-full items-center justify-center bg-gray-200 opacity-90",
-              isDragging || isUploading || isCreating ? undefined : "hidden",
+              isDragging || numUploading > 0 ? undefined : "hidden",
             )}
           >
-            {isUploading || isCreating ? (
+            {numUploading > 0 ? (
               <div className="flex items-center justify-center gap-2">
-                <p className="text-2xl font-bold text-gray-700">Uploading</p>
+                <p className="text-2xl font-bold text-gray-700">
+                  Uploading {numUploaded} / {numUploading}
+                </p>
                 <LoadingSpinner />
               </div>
             ) : (
-- 
cgit v1.2.3-70-g09d2

