Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add document preview
Marc Seitzbcbfc3fe94d7
diff --git a/components/datarooms/dataroom-document-card.tsx b/components/datarooms/dataroom-document-card.tsxindex 844ca45c..af0013e1 100644--- a/components/datarooms/dataroom-document-card.tsx+++ b/components/datarooms/dataroom-document-card.tsx@@ -33,6 +33,7 @@ import {} from "@/components/ui/dropdown-menu";import { AddToDataroomModal } from "../documents/add-document-to-dataroom-modal";+import { DocumentPreviewButton } from "../documents/document-preview-button";import FileProcessStatusBar from "../documents/file-process-status-bar";import { SetUnifiedPermissionsModal } from "./groups/set-unified-permissions-modal";import { MoveToDataroomFolderModal } from "./move-dataroom-folder-modal";@@ -243,6 +244,19 @@ export default function DataroomDocumentCard({</p></Link>+ <DocumentPreviewButton+ documentId={dataroomDocument.document.id}+ primaryVersion={{+ hasPages:+ dataroomDocument.document.versions?.[0]?.hasPages || false,+ type: dataroomDocument.document.type,+ numPages: null, // Not available in this context+ }}+ variant="outline"+ size="icon"+ className="z-10 h-8 w-8 border-gray-200 bg-transparent hover:bg-gray-200 dark:border-gray-700 hover:dark:bg-gray-700 lg:h-9 lg:w-9"+ />+<DropdownMenu open={menuOpen} onOpenChange={handleMenuStateChange}><DropdownMenuTrigger asChild><Buttondiff --git a/components/documents/document-card.tsx b/components/documents/document-card.tsxindex 4b09926a..91217828 100644--- a/components/documents/document-card.tsx+++ b/components/documents/document-card.tsx@@ -8,10 +8,10 @@ import { PlanEnum } from "@/ee/stripe/constants";import {BetweenHorizontalStartIcon,ChevronRight,+ EyeIcon,FileIcon,FolderIcon,FolderInputIcon,- Layers2Icon,MoreVertical,ServerIcon,TrashIcon,@@ -30,6 +30,7 @@ import { useCopyToClipboard } from "@/lib/utils/use-copy-to-clipboard";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import { DataroomTrialModal } from "@/components/datarooms/dataroom-trial-modal";import { AddToDataroomModal } from "@/components/documents/add-document-to-dataroom-modal";+import { DocumentPreviewModal } from "@/components/documents/document-preview-modal";import { MoveToFolderModal } from "@/components/documents/move-folder-modal";import BarChart from "@/components/shared/icons/bar-chart";import { Button } from "@/components/ui/button";@@ -72,6 +73,7 @@ export default function DocumentsCard({const [addDataroomOpen, setAddDataroomOpen] = useState<boolean>(false);const [trialModalOpen, setTrialModalOpen] = useState<boolean>(false);const [planModalOpen, setPlanModalOpen] = useState<boolean>(false);+ const [previewOpen, setPreviewOpen] = useState<boolean>(false);const { datarooms } = useDatarooms();@@ -344,6 +346,16 @@ export default function DocumentsCard({</DropdownMenuTrigger><DropdownMenuContent align="end" ref={dropdownRef}><DropdownMenuLabel>Actions</DropdownMenuLabel>+ <DropdownMenuItem+ onClick={() => {+ setPreviewOpen(true);+ setMenuOpen(false);+ }}+ >+ <EyeIcon className="mr-2 h-4 w-4" />+ Quick preview+ </DropdownMenuItem>+ <DropdownMenuSeparator /><DropdownMenuItem onClick={() => setMoveFolderOpen(true)}><FolderInputIcon className="mr-2 h-4 w-4" />Move to folder@@ -412,6 +424,12 @@ export default function DocumentsCard({setOpen={setPlanModalOpen}/>) : null}++ <DocumentPreviewModal+ documentId={prismaDocument.id}+ isOpen={previewOpen}+ onClose={() => setPreviewOpen(false)}+ /></>);-}\ No newline at end of file+}diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsxindex 7be7d6ad..8b3fa646 100644--- a/components/documents/document-header.tsx+++ b/components/documents/document-header.tsx@@ -576,9 +576,9 @@ export default function DocumentHeader({(!orientationLoading ? (<ButtonTooltip content="Change orientation"><Button- variant="ghost"+ variant="outline"size="icon"- className="hidden md:flex"+ className="hidden size-8 sm:flex lg:size-9"onClick={changeDocumentOrientation}title={`Change document orientation to ${primaryVersion.isVertical ? "landscape" : "portrait"}`}>@@ -604,13 +604,13 @@ export default function DocumentHeader({><ButtonTooltip content="Upload new version"><Button- variant="ghost"+ variant="outline"size="icon"onClick={(e) => {e.stopPropagation();setOpenAddDocModal(true);}}- className="hidden md:flex"+ className="hidden size-8 md:flex lg:size-9"><FileUp className="h-6 w-6" /></Button>@@ -640,7 +640,7 @@ export default function DocumentHeader({{actionRows.map((row, i) => (<ulkey={i.toString()}- className="flex flex-wrap items-center justify-end gap-2 md:flex-nowrap md:gap-4"+ className="flex flex-wrap items-center justify-end gap-x-4 md:flex-nowrap md:gap-x-2">{row.map((action, i) => (<li key={i}>{action}</li>diff --git a/components/documents/document-preview-button.tsx b/components/documents/document-preview-button.tsxnew file mode 100644index 00000000..c60d310f--- /dev/null+++ b/components/documents/document-preview-button.tsx@@ -0,0 +1,121 @@+import { useState } from "react";++import { EyeIcon, EyeOffIcon } from "lucide-react";++import { Button } from "@/components/ui/button";+import { ButtonTooltip } from "@/components/ui/tooltip";++import { DocumentPreviewModal } from "./document-preview-modal";++interface DocumentPreviewButtonProps {+ documentId: string;+ primaryVersion?: {+ hasPages?: boolean;+ type?: string | null;+ numPages?: number | null;+ };+ isProcessing?: boolean;+ variant?: "ghost" | "outline" | "default";+ size?: "sm" | "default" | "lg" | "icon";+ children?: React.ReactNode;+ className?: string;+ showTooltip?: boolean;+}++export function DocumentPreviewButton({+ documentId,+ primaryVersion,+ isProcessing = false,+ variant = "ghost",+ size = "icon",+ children,+ className,+ showTooltip = true,+}: DocumentPreviewButtonProps) {+ const [isPreviewOpen, setIsPreviewOpen] = useState(false);++ // Check if document type supports preview+ const supportsPreview = () => {+ if (!primaryVersion) return false;++ // Support documents with pages (PDFs, docs, slides, etc.)+ if (primaryVersion.hasPages) return true;++ // Support image documents+ if (primaryVersion.type === "image") return true;++ // Don't support sheets, notion, videos, etc.+ return false;+ };++ // Don't render if document type doesn't support preview+ if (!supportsPreview()) {+ return null;+ }++ const handlePreviewClick = (e: React.MouseEvent<HTMLButtonElement>) => {+ e.stopPropagation();+ e.preventDefault();++ if (isProcessing) return;+ setIsPreviewOpen(true);+ };++ const button = (+ <Button+ variant={variant}+ size={size}+ onClick={handlePreviewClick}+ disabled={isProcessing}+ className={className}+ >+ {children || (+ <>+ <EyeIcon className="h-4 w-4" />+ {size !== "icon" && <span className="ml-1">Preview</span>}+ </>+ )}+ </Button>+ );++ const wrappedButton = showTooltip ? (+ <ButtonTooltip+ content={+ isProcessing+ ? "Document is still processing"+ : "Quick preview of document"+ }+ >+ {button}+ </ButtonTooltip>+ ) : (+ button+ );++ return (+ <>+ {wrappedButton}+ <DocumentPreviewModal+ documentId={documentId}+ isOpen={isPreviewOpen}+ onClose={() => setIsPreviewOpen(false)}+ />+ </>+ );+}++// Helper function to check if document is processing+export function isDocumentProcessing(primaryVersion?: {+ hasPages?: boolean;+ type?: string | null;+ numPages?: number | null;+}) {+ if (!primaryVersion) return false;++ // Check if document type should have pages but doesn't+ const shouldHavePages = ["pdf", "docs", "slides", "cad"].includes(+ primaryVersion.type || "",+ );++ return shouldHavePages && !primaryVersion.hasPages;+}diff --git a/components/documents/document-preview-modal.tsx b/components/documents/document-preview-modal.tsxnew file mode 100644index 00000000..db4c10f2--- /dev/null+++ b/components/documents/document-preview-modal.tsx@@ -0,0 +1,109 @@+import { useEffect } from "react";++import { XIcon } from "lucide-react";+import { toast } from "sonner";++import { useDocumentPreview } from "@/lib/swr/use-document-preview";++import { Button } from "@/components/ui/button";+import { Dialog, DialogContent } from "@/components/ui/dialog";+import LoadingSpinner from "@/components/ui/loading-spinner";++import { PreviewViewer } from "./preview-viewers/preview-viewer";++interface DocumentPreviewModalProps {+ documentId: string;+ isOpen: boolean;+ onClose: () => void;+}++export function DocumentPreviewModal({+ documentId,+ isOpen,+ onClose,+}: DocumentPreviewModalProps) {+ const {+ document: documentData,+ loading,+ error,+ mutate,+ } = useDocumentPreview(documentId, isOpen);++ const handleClose = () => {+ onClose();+ };++ const handleKeyDown = (e: React.KeyboardEvent) => {+ if (e.key === "Escape") {+ handleClose();+ }+ };++ const handleContentClick = (e: React.MouseEvent) => {+ // Prevent clicks from propagating to underlying elements+ e.stopPropagation();+ };++ console.log("error", error);++ return (+ <Dialog open={isOpen} onOpenChange={handleClose}>+ <DialogContent+ className="h-[99vh] w-[90%] rounded-lg bg-gray-900 p-0 data-[state=open]:slide-in-from-bottom-0 md:w-[80vw] md:max-w-[80vw]"+ onKeyDown={handleKeyDown}+ onClick={handleContentClick}+ isPreviewDialog+ >+ {/* Header with close button */}+ <div className="absolute right-4 top-4 z-50">+ <Button+ variant="ghost"+ size="icon"+ onClick={handleClose}+ className="h-8 w-8 rounded-full bg-black/20 text-white hover:bg-black/40"+ >+ <XIcon className="h-4 w-4" />+ </Button>+ </div>++ {/* Loading state */}+ {loading && (+ <div className="flex h-full w-full items-center justify-center">+ <div className="text-center">+ <LoadingSpinner className="mx-auto h-8 w-8 text-white" />+ <p className="mt-2 text-sm text-gray-400">Loading preview...</p>+ </div>+ </div>+ )}++ {/* Error state */}+ {error && (+ <div className="flex h-full w-full items-center justify-center">+ <div className="text-center">+ <p className="text-red-400">+ {(() => {+ try {+ const errorData = JSON.parse((error as Error).message);+ return (+ errorData.message || "Failed to load document preview"+ );+ } catch {+ return (+ (error as Error).message ||+ "Failed to load document preview"+ );+ }+ })()}+ </p>+ </div>+ </div>+ )}++ {/* Document preview */}+ {documentData && !loading && !error && (+ <PreviewViewer documentData={documentData} onClose={handleClose} />+ )}+ </DialogContent>+ </Dialog>+ );+}diff --git a/components/documents/preview-viewers/index.ts b/components/documents/preview-viewers/index.tsnew file mode 100644index 00000000..3b0782ea--- /dev/null+++ b/components/documents/preview-viewers/index.ts@@ -0,0 +1,3 @@+export { PreviewImageViewer } from "./preview-image-viewer";+export { PreviewPagesViewer } from "./preview-pages-viewer";+export { PreviewViewer } from "./preview-viewer";diff --git a/components/documents/preview-viewers/preview-image-viewer.tsx b/components/documents/preview-viewers/preview-image-viewer.tsxnew file mode 100644index 00000000..44a1ddb3--- /dev/null+++ b/components/documents/preview-viewers/preview-image-viewer.tsx@@ -0,0 +1,82 @@+import { useState } from "react";++import { cn } from "@/lib/utils";++interface DocumentPreviewData {+ documentId: string;+ documentName: string;+ documentType: string;+ fileType: string;+ isVertical: boolean;+ numPages: number;+ pages?: {+ file: string;+ pageNumber: string;+ embeddedLinks: string[];+ pageLinks: { href: string; coords: string }[];+ metadata: { width: number; height: number; scaleFactor: number };+ }[];+ file?: string;+ sheetData?: any;+}++interface PreviewImageViewerProps {+ documentData: DocumentPreviewData;+ onClose: () => void;+}++export function PreviewImageViewer({+ documentData,+ onClose,+}: PreviewImageViewerProps) {+ const [imageLoaded, setImageLoaded] = useState(false);++ const { file, documentName } = documentData;++ if (!file) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <p className="text-gray-400">Image not available</p>+ </div>+ );+ }++ const handleImageLoad = () => {+ setImageLoaded(true);+ };++ return (+ <div className="relative h-full w-full overflow-hidden">+ {/* Document Title */}+ <div className="absolute left-1/2 top-4 z-50 -translate-x-1/2">+ <div className="rounded-lg bg-black/20 px-3 py-2 text-white">+ <span className="text-sm font-medium">{documentName}</span>+ </div>+ </div>++ {/* Image Content */}+ <div className="flex h-full w-full items-center justify-center p-4">+ <div className="relative max-h-full max-w-full">+ {!imageLoaded && (+ <div className="absolute inset-0 flex items-center justify-center">+ <div className="h-8 w-8 animate-spin rounded-full border-2 border-white border-t-transparent"></div>+ </div>+ )}++ <img+ src={file}+ alt={documentName}+ className={cn(+ "max-h-[calc(100vh-120px)] max-w-full object-contain transition-opacity duration-200",+ imageLoaded ? "opacity-100" : "opacity-0",+ )}+ onLoad={handleImageLoad}+ onError={() => setImageLoaded(true)}+ draggable={false}+ onContextMenu={(e) => e.preventDefault()}+ />+ </div>+ </div>+ </div>+ );+}diff --git a/components/documents/preview-viewers/preview-pages-viewer.tsx b/components/documents/preview-viewers/preview-pages-viewer.tsxnew file mode 100644index 00000000..9c9a7358--- /dev/null+++ b/components/documents/preview-viewers/preview-pages-viewer.tsx@@ -0,0 +1,201 @@+import { useEffect, useState } from "react";++import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";++import { cn } from "@/lib/utils";++import { Button } from "@/components/ui/button";++interface DocumentPreviewData {+ documentId: string;+ documentName: string;+ documentType: string;+ fileType: string;+ isVertical: boolean;+ numPages: number;+ pages?: {+ file: string;+ pageNumber: string;+ embeddedLinks: string[];+ pageLinks: { href: string; coords: string }[];+ metadata: { width: number; height: number; scaleFactor: number };+ }[];+ file?: string;+ sheetData?: any;+}++interface PreviewPagesViewerProps {+ documentData: DocumentPreviewData;+ onClose: () => void;+}++export function PreviewPagesViewer({+ documentData,+ onClose,+}: PreviewPagesViewerProps) {+ const [currentPage, setCurrentPage] = useState(1);+ const [imageCache, setImageCache] = useState<{ [key: number]: boolean }>({});+ const [imageLoaded, setImageLoaded] = useState(imageCache[1] || false);++ const { pages, numPages, documentName, isVertical } = documentData;++ if (!pages || pages.length === 0) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <p className="text-gray-400">No pages available for preview</p>+ </div>+ );+ }++ const currentPageData = pages[currentPage - 1];++ useEffect(() => {+ const handleKeyDown = (e: KeyboardEvent) => {+ switch (e.key) {+ case "ArrowLeft":+ goToPreviousPage();+ break;+ case "ArrowRight":+ goToNextPage();+ break;+ case "Escape":+ onClose();+ break;+ }+ };++ document.addEventListener("keydown", handleKeyDown);+ return () => document.removeEventListener("keydown", handleKeyDown);+ }, [currentPage, onClose]);++ const goToNextPage = () => {+ if (currentPage < numPages) {+ setCurrentPage(currentPage + 1);+ setImageLoaded(imageCache[currentPage + 1] || false);+ }+ };++ const goToPreviousPage = () => {+ if (currentPage > 1) {+ setCurrentPage(currentPage - 1);+ setImageLoaded(imageCache[currentPage - 1] || false);+ }+ };++ const handleImageLoad = () => {+ setImageLoaded(true);+ setImageCache((prev) => ({ ...prev, [currentPage]: true }));+ };++ if (!currentPageData) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <p className="text-gray-400">Page not found</p>+ </div>+ );+ }++ return (+ <div className="relative h-full w-full overflow-hidden">+ {/* Navigation Controls */}+ <div className="absolute left-4 top-4 z-50">+ <div className="flex items-center gap-2 rounded-lg bg-black/20 px-3 py-2 text-white">+ <span className="text-sm">+ Page {currentPage} of {numPages}+ </span>+ </div>+ </div>++ {/* Document Title */}+ <div className="absolute left-1/2 top-4 z-50 -translate-x-1/2">+ <div className="rounded-lg bg-black/20 px-3 py-2 text-white">+ <span className="text-sm font-medium">{documentName}</span>+ </div>+ </div>++ {/* Previous Page Button */}+ <Button+ variant="ghost"+ size="icon"+ onClick={goToPreviousPage}+ disabled={currentPage <= 1}+ className={cn(+ "absolute left-4 top-1/2 z-40 h-12 w-12 -translate-y-1/2 rounded-full bg-black/20 text-white hover:bg-black/40",+ currentPage <= 1 && "cursor-not-allowed opacity-50",+ )}+ >+ <ChevronLeftIcon className="h-6 w-6" />+ </Button>++ {/* Next Page Button */}+ <Button+ variant="ghost"+ size="icon"+ onClick={goToNextPage}+ disabled={currentPage >= numPages}+ className={cn(+ "absolute right-4 top-1/2 z-40 h-12 w-12 -translate-y-1/2 rounded-full bg-black/20 text-white hover:bg-black/40",+ currentPage >= numPages && "cursor-not-allowed opacity-50",+ )}+ >+ <ChevronRightIcon className="h-6 w-6" />+ </Button>++ {/* Page Content */}+ <div className="flex h-full w-full items-center justify-center p-4">+ <div className="relative max-h-full max-w-full">+ {!imageLoaded && (+ <div className="absolute inset-0 flex items-center justify-center">+ <div className="h-8 w-8 animate-spin rounded-full border-2 border-white border-t-transparent"></div>+ </div>+ )}++ <img+ src={currentPageData.file}+ alt={`Page ${currentPage}`}+ className={cn(+ "max-h-[calc(100vh-120px)] max-w-full object-contain transition-opacity duration-200",+ imageLoaded ? "opacity-100" : "opacity-0",+ )}+ onLoad={handleImageLoad}+ onError={() => {+ setImageLoaded(true);+ setImageCache((prev) => ({ ...prev, [currentPage]: true }));+ }}+ draggable={false}+ onContextMenu={(e) => e.preventDefault()}+ />+ </div>+ </div>++ {/* Bottom Navigation */}+ <div className="absolute bottom-4 left-1/2 z-50 -translate-x-1/2">+ <div className="flex items-center gap-2 rounded-lg bg-black/20 px-4 py-2">+ <Button+ variant="ghost"+ size="sm"+ onClick={goToPreviousPage}+ disabled={currentPage <= 1}+ className="h-8 px-3 text-white hover:bg-white/10"+ >+ Previous+ </Button>++ <span className="text-sm text-white">+ {currentPage} / {numPages}+ </span>++ <Button+ variant="ghost"+ size="sm"+ onClick={goToNextPage}+ disabled={currentPage >= numPages}+ className="h-8 px-3 text-white hover:bg-white/10"+ >+ Next+ </Button>+ </div>+ </div>+ </div>+ );+}diff --git a/components/documents/preview-viewers/preview-viewer.tsx b/components/documents/preview-viewers/preview-viewer.tsxnew file mode 100644index 00000000..b20bb946--- /dev/null+++ b/components/documents/preview-viewers/preview-viewer.tsx@@ -0,0 +1,82 @@+import { PreviewImageViewer } from "./preview-image-viewer";+import { PreviewPagesViewer } from "./preview-pages-viewer";++interface DocumentPreviewData {+ documentId: string;+ documentName: string;+ documentType: string;+ fileType: string;+ isVertical: boolean;+ numPages: number;+ pages?: {+ file: string;+ pageNumber: string;+ embeddedLinks: string[];+ pageLinks: { href: string; coords: string }[];+ metadata: { width: number; height: number; scaleFactor: number };+ }[];+ file?: string;+ sheetData?: any;+}++interface PreviewViewerProps {+ documentData: DocumentPreviewData;+ onClose: () => void;+}++export function PreviewViewer({ documentData, onClose }: PreviewViewerProps) {+ const renderViewer = () => {+ // Documents with pages (PDFs, docs, slides)+ if (documentData.pages && documentData.pages.length > 0) {+ return (+ <PreviewPagesViewer documentData={documentData} onClose={onClose} />+ );+ }++ // Single image files+ if (documentData.fileType === "image" && documentData.file) {+ return (+ <PreviewImageViewer documentData={documentData} onClose={onClose} />+ );+ }++ // Excel/CSV files+ if (documentData.fileType === "sheet" && documentData.sheetData) {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <div className="text-center">+ <p className="text-gray-400">+ Sheet preview coming soon. Please preview via a shared link.+ </p>+ </div>+ </div>+ );+ }++ // Notion documents (not fully supported yet)+ if (documentData.fileType === "notion") {+ return (+ <div className="flex h-full w-full items-center justify-center">+ <div className="text-center">+ <p className="text-gray-400">Notion document preview coming soon</p>+ </div>+ </div>+ );+ }++ // Fallback for unsupported types+ return (+ <div className="flex h-full w-full items-center justify-center">+ <div className="text-center">+ <p className="text-gray-400">+ Preview not available for this document type+ </p>+ </div>+ </div>+ );+ };++ return (+ <div className="relative h-full w-full bg-gray-900">{renderViewer()}</div>+ );+}diff --git a/components/ui/dialog.tsx b/components/ui/dialog.tsxindex 659a3a65..55e882ea 100644--- a/components/ui/dialog.tsx+++ b/components/ui/dialog.tsx@@ -18,10 +18,16 @@ DialogTrigger.displayName = DialogPrimitive.Trigger.displayName;const DialogPortal = ({children,+ isPreviewDialog,...props-}: DialogPrimitive.DialogPortalProps) => (+}: DialogPrimitive.DialogPortalProps & { isPreviewDialog?: boolean }) => (<DialogPrimitive.Portal {...props}>- <div className="fixed inset-0 z-50 flex items-end justify-center sm:items-center">+ <div+ className={cn(+ "fixed inset-0 z-50 flex items-end justify-center sm:items-center",+ isPreviewDialog ? "items-center" : "items-end",+ )}+ >{children}</div></DialogPrimitive.Portal>@@ -47,35 +53,41 @@ const DialogContent = React.forwardRef<React.ElementRef<typeof DialogPrimitive.Content>,React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {isDocumentDialog?: boolean;+ isPreviewDialog?: boolean;}->(({ className, children, isDocumentDialog, ...props }, ref) => (- <DialogPortal>- <DialogOverlay />- <DialogPrimitive.Content- ref={ref}- className={cn(- "fixed z-50 grid w-full gap-4 rounded-t-lg border border-gray-800 bg-background p-6 shadow-lg animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 sm:max-w-xl sm:rounded-lg sm:zoom-in-90 data-[state=open]:sm:slide-in-from-bottom-0 md:w-1/2",- className,- )}- onCloseAutoFocus={(event) => {- event.preventDefault();- document.body.style.pointerEvents = "";- }}- {...props}- >- {children}- <DialogPrimitive.Close+>(+ (+ { className, children, isDocumentDialog, isPreviewDialog, ...props },+ ref,+ ) => (+ <DialogPortal isPreviewDialog={isPreviewDialog}>+ <DialogOverlay />+ <DialogPrimitive.Content+ ref={ref}className={cn(- "absolute rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",- isDocumentDialog ? "right-8 top-20" : "right-4 top-4",+ "fixed z-50 grid w-full gap-4 rounded-t-lg border border-gray-800 bg-background p-6 shadow-lg animate-in data-[state=open]:fade-in-90 data-[state=open]:slide-in-from-bottom-10 sm:max-w-xl sm:rounded-lg sm:zoom-in-90 data-[state=open]:sm:slide-in-from-bottom-0 md:w-1/2",+ className,)}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ document.body.style.pointerEvents = "";+ }}+ {...props}>- <X className="h-4 w-4" />- <span className="sr-only">Close</span>- </DialogPrimitive.Close>- </DialogPrimitive.Content>- </DialogPortal>-));+ {children}+ <DialogPrimitive.Close+ className={cn(+ "absolute rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",+ isDocumentDialog ? "right-8 top-20" : "right-4 top-4",+ )}+ >+ <X className="h-4 w-4" />+ <span className="sr-only">Close</span>+ </DialogPrimitive.Close>+ </DialogPrimitive.Content>+ </DialogPortal>+ ),+);DialogContent.displayName = DialogPrimitive.Content.displayName;const DialogHeader = ({diff --git a/lib/swr/use-document-preview.ts b/lib/swr/use-document-preview.tsnew file mode 100644index 00000000..a26fa939--- /dev/null+++ b/lib/swr/use-document-preview.ts@@ -0,0 +1,44 @@+import useSWRImmutable from "swr/immutable";++import { fetcher } from "@/lib/utils";++interface DocumentPreviewData {+ documentId: string;+ documentName: string;+ documentType: string;+ fileType: string;+ isVertical: boolean;+ numPages: number;+ pages?: {+ file: string;+ pageNumber: string;+ embeddedLinks: string[];+ pageLinks: { href: string; coords: string }[];+ metadata: { width: number; height: number; scaleFactor: number };+ }[];+ file?: string;+ sheetData?: any;+}++export function useDocumentPreview(documentId: string, isOpen: boolean) {+ const {+ data: document,+ error,+ mutate,+ } = useSWRImmutable<DocumentPreviewData>(+ isOpen && documentId ? `/api/documents/${documentId}/preview-data` : null,+ fetcher,+ {+ dedupingInterval: 10000,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ },+ );++ return {+ document,+ loading: !error && !document && isOpen,+ error,+ mutate,+ };+}diff --git a/pages/api/documents/[id]/preview-data.ts b/pages/api/documents/[id]/preview-data.tsnew file mode 100644index 00000000..24be708f--- /dev/null+++ b/pages/api/documents/[id]/preview-data.ts@@ -0,0 +1,148 @@+import { NextApiRequest, NextApiResponse } from "next";++import { getServerSession } from "next-auth/next";++import { getFile } from "@/lib/files/get-file";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";++import { authOptions } from "../../auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).json({ message: "Unauthorized" });+ }++ const { id: documentId } = req.query as { id: string };+ const userId = (session.user as CustomUser).id;++ try {+ // Fetch document and verify team membership+ const document = await prisma.document.findUnique({+ where: { id: documentId },+ include: {+ team: {+ include: {+ users: {+ where: { userId },+ select: { userId: true },+ },+ },+ },+ versions: {+ where: { isPrimary: true },+ select: {+ id: true,+ type: true,+ hasPages: true,+ numPages: true,+ isVertical: true,+ file: true,+ storageType: true,+ pages: {+ orderBy: { pageNumber: "asc" },+ select: {+ file: true,+ storageType: true,+ pageNumber: true,+ embeddedLinks: true,+ pageLinks: true,+ metadata: true,+ },+ },+ },+ },+ },+ });++ // Check if document exists and user is team member+ if (!document || document.team.users.length === 0) {+ return res.status(403).json({ message: "Access denied" });+ }++ const primaryVersion = document.versions[0];+ if (!primaryVersion) {+ return res.status(404).json({ message: "Document version not found" });+ }++ // Prepare return data structure+ const returnData = {+ documentId,+ documentName: document.name,+ documentType: document.type,+ fileType: primaryVersion.type,+ isVertical: primaryVersion.isVertical,+ numPages: primaryVersion.numPages,+ pages: undefined as any,+ file: undefined as string | undefined,+ sheetData: undefined as any,+ };++ // Handle different file types+ if (primaryVersion.hasPages && primaryVersion.pages.length > 0) {+ // Documents with pages (PDFs, docs, slides)+ returnData.pages = await Promise.all(+ primaryVersion.pages.map(async (page) => {+ const { storageType, ...otherPageData } = page;+ return {+ ...otherPageData,+ file: await getFile({ data: page.file, type: storageType }),+ };+ }),+ );+ } else if (primaryVersion.type === "image") {+ // Single image files+ returnData.file = await getFile({+ data: primaryVersion.file,+ type: primaryVersion.storageType,+ });+ returnData.numPages = 1;+ } else if (primaryVersion.type === "sheet") {+ // Excel/CSV files - preview not supported+ return res.status(400).json({+ message:+ "Sheet preview not available. Please preview via a shared link.",+ });+ } else if (primaryVersion.type === "notion") {+ // Notion documents - preview not supported+ return res.status(400).json({+ message: "Notion document preview coming soon",+ });+ } else {+ // Check if document should be processed but isn't+ const shouldHavePages = ["pdf", "docs", "slides", "cad"].includes(+ primaryVersion.type || "",+ );++ if (shouldHavePages) {+ return res.status(400).json({+ message: "Document is still processing. Please wait and try again.",+ });+ } else {+ return res.status(400).json({+ message: "Preview not available for this document type",+ });+ }+ }++ return res.status(200).json(returnData);+ } catch (error) {+ log({+ message: "Error fetching document preview data",+ type: "error",+ mention: true,+ });+ console.error(error);+ return res.status(500).json({ message: "Internal server error" });+ }+}diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsxindex 5a2a575f..50645452 100644--- a/pages/documents/[id]/index.tsx+++ b/pages/documents/[id]/index.tsx@@ -11,6 +11,7 @@ import useLimits from "@/lib/swr/use-limits";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import DocumentHeader from "@/components/documents/document-header";+import { DocumentPreviewButton } from "@/components/documents/document-preview-button";import { StatsComponent } from "@/components/documents/stats";import VideoAnalytics from "@/components/documents/video-analytics";import AppLayout from "@/components/layouts/app";@@ -73,7 +74,18 @@ export default function DocumentPage() {primaryVersion={primaryVersion}prismaDocument={prismaDocument}teamId={teamInfo?.currentTeam?.id!}- actions={[<AddLinkButton key={"create-link"} />]}+ actions={[+ <DocumentPreviewButton+ key={"preview"}+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ variant="outline"+ size="default"+ showTooltip={false}+ className="h-8 whitespace-nowrap text-xs lg:h-9 lg:text-sm"+ />,+ <AddLinkButton key={"create-link"} />,+ ]}/>{/* Document Analytics */}