Skip to content

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

feat: add dataroom upload visibility with optimistic UI and persisted uploads

Marc Seitzee3faf4745d2
diff --git a/app/(ee)/api/links/[id]/upload/route.ts b/app/(ee)/api/links/[id]/upload/route.ts
index e3146518..4c3bf6ab 100644
--- a/app/(ee)/api/links/[id]/upload/route.ts
+++ b/app/(ee)/api/links/[id]/upload/route.ts
@@ -10,6 +10,107 @@ import { supportsAdvancedExcelMode } from "@/lib/utils/get-content-type";
import { runs } from "@trigger.dev/sdk/v3";
import { waitUntil } from "@vercel/functions";
+/**
+ * GET /api/links/[id]/upload?dataroomId=xxx
+ * Returns the viewer's previously uploaded documents for this dataroom.
+ */
+export async function GET(
+ request: NextRequest,
+ { params }: { params: { id: string } },
+) {
+ try {
+ const linkId = params.id;
+ const dataroomId = request.nextUrl.searchParams.get("dataroomId");
+
+ if (!linkId || !dataroomId) {
+ return NextResponse.json(
+ { message: "Missing required parameters" },
+ { status: 400 },
+ );
+ }
+
+ // Verify the dataroom session
+ const dataroomSession = await verifyDataroomSession(
+ request,
+ linkId,
+ dataroomId,
+ );
+
+ if (!dataroomSession || !dataroomSession.viewerId) {
+ return NextResponse.json(
+ { message: "Unauthorized" },
+ { status: 401 },
+ );
+ }
+
+ const { viewerId } = dataroomSession;
+
+ // Fetch the viewer's uploads for this dataroom
+ const uploads = await prisma.documentUpload.findMany({
+ where: {
+ viewerId,
+ dataroomId,
+ linkId,
+ },
+ select: {
+ id: true,
+ documentId: true,
+ dataroomDocumentId: true,
+ originalFilename: true,
+ uploadedAt: true,
+ document: {
+ select: {
+ id: true,
+ name: true,
+ type: true,
+ versions: {
+ where: { isPrimary: true },
+ select: {
+ id: true,
+ hasPages: true,
+ },
+ take: 1,
+ },
+ },
+ },
+ dataroomDocument: {
+ select: {
+ folderId: true,
+ },
+ },
+ },
+ orderBy: { uploadedAt: "desc" },
+ });
+
+ const formattedUploads = uploads.map((upload) => {
+ const fileType = upload.document?.type ?? "";
+ const hasPages = upload.document?.versions?.[0]?.hasPages ?? false;
+ const needsProcessing = ["pdf", "docs", "slides"].includes(fileType);
+ const isComplete = !needsProcessing || hasPages;
+
+ return {
+ id: upload.id,
+ documentId: upload.documentId,
+ dataroomDocumentId: upload.dataroomDocumentId,
+ documentVersionId: upload.document?.versions?.[0]?.id ?? null,
+ name: upload.originalFilename ?? upload.document?.name ?? "Unknown",
+ fileType,
+ folderId: upload.dataroomDocument?.folderId ?? null,
+ uploadedAt: upload.uploadedAt,
+ status: isComplete ? "complete" : "processing",
+ };
+ });
+
+ return NextResponse.json({ uploads: formattedUploads });
+ } catch (error) {
+ console.error("Error fetching viewer uploads:", error);
+ return NextResponse.json(
+ { message: "Error fetching uploads" },
+ { status: 500 },
+ );
+ }
+}
+
export async function POST(
request: NextRequest,
{ params }: { params: { id: string } },
@@ -233,6 +334,7 @@ export async function POST(
id: document.id,
name: document.name,
dataroomDocumentId: newDataroomDocument.id,
+ documentVersionId: document.versions[0]?.id,
folderId: dataroomFolderId,
fileType: document.type,
hasPages: (document.numPages ?? 0) > 0,
diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsx
index f3b92cb1..85df1fe3 100644
--- a/components/view/dataroom/dataroom-view.tsx
+++ b/components/view/dataroom/dataroom-view.tsx
@@ -286,7 +286,7 @@ export default function DataroomView({
if (submitted) {
return (
- <PendingUploadsProvider>
+ <PendingUploadsProvider linkId={link.id} dataroomId={dataroom?.id}>
<div
className="min-h-screen bg-white"
style={{ backgroundColor: dataroomViewBackgroundColor ?? undefined }}
diff --git a/components/view/dataroom/document-upload-modal.tsx b/components/view/dataroom/document-upload-modal.tsx
index 0a1d9432..8ea6bc82 100644
--- a/components/view/dataroom/document-upload-modal.tsx
+++ b/components/view/dataroom/document-upload-modal.tsx
@@ -1,13 +1,16 @@
-// components/view/dataroom/document-upload-button.tsx
import { useState } from "react";
-import { CheckCircle2, PlusIcon } from "lucide-react";
+import {
+ CheckCircle2,
+ FolderIcon,
+ PlusIcon,
+ UploadIcon,
+} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
- DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
@@ -18,11 +21,14 @@ export function DocumentUploadModal({
dataroomId,
viewerId,
folderId,
+ folderName,
}: {
linkId: string;
dataroomId: string;
viewerId: string;
folderId?: string;
+ /** Display name of the current folder (undefined = root) */
+ folderName?: string;
}) {
const [isOpen, setIsOpen] = useState(false);
const [uploadSuccess, setUploadSuccess] = useState(false);
@@ -57,38 +63,53 @@ export function DocumentUploadModal({
</Button>
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Upload Document to Dataroom</DialogTitle>
- <DialogDescription>
+ <DialogContent className="max-h-[85vh] max-w-2xl overflow-hidden border-0 p-0 shadow-2xl sm:max-w-xl sm:rounded-2xl">
+ <DialogHeader className="border-b border-gray-100 bg-gray-50 px-6 py-5 dark:border-gray-800 dark:bg-gray-900">
+ <DialogTitle className="flex items-center gap-2 text-lg font-semibold">
+ <UploadIcon className="h-5 w-5 text-muted-foreground" />
+ Upload Document to Dataroom
+ </DialogTitle>
+ <p className="mt-1 text-sm text-muted-foreground">
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>
+ processed in the background.
+ </p>
+ {folderName && (
+ <div className="mt-2 flex items-center gap-1.5 text-xs text-muted-foreground">
+ <FolderIcon className="h-3.5 w-3.5" />
+ <span>
+ Uploading to:{" "}
+ <span className="font-medium text-foreground">
+ {folderName}
+ </span>
+ </span>
+ </div>
+ )}
</DialogHeader>
- {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}
- />
- )}
+ <div className="px-6 py-5">
+ {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 in the dataroom.
+ </p>
+ </div>
+ ) : (
+ <ViewerUploadComponent
+ viewerData={{
+ id: viewerId,
+ linkId,
+ dataroomId,
+ }}
+ teamId="visitor-upload"
+ folderId={folderId}
+ onUploadSuccess={handleUploadSuccess}
+ />
+ )}
+ </div>
</DialogContent>
</Dialog>
</>
diff --git a/components/view/dataroom/pending-document-card.tsx b/components/view/dataroom/pending-document-card.tsx
index 27ed6cd7..871dbd28 100644
--- a/components/view/dataroom/pending-document-card.tsx
+++ b/components/view/dataroom/pending-document-card.tsx
@@ -1,33 +1,142 @@
-import { AlertCircle, FileIcon, Loader2, Upload } from "lucide-react";
+import { useRouter } from "next/router";
+
+import { useEffect } from "react";
+
+import {
+ AlertCircle,
+ CheckCircle2,
+ FileIcon,
+ FolderIcon,
+ Loader2,
+ Upload,
+} from "lucide-react";
import { useTheme } from "next-themes";
+import { toast } from "sonner";
+import useSWRImmutable from "swr/immutable";
-import { PendingUploadDocument } from "@/context/pending-uploads-context";
-import { cn } from "@/lib/utils";
+import {
+ PendingUploadDocument,
+ usePendingUploads,
+} from "@/context/pending-uploads-context";
+import { cn, fetcher } from "@/lib/utils";
import { fileIcon } from "@/lib/utils/get-file-icon";
+import { useDocumentProgressStatus } from "@/lib/utils/use-progress-status";
import { Progress } from "@/components/ui/progress";
+type FolderInfo = {
+ id: string;
+ name: string;
+ parentId: string | null;
+};
+
type PendingDocumentCardProps = {
pendingUpload: PendingUploadDocument;
+ /** Flat list of all folders for resolving folder paths */
+ folders?: FolderInfo[];
+ /** Link ID for building document URLs */
+ linkId?: string;
+ /** Callback to navigate to a folder */
+ onNavigateToFolder?: (folderId: string | null) => void;
+ /** Whether to show the folder path (used in My Uploads tab) */
+ showFolderPath?: boolean;
};
+/** Build a breadcrumb path like "Home > Company Info > Financials > Q4" */
+function getFolderPath(
+ folderId: string | null,
+ folders: FolderInfo[],
+): string {
+ if (!folderId) return "Home";
+
+ const parts: string[] = ["Home"];
+ const folderParts: string[] = [];
+ let current = folders.find((f) => f.id === folderId);
+ while (current) {
+ folderParts.unshift(current.name);
+ current = current.parentId
+ ? folders.find((f) => f.id === current!.parentId)
+ : undefined;
+ }
+ return [...parts, ...folderParts].join(" > ");
+}
+
export default function PendingDocumentCard({
pendingUpload,
+ folders = [],
+ linkId,
+ onNavigateToFolder,
+ showFolderPath = false,
}: PendingDocumentCardProps) {
const { theme, systemTheme } = useTheme();
+ const router = useRouter();
+ const { updatePendingUpload } = usePendingUploads();
const isLight =
theme === "light" || (theme === "system" && systemTheme === "light");
+ const { previewToken, domain, slug } = router.query as {
+ previewToken?: string;
+ domain?: string;
+ slug?: string;
+ };
+
+ // Fetch trigger public access token for processing documents
+ const needsTriggerTracking =
+ pendingUpload.status === "processing" && pendingUpload.documentVersionId;
+
+ const { data: tokenData } = useSWRImmutable<{ publicAccessToken: string }>(
+ needsTriggerTracking
+ ? `/api/progress-token?documentVersionId=${pendingUpload.documentVersionId}`
+ : null,
+ fetcher,
+ );
+
+ // Subscribe to Trigger.dev realtime for processing status
+ const { status: triggerStatus } = useDocumentProgressStatus(
+ pendingUpload.documentVersionId ?? "",
+ tokenData?.publicAccessToken,
+ );
+
+ // When trigger reports COMPLETED, update the upload status
+ useEffect(() => {
+ if (
+ needsTriggerTracking &&
+ triggerStatus.state === "COMPLETED" &&
+ pendingUpload.status === "processing"
+ ) {
+ updatePendingUpload(pendingUpload.id, { status: "complete" });
+ }
+ }, [
+ triggerStatus.state,
+ needsTriggerTracking,
+ pendingUpload.status,
+ pendingUpload.id,
+ updatePendingUpload,
+ ]);
+
+ const isError = pendingUpload.status === "error";
+ const isUploading = pendingUpload.status === "uploading";
+ const isProcessing = pendingUpload.status === "processing";
+ const isComplete = pendingUpload.status === "complete";
+ const isClickable = isComplete && pendingUpload.dataroomDocumentId && linkId;
+
const getStatusText = () => {
switch (pendingUpload.status) {
case "uploading":
return `Uploading... ${pendingUpload.progress}%`;
case "processing":
+ // Use trigger realtime text if available
+ if (triggerStatus.state === "EXECUTING" && triggerStatus.text) {
+ return triggerStatus.text;
+ }
+ if (triggerStatus.state === "QUEUED") {
+ return "Queued for processing...";
+ }
return "Processing document...";
case "error":
return pendingUpload.errorMessage || "Upload failed";
case "complete":
- return "Complete";
+ return "Ready";
default:
return "Pending";
}
@@ -41,14 +150,57 @@ export default function PendingDocumentCard({
return <Loader2 className="h-4 w-4 animate-spin text-orange-500" />;
case "error":
return <AlertCircle className="h-4 w-4 text-red-500" />;
+ case "complete":
+ return <CheckCircle2 className="h-4 w-4 text-green-500" />;
default:
return null;
}
};
- const isError = pendingUpload.status === "error";
- const isUploading = pendingUpload.status === "uploading";
- const isProcessing = pendingUpload.status === "processing";
+ // Real processing progress from trigger (0-100)
+ const processingProgress =
+ isProcessing && triggerStatus.state === "EXECUTING"
+ ? triggerStatus.progress
+ : undefined;
+
+ const handleDocumentClick = (e: React.MouseEvent) => {
+ if (!isClickable) {
+ if (isProcessing) {
+ e.preventDefault();
+ toast.error(
+ "Document is still processing. Please wait a moment and try again.",
+ );
+ }
+ return;
+ }
+
+ e.preventDefault();
+ if (domain && slug) {
+ window.open(
+ `/${slug}/d/${pendingUpload.dataroomDocumentId}`,
+ "_blank",
+ );
+ } else if (linkId) {
+ window.open(
+ `/view/${linkId}/d/${pendingUpload.dataroomDocumentId}${
+ previewToken ? `?previewToken=${previewToken}&preview=1` : ""
+ }`,
+ "_blank",
+ );
+ }
+ };
+
+ const handleFolderClick = (e: React.MouseEvent) => {
+ e.stopPropagation();
+ if (onNavigateToFolder) {
+ onNavigateToFolder(pendingUpload.folderId);
+ }
+ };
+
+ const folderPath =
+ showFolderPath && folders.length > 0
+ ? getFolderPath(pendingUpload.folderId, folders)
+ : null;
return (
<div
@@ -56,10 +208,27 @@ export default function PendingDocumentCard({
"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",
+ : isComplete
+ ? "ring-gray-200 hover:bg-secondary hover:ring-gray-300 dark:bg-secondary dark:ring-gray-700 hover:dark:ring-gray-500"
+ : "bg-blue-50/50 ring-blue-200 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">
+ {/* Clickable overlay for opening documents */}
+ {isClickable && (
+ <button
+ onClick={handleDocumentClick}
+ className="absolute inset-0 z-0 cursor-pointer"
+ aria-hidden="true"
+ />
+ )}
+
+ {/* pointer-events-none so clicks fall through to the button overlay above */}
+ <div
+ className={cn(
+ "flex min-w-0 shrink items-center space-x-2 sm:space-x-4",
+ isClickable && "pointer-events-none",
+ )}
+ >
<div className="mx-0.5 flex w-8 items-center justify-center text-center sm:mx-1">
{pendingUpload.fileType ? (
fileIcon({
@@ -72,32 +241,65 @@ export default function PendingDocumentCard({
)}
</div>
- <div className="flex-col flex-1 min-w-0">
+ <div className="min-w-0 flex-1 flex-col">
<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">
+ <div className="mt-1 flex items-center gap-2">
<p
className={cn(
"text-xs leading-5",
- isError ? "text-red-600 dark:text-red-400" : "text-muted-foreground",
+ isError
+ ? "text-red-600 dark:text-red-400"
+ : isComplete
+ ? "text-green-600 dark:text-green-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",
- )}
- />
+ {folderPath && isComplete && (
+ <>
+ <span className="text-xs text-muted-foreground">·</span>
+ <button
+ onClick={handleFolderClick}
+ className="pointer-events-auto z-10 flex items-center gap-1 text-xs text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <FolderIcon className="h-3 w-3" />
+ <span className="max-w-[200px] truncate sm:max-w-[300px]">
+ {folderPath}
+ </span>
+ </button>
+ </>
+ )}
+ {folderPath && !isComplete && (
+ <>
+ <span className="text-xs text-muted-foreground">·</span>
+ <span className="flex items-center gap-1 text-xs text-muted-foreground">
+ <FolderIcon className="h-3 w-3" />
+ <span className="max-w-[200px] truncate sm:max-w-[300px]">
+ {folderPath}
+ </span>
+ </span>
+ </>
)}
</div>
+ {(isUploading || isProcessing) && (
+ <Progress
+ value={
+ isProcessing
+ ? (processingProgress ?? 0)
+ : pendingUpload.progress
+ }
+ className={cn(
+ "mt-1.5 h-1 w-full max-w-[200px]",
+ isProcessing && !processingProgress && "animate-pulse",
+ )}
+ />
+ )}
</div>
</div>
</div>
diff --git a/components/view/viewer/dataroom-viewer.tsx b/components/view/viewer/dataroom-viewer.tsx
index 7ce1cd20..2ae4b636 100644
--- a/components/view/viewer/dataroom-viewer.tsx
+++ b/components/view/viewer/dataroom-viewer.tsx
@@ -1,6 +1,6 @@
import { useRouter } from "next/router";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
import React from "react";
import { ViewerChatPanel } from "@/ee/features/ai/components/viewer-chat-panel";
@@ -16,7 +16,7 @@ import {
ViewerGroupAccessControls,
} from "@prisma/client";
import * as SheetPrimitive from "@radix-ui/react-dialog";
-import { PanelLeftIcon, XIcon } from "lucide-react";
+import { PanelLeftIcon, UploadIcon, XIcon } from "lucide-react";
import { usePendingUploads } from "@/context/pending-uploads-context";
import { cn } from "@/lib/utils";
@@ -184,9 +184,16 @@ 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();
+ // Tab state: "documents" (normal view) or "my-uploads" (visitor's uploads)
+ const [activeTab, setActiveTab] = useState<"documents" | "my-uploads">(
+ "documents",
+ );
+
+ // Get pending uploads (in-flight + persisted from server)
+ const { getPendingUploadsForFolder, getAllUploads, hasUploads } =
+ usePendingUploads();
const pendingUploadsForFolder = getPendingUploadsForFolder(folderId);
+ const allUploads = getAllUploads();
const breadcrumbFolders = useMemo(
() => getParentFolders(folderId, folders),
@@ -603,14 +610,51 @@ export default function DataroomViewer({
dataroomId={dataroom?.id}
viewerId={viewerId}
folderId={folderId ?? undefined}
+ folderName={
+ folderId
+ ? folders.find((f) => f.id === folderId)?.name
+ : undefined
+ }
/>
)}
</div>
</div>
</div>
+ {/* Tabs: Documents / My Uploads */}
+ {viewData?.enableVisitorUpload && hasUploads && (
+ <div className="mt-4 flex items-center gap-1 border-b border-gray-200 dark:border-gray-700">
+ <button
+ onClick={() => setActiveTab("documents")}
+ className={cn(
+ "-mb-px border-b-2 px-3 py-2 text-sm font-medium transition-colors",
+ activeTab === "documents"
+ ? "border-foreground text-foreground"
+ : "border-transparent text-muted-foreground hover:border-gray-300 hover:text-foreground",
+ )}
+ >
+ Documents
+ </button>
+ <button
+ onClick={() => setActiveTab("my-uploads")}
+ className={cn(
+ "-mb-px flex items-center gap-1.5 border-b-2 px-3 py-2 text-sm font-medium transition-colors",
+ activeTab === "my-uploads"
+ ? "border-foreground text-foreground"
+ : "border-transparent text-muted-foreground hover:border-gray-300 hover:text-foreground",
+ )}
+ >
+ <UploadIcon className="h-3.5 w-3.5" />
+ My Uploads
+ <span className="inline-flex h-5 min-w-5 items-center justify-center rounded-full bg-muted px-1.5 text-xs font-medium">
+ {allUploads.length}
+ </span>
+ </button>
+ </div>
+ )}
+
{/* Search results banner */}
- {searchQuery && (
+ {searchQuery && activeTab === "documents" && (
<div className="mt-4 rounded-md border border-[var(--viewer-panel-border)] bg-[var(--viewer-control-bg)] px-4 py-3">
<div className="flex items-center gap-2">
<div className="text-sm font-medium text-[var(--viewer-muted-text)]">
@@ -624,28 +668,82 @@ export default function DataroomViewer({
</div>
)}
- <ul role="list" className="-mx-4 space-y-4 overflow-auto p-4">
- {/* Show pending uploads at the top */}
- {!searchQuery &&
- pendingUploadsForFolder.map((pendingUpload) => (
- <li key={pendingUpload.id}>
- <PendingDocumentCard pendingUpload={pendingUpload} />
+ {activeTab === "my-uploads" ? (
+ /* My Uploads tab - show all uploads across all folders */
+ <ul
+ role="list"
+ className="-mx-4 space-y-4 overflow-auto p-4"
+ >
+ {allUploads.length === 0 ? (
+ <li className="py-6 text-center text-muted-foreground">
+ No uploads yet. Upload documents using the &quot;Add
+ Document&quot; button.
</li>
- ))}
-
- {mixedItems.length === 0 &&
- pendingUploadsForFolder.length === 0 ? (
- <li className="py-6 text-center text-[var(--viewer-subtle-text)]">
- {searchQuery
- ? "No documents match your search."
- : "No items available."}
- </li>
- ) : (
- mixedItems.map((item) => (
- <li key={item.id}>{renderItem(item)}</li>
- ))
- )}
- </ul>
+ ) : (
+ allUploads.map((pendingUpload) => (
+ <li key={pendingUpload.id}>
+ <PendingDocumentCard
+ pendingUpload={pendingUpload}
+ folders={folders}
+ linkId={linkId}
+ showFolderPath
+ onNavigateToFolder={(id) => {
+ setFolderId(id);
+ setActiveTab("documents");
+ }}
+ />
+ </li>
+ ))
+ )}
+ </ul>
+ ) : (
+ /* Documents tab - normal folder view */
+ <ul
+ role="list"
+ className="-mx-4 space-y-4 overflow-auto p-4"
+ >
+ {/* Show pending uploads at the top of the current folder.
+ Complete uploads are shown unless the real document
+ already exists in mixedItems (e.g. after page refresh). */}
+ {!searchQuery &&
+ pendingUploadsForFolder
+ .filter((u) => {
+ if (u.status !== "complete") return true;
+ // Hide completed uploads whose real document is already in the list
+ return !mixedItems.some(
+ (item) =>
+ "versions" in item && item.id === u.documentId,
+ );
+ })
+ .map((pendingUpload) => (
+ <li key={pendingUpload.id}>
+ <PendingDocumentCard
+ pendingUpload={pendingUpload}
+ linkId={linkId}
+ />
+ </li>
+ ))}
+
+ {mixedItems.length === 0 &&
+ pendingUploadsForFolder.filter((u) => {
+ if (u.status !== "complete") return true;
+ return !mixedItems.some(
+ (item) =>
+ "versions" in item && item.id === u.documentId,
+ );
+ }).length === 0 ? (
+ <li className="py-6 text-center text-[var(--viewer-subtle-text)]">
+ {searchQuery
+ ? "No documents match your search."
+ : "No items available."}
+ </li>
+ ) : (
+ mixedItems.map((item) => (
+ <li key={item.id}>{renderItem(item)}</li>
+ ))
+ )}
+ </ul>
+ )}
</div>
<ScrollBar orientation="vertical" />
<ScrollBar orientation="horizontal" />
diff --git a/components/viewer-upload-component.tsx b/components/viewer-upload-component.tsx
index af1c87d8..8fb40d11 100644
--- a/components/viewer-upload-component.tsx
+++ b/components/viewer-upload-component.tsx
@@ -1,11 +1,14 @@
import { useRef, useState } from "react";
+import { FileUp } from "lucide-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 { cn } from "@/lib/utils";
+import { Progress } from "@/components/ui/progress";
import ViewerUploadZone from "@/components/viewer-upload-zone";
export function ViewerUploadComponent({
@@ -100,12 +103,20 @@ export function ViewerUploadComponent({
const result = await response.json();
+ // Determine if the file needs trigger processing (PDF, docs, slides)
+ // Images and Excel/CSV files are ready immediately after upload
+ const FILE_TYPES_NEEDING_PROCESSING = ["pdf", "docs", "slides"];
+ const needsProcessing =
+ result.document?.fileType &&
+ FILE_TYPES_NEEDING_PROCESSING.includes(result.document.fileType);
+
// Update pending upload with real document data
if (pendingId && result.document) {
updatePendingUpload(pendingId, {
- status: "processing", // Keep as processing until pages are ready
+ status: needsProcessing ? "processing" : "complete",
documentId: result.document.id,
dataroomDocumentId: result.document.dataroomDocumentId,
+ documentVersionId: result.document.documentVersionId,
fileType: result.document.fileType,
});
}
@@ -126,59 +137,79 @@ export function ViewerUploadComponent({
}
};
- return (
- <div className="p-4">
- <h1 className="mb-4 text-xl font-bold">Upload Documents</h1>
-
- <ViewerUploadZone
- onUploadStart={handleUploadStart}
- onUploadProgress={handleUploadProgress}
- onUploadComplete={handleUploadComplete}
- onUploadRejected={(rejected) => setRejectedFiles(rejected)}
- viewerData={viewerData}
- teamId={teamId}
- >
- <div className="rounded-lg border-2 border-dashed border-gray-300 p-8 text-center">
- <p>Drag & drop files here, or click to select files</p>
- <p className="mt-2 text-sm text-gray-500">
- Supported file types: PDF, Word, Excel, CSV
- </p>
+ const isUploading = uploads.length > 0;
- {/* Display current uploads */}
- {uploads.length > 0 && (
- <div className="mt-4">
- <h3 className="font-medium">Uploads</h3>
- <ul className="mt-2 space-y-2">
- {uploads.map((upload, index) => (
- <li key={index} className="text-sm">
- {upload.fileName} - {upload.progress}%
- <div className="mt-1 h-1 rounded-full bg-gray-200">
- <div
- className="h-1 rounded-full bg-blue-500"
- style={{ width: `${upload.progress}%` }}
- />
- </div>
- </li>
- ))}
- </ul>
+ return (
+ <ViewerUploadZone
+ onUploadStart={handleUploadStart}
+ onUploadProgress={handleUploadProgress}
+ onUploadComplete={handleUploadComplete}
+ onUploadRejected={(rejected) => setRejectedFiles(rejected)}
+ viewerData={viewerData}
+ teamId={teamId}
+ >
+ {isUploading ? (
+ <div className="space-y-3">
+ {uploads.map((upload, index) => (
+ <div
+ key={index}
+ className="flex items-center gap-3 rounded-lg border border-gray-200 bg-gray-50 p-3 dark:border-gray-700 dark:bg-gray-800"
+ >
+ <FileUp className="h-5 w-5 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-foreground">
+ {upload.fileName}
+ </p>
+ <div className="mt-1.5 flex items-center gap-2">
+ <Progress
+ value={upload.progress}
+ className="h-1.5 flex-1"
+ />
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
+ {upload.progress}%
+ </span>
+ </div>
+ </div>
</div>
+ ))}
+ </div>
+ ) : (
+ <div
+ className={cn(
+ "flex flex-col items-center justify-center rounded-xl border-2 border-dashed px-6 py-10 text-center transition-colors",
+ "border-gray-300 hover:border-gray-400 dark:border-gray-600 dark:hover:border-gray-500",
)}
+ >
+ <div className="mb-3 flex h-10 w-10 items-center justify-center rounded-full bg-gray-100 dark:bg-gray-800">
+ <FileUp className="h-5 w-5 text-muted-foreground" />
+ </div>
+ <p className="text-sm font-medium text-foreground">
+ Drag & drop files here, or click to select files
+ </p>
+ <p className="mt-1 text-xs text-muted-foreground">
+ Supported file types: PDF, Excel, CSV, Images
+ </p>
+ </div>
+ )}
- {/* Display rejected files */}
- {rejectedFiles.length > 0 && (
- <div className="mt-4">
- <h3 className="font-medium text-red-500">Rejected Files</h3>
- <ul className="mt-2 space-y-1">
- {rejectedFiles.map((file, index) => (
- <li key={index} className="text-sm text-red-500">
- {file.fileName}: {file.message}
- </li>
- ))}
- </ul>
- </div>
- )}
+ {/* Display rejected files */}
+ {rejectedFiles.length > 0 && (
+ <div className="mt-3 rounded-lg border border-red-200 bg-red-50 p-3 dark:border-red-800 dark:bg-red-950/30">
+ <p className="text-xs font-medium text-red-600 dark:text-red-400">
+ Some files were rejected:
+ </p>
+ <ul className="mt-1.5 space-y-0.5">
+ {rejectedFiles.map((file, index) => (
+ <li
+ key={index}
+ className="text-xs text-red-500 dark:text-red-400"
+ >
+ {file.fileName}: {file.message}
+ </li>
+ ))}
+ </ul>
</div>
- </ViewerUploadZone>
- </div>
+ )}
+ </ViewerUploadZone>
);
}
diff --git a/components/viewer-upload-zone.tsx b/components/viewer-upload-zone.tsx
index 19e72e1d..d14ca8a1 100644
--- a/components/viewer-upload-zone.tsx
+++ b/components/viewer-upload-zone.tsx
@@ -179,16 +179,14 @@ export default function ViewerUploadZone({
/>
{isDragActive && (
- <div className="sticky top-1/2 z-50 -translate-y-1/2 px-2">
- <div className="flex justify-center">
- <div className="inline-flex flex-col rounded-lg bg-background/95 px-6 py-4 text-center ring-1 ring-gray-900/5 dark:bg-gray-900/95 dark:ring-white/10">
- <span className="font-medium text-foreground">
- Drop your file(s) here
- </span>
- <p className="mt-1 text-xs leading-5 text-muted-foreground">
- Only *.pdf, *.doc, *.docx, *.xls, *.xlsx, *.csv, *.ods files
- </p>
- </div>
+ <div className="flex h-full items-center justify-center">
+ <div className="inline-flex flex-col rounded-lg bg-background/95 px-6 py-4 text-center ring-1 ring-gray-900/5 dark:bg-gray-900/95 dark:ring-white/10">
+ <span className="font-medium text-foreground">
+ Drop your file(s) here
+ </span>
+ <p className="mt-1 text-xs leading-5 text-muted-foreground">
+ Only *.pdf, *.xls, *.xlsx, *.csv, *.tsv, *.ods files
+ </p>
</div>
</div>
)}
diff --git a/context/pending-uploads-context.tsx b/context/pending-uploads-context.tsx
index 443d2f29..fde99bf8 100644
--- a/context/pending-uploads-context.tsx
+++ b/context/pending-uploads-context.tsx
@@ -2,21 +2,27 @@ import {
createContext,
useCallback,
useContext,
+ useEffect,
useMemo,
+ useRef,
useState,
} from "react";
export type PendingUploadDocument = {
- id: string; // Temporary ID for optimistic rendering
+ id: string;
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
+ documentId?: string;
+ dataroomDocumentId?: string;
+ /** Version ID used to subscribe to Trigger.dev realtime processing updates */
+ documentVersionId?: string;
fileType?: string;
errorMessage?: string;
+ /** Whether this upload was loaded from the server (persisted) */
+ persisted?: boolean;
};
export type PendingUploadsContextType = {
@@ -28,7 +34,15 @@ export type PendingUploadsContextType = {
) => void;
removePendingUpload: (id: string) => void;
clearCompletedUploads: () => void;
- getPendingUploadsForFolder: (folderId: string | null) => PendingUploadDocument[];
+ getPendingUploadsForFolder: (
+ folderId: string | null,
+ ) => PendingUploadDocument[];
+ /** Returns all uploads (in-flight + persisted) */
+ getAllUploads: () => PendingUploadDocument[];
+ /** Whether the visitor has any uploads */
+ hasUploads: boolean;
+ /** Whether persisted uploads are still loading */
+ isLoading: boolean;
};
export const initialState: PendingUploadsContextType = {
@@ -38,6 +52,9 @@ export const initialState: PendingUploadsContextType = {
removePendingUpload: () => {},
clearCompletedUploads: () => {},
getPendingUploadsForFolder: () => [],
+ getAllUploads: () => [],
+ hasUploads: false,
+ isLoading: false,
};
const PendingUploadsContext =
@@ -45,12 +62,65 @@ const PendingUploadsContext =
export const PendingUploadsProvider = ({
children,
+ linkId,
+ dataroomId,
}: {
children: React.ReactNode;
+ linkId?: string;
+ dataroomId?: string;
}): JSX.Element => {
- const [pendingUploads, setPendingUploads] = useState<PendingUploadDocument[]>(
- [],
- );
+ // In-flight uploads from the current session (uploading, processing, etc.)
+ const [pendingUploads, setPendingUploads] = useState<
+ PendingUploadDocument[]
+ >([]);
+ // Persisted uploads loaded from the server
+ const [persistedUploads, setPersistedUploads] = useState<
+ PendingUploadDocument[]
+ >([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const fetchedRef = useRef(false);
+
+ // Fetch the viewer's persisted uploads on mount
+ useEffect(() => {
+ if (!linkId || !dataroomId || fetchedRef.current) return;
+ fetchedRef.current = true;
+
+ const fetchUploads = async () => {
+ setIsLoading(true);
+ try {
+ const res = await fetch(
+ `/api/links/${linkId}/upload?dataroomId=${dataroomId}`,
+ );
+ if (!res.ok) return;
+
+ const data = await res.json();
+ if (data.uploads && Array.isArray(data.uploads)) {
+ const loaded: PendingUploadDocument[] = data.uploads.map(
+ (u: any) => ({
+ id: u.id,
+ name: u.name,
+ folderId: u.folderId,
+ uploadedAt: new Date(u.uploadedAt),
+ status: u.status as "complete" | "processing",
+ progress: 100,
+ documentId: u.documentId,
+ dataroomDocumentId: u.dataroomDocumentId,
+ documentVersionId: u.documentVersionId ?? undefined,
+ fileType: u.fileType,
+ persisted: true,
+ }),
+ );
+ setPersistedUploads(loaded);
+ }
+ } catch (err) {
+ console.error("Failed to fetch viewer uploads:", err);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchUploads();
+ }, [linkId, dataroomId]);
const addPendingUpload = useCallback((upload: PendingUploadDocument) => {
setPendingUploads((prev) => [...prev, upload]);
@@ -77,29 +147,58 @@ export const PendingUploadsProvider = ({
);
}, []);
+ // Merge in-flight and persisted uploads, deduplicating by documentId
+ const allUploads = useMemo(() => {
+ // In-flight uploads take priority (they have real-time status)
+ const inFlightDocIds = new Set(
+ pendingUploads
+ .filter((u) => u.documentId)
+ .map((u) => u.documentId),
+ );
+
+ // Filter out persisted uploads that already have an in-flight version
+ const filteredPersisted = persistedUploads.filter(
+ (u) => !inFlightDocIds.has(u.documentId),
+ );
+
+ return [...pendingUploads, ...filteredPersisted];
+ }, [pendingUploads, persistedUploads]);
+
const getPendingUploadsForFolder = useCallback(
(folderId: string | null) => {
- return pendingUploads.filter((upload) => upload.folderId === folderId);
+ return allUploads.filter((upload) => upload.folderId === folderId);
},
- [pendingUploads],
+ [allUploads],
);
+ const getAllUploads = useCallback(() => {
+ return allUploads;
+ }, [allUploads]);
+
+ const hasUploads = allUploads.length > 0;
+
const value = useMemo(
() => ({
- pendingUploads,
+ pendingUploads: allUploads,
addPendingUpload,
updatePendingUpload,
removePendingUpload,
clearCompletedUploads,
getPendingUploadsForFolder,
+ getAllUploads,
+ hasUploads,
+ isLoading,
}),
[
- pendingUploads,
+ allUploads,
addPendingUpload,
updatePendingUpload,
removePendingUpload,
clearCompletedUploads,
getPendingUploadsForFolder,
+ getAllUploads,
+ hasUploads,
+ isLoading,
],
);