Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: show uploaded documents immediately with processing state

Cursor Agenta44564ad1c44
diff --git a/app/(ee)/api/links/[id]/upload/route.ts b/app/(ee)/api/links/[id]/upload/route.ts
index 46a97670..fee7f055 100644
--- a/app/(ee)/api/links/[id]/upload/route.ts
+++ b/app/(ee)/api/links/[id]/upload/route.ts
@@ -148,7 +148,19 @@ export async function POST(
},
});
- return NextResponse.json({ success: true });
+ // Return document data for optimistic UI rendering
+ return NextResponse.json({
+ success: true,
+ document: {
+ id: document.id,
+ name: document.name,
+ dataroomDocumentId: newDataroomDocument.id,
+ folderId: dataroomFolderId,
+ fileType: document.type,
+ hasPages: document.versions[0]?.hasPages ?? false,
+ createdAt: document.createdAt,
+ },
+ });
} catch (error) {
console.error("Error uploading document:", error);
return NextResponse.json(
diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsx
index 83091576..7654effb 100644
--- a/components/view/dataroom/dataroom-view.tsx
+++ b/components/view/dataroom/dataroom-view.tsx
@@ -6,6 +6,7 @@ import { DataroomBrand } from "@prisma/client";
import Cookies from "js-cookie";
import { toast } from "sonner";
+import { PendingUploadsProvider } from "@/context/pending-uploads-context";
import { useAnalytics } from "@/lib/analytics";
import { SUPPORTED_DOCUMENT_SIMPLE_TYPES } from "@/lib/constants";
import { useDisablePrint } from "@/lib/hooks/use-disable-print";
@@ -278,31 +279,33 @@ export default function DataroomView({
if (submitted) {
return (
- <div className="bg-gray-950">
- <DataroomViewer
- accessControls={link.accessControls || group?.accessControls || []}
- brand={brand!}
- viewId={viewData.viewId}
- isPreview={viewData.isPreview}
- linkId={link.id}
- dataroom={dataroom}
- allowDownload={link.allowDownload!}
- enableIndexFile={link.enableIndexFile}
- folderId={folderId}
- setFolderId={setFolderId}
- viewerId={viewData.viewerId}
- viewData={viewData}
- isEmbedded={isEmbedded}
- dataroomIndexEnabled={dataroomIndexEnabled}
- viewerEmail={
- viewData.viewerEmail ??
- data.email ??
- verifiedEmail ??
- userEmail ??
- undefined
- }
- />
- </div>
+ <PendingUploadsProvider>
+ <div className="bg-gray-950">
+ <DataroomViewer
+ accessControls={link.accessControls || group?.accessControls || []}
+ brand={brand!}
+ viewId={viewData.viewId}
+ isPreview={viewData.isPreview}
+ linkId={link.id}
+ dataroom={dataroom}
+ allowDownload={link.allowDownload!}
+ enableIndexFile={link.enableIndexFile}
+ folderId={folderId}
+ setFolderId={setFolderId}
+ viewerId={viewData.viewerId}
+ viewData={viewData}
+ isEmbedded={isEmbedded}
+ dataroomIndexEnabled={dataroomIndexEnabled}
+ viewerEmail={
+ viewData.viewerEmail ??
+ data.email ??
+ verifiedEmail ??
+ userEmail ??
+ undefined
+ }
+ />
+ </div>
+ </PendingUploadsProvider>
);
}
diff --git a/components/view/dataroom/document-upload-modal.tsx b/components/view/dataroom/document-upload-modal.tsx
index 0b9e933c..0a1d9432 100644
--- a/components/view/dataroom/document-upload-modal.tsx
+++ b/components/view/dataroom/document-upload-modal.tsx
@@ -1,7 +1,7 @@
// components/view/dataroom/document-upload-button.tsx
import { useState } from "react";
-import { PlusIcon } from "lucide-react";
+import { CheckCircle2, PlusIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
@@ -25,6 +25,23 @@ export function DocumentUploadModal({
folderId?: string;
}) {
const [isOpen, setIsOpen] = useState(false);
+ const [uploadSuccess, setUploadSuccess] = useState(false);
+
+ const handleUploadSuccess = () => {
+ setUploadSuccess(true);
+ // Auto-close the dialog after a short delay to show success message
+ setTimeout(() => {
+ setIsOpen(false);
+ setUploadSuccess(false);
+ }, 1500);
+ };
+
+ const handleOpenChange = (open: boolean) => {
+ setIsOpen(open);
+ if (!open) {
+ setUploadSuccess(false);
+ }
+ };
return (
<>
@@ -39,25 +56,39 @@ export function DocumentUploadModal({
<span>Add Document</span>
</Button>
- <Dialog open={isOpen} onOpenChange={setIsOpen}>
+ <Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Upload Document to Dataroom</DialogTitle>
<DialogDescription>
- The data room manager will receive a notification when the
- document is uploaded and approve the document. Only then, it will
- be visible to all visitors.
+ Your document will appear immediately in the dataroom and will be
+ processed in the background. The data room manager will be
+ notified of your upload.
</DialogDescription>
</DialogHeader>
- <ViewerUploadComponent
- viewerData={{
- id: viewerId,
- linkId,
- dataroomId,
- }}
- teamId="visitor-upload"
- folderId={folderId}
- />
+
+ {uploadSuccess ? (
+ <div className="flex flex-col items-center justify-center py-8">
+ <CheckCircle2 className="h-12 w-12 text-green-500" />
+ <p className="mt-3 text-sm font-medium text-foreground">
+ Document uploaded successfully!
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Your document is now visible and being processed.
+ </p>
+ </div>
+ ) : (
+ <ViewerUploadComponent
+ viewerData={{
+ id: viewerId,
+ linkId,
+ dataroomId,
+ }}
+ teamId="visitor-upload"
+ folderId={folderId}
+ onUploadSuccess={handleUploadSuccess}
+ />
+ )}
</DialogContent>
</Dialog>
</>
diff --git a/components/view/dataroom/pending-document-card.tsx b/components/view/dataroom/pending-document-card.tsx
new file mode 100644
index 00000000..27ed6cd7
--- /dev/null
+++ b/components/view/dataroom/pending-document-card.tsx
@@ -0,0 +1,105 @@
+import { AlertCircle, FileIcon, Loader2, Upload } from "lucide-react";
+import { useTheme } from "next-themes";
+
+import { PendingUploadDocument } from "@/context/pending-uploads-context";
+import { cn } from "@/lib/utils";
+import { fileIcon } from "@/lib/utils/get-file-icon";
+
+import { Progress } from "@/components/ui/progress";
+
+type PendingDocumentCardProps = {
+ pendingUpload: PendingUploadDocument;
+};
+
+export default function PendingDocumentCard({
+ pendingUpload,
+}: PendingDocumentCardProps) {
+ const { theme, systemTheme } = useTheme();
+ const isLight =
+ theme === "light" || (theme === "system" && systemTheme === "light");
+
+ const getStatusText = () => {
+ switch (pendingUpload.status) {
+ case "uploading":
+ return `Uploading... ${pendingUpload.progress}%`;
+ case "processing":
+ return "Processing document...";
+ case "error":
+ return pendingUpload.errorMessage || "Upload failed";
+ case "complete":
+ return "Complete";
+ default:
+ return "Pending";
+ }
+ };
+
+ const getStatusIcon = () => {
+ switch (pendingUpload.status) {
+ case "uploading":
+ return <Upload className="h-4 w-4 animate-pulse text-blue-500" />;
+ case "processing":
+ return <Loader2 className="h-4 w-4 animate-spin text-orange-500" />;
+ case "error":
+ return <AlertCircle className="h-4 w-4 text-red-500" />;
+ default:
+ return null;
+ }
+ };
+
+ const isError = pendingUpload.status === "error";
+ const isUploading = pendingUpload.status === "uploading";
+ const isProcessing = pendingUpload.status === "processing";
+
+ return (
+ <div
+ className={cn(
+ "group/row relative flex items-center justify-between rounded-lg border-0 p-3 ring-1 transition-all sm:p-4",
+ isError
+ ? "bg-red-50/50 ring-red-200 dark:bg-red-950/20 dark:ring-red-800"
+ : "ring-blue-200 bg-blue-50/50 dark:bg-blue-950/20 dark:ring-blue-800",
+ )}
+ >
+ <div className="z-0 flex min-w-0 shrink items-center space-x-2 sm:space-x-4">
+ <div className="mx-0.5 flex w-8 items-center justify-center text-center sm:mx-1">
+ {pendingUpload.fileType ? (
+ fileIcon({
+ fileType: pendingUpload.fileType,
+ className: "h-8 w-8 opacity-60",
+ isLight,
+ })
+ ) : (
+ <FileIcon className="h-8 w-8 text-muted-foreground opacity-60" />
+ )}
+ </div>
+
+ <div className="flex-col flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <h2 className="min-w-0 max-w-[300px] truncate text-sm font-semibold leading-6 text-foreground sm:max-w-lg">
+ {pendingUpload.name}
+ </h2>
+ {getStatusIcon()}
+ </div>
+ <div className="mt-1 flex flex-col gap-1">
+ <p
+ className={cn(
+ "text-xs leading-5",
+ isError ? "text-red-600 dark:text-red-400" : "text-muted-foreground",
+ )}
+ >
+ {getStatusText()}
+ </p>
+ {(isUploading || isProcessing) && (
+ <Progress
+ value={isProcessing ? 100 : pendingUpload.progress}
+ className={cn(
+ "h-1 w-full max-w-[200px]",
+ isProcessing && "animate-pulse",
+ )}
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/view/viewer/dataroom-viewer.tsx b/components/view/viewer/dataroom-viewer.tsx
index 89273df7..4e047ea7 100644
--- a/components/view/viewer/dataroom-viewer.tsx
+++ b/components/view/viewer/dataroom-viewer.tsx
@@ -18,6 +18,7 @@ import {
import * as SheetPrimitive from "@radix-ui/react-dialog";
import { PanelLeftIcon, XIcon } from "lucide-react";
+import { usePendingUploads } from "@/context/pending-uploads-context";
import { cn } from "@/lib/utils";
import {
HIERARCHICAL_DISPLAY_STYLE,
@@ -49,6 +50,7 @@ import { DocumentUploadModal } from "../dataroom/document-upload-modal";
import FolderCard from "../dataroom/folder-card";
import IndexFileDialog from "../dataroom/index-file-dialog";
import DataroomNav from "../dataroom/nav-dataroom";
+import PendingDocumentCard from "../dataroom/pending-document-card";
const ViewerBreadcrumbItem = ({
folder,
@@ -171,6 +173,10 @@ export default function DataroomViewer({
const router = useRouter();
const searchQuery = (router.query.search as string)?.toLowerCase() || "";
+ // Get pending uploads for the current folder
+ const { getPendingUploadsForFolder } = usePendingUploads();
+ const pendingUploadsForFolder = getPendingUploadsForFolder(folderId);
+
const breadcrumbFolders = useMemo(
() => getParentFolders(folderId, folders),
[folderId, folders],
@@ -536,7 +542,16 @@ export default function DataroomViewer({
)}
<ul role="list" className="-mx-4 space-y-4 overflow-auto p-4">
- {mixedItems.length === 0 ? (
+ {/* Show pending uploads at the top */}
+ {!searchQuery &&
+ pendingUploadsForFolder.map((pendingUpload) => (
+ <li key={pendingUpload.id}>
+ <PendingDocumentCard pendingUpload={pendingUpload} />
+ </li>
+ ))}
+
+ {mixedItems.length === 0 &&
+ pendingUploadsForFolder.length === 0 ? (
<li className="py-6 text-center text-muted-foreground">
{searchQuery
? "No documents match your search."
diff --git a/components/viewer-upload-component.tsx b/components/viewer-upload-component.tsx
index 35a5a32c..a19dfc35 100644
--- a/components/viewer-upload-component.tsx
+++ b/components/viewer-upload-component.tsx
@@ -1,8 +1,10 @@
-import { useState } from "react";
+import { useRef, useState } from "react";
import { toast } from "sonner";
+import { usePendingUploads } from "@/context/pending-uploads-context";
import { DocumentData } from "@/lib/documents/create-document";
+import { newId } from "@/lib/id-helper";
import ViewerUploadZone from "@/components/viewer-upload-zone";
@@ -10,10 +12,12 @@ export function ViewerUploadComponent({
viewerData,
teamId,
folderId,
+ onUploadSuccess,
}: {
viewerData: { id: string; linkId: string; dataroomId?: string };
teamId: string;
folderId?: string;
+ onUploadSuccess?: () => void;
}) {
const [uploads, setUploads] = useState<
{ fileName: string; progress: number }[]
@@ -22,22 +26,60 @@ export function ViewerUploadComponent({
{ fileName: string; message: string }[]
>([]);
+ const { addPendingUpload, updatePendingUpload } = usePendingUploads();
+
+ // Map file names to their pending upload IDs
+ const pendingUploadIds = useRef<Map<string, string>>(new Map());
+
const handleUploadStart = (
- uploads: { fileName: string; progress: number }[],
+ newUploads: { fileName: string; progress: number }[],
) => {
- setUploads(uploads);
+ setUploads(newUploads);
+
+ // Add each file to pending uploads context
+ newUploads.forEach((upload) => {
+ const pendingId = newId("pending");
+ pendingUploadIds.current.set(upload.fileName, pendingId);
+
+ addPendingUpload({
+ id: pendingId,
+ name: upload.fileName,
+ folderId: folderId ?? null,
+ uploadedAt: new Date(),
+ status: "uploading",
+ progress: 0,
+ });
+ });
};
const handleUploadProgress = (index: number, progress: number) => {
setUploads((prev) => {
const updated = [...prev];
- updated[index] = { ...updated[index], progress };
+ if (updated[index]) {
+ updated[index] = { ...updated[index], progress };
+
+ // Update pending upload progress
+ const pendingId = pendingUploadIds.current.get(updated[index].fileName);
+ if (pendingId) {
+ updatePendingUpload(pendingId, { progress });
+ }
+ }
return updated;
});
};
const handleUploadComplete = async (documentData: DocumentData) => {
- // Call your API to add the document to the dataroom or store it for viewer uploads
+ const pendingId = pendingUploadIds.current.get(documentData.name);
+
+ // Update status to processing (file uploaded to S3, now being processed by backend)
+ if (pendingId) {
+ updatePendingUpload(pendingId, {
+ status: "processing",
+ progress: 100,
+ });
+ }
+
+ // Call the API to add the document to the dataroom
try {
const response = await fetch(`/api/links/${viewerData.linkId}/upload`, {
method: "POST",
@@ -56,10 +98,31 @@ export function ViewerUploadComponent({
throw new Error(errorData.message || "Failed to process upload");
}
- // Optional: You might want to update UI or fetch updated document list
+ const result = await response.json();
+
+ // Update pending upload with real document data
+ if (pendingId && result.document) {
+ updatePendingUpload(pendingId, {
+ status: "processing", // Keep as processing until pages are ready
+ documentId: result.document.id,
+ dataroomDocumentId: result.document.dataroomDocumentId,
+ fileType: result.document.fileType,
+ });
+ }
+
+ // Notify parent component of successful upload
+ onUploadSuccess?.();
} catch (error) {
console.error("Error processing upload:", error);
toast.error((error as Error).message || "Failed to upload document");
+
+ // Update pending upload with error status
+ if (pendingId) {
+ updatePendingUpload(pendingId, {
+ status: "error",
+ errorMessage: (error as Error).message || "Failed to upload document",
+ });
+ }
}
};
diff --git a/context/pending-uploads-context.tsx b/context/pending-uploads-context.tsx
new file mode 100644
index 00000000..443d2f29
--- /dev/null
+++ b/context/pending-uploads-context.tsx
@@ -0,0 +1,113 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useMemo,
+ useState,
+} from "react";
+
+export type PendingUploadDocument = {
+ id: string; // Temporary ID for optimistic rendering
+ name: string;
+ folderId: string | null;
+ uploadedAt: Date;
+ status: "uploading" | "processing" | "complete" | "error";
+ progress: number;
+ documentId?: string; // Real document ID after API response
+ dataroomDocumentId?: string; // Real dataroom document ID after API response
+ fileType?: string;
+ errorMessage?: string;
+};
+
+export type PendingUploadsContextType = {
+ pendingUploads: PendingUploadDocument[];
+ addPendingUpload: (upload: PendingUploadDocument) => void;
+ updatePendingUpload: (
+ id: string,
+ update: Partial<PendingUploadDocument>,
+ ) => void;
+ removePendingUpload: (id: string) => void;
+ clearCompletedUploads: () => void;
+ getPendingUploadsForFolder: (folderId: string | null) => PendingUploadDocument[];
+};
+
+export const initialState: PendingUploadsContextType = {
+ pendingUploads: [],
+ addPendingUpload: () => {},
+ updatePendingUpload: () => {},
+ removePendingUpload: () => {},
+ clearCompletedUploads: () => {},
+ getPendingUploadsForFolder: () => [],
+};
+
+const PendingUploadsContext =
+ createContext<PendingUploadsContextType>(initialState);
+
+export const PendingUploadsProvider = ({
+ children,
+}: {
+ children: React.ReactNode;
+}): JSX.Element => {
+ const [pendingUploads, setPendingUploads] = useState<PendingUploadDocument[]>(
+ [],
+ );
+
+ const addPendingUpload = useCallback((upload: PendingUploadDocument) => {
+ setPendingUploads((prev) => [...prev, upload]);
+ }, []);
+
+ const updatePendingUpload = useCallback(
+ (id: string, update: Partial<PendingUploadDocument>) => {
+ setPendingUploads((prev) =>
+ prev.map((upload) =>
+ upload.id === id ? { ...upload, ...update } : upload,
+ ),
+ );
+ },
+ [],
+ );
+
+ const removePendingUpload = useCallback((id: string) => {
+ setPendingUploads((prev) => prev.filter((upload) => upload.id !== id));
+ }, []);
+
+ const clearCompletedUploads = useCallback(() => {
+ setPendingUploads((prev) =>
+ prev.filter((upload) => upload.status !== "complete"),
+ );
+ }, []);
+
+ const getPendingUploadsForFolder = useCallback(
+ (folderId: string | null) => {
+ return pendingUploads.filter((upload) => upload.folderId === folderId);
+ },
+ [pendingUploads],
+ );
+
+ const value = useMemo(
+ () => ({
+ pendingUploads,
+ addPendingUpload,
+ updatePendingUpload,
+ removePendingUpload,
+ clearCompletedUploads,
+ getPendingUploadsForFolder,
+ }),
+ [
+ pendingUploads,
+ addPendingUpload,
+ updatePendingUpload,
+ removePendingUpload,
+ clearCompletedUploads,
+ getPendingUploadsForFolder,
+ ],
+ );
+
+ return (
+ <PendingUploadsContext.Provider value={value}>
+ {children}
+ </PendingUploadsContext.Provider>
+ );
+};
+
+export const usePendingUploads = () => useContext(PendingUploadsContext);
diff --git a/lib/id-helper.ts b/lib/id-helper.ts
index 2e393610..ce438c71 100644
--- a/lib/id-helper.ts
+++ b/lib/id-helper.ts
@@ -48,4 +48,5 @@ export const newId = new IdGenerator({
token: "pmk",
clickEvent: "click",
preset: "preset",
+ pending: "pending", // for pending uploads
}).id;