Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: improve bulk upload
Marc Seitz29c47ac2ba40
diff --git a/components/datarooms/dataroom-items-list.tsx b/components/datarooms/dataroom-items-list.tsxindex 53561cd2..3a14be4d 100644--- a/components/datarooms/dataroom-items-list.tsx+++ b/components/datarooms/dataroom-items-list.tsx@@ -50,11 +50,12 @@ import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { Portal } from "@/components/ui/portal";import { ButtonTooltip } from "@/components/ui/tooltip";-import { UploadNotificationDrawer } from "@/components/upload-notification";-import UploadZone, {- RejectedFile,- UploadState,-} from "@/components/upload-zone";+import {+ useUploadCallbacks,+ useUploadProgress,+} from "@/context/upload-progress-context";++import UploadZone from "@/components/upload-zone";import { itemsMessage } from "./folders/utils";import { MoveToDataroomFolderModal } from "./move-dataroom-folder-modal";@@ -84,8 +85,15 @@ export function DataroomItemsList({const { isMobile } = useMediaQuery();const { applyPermissions } = useDataroomPermissions();- const [uploads, setUploads] = useState<UploadState[]>([]);- const [rejectedFiles, setRejectedFiles] = useState<RejectedFile[]>([]);+ const { setRejectedFiles, cancelledItemIdsRef } = useUploadProgress();+ const {+ onTraversalStart,+ onUploadBatchStart,+ onUploadBatchUpdate,+ onUploadRejected,+ onUploadAborted,+ } = useUploadCallbacks();+const [showGroupPermissions, setShowGroupPermissions] = useState(false);const [uploadedFiles, setUploadedFiles] = useState<{@@ -95,7 +103,6 @@ export function DataroomItemsList({}[]>([]);- const [showDrawer, setShowDrawer] = useState(false);const [moveFolderOpen, setMoveFolderOpen] = useState<boolean>(false);const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });@@ -131,9 +138,6 @@ export function DataroomItemsList({[mixedItems, setFolderToDelete, setDeleteModalOpen, setSelectedFolders],);- const handleCloseDrawer = () => {- setShowDrawer(false);- };const { setShowRemoveDataroomItemModal, RemoveDataroomItemModal } =useRemoveDataroomItemsModal({@@ -590,33 +594,14 @@ export function DataroomItemsList({<><UploadZonefolderPathName={folderPathName?.join("/")}- onUploadStart={(newUploads) => {- setUploads((prevUploads) => [...prevUploads, ...newUploads]);- setShowDrawer(true);- }}- onUploadProgress={(index, progress, documentId) => {- setUploads((prevUploads) => {- const recentBatchStartIndex = prevUploads.length - index - 1;- if (- recentBatchStartIndex < 0 ||- recentBatchStartIndex >= prevUploads.length- ) {- return prevUploads;- }- return prevUploads.map((upload, i) =>- i === recentBatchStartIndex- ? { ...upload, progress, documentId }- : upload,- );- });- }}+ onTraversalStart={onTraversalStart}+ onUploadBatchStart={onUploadBatchStart}+ onUploadBatchUpdate={onUploadBatchUpdate}+ onUploadRejected={onUploadRejected}+ onUploadAborted={onUploadAborted}onUploadSuccess={handleUploadSuccess}- onUploadRejected={(rejected) => {- setRejectedFiles((prevRejected) => [...prevRejected, ...rejected]);- setShowDrawer(true);- }}- setUploads={setUploads}setRejectedFiles={setRejectedFiles}+ cancelledItemIdsRef={cancelledItemIdsRef}dataroomId={dataroomId}dataroomName={dataroom?.name}>@@ -721,17 +706,6 @@ export function DataroomItemsList({</>)}</UploadZone>- {showDrawer ? (- <UploadNotificationDrawer- open={showDrawer}- onOpenChange={setShowDrawer}- uploads={uploads}- handleCloseDrawer={handleCloseDrawer}- setUploads={setUploads}- rejectedFiles={rejectedFiles}- setRejectedFiles={setRejectedFiles}- />- ) : null}{showGroupPermissions && dataroomId && (<SetUnifiedPermissionsModaldiff --git a/components/documents/documents-list.tsx b/components/documents/documents-list.tsxindex c78f072f..6a767dd2 100644--- a/components/documents/documents-list.tsx+++ b/components/documents/documents-list.tsx@@ -35,12 +35,13 @@ import { FolderWithCount, FolderWithCountAndPath } from "@/lib/swr/use-documentsimport { DocumentWithLinksAndLinkCountAndViewCount } from "@/lib/types";import { useMediaQuery } from "@/lib/utils/use-media-query";+import {+ useUploadCallbacks,+ useUploadProgress,+} from "@/context/upload-progress-context";+import { Skeleton } from "@/components/ui/skeleton";-import { UploadNotificationDrawer } from "@/components/upload-notification";-import UploadZone, {- RejectedFile,- UploadState,-} from "@/components/upload-zone";+import UploadZone from "@/components/upload-zone";import { itemsMessage } from "../datarooms/folders/utils";import { Button } from "../ui/button";@@ -56,16 +57,6 @@ import { EmptyDocuments } from "./empty-document";import FolderCard from "./folder-card";import { MoveToFolderModal, TSelectedFolder } from "./move-folder-modal";-export type Upload = {- fileName: string;- progress: number;- documentId?: string;-};--export type File = {- fileName: string;- message: string;-};export function DocumentsList({folders,@@ -83,13 +74,17 @@ export function DocumentsList({foldersLoading: boolean;}) {const { isMobile } = useMediaQuery();+ const { setRejectedFiles, cancelledItemIdsRef } = useUploadProgress();+ const {+ onTraversalStart,+ onUploadBatchStart,+ onUploadBatchUpdate,+ onUploadRejected,+ onUploadAborted,+ } = useUploadCallbacks();- const [uploads, setUploads] = useState<UploadState[]>([]);- const [rejectedFiles, setRejectedFiles] = useState<RejectedFile[]>([]);const [selectedDocuments, setSelectedDocuments] = useState<string[]>([]);const [selectedFolders, setSelectedFolders] = useState<string[]>([]);-- const [showDrawer, setShowDrawer] = useState<boolean>(false);const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });const [draggedDocument, setDraggedDocument] =useState<DocumentWithLinksAndLinkCountAndViewCount | null>(null);@@ -340,9 +335,6 @@ export function DocumentsList({setIsOverFolder(false);};- const handleCloseDrawer = () => {- setShowDrawer(false);- };const resetSelection = () => {setSelectedDocuments([]);@@ -547,32 +539,13 @@ export function DocumentsList({<><UploadZonefolderPathName={folderPathName?.join("/")}- onUploadStart={(newUploads) => {- setUploads((prevUploads) => [...prevUploads, ...newUploads]);- setShowDrawer(true);- }}- onUploadProgress={(index, progress, documentId) => {- setUploads((prevUploads) => {- const recentBatchStartIndex = prevUploads.length - index - 1;- if (- recentBatchStartIndex < 0 ||- recentBatchStartIndex >= prevUploads.length- ) {- return prevUploads;- }- return prevUploads.map((upload, i) =>- i === recentBatchStartIndex- ? { ...upload, progress, documentId }- : upload,- );- });- }}- onUploadRejected={(rejected) => {- setRejectedFiles((prevRejected) => [...prevRejected, ...rejected]);- setShowDrawer(true);- }}- setUploads={setUploads}+ onTraversalStart={onTraversalStart}+ onUploadBatchStart={onUploadBatchStart}+ onUploadBatchUpdate={onUploadBatchUpdate}+ onUploadRejected={onUploadRejected}+ onUploadAborted={onUploadAborted}setRejectedFiles={setRejectedFiles}+ cancelledItemIdsRef={cancelledItemIdsRef}>{isMobile ? (<div className="space-y-4">@@ -840,17 +813,6 @@ export function DocumentsList({</>)}</UploadZone>- {showDrawer ? (- <UploadNotificationDrawer- open={showDrawer}- onOpenChange={setShowDrawer}- uploads={uploads}- handleCloseDrawer={handleCloseDrawer}- setUploads={setUploads}- rejectedFiles={rejectedFiles}- setRejectedFiles={setRejectedFiles}- />- ) : null}<DeleteFolderModal /><DeleteItemsModal /></>diff --git a/components/ui/gauge.tsx b/components/ui/gauge.tsxindex 12012285..ecc61424 100644--- a/components/ui/gauge.tsx+++ b/components/ui/gauge.tsx@@ -4,7 +4,7 @@ export const Gauge = ({showValue = true,}: {value: number;- size: "xs" | "small" | "medium" | "large";+ size: "xxs" | "xs" | "small" | "medium" | "large";showValue: boolean;}) => {const circumference = 332; //2 * Math.PI * 53; // 2 * pi * radius@@ -14,6 +14,11 @@ export const Gauge = ({const strokeDashoffset = initialOffset - valueInCircumference;const sizes = {+ xxs: {+ width: "20",+ height: "20",+ textSize: "text-[10px]",+ },xs: {width: "24",height: "24",diff --git a/components/upload-notification.tsx b/components/upload-notification.tsxindex 7cee80d7..88646693 100644--- a/components/upload-notification.tsx+++ b/components/upload-notification.tsx@@ -1,4 +1,14 @@-import { CheckIcon, XIcon } from "lucide-react";+import { memo, useMemo, useState } from "react";++import {+ BanIcon,+ CheckIcon,+ ChevronDownIcon,+ ChevronUpIcon,+ FileIcon,+ FolderIcon,+ XIcon,+} from "lucide-react";import {Drawer,@@ -9,106 +19,294 @@ import {} from "@/components/ui/drawer";import { Gauge } from "./ui/gauge";-import { RejectedFile, UploadState } from "./upload-zone";+import { ButtonTooltip } from "./ui/tooltip";+import { RejectedFile, UploadBatchState, UploadItemState } from "./upload-zone";interface UploadNotificationDrawerProps {open: boolean;onOpenChange: (open: boolean) => void;- uploads: UploadState[];- setUploads: (uploads: UploadState[]) => void;+ batch: UploadBatchState | null;+ setBatch: (batch: UploadBatchState | null) => void;rejectedFiles: RejectedFile[];setRejectedFiles: (rejected: RejectedFile[]) => void;handleCloseDrawer: () => void;+ onCancel?: () => void;+ onCancelItem?: (itemId: string) => void;}+function formatTimeLeft(ms: number): string {+ if (ms < 1000) return "Finishing upload...";+ const totalSeconds = Math.ceil(ms / 1000);+ if (totalSeconds < 60) return `${totalSeconds} sec left...`;+ const minutes = Math.ceil(totalSeconds / 60);+ return `${minutes} min left...`;+}++const ItemRow = memo(+ function ItemRow({+ item,+ onCancelItem,+ isBatchDone,+ }: {+ item: UploadItemState;+ onCancelItem?: (itemId: string) => void;+ isBatchDone: boolean;+ }) {+ const [hovered, setHovered] = useState(false);+ const done =+ item.completedEntries + item.failedEntries >= item.totalEntries;+ const progress =+ item.totalEntries > 0+ ? Math.round(+ ((item.completedEntries + item.failedEntries) / item.totalEntries) *+ 100,+ )+ : 0;++ const indicator = () => {+ if (item.cancelled) {+ return (+ <ButtonTooltip content="Upload cancelled" sideOffset={4}>+ <BanIcon className="h-5 w-5 text-muted-foreground" />+ </ButtonTooltip>+ );+ }++ if (done) {+ if (hovered) {+ return (+ <a+ href={item.folderHref}+ className="flex h-5 w-5 items-center justify-center"+ title={`Open ${item.name}`}+ >+ {item.type === "folder" ? (+ <FolderIcon className="h-4 w-4 text-foreground" />+ ) : (+ <FileIcon className="h-4 w-4 text-foreground" />+ )}+ </a>+ );+ }+ return (+ <CheckIcon+ className="h-5 w-5 rounded-full bg-emerald-500 p-0.5 text-white"+ strokeWidth={3}+ />+ );+ }++ if (hovered && onCancelItem && !isBatchDone) {+ return (+ <button+ onClick={() => onCancelItem(item.itemId)}+ className="flex h-5 w-5 items-center justify-center rounded-full hover:bg-gray-200 dark:hover:bg-gray-700"+ title="Cancel upload"+ >+ <XIcon className="h-3.5 w-3.5 text-muted-foreground" />+ </button>+ );+ }++ return (+ <div className="flex h-5 w-5 items-center justify-center">+ <Gauge value={progress} size="xxs" showValue={false} />+ </div>+ );+ };++ return (+ <div+ className="flex items-center justify-between px-4 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-800/50"+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ >+ <div className="flex items-center gap-2.5 overflow-hidden">+ {item.type === "folder" ? (+ <FolderIcon className="h-5 w-5 shrink-0 text-muted-foreground" />+ ) : (+ <FileIcon className="h-5 w-5 shrink-0 text-muted-foreground" />+ )}+ <span className="truncate text-sm">{item.name}</span>+ </div>+ <div className="flex shrink-0 items-center gap-2.5">+ {!item.cancelled &&+ (item.totalEntries > 0 ? (+ <span className="text-xs tabular-nums text-muted-foreground">+ {item.completedEntries} of {item.totalEntries}+ </span>+ ) : (+ <span className="text-xs text-muted-foreground">+ Preparing...+ </span>+ ))}+ <div className="flex h-5 w-5 items-center justify-center">+ {item.totalEntries === 0 && !item.cancelled ? (+ <div className="h-4 w-4 animate-spin rounded-full border-2 border-gray-300 border-t-primary" />+ ) : (+ indicator()+ )}+ </div>+ </div>+ </div>+ );+ },+ (prev, next) => {+ const a = prev.item;+ const b = next.item;+ return (+ a.itemId === b.itemId &&+ a.completedEntries === b.completedEntries &&+ a.failedEntries === b.failedEntries &&+ a.totalEntries === b.totalEntries &&+ a.cancelled === b.cancelled &&+ prev.isBatchDone === next.isBatchDone &&+ prev.onCancelItem === next.onCancelItem+ );+ },+);+export function UploadNotificationDrawer({open,onOpenChange,- uploads,- setUploads,+ batch,+ setBatch,rejectedFiles,setRejectedFiles,handleCloseDrawer,+ onCancel,+ onCancelItem,}: UploadNotificationDrawerProps) {- const uploadCount = uploads.length;- const failedCount = rejectedFiles.length;+ const [expanded, setExpanded] = useState(true);++ const totalEntries = batch?.totalEntries ?? 0;+ const completedEntries = batch?.completedEntries ?? 0;+ const batchFailedEntries = batch?.failedEntries ?? 0;+ const isCancelled = batch?.cancelled === true;+ const isComplete =+ !isCancelled &&+ completedEntries + batchFailedEntries >= totalEntries &&+ totalEntries > 0;+ const isDone = isComplete || isCancelled;++ const itemCount = batch?.items.length ?? 0;+ const isPreparing = batch === null || itemCount === 0;++ const timeLeftLabel = useMemo(() => {+ if (!batch || isDone) return null;+ const elapsed = Date.now() - batch.startedAt;+ const processed = completedEntries + batchFailedEntries;+ if (processed === 0 || elapsed < 2000) return "Calculating...";+ const rate = processed / elapsed;+ const remaining = totalEntries - processed;+ const msLeft = remaining / rate;+ return formatTimeLeft(msLeft);+ }, [batch, completedEntries, batchFailedEntries, totalEntries, isDone]);const onOpenChangeHandler = (open: boolean) => {onOpenChange(open);if (!open) {- setUploads([]);+ setBatch(null);setRejectedFiles([]);}};+ const cancelledItemCount = batch?.items.filter((it) => it.cancelled).length ?? 0;++ const headerTitle = isPreparing+ ? "Preparing upload..."+ : isCancelled+ ? cancelledItemCount === itemCount+ ? `${itemCount} upload${itemCount !== 1 ? "s" : ""} canceled`+ : "Upload canceled"+ : isComplete+ ? `${itemCount} upload${itemCount !== 1 ? "s" : ""} complete`+ : `Uploading ${itemCount} item${itemCount !== 1 ? "s" : ""}`;+return (- <div className="h-50 fixed bottom-0 right-20">+ <div className="h-50 fixed bottom-0 right-20 z-50"><Drawermodal={false}open={open}onOpenChange={onOpenChangeHandler}dismissible={false}>- <DrawerContent className="inset-x-auto right-6 max-h-[250px] w-1/5 min-w-[350px] max-w-[400px] shadow-md focus-visible:outline-none">- <DrawerHeader className="flex h-10 items-center justify-between rounded-t-lg border-b border-transparent bg-gray-100 dark:bg-gray-900">- <div className="flex items-center space-x-1">- <DrawerTitle>{uploadCount} uploads</DrawerTitle>- {failedCount > 0 ? (- <p className="text-sm">- (- <span className="text-destructive">{failedCount} failed</span>- )- </p>- ) : null}- </div>- <DrawerClose- className="rounded-full p-1 hover:bg-gray-200 hover:dark:bg-gray-800"- onClick={handleCloseDrawer}- >- <XIcon className="h-6 w-6" />- </DrawerClose>- </DrawerHeader>- <div className="mx-auto flex w-full flex-1 flex-col overflow-y-auto">- {uploads.map((upload, index) => (- <div- key={index}- className="px-4 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-800/50"+ <DrawerContent className="inset-x-auto right-6 max-h-[400px] w-1/5 min-w-[350px] max-w-[400px] shadow-md focus-visible:outline-none">+ <DrawerHeader className="flex h-auto items-center justify-between rounded-t-lg border-b border-gray-200 bg-gray-100 px-4 py-3 dark:border-gray-700 dark:bg-gray-900">+ <DrawerTitle className="text-sm font-medium">+ {headerTitle}+ </DrawerTitle>+ <div className="flex shrink-0 items-center gap-1">+ <button+ onClick={() => setExpanded(!expanded)}+ className="rounded-full p-1 hover:bg-gray-200 dark:hover:bg-gray-800">- {upload.progress === 100 && upload.documentId ? (- <a- href={`/documents/${upload.documentId}`}- className="flex items-center justify-between group"- >- <span className="w-72 truncate text-sm">{upload.fileName}</span>- <CheckIcon- className="h-6 w-6 rounded-full bg-emerald-500 p-1 text-background"- strokeWidth={3}- />- </a>+ {expanded ? (+ <ChevronDownIcon className="h-5 w-5" />) : (- <div className="flex items-center justify-between">- <span className="w-72 truncate text-sm text-gray-500 dark:text-gray-400">{upload.fileName}</span>- <Gauge- value={upload.progress}- size={"xs"}- showValue={true}- />- </div>+ <ChevronUpIcon className="h-5 w-5" />)}- </div>- ))}- {rejectedFiles.map((rejected, index) => (- <div- key={index}- className="flex items-center justify-between px-4 py-2.5 text-sm text-red-500 hover:bg-gray-50 dark:hover:bg-gray-800/50"+ </button>+ <DrawerClose+ className="rounded-full p-1 hover:bg-gray-200 dark:hover:bg-gray-800"+ onClick={handleCloseDrawer}>- <span className="w-72 truncate">{rejected.fileName}</span>- <span className="text-xs">{rejected.message}</span>+ <XIcon className="h-5 w-5" />+ </DrawerClose>+ </div>+ </DrawerHeader>++ {expanded && (+ <>+ {!isDone && !isPreparing && timeLeftLabel && (+ <div className="flex items-center justify-between border-b border-gray-200 bg-blue-50/60 px-4 py-2 dark:border-gray-700 dark:bg-blue-950/30">+ <span className="text-xs text-muted-foreground">+ {timeLeftLabel}+ </span>+ {onCancel && (+ <button+ onClick={onCancel}+ className="text-xs font-medium text-primary hover:underline"+ >+ Cancel+ </button>+ )}+ </div>+ )}++ <div className="flex w-full flex-1 flex-col overflow-y-auto">+ {batch?.items.map((item) => (+ <ItemRow+ key={item.itemId}+ item={item}+ onCancelItem={onCancelItem}+ isBatchDone={isDone}+ />+ ))}</div>- ))}- </div>++ {rejectedFiles.length > 0 && (+ <div className="border-t border-gray-200 dark:border-gray-700">+ <div className="px-4 py-1.5 text-xs font-medium text-destructive">+ {rejectedFiles.length} failed+ </div>+ {rejectedFiles.map((rejected, index) => (+ <div+ key={index}+ className="flex items-center justify-between px-4 py-2 text-sm text-red-500 hover:bg-gray-50 dark:hover:bg-gray-800/50"+ >+ <span className="w-56 truncate">{rejected.fileName}</span>+ <span className="shrink-0 text-xs">+ {rejected.message}+ </span>+ </div>+ ))}+ </div>+ )}+ </>+ )}</DrawerContent></Drawer></div>);-};+}diff --git a/components/upload-zone.tsx b/components/upload-zone.tsxindex bdb6678a..cd2c0cd8 100644--- a/components/upload-zone.tsx+++ b/components/upload-zone.tsx@@ -46,13 +46,13 @@ interface FileWithPaths extends File {path?: string;whereToUploadPath?: string;dataroomUploadPath?: string;-}--export interface UploadState {- fileName: string;- progress: number;- documentId?: string;- uploadId: string;+ /** Name of the top-level drag item this file belongs to */+ topLevelItemName?: string;+ topLevelItemIsFolder?: boolean;+ /** Number of folders created during traversal for this top-level item */+ topLevelItemFolderCount?: number;+ /** Server-generated slug path for the top-level folder (e.g. "folder-with-100-subfolders") */+ topLevelItemFolderPath?: string;}export interface RejectedFile {@@ -60,13 +60,53 @@ export interface RejectedFile {message: string;}+export interface UploadItemState {+ itemId: string;+ name: string;+ type: "folder" | "file";+ /** Total entries: all nested folders + all files for folders; 1 for loose files */+ totalEntries: number;+ completedEntries: number;+ failedEntries: number;+ cancelled?: boolean;+ /** Pre-computed link for completed folder items */+ folderHref?: string;+}++export interface UploadBatchState {+ batchId: string;+ items: UploadItemState[];+ startedAt: number;+ /** Total entries across all items (folders + files) */+ totalEntries: number;+ completedEntries: number;+ failedEntries: number;+ cancelled?: boolean;+}++const UPLOAD_CONCURRENCY = 5;++async function processWithConcurrency<T>(+ tasks: (() => Promise<T>)[],+ concurrency: number,+): Promise<T[]> {+ const results: T[] = new Array(tasks.length);+ let nextIndex = 0;++ async function worker() {+ while (nextIndex < tasks.length) {+ const i = nextIndex++;+ results[i] = await tasks[i]();+ }+ }++ await Promise.all(Array.from({ length: concurrency }, () => worker()));+ return results;+}+interface UploadZoneProps extends React.PropsWithChildren {- onUploadStart: (uploads: UploadState[]) => void;- onUploadProgress: (- index: number,- progress: number,- documentId?: string,- ) => void;+ onUploadBatchStart: (batch: UploadBatchState, cancelFn: () => void) => void;+ onUploadBatchUpdate: (batchId: string, update: Partial<UploadBatchState>) => void;onUploadRejected: (rejected: RejectedFile[]) => void;onUploadSuccess?: (files: {@@ -75,8 +115,12 @@ interface UploadZoneProps extends React.PropsWithChildren {dataroomDocumentId: string;}[],) => void;- setUploads: React.Dispatch<React.SetStateAction<UploadState[]>>;+ onTraversalStart?: (+ preliminaryItems?: { name: string; isFolder: boolean }[],+ ) => void;+ onUploadAborted?: () => void;setRejectedFiles: React.Dispatch<React.SetStateAction<RejectedFile[]>>;+ cancelledItemIdsRef?: React.RefObject<Set<string>>;folderPathName?: string;dataroomId?: string;dataroomName?: string;@@ -84,13 +128,15 @@ interface UploadZoneProps extends React.PropsWithChildren {export default function UploadZone({children,- onUploadStart,- onUploadProgress,+ onUploadBatchStart,+ onUploadBatchUpdate,onUploadRejected,onUploadSuccess,+ onTraversalStart,+ onUploadAborted,folderPathName,- setUploads,setRejectedFiles,+ cancelledItemIdsRef,dataroomId,dataroomName,}: UploadZoneProps) {@@ -263,7 +309,6 @@ export default function UploadZone({const onDrop = useCallback(async (acceptedFiles: FileWithPaths[]) => {- // Check if team is pausedif (isPaused) {toast.error("Your subscription is paused. Resume your subscription to upload documents.",@@ -274,6 +319,7 @@ export default function UploadZone({},},);+ onUploadAborted?.();return;}@@ -288,14 +334,13 @@ export default function UploadZone({duration: 8000,},);+ onUploadAborted?.();return;}let filesToUpload = acceptedFiles;if (fileLimitTruncatedRef.current) {- // Folder traversal was already capped at remainingDocuments –- // no extra folders were created, just show the warning.fileLimitTruncatedRef.current = false;toast.warning(`Your upload was limited to ${acceptedFiles.length} file${acceptedFiles.length === 1 ? "" : "s"} because your plan only allows ${remainingDocuments} more document${remainingDocuments === 1 ? "" : "s"} (${limits?.usage?.documents}/${limits?.documents} used).`,@@ -308,8 +353,6 @@ export default function UploadZone({},);} else if (hasDocumentLimit && acceptedFiles.length > remainingDocuments) {- // Safety net for the file-picker path (no folder traversal) or- // race conditions where the cap was slightly exceeded.const skippedCount = acceptedFiles.length - remainingDocuments;toast.warning(`You're trying to upload ${acceptedFiles.length} files, but your plan only allows ${remainingDocuments} more document${remainingDocuments === 1 ? "" : "s"} (${limits?.usage?.documents}/${limits?.documents} used). ${skippedCount} file${skippedCount === 1 ? "" : "s"} will be skipped.`,@@ -322,16 +365,23 @@ export default function UploadZone({},);filesToUpload = acceptedFiles.slice(0, remainingDocuments);+ const skippedFiles = acceptedFiles.slice(remainingDocuments);+ setRejectedFiles((prev) => [+ ...skippedFiles.map((f) => ({+ fileName: f.name,+ message: "Skipped (document limit reached)",+ })),+ ...prev,+ ]);}- // Validate files and separate into valid and invalidconst validatedFiles = filesToUpload.reduce<{valid: FileWithPaths[];invalid: { fileName: string; message: string }[];}>((acc, file) => {const fileSizeLimitMB = getFileSizeLimit(file.type, fileSizeLimits);- const fileSizeLimit = fileSizeLimitMB * 1024 * 1024; // Convert to bytes+ const fileSizeLimit = fileSizeLimitMB * 1024 * 1024;if (file.size > fileSizeLimit) {acc.invalid.push({@@ -350,223 +400,297 @@ export default function UploadZone({{ valid: [], invalid: [] },);- // Handle rejected files firstif (validatedFiles.invalid.length > 0) {setRejectedFiles((prev) => [...validatedFiles.invalid, ...prev]);- // If all files were rejected, show a summary toastif (validatedFiles.valid.length === 0) {toast.error(`${validatedFiles.invalid.length} file(s) exceeded size limits`,);+ onUploadAborted?.();return;}}- // Continue with valid files- const newUploads = validatedFiles.valid.map((file) => ({- fileName: file.name,- progress: 0,- uploadId: crypto.randomUUID(),- }));+ // Group files by their top-level drag item+ const itemGroups = new Map<+ string,+ {+ name: string;+ isFolder: boolean;+ folderCount: number;+ folderSlugPath?: string;+ files: FileWithPaths[];+ }+ >();+ for (const file of validatedFiles.valid) {+ const key = file.topLevelItemName ?? file.name;+ const existing = itemGroups.get(key);+ if (existing) {+ existing.files.push(file);+ } else {+ itemGroups.set(key, {+ name: key,+ isFolder: file.topLevelItemIsFolder ?? false,+ folderCount: file.topLevelItemFolderCount ?? 0,+ folderSlugPath: file.topLevelItemFolderPath,+ files: [file],+ });+ }+ }- onUploadStart(newUploads);+ const batchId = crypto.randomUUID();+ let totalEntriesAcrossAll = 0;- const uploadPromises = validatedFiles.valid.map(async (file, index) => {- // Due to `getFilesFromEvent` file.path will always hold a valid value and represents the value of webkitRelativePath.- // We no longer need to use webkitRelativePath because everything is been handled in `getFilesFromEvent`- const path = file.path || file.name;+ const items: UploadItemState[] = Array.from(itemGroups.values()).map(+ (group) => {+ const folderCount = group.isFolder ? group.folderCount : 0;+ const total = folderCount + group.files.length;+ totalEntriesAcrossAll += total;- // count the number of pages in the file- let numPages = 1;- if (file.type === "application/pdf") {- const buffer = await file.arrayBuffer();- numPages = await getPagesCount(buffer);+ let folderHref: string | undefined;+ if (group.isFolder && group.folderSlugPath) {+ folderHref = dataroomId+ ? `/datarooms/${dataroomId}/documents/${group.folderSlugPath}`+ : `/documents/tree/${group.folderSlugPath}`;+ }- if (numPages > fileSizeLimits.maxPages) {- setUploads((prev) =>- prev.filter((upload) => upload.fileName !== file.name),- );+ return {+ itemId: crypto.randomUUID(),+ name: group.name,+ type: group.isFolder ? ("folder" as const) : ("file" as const),+ totalEntries: total,+ completedEntries: folderCount,+ failedEntries: 0,+ folderHref,+ };+ },+ );- return setRejectedFiles((prev) => [- {- fileName: file.name,- message: `File has too many pages (max. ${fileSizeLimits.maxPages})`,- },- ...prev,- ]);- }- }+ const batch: UploadBatchState = {+ batchId,+ items,+ startedAt: Date.now(),+ totalEntries: totalEntriesAcrossAll,+ // Folders created during traversal count as completed entries+ completedEntries: items.reduce((s, it) => s + it.completedEntries, 0),+ failedEntries: 0,+ };- const { complete } = await resumableUpload({- file, // File- onProgress: (bytesUploaded, bytesTotal) => {- const progress = Math.min(- Math.round((bytesUploaded / bytesTotal) * 100),- 99,- );- setUploads((prevUploads) => {- const updatedUploads = prevUploads.map((upload) =>- upload.uploadId === newUploads[index].uploadId- ? { ...upload, progress }- : upload,- );- const currentUpload = updatedUploads.find(- (upload) => upload.uploadId === newUploads[index].uploadId,- );+ const dropCancelled = { current: false };+ onUploadBatchStart(batch, () => {+ dropCancelled.current = true;+ });- onUploadProgress(index, progress, currentUpload?.documentId);- return updatedUploads;- });- },- onError: (error) => {- setUploads((prev) =>- prev.filter(- (upload) => upload.uploadId !== newUploads[index].uploadId,- ),- );+ // Build a lookup: file -> which UploadItemState it belongs to+ const fileToItem = new Map<FileWithPaths, UploadItemState>();+ let itemIdx = 0;+ for (const group of itemGroups.values()) {+ const item = items[itemIdx++];+ for (const file of group.files) {+ fileToItem.set(file, item);+ }+ }- setRejectedFiles((prev) => [- { fileName: file.name, message: "Error uploading file" },- ...prev,- ]);- },- ownerId: (session?.user as CustomUser).id,- teamId: teamInfo?.currentTeam?.id as string,- numPages,- relativePath: path.substring(0, path.lastIndexOf("/")),+ let completedCount = batch.completedEntries;+ let failedCount = 0;++ const emitUpdate = () => {+ onUploadBatchUpdate(batchId, {+ items: items.map((it) => ({ ...it })),+ completedEntries: completedCount,+ failedEntries: failedCount,});+ };- const uploadResult = await complete;+ const uploadTasks = validatedFiles.valid.map((file) => async () => {+ if (dropCancelled.current) return undefined;- let contentType = uploadResult.fileType;- let supportedFileType = getSupportedContentType(contentType) ?? "";+ const path = file.path || file.name;+ const parentItem = fileToItem.get(file)!;- if (- uploadResult.fileName.endsWith(".dwg") ||- uploadResult.fileName.endsWith(".dxf")- ) {- supportedFileType = "cad";- contentType = `image/vnd.${uploadResult.fileName.split(".").pop()}`;+ // Skip files for cancelled items+ if (cancelledItemIdsRef?.current?.has(parentItem.itemId)) {+ return undefined;}- if (uploadResult.fileName.endsWith(".xlsm")) {- supportedFileType = "sheet";- contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";- }+ try {+ let numPages = 1;+ if (file.type === "application/pdf") {+ const buffer = await file.arrayBuffer();+ numPages = await getPagesCount(buffer);- if (- uploadResult.fileName.endsWith(".kml") ||- uploadResult.fileName.endsWith(".kmz")- ) {- supportedFileType = "map";- contentType = `application/vnd.google-earth.${uploadResult.fileName.endsWith(".kml") ? "kml+xml" : "kmz"}`;- }+ if (numPages > fileSizeLimits.maxPages) {+ failedCount++;+ parentItem.failedEntries++;+ setRejectedFiles((prev) => [+ {+ fileName: file.name,+ message: `File has too many pages (max. ${fileSizeLimits.maxPages})`,+ },+ ...prev,+ ]);+ emitUpdate();+ return undefined;+ }+ }- const documentData: DocumentData = {- key: uploadResult.id,- supportedFileType: supportedFileType,- name: file.name,- storageType: DocumentStorageType.S3_PATH,- contentType: contentType,- fileSize: file.size,- };-- const fileUploadPathName = file?.whereToUploadPath;- const dataroomUploadPathName = file?.dataroomUploadPath;-- const response = await createDocument({- documentData,- teamId: teamInfo?.currentTeam?.id as string,- numPages: uploadResult.numPages,- folderPathName: fileUploadPathName,- });+ const { complete } = await resumableUpload({+ file,+ onProgress: (bytesUploaded, bytesTotal) => {+ const _progress = Math.min(+ Math.round((bytesUploaded / bytesTotal) * 100),+ 99,+ );+ emitUpdate();+ },+ onError: () => {+ failedCount++;+ parentItem.failedEntries++;+ setRejectedFiles((prev) => [+ { fileName: file.name, message: "Error uploading file" },+ ...prev,+ ]);+ emitUpdate();+ },+ ownerId: (session?.user as CustomUser).id,+ teamId: teamInfo?.currentTeam?.id as string,+ numPages,+ relativePath: path.substring(0, path.lastIndexOf("/")),+ });++ const uploadResult = await complete;++ let contentType = uploadResult.fileType;+ let supportedFileType = getSupportedContentType(contentType) ?? "";++ if (+ uploadResult.fileName.endsWith(".dwg") ||+ uploadResult.fileName.endsWith(".dxf")+ ) {+ supportedFileType = "cad";+ contentType = `image/vnd.${uploadResult.fileName.split(".").pop()}`;+ }- // add the new document to the list- mutate(`/api/teams/${teamInfo?.currentTeam?.id}/documents`);+ if (uploadResult.fileName.endsWith(".xlsm")) {+ supportedFileType = "sheet";+ contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";+ }- fileUploadPathName &&- mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/folders/documents/${fileUploadPathName}`,- );+ if (+ uploadResult.fileName.endsWith(".kml") ||+ uploadResult.fileName.endsWith(".kmz")+ ) {+ supportedFileType = "map";+ contentType = `application/vnd.google-earth.${uploadResult.fileName.endsWith(".kml") ? "kml+xml" : "kmz"}`;+ }- const document = await response.json();- let dataroomResponse;- if (dataroomId) {- try {- dataroomResponse = await fetch(- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- documentId: document.id,- folderPathName: dataroomUploadPathName || fileUploadPathName,- }),- },- );+ const documentData: DocumentData = {+ key: uploadResult.id,+ supportedFileType: supportedFileType,+ name: file.name,+ storageType: DocumentStorageType.S3_PATH,+ contentType: contentType,+ fileSize: file.size,+ };- if (!dataroomResponse?.ok) {- const { message } = await dataroomResponse.json();- console.error(- "An error occurred while adding document to the dataroom: ",- message,- );- return;- }+ const fileUploadPathName = file?.whereToUploadPath;+ const dataroomUploadPathName = file?.dataroomUploadPath;++ const response = await createDocument({+ documentData,+ teamId: teamInfo?.currentTeam?.id as string,+ numPages: uploadResult.numPages,+ folderPathName: fileUploadPathName,+ });++ mutate(`/api/teams/${teamInfo?.currentTeam?.id}/documents`);+ fileUploadPathName &&mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,+ `/api/teams/${teamInfo?.currentTeam?.id}/folders/documents/${fileUploadPathName}`,);- (dataroomUploadPathName || fileUploadPathName) &&++ const document = await response.json();+ let dataroomResponse;+ if (dataroomId) {+ try {+ dataroomResponse = await fetch(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentId: document.id,+ folderPathName: dataroomUploadPathName || fileUploadPathName,+ }),+ },+ );++ if (!dataroomResponse?.ok) {+ const { message } = await dataroomResponse.json();+ console.error(+ "An error occurred while adding document to the dataroom: ",+ message,+ );+ return undefined;+ }+mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${dataroomUploadPathName || fileUploadPathName}`,+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/documents`,);- } catch (error) {- console.error(- "An error occurred while adding document to the dataroom: ",- error,- );+ (dataroomUploadPathName || fileUploadPathName) &&+ mutate(+ `/api/teams/${teamInfo?.currentTeam?.id}/datarooms/${dataroomId}/folders/documents/${dataroomUploadPathName || fileUploadPathName}`,+ );+ } catch (error) {+ console.error(+ "An error occurred while adding document to the dataroom: ",+ error,+ );+ }}- }- // update progress to 100%- setUploads((prevUploads) =>- prevUploads.map((upload) =>- upload.uploadId === newUploads[index].uploadId- ? { ...upload, progress: 100, documentId: document.id }- : upload,- ),- );-- analytics.capture("Document Added", {- documentId: document.id,- name: document.name,- numPages: document.numPages,- path: router.asPath,- type: document.type,- contentType: document.contentType,- teamId: teamInfo?.currentTeam?.id,- bulkupload: true,- dataroomId: dataroomId,- $set: {+ completedCount++;+ parentItem.completedEntries++;+ emitUpdate();++ analytics.capture("Document Added", {+ documentId: document.id,+ name: document.name,+ numPages: document.numPages,+ path: router.asPath,+ type: document.type,+ contentType: document.contentType,teamId: teamInfo?.currentTeam?.id,- teamPlan: plan,- },- });- const dataroomDocumentId = dataroomResponse?.ok- ? (await dataroomResponse.json()).id- : null;-- return { ...document, dataroomDocumentId: dataroomDocumentId };+ bulkupload: true,+ dataroomId: dataroomId,+ $set: {+ teamId: teamInfo?.currentTeam?.id,+ teamPlan: plan,+ },+ });+ const dataroomDocumentId = dataroomResponse?.ok+ ? (await dataroomResponse.json()).id+ : null;++ return { ...document, dataroomDocumentId: dataroomDocumentId };+ } catch (error) {+ failedCount++;+ parentItem.failedEntries++;+ setRejectedFiles((prev) => [+ { fileName: file.name, message: "Error uploading file" },+ ...prev,+ ]);+ emitUpdate();+ return undefined;+ }});- const documents = Promise.all(uploadPromises).finally(() => {- /* If it a parentFolder was created prior to the upload, we would need to update that- how many documents and folders does this folder contain rather than displaying 0- */+ try {+ const results = await processWithConcurrency(uploadTasks, UPLOAD_CONCURRENCY);mutate(`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}?root=true`,@@ -576,18 +700,22 @@ export default function UploadZone({mutate(`/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}/${folderPathName}`,);- });- const uploadedDocuments = await documents;- const dataroomDocuments = uploadedDocuments.map((document) => ({- documentId: document.id,- dataroomDocumentId: document.dataroomDocumentId,- fileName: document.name,- }));- onUploadSuccess?.(dataroomDocuments);++ const uploadedDocuments = results.filter(Boolean);+ const dataroomDocuments = uploadedDocuments.map((document: any) => ({+ documentId: document.id,+ dataroomDocumentId: document.dataroomDocumentId,+ fileName: document.name,+ }));+ onUploadSuccess?.(dataroomDocuments);+ } catch (error) {+ console.error("Upload batch failed:", error);+ }},[- onUploadStart,- onUploadProgress,+ onUploadBatchStart,+ onUploadBatchUpdate,+ onUploadAborted,endpointTargetType,fileSizeLimits,isFree,@@ -605,11 +733,43 @@ export default function UploadZone({return [];}+ // Extract top-level item names from the drop so the drawer can show them immediately+ let preliminaryItems: { name: string; isFolder: boolean }[] | undefined;+ if ("dataTransfer" in event && event.dataTransfer) {+ preliminaryItems = Array.from(+ event.dataTransfer.items,+ (item) => {+ const entry =+ (typeof item?.webkitGetAsEntry === "function" &&+ item.webkitGetAsEntry()) ??+ (typeof (item as any)?.getAsEntry === "function" &&+ (item as any).getAsEntry()) ??+ null;+ return {+ name: entry?.name ?? (item.type || "Unknown"),+ isFolder: entry?.isDirectory ?? false,+ };+ },+ ).filter((e) => e.name !== "Unknown");+ } else if (+ "target" in event &&+ event.target instanceof HTMLInputElement &&+ event.target.files+ ) {+ preliminaryItems = Array.from(event.target.files, (f) => ({+ name: f.name,+ isFolder: false,+ }));+ }+ onTraversalStart?.(preliminaryItems);+fileLimitTruncatedRef.current = false;- const fileLimit =+ const maxFilesPerUpload = fileSizeLimits.maxFiles ?? 150;+ const planDocumentLimit =hasDocumentLimit && isFinite(remainingDocuments)? Math.max(0, remainingDocuments): Infinity;+ const fileLimit = Math.min(maxFilesPerUpload, planDocumentLimit);let collectedFileCount = 0;// Early check: skip folder traversal (and folder creation) if document limit is already reached@@ -649,6 +809,8 @@ export default function UploadZone({entry: FileSystemEntry,parentPathOfThisEntry?: string,dataroomParentPath?: string,+ folderCounter?: { count: number },+ folderPathCapture?: { value?: string },): Promise<FileWithPaths[]> => {/*** Summary of this function:@@ -663,10 +825,6 @@ export default function UploadZone({return files;}- if (collectedFileCount >= fileLimit) {- return files;- }-if (entry.isDirectory) {/*** Let's create the folder.@@ -706,6 +864,24 @@ export default function UploadZone({path: parentPathOfThisEntry ?? folderPathName,});+ // Revalidate SWR so the folder appears in the UI immediately+ mutate(`/api/teams/${teamInfo.currentTeam.id}/folders?root=true`);+ const parentPath = parentPathOfThisEntry ?? folderPathName;+ if (parentPath) {+ mutate(+ `/api/teams/${teamInfo.currentTeam.id}/folders/${parentPath}`,+ );+ mutate(+ `/api/teams/${teamInfo.currentTeam.id}/folders/documents/${parentPath}`,+ );+ }++ if (folderCounter) folderCounter.count++;+ if (folderPathCapture && folderPathCapture.value === undefined) {+ folderPathCapture.value = folderPath.startsWith("/")+ ? folderPath.slice(1)+ : folderPath;+ }analytics.capture("Folder Added", { folderName: entry.name });const dirReader = (@@ -728,6 +904,8 @@ export default function UploadZone({subEntry,resolvedFolderPath,undefined,+ folderCounter,+ folderPathCapture,)),);}@@ -761,6 +939,13 @@ export default function UploadZone({replicateDataroomFolders,});+ if (folderCounter) folderCounter.count++;+ if (folderPathCapture && folderPathCapture.value === undefined) {+ folderPathCapture.value = dataroomPath.startsWith("/")+ ? dataroomPath.slice(1)+ : dataroomPath;+ }+const dirReader = (entry as FileSystemDirectoryEntry).createReader();@@ -788,6 +973,8 @@ export default function UploadZone({subEntry,resolvedMainDocsPath,resolvedDataroomPath,+ folderCounter,+ folderPathCapture,)),);}@@ -880,20 +1067,30 @@ export default function UploadZone({const fileResults = await Promise.all(Array.from(items, (item) => {- // MDN Note: This function is implemented as webkitGetAsEntry() in non-WebKit browsers including Firefox at this time; it may be renamed to getAsEntry() in the future, so you should code defensively, looking for both.const entry =(typeof item?.webkitGetAsEntry === "function" &&item.webkitGetAsEntry()) ??(typeof (item as any)?.getAsEntry === "function" &&(item as any).getAsEntry()) ??null;- return entry- ? traverseFolder(- entry,- folderPathName,- dataroomId ? folderPathName : undefined,- )- : [];+ if (!entry) return [];+ const counter = { count: 0 };+ const pathCapture: { value?: string } = {};+ return traverseFolder(+ entry,+ folderPathName,+ dataroomId ? folderPathName : undefined,+ counter,+ pathCapture,+ ).then((files) => {+ for (const f of files) {+ f.topLevelItemName = entry.name;+ f.topLevelItemIsFolder = entry.isDirectory;+ f.topLevelItemFolderCount = counter.count;+ f.topLevelItemFolderPath = pathCapture.value;+ }+ return files;+ });}),);fileResults.forEach((fileResult) =>@@ -910,6 +1107,8 @@ export default function UploadZone({file.path = file.name;file.whereToUploadPath = folderPathName;file.dataroomUploadPath = folderPathName;+ file.topLevelItemName = file.name;+ file.topLevelItemIsFolder = false;filesToBePassedToOnDrop.push(event.target.files[i]);}}@@ -932,6 +1131,9 @@ export default function UploadZone({getOrCreateDataroomFolder,hasDocumentLimit,remainingDocuments,+ fileSizeLimits,+ replicateDataroomFolders,+ onTraversalStart,],);diff --git a/context/upload-progress-context.tsx b/context/upload-progress-context.tsxnew file mode 100644index 00000000..364a344c--- /dev/null+++ b/context/upload-progress-context.tsx@@ -0,0 +1,355 @@+import {+ createContext,+ useCallback,+ useContext,+ useMemo,+ useRef,+ useState,+} from "react";++import { UploadNotificationDrawer } from "@/components/upload-notification";+import {+ RejectedFile,+ UploadBatchState,+ UploadItemState,+} from "@/components/upload-zone";++interface UploadProgressContextType {+ uploadBatch: UploadBatchState | null;+ setUploadBatch: React.Dispatch<+ React.SetStateAction<UploadBatchState | null>+ >;+ rejectedFiles: RejectedFile[];+ setRejectedFiles: React.Dispatch<React.SetStateAction<RejectedFile[]>>;+ showDrawer: boolean;+ setShowDrawer: (show: boolean) => void;+ cancelUpload: (() => void) | null;+ addCancelFn: (fn: () => void) => void;+ cancelItem: (itemId: string) => void;+ cancelledItemIds: Set<string>;+ cancelledItemIdsRef: React.RefObject<Set<string>>;+}++const UploadProgressContext = createContext<UploadProgressContextType | null>(+ null,+);++export function UploadProgressProvider({+ children,+}: {+ children: React.ReactNode;+}) {+ const [uploadBatch, setUploadBatch] = useState<UploadBatchState | null>(null);+ const [rejectedFiles, setRejectedFiles] = useState<RejectedFile[]>([]);+ const [showDrawer, setShowDrawer] = useState(false);+ const [hasCancelFns, setHasCancelFns] = useState(false);+ const cancelFnsRef = useRef<(() => void)[]>([]);+ const [cancelledItemIds, setCancelledItemIds] = useState<Set<string>>(+ new Set(),+ );+ const cancelledItemIdsRef = useRef(cancelledItemIds);+ cancelledItemIdsRef.current = cancelledItemIds;++ const addCancelFn = useCallback((fn: () => void) => {+ cancelFnsRef.current.push(fn);+ setHasCancelFns(true);+ }, []);++ const cancelUpload = useCallback(() => {+ cancelFnsRef.current.forEach((fn) => fn());+ cancelFnsRef.current = [];+ setHasCancelFns(false);+ setUploadBatch((prev) => {+ if (!prev) return prev;+ let addedCompleted = 0;+ const updatedItems = prev.items.map((it) => {+ if (it.cancelled) return it;+ const remaining =+ it.totalEntries - it.completedEntries - it.failedEntries;+ if (remaining > 0) {+ addedCompleted += remaining;+ return {+ ...it,+ cancelled: true,+ completedEntries: it.totalEntries - it.failedEntries,+ } as UploadItemState;+ }+ return it;+ });+ return {+ ...prev,+ cancelled: true,+ completedEntries: prev.completedEntries + addedCompleted,+ items: updatedItems,+ };+ });+ }, []);++ const cancelItem = useCallback((itemId: string) => {+ setCancelledItemIds((prev) => {+ const next = new Set(prev);+ next.add(itemId);+ return next;+ });+ setUploadBatch((prev) => {+ if (!prev) return prev;+ const target = prev.items.find((it) => it.itemId === itemId);+ if (!target || target.cancelled) return prev;+ const remaining =+ target.totalEntries - target.completedEntries - target.failedEntries;+ return {+ ...prev,+ completedEntries: prev.completedEntries + remaining,+ items: prev.items.map((it) =>+ it.itemId === itemId+ ? ({+ ...it,+ cancelled: true,+ completedEntries: it.totalEntries - it.failedEntries,+ } as UploadItemState)+ : it,+ ),+ };+ });+ }, []);++ const handleCloseDrawer = useCallback(() => {+ setShowDrawer(false);+ setUploadBatch(null);+ setRejectedFiles([]);+ setCancelledItemIds(new Set());+ cancelFnsRef.current = [];+ setHasCancelFns(false);+ }, []);++ const handleOpenChange = useCallback((open: boolean) => {+ setShowDrawer(open);+ if (!open) {+ setUploadBatch(null);+ setRejectedFiles([]);+ setCancelledItemIds(new Set());+ cancelFnsRef.current = [];+ setHasCancelFns(false);+ }+ }, []);++ const value = useMemo<UploadProgressContextType>(+ () => ({+ uploadBatch,+ setUploadBatch,+ rejectedFiles,+ setRejectedFiles,+ showDrawer,+ setShowDrawer,+ cancelUpload: hasCancelFns ? cancelUpload : null,+ addCancelFn,+ cancelItem,+ cancelledItemIds,+ cancelledItemIdsRef,+ }),+ [+ uploadBatch,+ rejectedFiles,+ showDrawer,+ hasCancelFns,+ cancelUpload,+ addCancelFn,+ cancelItem,+ cancelledItemIds,+ ],+ );++ return (+ <UploadProgressContext.Provider value={value}>+ {children}+ {showDrawer ? (+ <UploadNotificationDrawer+ open={showDrawer}+ onOpenChange={handleOpenChange}+ batch={uploadBatch}+ setBatch={setUploadBatch}+ rejectedFiles={rejectedFiles}+ setRejectedFiles={setRejectedFiles}+ handleCloseDrawer={handleCloseDrawer}+ onCancel={hasCancelFns ? cancelUpload : undefined}+ onCancelItem={cancelItem}+ />+ ) : null}+ </UploadProgressContext.Provider>+ );+}++export function useUploadProgress() {+ const ctx = useContext(UploadProgressContext);+ if (!ctx) {+ throw new Error(+ "useUploadProgress must be used within UploadProgressProvider",+ );+ }+ return ctx;+}++/** Stable callbacks for wiring UploadZone to the shared upload-progress context. */+export function useUploadCallbacks() {+ const { setUploadBatch, setRejectedFiles, setShowDrawer, addCancelFn } =+ useUploadProgress();++ const onTraversalStart = useCallback(+ (preliminaryItems?: { name: string; isFolder: boolean }[]) => {+ setUploadBatch((prev) => {+ const isDone =+ prev &&+ (prev.cancelled ||+ (prev.totalEntries > 0 &&+ prev.completedEntries + prev.failedEntries >=+ prev.totalEntries));+ const baseBatch = isDone ? null : prev;+ if (!preliminaryItems?.length) return baseBatch;+ const newItems = preliminaryItems.map((pi) => ({+ itemId: crypto.randomUUID(),+ name: pi.name,+ type: (pi.isFolder ? "folder" : "file") as "folder" | "file",+ totalEntries: 0,+ completedEntries: 0,+ failedEntries: 0,+ }));+ if (!baseBatch) {+ return {+ batchId: crypto.randomUUID(),+ items: newItems,+ startedAt: Date.now(),+ totalEntries: 0,+ completedEntries: 0,+ failedEntries: 0,+ };+ }+ return {+ ...baseBatch,+ items: [...baseBatch.items, ...newItems],+ };+ });+ setShowDrawer(true);+ },+ [setUploadBatch, setShowDrawer],+ );++ const onUploadBatchStart = useCallback(+ (batch: UploadBatchState, cancelFn: () => void) => {+ addCancelFn(cancelFn);+ setUploadBatch((prev) => {+ if (!prev || prev.cancelled) return batch;+ const isPreliminary = prev.totalEntries === 0;+ if (isPreliminary) {+ const realNames = new Set(batch.items.map((it) => it.name));+ const kept = prev.items+ .filter((it) => !realNames.has(it.name))+ .map((it) => ({ ...it, cancelled: true }));+ return {+ ...batch,+ items: [...batch.items, ...kept],+ totalEntries: batch.totalEntries,+ completedEntries: batch.completedEntries,+ failedEntries: batch.failedEntries,+ };+ }+ const isActive =+ prev.completedEntries + prev.failedEntries < prev.totalEntries;+ if (isActive) {+ return {+ ...prev,+ items: [...prev.items, ...batch.items],+ totalEntries: prev.totalEntries + batch.totalEntries,+ completedEntries:+ prev.completedEntries + batch.completedEntries,+ failedEntries: prev.failedEntries + batch.failedEntries,+ };+ }+ return batch;+ });+ setShowDrawer(true);+ },+ [addCancelFn, setUploadBatch, setShowDrawer],+ );++ const onUploadBatchUpdate = useCallback(+ (_batchId: string, update: Partial<UploadBatchState>) => {+ setUploadBatch((prev) => {+ if (!prev || prev.cancelled) return prev;+ const mergedItems = [...prev.items];+ if (update.items) {+ const indexMap = new Map<string, number>();+ for (let i = 0; i < mergedItems.length; i++) {+ indexMap.set(mergedItems[i].itemId, i);+ }+ for (const incoming of update.items) {+ const idx = indexMap.get(incoming.itemId);+ if (idx !== undefined && !mergedItems[idx].cancelled) {+ mergedItems[idx] = incoming;+ }+ }+ }+ let totalEntries = 0;+ let completedEntries = 0;+ let failedEntries = 0;+ for (const it of mergedItems) {+ totalEntries += it.totalEntries;+ completedEntries += it.completedEntries;+ failedEntries += it.failedEntries;+ }+ return {+ ...prev,+ items: mergedItems,+ totalEntries,+ completedEntries,+ failedEntries,+ };+ });+ },+ [setUploadBatch],+ );++ const onUploadRejected = useCallback(+ (rejected: RejectedFile[]) => {+ setRejectedFiles((prevRejected) => [...prevRejected, ...rejected]);+ const rejectedNames = new Set(rejected.map((r) => r.fileName));+ setUploadBatch((prev) => {+ if (!prev) return prev;+ let changed = false;+ const updatedItems = prev.items.map((it) => {+ if (+ it.totalEntries === 0 &&+ !it.cancelled &&+ rejectedNames.has(it.name)+ ) {+ changed = true;+ return { ...it, cancelled: true };+ }+ return it;+ });+ return changed ? { ...prev, items: updatedItems } : prev;+ });+ setShowDrawer(true);+ },+ [setRejectedFiles, setUploadBatch, setShowDrawer],+ );++ const onUploadAborted = useCallback(() => {+ setUploadBatch((prev) => {+ if (!prev) return prev;+ const updatedItems = prev.items.map((it) =>+ it.totalEntries === 0 && !it.cancelled+ ? { ...it, cancelled: true }+ : it,+ );+ return { ...prev, items: updatedItems };+ });+ }, [setUploadBatch]);++ return {+ onTraversalStart,+ onUploadBatchStart,+ onUploadBatchUpdate,+ onUploadRejected,+ onUploadAborted,+ };+}diff --git a/pages/_app.tsx b/pages/_app.tsxindex 3a71e952..60bfb569 100644--- a/pages/_app.tsx+++ b/pages/_app.tsx@@ -3,6 +3,7 @@ import { Inter } from "next/font/google";import Head from "next/head";import { TeamProvider } from "@/context/team-context";+import { UploadProgressProvider } from "@/context/upload-progress-context";import type { Session } from "next-auth";import { SessionProvider } from "next-auth/react";import { NuqsAdapter } from "nuqs/adapters/next/pages";@@ -82,8 +83,10 @@ export default function App({<Component {...pageProps} />) : (<TeamProvider>- <Component {...pageProps} />- <DealflowPopup />+ <UploadProgressProvider>+ <Component {...pageProps} />+ <DealflowPopup />+ </UploadProgressProvider></TeamProvider>)}</TooltipProvider>