Skip to content

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

feat: add new files button

Marc Seitz5367d382fc14
diff --git a/components/documents/add-document-dropdown.tsx b/components/documents/add-document-dropdown.tsx
new file mode 100644
index 00000000..2f74e40d
--- /dev/null
+++ b/components/documents/add-document-dropdown.tsx
@@ -0,0 +1,387 @@
+import { useCallback, useMemo, useState } from "react";
+
+import { PlanEnum } from "@/ee/stripe/constants";
+import {
+ ChevronDownIcon,
+ FileUpIcon,
+ FolderPlusIcon,
+ FolderUpIcon,
+ LinkIcon,
+ PlusIcon,
+} from "lucide-react";
+import { useHotkeys } from "react-hotkeys-hook";
+import { toast } from "sonner";
+
+import { useUploadProgress } from "@/context/upload-progress-context";
+import { usePlan } from "@/lib/swr/use-billing";
+import useLimits from "@/lib/swr/use-limits";
+import { cn } from "@/lib/utils";
+
+import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
+import { AddDocumentModal } from "@/components/documents/add-document-modal";
+import { AddFolderModal } from "@/components/folders/add-folder-modal";
+import NotionIcon from "@/components/shared/icons/files/notion";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+
+type DocModalState = {
+ open: boolean;
+ defaultTab: "document" | "notion";
+ defaultUploadMode: "file" | "link";
+};
+
+interface AddDocumentDropdownProps {
+ isDataroom?: boolean;
+ dataroomId?: string;
+ disabled?: boolean;
+ size?: "default" | "sm";
+ className?: string;
+ variant?: "unified" | "split";
+}
+
+export function AddDocumentDropdown({
+ isDataroom,
+ dataroomId,
+ disabled,
+ size = "default",
+ className,
+ variant = "unified",
+}: AddDocumentDropdownProps) {
+ const { isFree, isTrial } = usePlan();
+ const { canAddDocuments } = useLimits();
+ const { uploadTriggers } = useUploadProgress();
+
+ const [menuOpen, setMenuOpen] = useState(false);
+ const [folderOpen, setFolderOpen] = useState(false);
+ const [docModal, setDocModal] = useState<DocModalState>({
+ open: false,
+ defaultTab: "document",
+ defaultUploadMode: "file",
+ });
+ const [upgradeModal, setUpgradeModal] = useState<{
+ open: boolean;
+ trigger: string;
+ highlight: string[];
+ }>({ open: false, trigger: "", highlight: [] });
+
+ const requiresUpgradeForFolders = isFree && !isTrial;
+ const requiresUpgradeForWebLink = isFree && !isTrial;
+
+ const enforceDocumentLimit = useCallback((): boolean => {
+ // Paused subscriptions still surface a toast via AddDocumentModal /
+ // UploadZone, so we only handle the plan-limit gate here.
+ if (!canAddDocuments) {
+ setUpgradeModal({
+ open: true,
+ trigger: "limit_upload_documents",
+ highlight: ["documents"],
+ });
+ return false;
+ }
+ return true;
+ }, [canAddDocuments]);
+
+ const handleCreateFolder = useCallback(() => {
+ if (requiresUpgradeForFolders) {
+ setUpgradeModal({
+ open: true,
+ trigger: "add_folder_button",
+ highlight: ["folder", "folder-sharing", "datarooms"],
+ });
+ return;
+ }
+ setFolderOpen(true);
+ }, [requiresUpgradeForFolders]);
+
+ const handleUploadFiles = useCallback(() => {
+ if (!enforceDocumentLimit()) return;
+ if (uploadTriggers) {
+ uploadTriggers.openFilesPicker();
+ return;
+ }
+ // No UploadZone is mounted in the visible tree (e.g. while a dataroom
+ // search is active and the search-results view replaces the items list).
+ // Fall back to the single-file modal so the action isn't a silent no-op.
+ setDocModal({
+ open: true,
+ defaultTab: "document",
+ defaultUploadMode: "file",
+ });
+ }, [enforceDocumentLimit, uploadTriggers]);
+
+ const handleUploadFolder = useCallback(() => {
+ if (!enforceDocumentLimit()) return;
+ if (uploadTriggers) {
+ uploadTriggers.openFolderPicker();
+ return;
+ }
+ // Folder upload requires the directory-mode picker rendered inside
+ // UploadZone; no modal fallback exists. Tell the user how to recover
+ // (typically: clear the active search) rather than failing silently.
+ toast.info("Clear the search to upload a folder here.");
+ }, [enforceDocumentLimit, uploadTriggers]);
+
+ const handleAddNotion = useCallback(() => {
+ if (!enforceDocumentLimit()) return;
+ setDocModal({
+ open: true,
+ defaultTab: "notion",
+ defaultUploadMode: "file",
+ });
+ }, [enforceDocumentLimit]);
+
+ const handleAddWebLink = useCallback(() => {
+ if (requiresUpgradeForWebLink) {
+ setUpgradeModal({
+ open: true,
+ trigger: "add_web_link_document",
+ highlight: ["link"],
+ });
+ return;
+ }
+ if (!enforceDocumentLimit()) return;
+ setDocModal({
+ open: true,
+ defaultTab: "document",
+ defaultUploadMode: "link",
+ });
+ }, [enforceDocumentLimit, requiresUpgradeForWebLink]);
+
+ // Google Drive-style "N then …" sequences: press N, then F / U / I within
+ // the library's default sequence timeout. Plain letters (no ctrl/cmd) keep
+ // these clear of every browser-reserved combo while staying discoverable
+ // through the menu hints. The shared guard prevents firing while the user
+ // is typing in an editable surface.
+ const isEditableTarget = useCallback((e: KeyboardEvent): boolean => {
+ const target = e.target as HTMLElement | null;
+ return !!(
+ target &&
+ (target.isContentEditable ||
+ ["INPUT", "TEXTAREA", "SELECT"].includes(target.tagName))
+ );
+ }, []);
+
+ const sequenceOptions = useMemo(
+ () => ({ preventDefault: false, enableOnFormTags: false as const }),
+ [],
+ );
+
+ useHotkeys(
+ "n>f",
+ (e) => {
+ if (disabled || isEditableTarget(e)) return;
+ e.preventDefault();
+ handleCreateFolder();
+ },
+ sequenceOptions,
+ [handleCreateFolder, disabled, isEditableTarget],
+ );
+
+ useHotkeys(
+ "n>u",
+ (e) => {
+ if (disabled || isEditableTarget(e)) return;
+ e.preventDefault();
+ handleUploadFiles();
+ },
+ sequenceOptions,
+ [handleUploadFiles, disabled, isEditableTarget],
+ );
+
+ useHotkeys(
+ "n>i",
+ (e) => {
+ if (disabled || isEditableTarget(e)) return;
+ e.preventDefault();
+ handleUploadFolder();
+ },
+ sequenceOptions,
+ [handleUploadFolder, disabled, isEditableTarget],
+ );
+
+ // Memoize so the doc modal doesn't reset itself between renders.
+ const docModalKey = useMemo(
+ () => `${docModal.defaultTab}-${docModal.defaultUploadMode}`,
+ [docModal.defaultTab, docModal.defaultUploadMode],
+ );
+
+ return (
+ <>
+ <DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
+ {variant === "split" ? (
+ <div className="flex items-center gap-x-2">
+ <Button
+ size={size}
+ disabled={disabled}
+ onClick={handleUploadFiles}
+ className={cn(
+ "flex items-center justify-start gap-x-1 whitespace-nowrap px-2 text-left sm:gap-x-2 sm:px-3",
+ className,
+ )}
+ title="Add document"
+ >
+ <PlusIcon
+ className="h-4 w-4 shrink-0 sm:h-5 sm:w-5"
+ aria-hidden="true"
+ />
+ <span className="text-xs sm:text-sm">
+ <span className="hidden sm:inline">Add document</span>
+ <span className="sm:hidden">Add</span>
+ </span>
+ </Button>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="outline"
+ size={size}
+ disabled={disabled}
+ className="group flex items-center gap-x-1 whitespace-nowrap border-gray-500 bg-gray-50 px-2 hover:bg-gray-200 dark:bg-black hover:dark:bg-muted sm:gap-x-2 sm:px-3"
+ aria-label="More upload options"
+ title="More options"
+ >
+ <span className="text-xs sm:text-sm">More</span>
+ <ChevronDownIcon
+ className="!size-3.5 shrink-0 opacity-80 transition-transform group-data-[state=open]:rotate-180"
+ aria-hidden="true"
+ />
+ </Button>
+ </DropdownMenuTrigger>
+ </div>
+ ) : (
+ <DropdownMenuTrigger asChild>
+ <Button
+ size={size}
+ disabled={disabled}
+ className={cn(
+ "group flex items-center justify-start gap-x-1 whitespace-nowrap px-2 text-left sm:gap-x-2 sm:px-3",
+ className,
+ )}
+ title="Add"
+ >
+ <PlusIcon
+ className="h-4 w-4 shrink-0 sm:h-5 sm:w-5"
+ aria-hidden="true"
+ />
+ <span className="text-xs sm:text-sm">Add</span>
+ <ChevronDownIcon
+ // !size overrides the Button cva's `[&_svg]:size-5` rule.
+ className="ml-0.5 !size-3.5 shrink-0 opacity-80 transition-transform group-data-[state=open]:rotate-180"
+ aria-hidden="true"
+ />
+ </Button>
+ </DropdownMenuTrigger>
+ )}
+ <DropdownMenuContent align="end" className="w-64">
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setMenuOpen(false);
+ handleCreateFolder();
+ }}
+ >
+ <FolderPlusIcon className="h-4 w-4" aria-hidden="true" />
+ <span>Create folder</span>
+ <DropdownMenuShortcut className="tracking-normal">
+ N then F
+ </DropdownMenuShortcut>
+ </DropdownMenuItem>
+
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
+ Upload from computer
+ </DropdownMenuLabel>
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setMenuOpen(false);
+ handleUploadFiles();
+ }}
+ >
+ <FileUpIcon className="h-4 w-4" aria-hidden="true" />
+ <span>Files</span>
+ <DropdownMenuShortcut className="tracking-normal">
+ N then U
+ </DropdownMenuShortcut>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setMenuOpen(false);
+ handleUploadFolder();
+ }}
+ >
+ <FolderUpIcon className="h-4 w-4" aria-hidden="true" />
+ <span>Folder</span>
+ <DropdownMenuShortcut className="tracking-normal">
+ N then I
+ </DropdownMenuShortcut>
+ </DropdownMenuItem>
+
+ <DropdownMenuSeparator />
+ <DropdownMenuLabel className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
+ More options
+ </DropdownMenuLabel>
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setMenuOpen(false);
+ handleAddNotion();
+ }}
+ >
+ <NotionIcon className="h-4 w-4" aria-hidden="true" />
+ <span>Add Notion page</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onSelect={(e) => {
+ e.preventDefault();
+ setMenuOpen(false);
+ handleAddWebLink();
+ }}
+ >
+ <LinkIcon className="h-4 w-4" aria-hidden="true" />
+ <span>Add web link</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <AddFolderModal
+ open={folderOpen}
+ onOpenChange={setFolderOpen}
+ isDataroom={isDataroom}
+ dataroomId={dataroomId}
+ />
+
+ <AddDocumentModal
+ key={docModalKey}
+ openModal={docModal.open}
+ setAddDocumentModalOpen={(open) =>
+ setDocModal((prev) => ({ ...prev, open }))
+ }
+ defaultTab={docModal.defaultTab}
+ defaultUploadMode={docModal.defaultUploadMode}
+ isDataroom={isDataroom}
+ dataroomId={dataroomId}
+ />
+
+ <UpgradePlanModal
+ clickedPlan={PlanEnum.Pro}
+ trigger={upgradeModal.trigger}
+ highlightItem={upgradeModal.highlight}
+ open={upgradeModal.open}
+ setOpen={(open) =>
+ setUpgradeModal((prev) => ({
+ ...prev,
+ open: typeof open === "function" ? open(prev.open) : open,
+ }))
+ }
+ />
+ </>
+ );
+}
diff --git a/components/documents/add-document-modal.tsx b/components/documents/add-document-modal.tsx
index cd4ae0ef..3cfab3cc 100644
--- a/components/documents/add-document-modal.tsx
+++ b/components/documents/add-document-modal.tsx
@@ -4,6 +4,7 @@ import { useRouter } from "next/router";
import { FormEvent, useEffect, useState } from "react";
import { useTeam } from "@/context/team-context";
+import { useUploadProgress } from "@/context/upload-progress-context";
import { PlanEnum } from "@/ee/stripe/constants";
import { DefaultPermissionStrategy } from "@prisma/client";
import { parsePageId } from "notion-utils";
@@ -60,13 +61,19 @@ export function AddDocumentModal({
dataroomId,
setAddDocumentModalOpen,
openModal,
+ defaultTab = "document",
+ defaultUploadMode = "file",
}: {
newVersion?: boolean;
- children: React.ReactNode;
+ children?: React.ReactNode;
isDataroom?: boolean;
openModal?: boolean;
dataroomId?: string;
setAddDocumentModalOpen?: (isOpen: boolean) => void;
+ /** Initial tab shown when the modal opens. */
+ defaultTab?: "document" | "notion";
+ /** Initial upload mode within the Document tab (file picker vs. web link). */
+ defaultUploadMode?: "file" | "link";
}) {
const router = useRouter();
const analytics = useAnalytics();
@@ -75,7 +82,12 @@ export function AddDocumentModal({
const [currentFile, setCurrentFile] = useState<File | null>(null);
const [notionLink, setNotionLink] = useState<string | null>(null);
const [webLink, setWebLink] = useState<string | null>(null);
- const [uploadMode, setUploadMode] = useState<"file" | "link">("file");
+ const [activeTab, setActiveTab] = useState<"document" | "notion">(
+ defaultTab,
+ );
+ const [uploadMode, setUploadMode] = useState<"file" | "link">(
+ defaultUploadMode,
+ );
const [showGroupPermissions, setShowGroupPermissions] = useState(false);
const [uploadedFiles, setUploadedFiles] = useState<
{
@@ -88,13 +100,21 @@ export function AddDocumentModal({
const { canAddDocuments, limits } = useLimits();
const { plan, isFree, isTrial, isPaused } = usePlan();
const { dataroom } = useDataroom();
+ const { uploadTriggers } = useUploadProgress();
const teamId = teamInfo?.currentTeam?.id as string;
const { applyPermissions } = useDataroomPermissions();
useEffect(() => {
- if (openModal) setIsOpen(openModal);
- }, [openModal]);
+ if (openModal) {
+ setIsOpen(true);
+ // Reset to the caller-requested starting state every time we open the
+ // modal programmatically so e.g. clicking "Notion" in the +Add menu
+ // never lands on a stale "link" upload form left over from last time.
+ setActiveTab(defaultTab);
+ setUploadMode(defaultUploadMode);
+ }
+ }, [openModal, defaultTab, defaultUploadMode]);
/** current folder name */
const currentFolderPath = router.query.name as string[] | undefined;
@@ -611,6 +631,7 @@ export function AddDocumentModal({
} finally {
setUploading(false);
setIsOpen(false);
+ setAddDocumentModalOpen && setAddDocumentModalOpen(false);
}
};
@@ -758,6 +779,7 @@ export function AddDocumentModal({
} finally {
setUploading(false);
setIsOpen(false);
+ setAddDocumentModalOpen && setAddDocumentModalOpen(false);
}
};
@@ -794,7 +816,9 @@ export function AddDocumentModal({
return (
<>
<Dialog open={isOpen} onOpenChange={clearModelStates}>
- <DialogTrigger asChild>{children}</DialogTrigger>
+ {children ? (
+ <DialogTrigger asChild>{children}</DialogTrigger>
+ ) : null}
<DialogContent
className="border-none bg-transparent text-foreground shadow-none"
isDocumentDialog
@@ -803,7 +827,12 @@ export function AddDocumentModal({
<DialogDescription className="sr-only">
An overlayed modal that can be clicked to upload a document
</DialogDescription>
- <Tabs defaultValue="document">
+ <Tabs
+ value={activeTab}
+ onValueChange={(value) =>
+ setActiveTab(value as "document" | "notion")
+ }
+ >
{!newVersion ? (
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="document">Document</TabsTrigger>
@@ -877,11 +906,11 @@ export function AddDocumentModal({
<button
type="button"
className="underline-offset-4 transition-all hover:text-gray-800 hover:underline hover:dark:text-muted-foreground/80"
+ disabled={!uploadTriggers}
onClick={(e) => {
e.stopPropagation();
- document
- .getElementById("upload-multi-files-zone")
- ?.click();
+ if (!uploadTriggers) return;
+ uploadTriggers.openFilesPicker();
clearModelStates();
}}
>
diff --git a/components/folders/add-folder-modal.tsx b/components/folders/add-folder-modal.tsx
index 91927467..119b4c29 100644
--- a/components/folders/add-folder-modal.tsx
+++ b/components/folders/add-folder-modal.tsx
@@ -1,6 +1,6 @@
import { useRouter } from "next/router";
-import { useState } from "react";
+import { useRef, useState } from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
@@ -35,31 +35,44 @@ import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
import { FolderIconColorPicker } from "./folder-icon-picker";
export function AddFolderModal({
- // open,
- // setOpen,
+ open: openProp,
+ onOpenChange,
onAddition,
isDataroom,
dataroomId,
children,
}: {
- // open?: boolean;
- // setOpen?: React.Dispatch<React.SetStateAction<boolean>>;
+ /** Controlled open state. Pair with `onOpenChange` to drive from outside. */
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
onAddition?: (folderName: string) => void;
isDataroom?: boolean;
dataroomId?: string;
children?: React.ReactNode;
}) {
const router = useRouter();
+ const folderNameInputRef = useRef<HTMLInputElement>(null);
const [folderName, setFolderName] = useState<string>("");
const [folderIcon, setFolderIcon] = useState<FolderIconId>(DEFAULT_FOLDER_ICON);
const [folderColor, setFolderColor] = useState<FolderColorId>(DEFAULT_FOLDER_COLOR);
const [loading, setLoading] = useState<boolean>(false);
- const [open, setOpen] = useState<boolean>(false);
+ const [uncontrolledOpen, setUncontrolledOpen] = useState<boolean>(false);
+ const isControlled = openProp !== undefined;
+ const open = isControlled ? openProp : uncontrolledOpen;
+ const setOpen = (next: boolean) => {
+ if (!isControlled) setUncontrolledOpen(next);
+ onOpenChange?.(next);
+ };
const teamInfo = useTeam();
const { isFree, isTrial } = usePlan();
const analytics = useAnalytics();
+ // Free plans (outside of trial) can't create folders. Centralize the gate
+ // so it applies to both trigger usage (`children`) and controlled usage
+ // (`open`/`onOpenChange`); otherwise a programmatic open would bypass it.
+ const isCreationAllowed = !(isFree && !isTrial);
+
/** current folder name */
const currentFolderPath = router.query.name as string[] | undefined;
@@ -85,6 +98,13 @@ export function AddFolderModal({
event.preventDefault();
event.stopPropagation();
+ // Defense in depth: the form isn't rendered when creation is blocked,
+ // but guard the creation path so a stale/leaked submission can't slip past.
+ if (!isCreationAllowed) {
+ setOpen(false);
+ return;
+ }
+
if (!validation.success) {
toast.error(validation.error.errors[0].message);
return;
@@ -155,8 +175,9 @@ export function AddFolderModal({
}
};
- // If the team is on a free plan, show the upgrade modal
- if (isFree && !isTrial) {
+ // If the team is on a free plan, show the upgrade modal regardless of how
+ // the consumer opens the dialog (trigger child or controlled props).
+ if (!isCreationAllowed) {
if (children) {
return (
<UpgradePlanModal
@@ -168,12 +189,34 @@ export function AddFolderModal({
</UpgradePlanModal>
);
}
+ // Controlled/programmatic usage: surface the upgrade modal in place of the
+ // create-folder dialog so callers can't bypass the gate by passing `open`.
+ return (
+ <UpgradePlanModal
+ clickedPlan={PlanEnum.Pro}
+ trigger={"add_folder_button"}
+ highlightItem={["folder", "folder-sharing", "datarooms"]}
+ open={open}
+ setOpen={(next) => {
+ const value = typeof next === "function" ? next(open) : next;
+ setOpen(value);
+ }}
+ />
+ );
}
return (
<Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent className="sm:max-w-[425px]">
+ {children ? <DialogTrigger asChild>{children}</DialogTrigger> : null}
+ <DialogContent
+ className="sm:max-w-[425px]"
+ onOpenAutoFocus={(e) => {
+ // Override Radix's default focus (which lands on the icon picker
+ // button) so the user can start typing the folder name immediately.
+ e.preventDefault();
+ folderNameInputRef.current?.focus();
+ }}
+ >
<DialogHeader className="text-start">
<DialogTitle>Add Folder</DialogTitle>
<DialogDescription>
@@ -192,6 +235,7 @@ export function AddFolderModal({
onColorChange={setFolderColor}
/>
<Input
+ ref={folderNameInputRef}
id="folder-name"
placeholder="Choose a helpful name"
className="flex-1"
@@ -204,7 +248,7 @@ export function AddFolderModal({
<Button
type="submit"
className="h-9 w-full"
- disabled={!validation.success}
+ disabled={!validation.success || !isCreationAllowed}
loading={loading}
>
Create
diff --git a/components/upload-zone.tsx b/components/upload-zone.tsx
index 2f777415..2f0643fd 100644
--- a/components/upload-zone.tsx
+++ b/components/upload-zone.tsx
@@ -3,6 +3,7 @@ import { useRouter } from "next/router";
import { useCallback, useEffect, useMemo, useRef } from "react";
import { useTeam } from "@/context/team-context";
+import { useUploadProgress } from "@/context/upload-progress-context";
import { DocumentStorageType } from "@prisma/client";
import { useSession } from "next-auth/react";
import { DropEvent, FileRejection, useDropzone } from "react-dropzone";
@@ -16,6 +17,10 @@ import {
SUPPORTED_DOCUMENT_MIME_TYPES,
} from "@/lib/constants";
import { DocumentData, createDocument } from "@/lib/documents/create-document";
+import {
+ MULTIPART_SIZE_THRESHOLD,
+ multipartUpload,
+} from "@/lib/files/multipart-upload";
import { resumableUpload } from "@/lib/files/tus-upload";
import {
BulkFolderRequestItem,
@@ -158,6 +163,57 @@ function stripLeadingSlash(p: string | null | undefined): string | undefined {
return p.startsWith("/") ? p.slice(1) : p;
}
+/**
+ * Attempts to repair the MIME type of a `File` whose `type` was reported as
+ * empty by the browser (Firefox does this for files yielded from a folder
+ * picker). Looks up the file extension against the supplied accept map; if a
+ * matching entry is found, returns a new `File` with the inferred MIME so
+ * downstream size/plan checks and the eventual S3 upload all see the right
+ * content type. Mirrors the inference the drag-drop walker already performs.
+ */
+function inferMimeFromExtensionMap(
+ file: File,
+ acceptable: Record<string, readonly string[]>,
+): File {
+ if (file.type) return file;
+ const ext = file.name.split(".").pop()?.toLowerCase();
+ if (!ext) return file;
+ for (const [mime, extsUntyped] of Object.entries(acceptable)) {
+ const exts = extsUntyped as readonly string[];
+ if (exts.some((e) => e.toLowerCase() === "." + ext)) {
+ return new File([file], file.name, {
+ type: mime,
+ lastModified: file.lastModified,
+ });
+ }
+ }
+ return file;
+}
+
+/**
+ * Mirrors react-dropzone's `accept` filtering for the folder-picker code
+ * path: a file is acceptable when its MIME matches a key in the accept map
+ * OR its extension matches one of the value-side extensions. The folder
+ * picker bypasses dropzone entirely, so without this gate a free-plan user
+ * could pick a folder containing paid-only file types and start the upload
+ * pipeline — bytes would land in S3 and only be rejected at document-
+ * creation time, after the upload had already happened.
+ */
+function isAcceptableForPlan(
+ file: File,
+ acceptable: Record<string, readonly string[]>,
+): boolean {
+ if (file.type && file.type in acceptable) return true;
+ const lowerName = file.name.toLowerCase();
+ const dotExt = "." + (lowerName.split(".").pop() ?? "");
+ for (const exts of Object.values(acceptable)) {
+ for (const e of exts as readonly string[]) {
+ if (e.toLowerCase() === dotExt) return true;
+ }
+ }
+ return false;
+}
+
/**
* Parent path (without leading slash) of a folder path expressed in the
* client-side "no leading slash" format. Returns undefined when the parent is
@@ -225,6 +281,14 @@ export default function UploadZone({
const teamInfo = useTeam();
const { data: session } = useSession();
const { limits, canAddDocuments, isPaused } = useLimits();
+ const { registerUploadTriggers } = useUploadProgress();
+
+ // Refs to the two hidden file inputs rendered inside this zone. Used to
+ // open the OS picker without traversing the DOM by id, so callers
+ // (e.g. AddDocumentDropdown) can trigger uploads through context rather
+ // than reaching across scopes.
+ const filesInputRef = useRef<HTMLInputElement | null>(null);
+ const folderInputRef = useRef<HTMLInputElement | null>(null);
const hasDocumentLimit = limits?.documents != null && limits.documents > 0;
const remainingDocuments = hasDocumentLimit
? limits.documents - (limits?.usage?.documents ?? 0)
@@ -248,6 +312,19 @@ export default function UploadZone({
dataroomFolderCreationPromiseRef.current = null;
}, [replicateDataroomFolders, dataroomId]);
+ // Expose imperative picker triggers via context so the +Add dropdown
+ // (rendered in the page toolbar, outside this zone) can open the
+ // OS file picker without reaching into the DOM via `getElementById`.
+ // While disabled, we deliberately don't register — callers will fall
+ // back to their no-zone path (e.g. opening the single-file modal).
+ useEffect(() => {
+ if (disabled) return;
+ return registerUploadTriggers({
+ openFilesPicker: () => filesInputRef.current?.click(),
+ openFolderPicker: () => folderInputRef.current?.click(),
+ });
+ }, [registerUploadTriggers, disabled]);
+
const fileSizeLimits = useMemo(
() =>
getFileSizeLimits({
@@ -347,6 +424,150 @@ export default function UploadZone({
? `datarooms/${dataroomId}/folders`
: "folders";
+ // Shared bulk-folder-create helper used by both the drag-drop walker and the
+ // `<input webkitdirectory>` picker. Performs the same API calls, analytics,
+ // and SWR cache invalidation regardless of how the folder list was sourced.
+ const createFoldersForUpload = useCallback(
+ async (
+ allFolders: BulkFolderRequestItem[],
+ ): Promise<{
+ dataroomByTemp: Map<string, BulkFolderResultItem>;
+ mainDocsByTemp: Map<string, BulkFolderResultItem>;
+ dataroomFolderInMainDocsPath?: string;
+ } | null> => {
+ let dataroomByTemp = new Map<string, BulkFolderResultItem>();
+ let mainDocsByTemp = new Map<string, BulkFolderResultItem>();
+ let dataroomFolderInMainDocsPath: string | undefined;
+
+ const teamId = teamInfo?.currentTeam?.id;
+ if (!teamId) {
+ setRejectedFiles((prev) => [
+ { fileName: "Unknown Team", message: "Team Id not found" },
+ ...prev,
+ ]);
+ return null;
+ }
+
+ const rootPathForApi =
+ folderPathName && folderPathName.length > 0
+ ? "/" + folderPathName
+ : "/";
+
+ if (allFolders.length === 0) {
+ if (!replicateDataroomFolders && dataroomId && dataroomName) {
+ dataroomFolderInMainDocsPath = await getOrCreateDataroomFolder();
+ }
+ return {
+ dataroomByTemp,
+ mainDocsByTemp,
+ dataroomFolderInMainDocsPath,
+ };
+ }
+
+ try {
+ if (dataroomId) {
+ // Replicated copies in main docs always live at the team root,
+ // regardless of where in the dataroom the user dropped the tree.
+ const tasks: Promise<void>[] = [
+ bulkCreateFoldersChunked({
+ url: `/api/teams/${teamId}/datarooms/${dataroomId}/folders/bulk`,
+ rootPath: rootPathForApi,
+ folders: allFolders,
+ }).then((rows) => {
+ dataroomByTemp = new Map(rows.map((r) => [r.tempId, r]));
+ }),
+ ];
+ if (replicateDataroomFolders) {
+ tasks.push(
+ bulkCreateFoldersChunked({
+ url: `/api/teams/${teamId}/folders/bulk`,
+ rootPath: "/",
+ folders: allFolders,
+ }).then((rows) => {
+ mainDocsByTemp = new Map(rows.map((r) => [r.tempId, r]));
+ }),
+ );
+ } else if (dataroomName) {
+ dataroomFolderInMainDocsPath = await getOrCreateDataroomFolder();
+ }
+ await Promise.all(tasks);
+ } else {
+ const rows = await bulkCreateFoldersChunked({
+ url: `/api/teams/${teamId}/folders/bulk`,
+ rootPath: rootPathForApi,
+ folders: allFolders,
+ });
+ mainDocsByTemp = new Map(rows.map((r) => [r.tempId, r]));
+ }
+
+ analytics.capture("Folder Added (bulk)", {
+ count: allFolders.length,
+ dataroomId: dataroomId,
+ replicated: dataroomId ? replicateDataroomFolders : undefined,
+ });
+
+ // Broad one-shot revalidation of every cached folder/document key
+ // for this scope. See the original drag-drop branch for a longer
+ // rationale — this short-circuits the SWR cache staleness that
+ // otherwise lingers for deep paths after a bulk create.
+ const isDataroomFolderKey = (key: unknown) =>
+ typeof key === "string" &&
+ dataroomId !== undefined &&
+ (key.startsWith(
+ `/api/teams/${teamId}/datarooms/${dataroomId}/folders`,
+ ) ||
+ key.startsWith(
+ `/api/teams/${teamId}/datarooms/${dataroomId}/folder-documents`,
+ ) ||
+ key.startsWith(
+ `/api/teams/${teamId}/datarooms/${dataroomId}/documents`,
+ ));
+ const isMainDocsFolderKey = (key: unknown) =>
+ typeof key === "string" &&
+ (key.startsWith(`/api/teams/${teamId}/folders`) ||
+ key.startsWith(`/api/teams/${teamId}/folder-documents`) ||
+ key === `/api/teams/${teamId}/documents`);
+
+ if (dataroomId) {
+ mutate(isDataroomFolderKey);
+ if (replicateDataroomFolders) mutate(isMainDocsFolderKey);
+ } else {
+ mutate(isMainDocsFolderKey);
+ }
+
+ if (!replicateDataroomFolders && dataroomId && dataroomName) {
+ dataroomFolderInMainDocsPath = await getOrCreateDataroomFolder();
+ }
+
+ return {
+ dataroomByTemp,
+ mainDocsByTemp,
+ dataroomFolderInMainDocsPath,
+ };
+ } catch (error) {
+ console.error("Bulk folder creation failed:", error);
+ setRejectedFiles((prev) => [
+ ...allFolders.map((f) => ({
+ fileName: f.name,
+ message: "Failed to create the folder",
+ })),
+ ...prev,
+ ]);
+ return null;
+ }
+ },
+ [
+ teamInfo,
+ folderPathName,
+ dataroomId,
+ dataroomName,
+ replicateDataroomFolders,
+ getOrCreateDataroomFolder,
+ analytics,
+ setRejectedFiles,
+ ],
+ );
+
const onDropRejected = useCallback(
(rejectedFiles: FileRejection[]) => {
const hasTooManyFiles = rejectedFiles.some(({ errors }) =>
@@ -643,73 +864,108 @@ export default function UploadZone({
}
}
- const { complete } = await resumableUpload({
- file,
- onProgress: (bytesUploaded, _bytesTotal) => {
- fileBytesUploaded.set(file, bytesUploaded);
- 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("/")),
- });
+ // Files above the multipart threshold bypass the TUS Vercel
+ // function and PUT directly to S3 using pre-signed part URLs. TUS
+ // is still preferred for smaller files: each chunk is bounded by
+ // the function's `maxDuration`, but TUS's resumable behavior is
+ // valuable on flaky networks for the medium-file long tail.
+ const useMultipart =
+ process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT === "s3" &&
+ file.size > MULTIPART_SIZE_THRESHOLD;
+
+ let storageKey: string;
+ let storageFileName: string;
+ let storageFileType: string;
+ let storageNumPages: number;
+
+ if (useMultipart) {
+ const result = await multipartUpload({
+ file,
+ teamId: teamInfo?.currentTeam?.id as string,
+ numPages,
+ contentType: file.type,
+ onProgress: (bytesUploaded) => {
+ fileBytesUploaded.set(file, bytesUploaded);
+ emitUpdate();
+ },
+ });
+ storageKey = result.key;
+ storageFileName = result.fileName;
+ storageFileType = result.fileType;
+ storageNumPages = result.numPages;
+ } else {
+ const { complete } = await resumableUpload({
+ file,
+ onProgress: (bytesUploaded, _bytesTotal) => {
+ fileBytesUploaded.set(file, bytesUploaded);
+ 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;
+ const uploadResult = await complete;
+ storageKey = uploadResult.id;
+ storageFileName = uploadResult.fileName;
+ storageFileType = uploadResult.fileType;
+ storageNumPages = uploadResult.numPages;
+ }
- let contentType = uploadResult.fileType;
+ let contentType = storageFileType;
let supportedFileType = getSupportedContentType(contentType) ?? "";
if (
- uploadResult.fileName.endsWith(".dwg") ||
- uploadResult.fileName.endsWith(".dxf")
+ storageFileName.endsWith(".dwg") ||
+ storageFileName.endsWith(".dxf")
) {
supportedFileType = "cad";
- contentType = `image/vnd.${uploadResult.fileName.split(".").pop()}`;
+ contentType = `image/vnd.${storageFileName.split(".").pop()}`;
}
- if (uploadResult.fileName.endsWith(".xlsm")) {
+ if (storageFileName.endsWith(".xlsm")) {
supportedFileType = "sheet";
contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";
}
if (
- uploadResult.fileName.endsWith(".kml") ||
- uploadResult.fileName.endsWith(".kmz")
+ storageFileName.endsWith(".kml") ||
+ storageFileName.endsWith(".kmz")
) {
supportedFileType = "map";
- contentType = `application/vnd.google-earth.${uploadResult.fileName.endsWith(".kml") ? "kml+xml" : "kmz"}`;
+ contentType = `application/vnd.google-earth.${storageFileName.endsWith(".kml") ? "kml+xml" : "kmz"}`;
}
if (
- uploadResult.fileName.endsWith(".tif") ||
- uploadResult.fileName.endsWith(".tiff")
+ storageFileName.endsWith(".tif") ||
+ storageFileName.endsWith(".tiff")
) {
supportedFileType = "other";
contentType = "image/tiff";
}
- if (uploadResult.fileName.endsWith(".ecw")) {
+ if (storageFileName.endsWith(".ecw")) {
supportedFileType = "other";
contentType = "image/x-ecw";
}
- if (uploadResult.fileName.endsWith(".bak")) {
+ if (storageFileName.endsWith(".bak")) {
supportedFileType = "other";
contentType = "application/x-bak";
}
const documentData: DocumentData = {
- key: uploadResult.id,
+ key: storageKey,
supportedFileType: supportedFileType,
name: file.name,
storageType: DocumentStorageType.S3_PATH,
@@ -723,7 +979,7 @@ export default function UploadZone({
const response = await createDocument({
documentData,
teamId: teamInfo?.currentTeam?.id as string,
- numPages: uploadResult.numPages,
+ numPages: storageNumPages,
folderPathName: fileUploadPathName,
});
@@ -1097,103 +1353,10 @@ export default function UploadZone({
const allFiles = walkResults.flatMap((r) => r.files);
// ----- Bulk-create folders (one request per scope, in parallel).
- let dataroomByTemp = new Map<string, BulkFolderResultItem>();
- let mainDocsByTemp = new Map<string, BulkFolderResultItem>();
-
- const rootPathForApi =
- folderPathName && folderPathName.length > 0
- ? "/" + folderPathName
- : "/";
-
- if (allFolders.length > 0) {
- try {
- if (dataroomId) {
- // Replicated copies in main docs always live at the team root,
- // regardless of where in the dataroom the user dropped the tree.
- const tasks: Promise<void>[] = [
- bulkCreateFoldersChunked({
- url: `/api/teams/${teamId}/datarooms/${dataroomId}/folders/bulk`,
- rootPath: rootPathForApi,
- folders: allFolders,
- }).then((rows) => {
- dataroomByTemp = new Map(rows.map((r) => [r.tempId, r]));
- }),
- ];
- if (replicateDataroomFolders) {
- tasks.push(
- bulkCreateFoldersChunked({
- url: `/api/teams/${teamId}/folders/bulk`,
- rootPath: "/",
- folders: allFolders,
- }).then((rows) => {
- mainDocsByTemp = new Map(rows.map((r) => [r.tempId, r]));
- }),
- );
- } else if (dataroomName) {
- await getOrCreateDataroomFolder();
- }
- await Promise.all(tasks);
- } else {
- const rows = await bulkCreateFoldersChunked({
- url: `/api/teams/${teamId}/folders/bulk`,
- rootPath: rootPathForApi,
- folders: allFolders,
- });
- mainDocsByTemp = new Map(rows.map((r) => [r.tempId, r]));
- }
-
- analytics.capture("Folder Added (bulk)", {
- count: allFolders.length,
- dataroomId: dataroomId,
- replicated: dataroomId ? replicateDataroomFolders : undefined,
- });
-
- // Broad one-shot revalidation of every cached folder/document key
- // for this scope. Targeted mutates only cover root + the user's
- // current view, which leaves deep paths the user navigated to
- // *during* bulk-create stuck on whatever empty/404 response SWR
- // fetched while the transaction was still in flight (SWR has
- // revalidateOnFocus: false + dedupingInterval: 30s, so the stale
- // cache otherwise persists). mutate(filterFn) only refetches keys
- // already in cache — typically 2–10 keys, fired once at the end of
- // bulkCreateFolders, not per file — so the "GET burst" cost is
- // negligible and bounded.
- const isDataroomFolderKey = (key: unknown) =>
- typeof key === "string" &&
- dataroomId !== undefined &&
- (key.startsWith(
- `/api/teams/${teamId}/datarooms/${dataroomId}/folders`,
- ) ||
- key.startsWith(
- `/api/teams/${teamId}/datarooms/${dataroomId}/folder-documents`,
- ) ||
- key.startsWith(
- `/api/teams/${teamId}/datarooms/${dataroomId}/documents`,
- ));
- const isMainDocsFolderKey = (key: unknown) =>
- typeof key === "string" &&
- (key.startsWith(`/api/teams/${teamId}/folders`) ||
- key.startsWith(`/api/teams/${teamId}/folder-documents`) ||
- key === `/api/teams/${teamId}/documents`);
-
- if (dataroomId) {
- mutate(isDataroomFolderKey);
- if (replicateDataroomFolders) mutate(isMainDocsFolderKey);
- } else {
- mutate(isMainDocsFolderKey);
- }
- } catch (error) {
- console.error("Bulk folder creation failed:", error);
- setRejectedFiles((prev) => [
- ...allFolders.map((f) => ({
- fileName: f.name,
- message: "Failed to create the folder",
- })),
- ...prev,
- ]);
- return [];
- }
- }
+ const bulkCreateResult = await createFoldersForUpload(allFolders);
+ if (!bulkCreateResult) return [];
+ const { dataroomByTemp, mainDocsByTemp, dataroomFolderInMainDocsPath } =
+ bulkCreateResult;
// Per-top-level folder count for the upload-drawer progress bar.
const parentByTemp = new Map(
@@ -1213,12 +1376,6 @@ export default function UploadZone({
);
}
- // ----- Resolve files (read content + annotate).
- let dataroomFolderInMainDocsPath: string | undefined;
- if (!replicateDataroomFolders && dataroomId && dataroomName) {
- dataroomFolderInMainDocsPath = await getOrCreateDataroomFolder();
- }
-
const filesToBePassedToOnDrop: FileWithPaths[] = [];
for (let i = 0; i < allFiles.length; i++) {
@@ -1321,15 +1478,277 @@ export default function UploadZone({
teamInfo,
dataroomId,
dataroomName,
- analytics,
setRejectedFiles,
acceptableDropZoneFileTypes,
- getOrCreateDataroomFolder,
hasDocumentLimit,
remainingDocuments,
fileSizeLimits,
replicateDataroomFolders,
onTraversalStart,
+ createFoldersForUpload,
+ ],
+ );
+
+ // Handle the `<input webkitdirectory>` change event: builds a folder tree
+ // from each File's `webkitRelativePath`, bulk-creates the folders, annotates
+ // the files with the same metadata produced by the drag-drop walker, then
+ // hands them off to `onDrop`. Used by the dedicated folder-upload control
+ // in the +Add menu since `<input type="file">` alone cannot preserve
+ // hierarchy.
+ const handleFolderPickerChange = useCallback(
+ async (event: React.ChangeEvent<HTMLInputElement>) => {
+ const rawFiles = Array.from(event.target.files ?? []);
+ // Reset value so the same folder can be re-picked.
+ event.target.value = "";
+
+ if (rawFiles.length === 0) return;
+
+ fileLimitTruncatedRef.current = false;
+ const maxFilesPerUpload = fileSizeLimits.maxFiles ?? 150;
+ const planDocumentLimit =
+ hasDocumentLimit && isFinite(remainingDocuments)
+ ? Math.max(0, remainingDocuments)
+ : Infinity;
+ const fileLimit = Math.min(maxFilesPerUpload, planDocumentLimit);
+
+ if (fileLimit <= 0) {
+ onUploadAborted?.();
+ return;
+ }
+
+ // Surface the top-level folder name(s) immediately so the progress
+ // drawer can render before we await the bulk-create round-trip.
+ const topLevelNames: string[] = [];
+ const seenTopLevel = new Set<string>();
+ for (const f of rawFiles) {
+ const rel = (f as any).webkitRelativePath || f.name;
+ const top = rel.split("/")[0];
+ if (top && !seenTopLevel.has(top)) {
+ seenTopLevel.add(top);
+ topLevelNames.push(top);
+ }
+ }
+ onTraversalStart?.(
+ topLevelNames.map((name) => ({ name, isFolder: true })),
+ );
+
+ // Filter against the plan's accept map BEFORE we create any folders
+ // server-side or sign any S3 uploads. The folder picker bypasses
+ // react-dropzone's `accept` validation that the drag-drop and
+ // multi-file flows rely on, so without this gate a free-plan user
+ // could pick a folder containing paid-only file types (e.g. .docx,
+ // .pptx) and walk the whole upload pipeline — bytes would PUT to S3
+ // and only be rejected at document-creation time. Also handles the
+ // Firefox empty-MIME folder-picker case the same way the drag-drop
+ // walker does so consistent files reach `onDrop`.
+ const inputFiles: File[] = [];
+ const relByFile = new Map<File, string>();
+ const rejectedTypePerTopLevel = new Map<
+ string,
+ { paths: string[]; supportedOnPaid: boolean }
+ >();
+ for (const raw of rawFiles) {
+ const rel = (raw as any).webkitRelativePath || raw.name;
+ const top = rel.split("/")[0] ?? raw.name;
+ const candidate = inferMimeFromExtensionMap(
+ raw,
+ acceptableDropZoneFileTypes,
+ );
+ if (!isAcceptableForPlan(candidate, acceptableDropZoneFileTypes)) {
+ const supportedOnPaid = isAcceptableForPlan(
+ candidate,
+ allAcceptableDropZoneMimeTypes,
+ );
+ const entry = rejectedTypePerTopLevel.get(top) ?? {
+ paths: [],
+ supportedOnPaid: false,
+ };
+ entry.paths.push(rel);
+ // Treat the group as "paid-only" if ANY rejected file in it would
+ // be accepted on a paid plan — surfaces the upgrade-friendly
+ // message instead of a generic "unsupported" one.
+ entry.supportedOnPaid = entry.supportedOnPaid || supportedOnPaid;
+ rejectedTypePerTopLevel.set(top, entry);
+ continue;
+ }
+ inputFiles.push(candidate);
+ relByFile.set(candidate, rel);
+ }
+
+ if (rejectedTypePerTopLevel.size > 0) {
+ const rejectedEntries: RejectedFile[] = [];
+ for (const [name, { paths, supportedOnPaid }] of rejectedTypePerTopLevel) {
+ rejectedEntries.push({
+ fileName: `${name}: ${paths.length} file${
+ paths.length !== 1 ? "s" : ""
+ } not uploaded`,
+ message:
+ isFree && !isTrial && supportedOnPaid
+ ? "File type not supported on free plan"
+ : "File type not supported",
+ reason: "plan-limit",
+ skippedFileNames: paths,
+ });
+ }
+ setRejectedFiles((prev) => [...rejectedEntries, ...prev]);
+ }
+
+ if (inputFiles.length === 0) {
+ onUploadAborted?.();
+ return;
+ }
+
+ // Build folder graph from webkitRelativePath segments. Driven by the
+ // validated `inputFiles` so folders that contained only rejected
+ // files don't get created server-side.
+ const folderTempIdByPath = new Map<string, string>();
+ const topLevelTempIdByName = new Map<string, string>();
+ const allFolders: BulkFolderRequestItem[] = [];
+
+ for (const file of inputFiles) {
+ const rel = relByFile.get(file)!;
+ const parts = rel.split("/").filter((s: string) => s.length > 0);
+ if (parts.length < 2) continue;
+ for (let i = 0; i < parts.length - 1; i++) {
+ const segment = parts[i];
+ if (isSystemFile(segment) || segment.trim() === "") continue;
+ const folderPath = parts.slice(0, i + 1).join("/");
+ if (folderTempIdByPath.has(folderPath)) continue;
+ const parentPath = i > 0 ? parts.slice(0, i).join("/") : null;
+ const parentTempId = parentPath
+ ? (folderTempIdByPath.get(parentPath) ?? null)
+ : null;
+ const tempId = crypto.randomUUID();
+ folderTempIdByPath.set(folderPath, tempId);
+ if (i === 0) topLevelTempIdByName.set(segment, tempId);
+ allFolders.push({ tempId, name: segment, parentTempId });
+ }
+ }
+
+ const bulkCreateResult = await createFoldersForUpload(allFolders);
+ if (!bulkCreateResult) {
+ onUploadAborted?.();
+ return;
+ }
+ const { dataroomByTemp, mainDocsByTemp, dataroomFolderInMainDocsPath } =
+ bulkCreateResult;
+
+ // Per-top-level folder count for the upload-drawer progress bar.
+ const parentByTemp = new Map(
+ allFolders.map((f) => [f.tempId, f.parentTempId ?? null]),
+ );
+ const folderCountByTopLevelTempId = new Map<string, number>();
+ for (const f of allFolders) {
+ let cur: string | null = f.parentTempId ?? null;
+ let topLevel = f.tempId;
+ while (cur) {
+ topLevel = cur;
+ cur = parentByTemp.get(cur) ?? null;
+ }
+ folderCountByTopLevelTempId.set(
+ topLevel,
+ (folderCountByTopLevelTempId.get(topLevel) ?? 0) + 1,
+ );
+ }
+
+ const annotated: FileWithPaths[] = [];
+ const skippedPerTopLevel = new Map<string, string[]>();
+
+ for (let i = 0; i < inputFiles.length; i++) {
+ const file = inputFiles[i] as FileWithPaths;
+ const rel = relByFile.get(file) ?? (file as any).webkitRelativePath ?? file.name;
+ const parts: string[] = rel
+ .split("/")
+ .filter((s: string) => s.length > 0);
+ const fileName = parts[parts.length - 1] ?? file.name;
+ if (isSystemFile(fileName)) continue;
+
+ if (annotated.length >= fileLimit) {
+ const top = parts[0] ?? file.name;
+ const list = skippedPerTopLevel.get(top) ?? [];
+ list.push(rel);
+ skippedPerTopLevel.set(top, list);
+ fileLimitTruncatedRef.current = true;
+ continue;
+ }
+
+ const parentFolderPath =
+ parts.length > 1 ? parts.slice(0, -1).join("/") : "";
+ const parentTempId = parentFolderPath
+ ? (folderTempIdByPath.get(parentFolderPath) ?? null)
+ : null;
+ const topLevelName = parts[0] ?? file.name;
+ const topLevelTempId = topLevelTempIdByName.get(topLevelName) ?? null;
+ const isFolderUpload = parts.length > 1;
+
+ file.path = rel;
+
+ const mainDocsFolderPath = parentTempId
+ ? stripLeadingSlash(mainDocsByTemp.get(parentTempId)?.path)
+ : folderPathName;
+ const dataroomFolderPath = parentTempId
+ ? stripLeadingSlash(dataroomByTemp.get(parentTempId)?.path)
+ : folderPathName;
+
+ if (!replicateDataroomFolders && dataroomId && dataroomName) {
+ file.whereToUploadPath = dataroomFolderInMainDocsPath;
+ } else {
+ file.whereToUploadPath = mainDocsFolderPath;
+ }
+ file.dataroomUploadPath = dataroomId ? dataroomFolderPath : undefined;
+
+ file.topLevelItemName = topLevelName;
+ file.topLevelItemIsFolder = isFolderUpload;
+ if (topLevelTempId) {
+ file.topLevelItemFolderCount =
+ folderCountByTopLevelTempId.get(topLevelTempId) ?? 0;
+ const topLevelDataroom = dataroomByTemp.get(topLevelTempId);
+ const topLevelMainDocs = mainDocsByTemp.get(topLevelTempId);
+ file.topLevelItemFolderPath = dataroomId
+ ? stripLeadingSlash(topLevelDataroom?.path)
+ : stripLeadingSlash(topLevelMainDocs?.path);
+ file.topLevelDataroomFolderId = topLevelDataroom?.id;
+ }
+
+ annotated.push(file);
+ }
+
+ if (skippedPerTopLevel.size > 0) {
+ const skippedEntries: RejectedFile[] = [];
+ for (const [name, paths] of skippedPerTopLevel) {
+ skippedEntries.push({
+ fileName: `${name}: ${paths.length} file${paths.length !== 1 ? "s" : ""} not uploaded`,
+ message: "Document limit reached",
+ reason: "plan-limit",
+ skippedFileNames: paths,
+ });
+ }
+ setRejectedFiles((prev) => [...skippedEntries, ...prev]);
+ }
+
+ if (annotated.length === 0) {
+ onUploadAborted?.();
+ return;
+ }
+
+ await onDrop(annotated);
+ },
+ [
+ acceptableDropZoneFileTypes,
+ folderPathName,
+ dataroomId,
+ dataroomName,
+ replicateDataroomFolders,
+ fileSizeLimits,
+ hasDocumentLimit,
+ remainingDocuments,
+ isFree,
+ isTrial,
+ onDrop,
+ onTraversalStart,
+ onUploadAborted,
+ setRejectedFiles,
+ createFoldersForUpload,
],
);
@@ -1347,6 +1766,31 @@ export default function UploadZone({
noDragEventsBubbling: disabled,
});
+ // Forward the dropzone's internal input ref into our own ref alongside it,
+ // so dropzone's `open()` / cancel-detection paths keep working AND our
+ // context-based picker triggers can call `.click()` on the same node.
+ // `DropzoneInputProps` doesn't type the `ref` field that `getInputProps()`
+ // returns at runtime, so we narrow the shape explicitly here.
+ const dropzoneFilesInputProps = getInputProps() as ReturnType<
+ typeof getInputProps
+ > & {
+ ref?: React.Ref<HTMLInputElement>;
+ };
+ const setFilesInputNode = useCallback(
+ (node: HTMLInputElement | null) => {
+ filesInputRef.current = node;
+ const dropzoneRef = dropzoneFilesInputProps.ref;
+ if (typeof dropzoneRef === "function") {
+ (dropzoneRef as React.RefCallback<HTMLInputElement>)(node);
+ } else if (dropzoneRef) {
+ (
+ dropzoneRef as React.MutableRefObject<HTMLInputElement | null>
+ ).current = node;
+ }
+ },
+ [dropzoneFilesInputProps.ref],
+ );
+
return (
<div
{...getRootProps({ onClick: (evt) => evt.stopPropagation() })}
@@ -1364,12 +1808,31 @@ export default function UploadZone({
)}
>
<input
- {...getInputProps()}
+ {...dropzoneFilesInputProps}
+ ref={setFilesInputNode}
name="file"
id="upload-multi-files-zone"
className="sr-only"
/>
+ {/* Dedicated folder picker (preserves directory hierarchy via
+ `webkitRelativePath`). Triggered programmatically from the +Add
+ menu; the dropzone's regular input above keeps flat-file behavior.
+ `webkitdirectory` / `directory` are non-standard so we spread them
+ past the typed props. */}
+ <input
+ ref={folderInputRef}
+ type="file"
+ multiple
+ id="upload-folder-zone"
+ className="sr-only"
+ onChange={handleFolderPickerChange}
+ disabled={disabled}
+ aria-hidden="true"
+ tabIndex={-1}
+ {...({ webkitdirectory: "", directory: "" } as Record<string, string>)}
+ />
+
{isDragActive && (
<div className="sticky top-1/2 z-50 -translate-y-1/2 px-2">
<div className="flex justify-center">
diff --git a/context/upload-progress-context.tsx b/context/upload-progress-context.tsx
index 39610c18..86f86093 100644
--- a/context/upload-progress-context.tsx
+++ b/context/upload-progress-context.tsx
@@ -8,12 +8,26 @@ import {
} from "react";
import { UploadNotificationDrawer } from "@/components/upload-notification";
-import {
+// Type-only import so adding the reverse runtime dependency (UploadZone
+// importing this context) doesn't create a runtime circular import.
+import type {
RejectedFile,
UploadBatchState,
UploadItemState,
} from "@/components/upload-zone";
+/**
+ * Imperative triggers exposed by a mounted `UploadZone` so that callers
+ * elsewhere in the tree (e.g. the +Add dropdown rendered in the page
+ * toolbar) can open the file/folder picker without reaching into the DOM
+ * via `document.getElementById`. `null` when no zone is currently mounted
+ * — callers should fall back gracefully (e.g. open the single-file modal).
+ */
+export interface UploadZoneTriggers {
+ openFilesPicker: () => void;
+ openFolderPicker: () => void;
+}
+
interface UploadProgressContextType {
uploadBatch: UploadBatchState | null;
setUploadBatch: React.Dispatch<
@@ -28,6 +42,19 @@ interface UploadProgressContextType {
cancelItem: (itemId: string) => void;
cancelledItemIds: Set<string>;
cancelledItemIdsRef: React.RefObject<Set<string>>;
+ /**
+ * Triggers registered by the currently-mounted `UploadZone`, or `null`
+ * if none is mounted in the visible tree (e.g. while the dataroom search
+ * results are showing instead of the items list).
+ */
+ uploadTriggers: UploadZoneTriggers | null;
+ /**
+ * Registers the given triggers and returns an unregister function.
+ * Last-mount-wins; the unregister fn only clears state if the currently
+ * registered object is still the same one we registered (so a late
+ * unmount can't wipe out a newer registration).
+ */
+ registerUploadTriggers: (triggers: UploadZoneTriggers) => () => void;
}
const UploadProgressContext = createContext<UploadProgressContextType | null>(
@@ -63,6 +90,23 @@ export function UploadProgressProvider({
const cancelledItemIdsRef = useRef(cancelledItemIds);
cancelledItemIdsRef.current = cancelledItemIds;
+ const [uploadTriggers, setUploadTriggers] =
+ useState<UploadZoneTriggers | null>(null);
+
+ const registerUploadTriggers = useCallback(
+ (triggers: UploadZoneTriggers) => {
+ setUploadTriggers(triggers);
+ return () => {
+ // Identity guard: only clear if the same object is still registered.
+ // Prevents a late unmount from wiping out a newer registration.
+ setUploadTriggers((current) =>
+ current === triggers ? null : current,
+ );
+ };
+ },
+ [],
+ );
+
const addCancelFn = useCallback((fn: () => void) => {
cancelFnsRef.current.push(fn);
setHasCancelFns(true);
@@ -168,6 +212,8 @@ export function UploadProgressProvider({
cancelItem,
cancelledItemIds,
cancelledItemIdsRef,
+ uploadTriggers,
+ registerUploadTriggers,
}),
[
uploadBatch,
@@ -178,6 +224,8 @@ export function UploadProgressProvider({
addCancelFn,
cancelItem,
cancelledItemIds,
+ uploadTriggers,
+ registerUploadTriggers,
],
);
diff --git a/lib/files/multipart-upload.ts b/lib/files/multipart-upload.ts
new file mode 100644
index 00000000..a9dc9d2d
--- /dev/null
+++ b/lib/files/multipart-upload.ts
@@ -0,0 +1,231 @@
+import { newId } from "@/lib/id-helper";
+import type {
+ MultipartCompleteRequest,
+ MultipartGetPartUrlsRequest,
+ MultipartInitiateRequest,
+} from "@/lib/zod/schemas/multipart";
+
+/**
+ * Direct-to-S3 multipart upload with per-part progress reporting.
+ *
+ * Drives the same `/api/file/s3/multipart` endpoint that
+ * `lib/files/put-file.ts` already uses for the single-file modal flow, but
+ * exposes a streaming `onProgress` callback so the bulk upload zone can keep
+ * its byte-level progress UI when the TUS function path is bypassed for
+ * large files.
+ *
+ * Three reasons for a separate helper instead of extending `putFile`:
+ * - Need XHR `xhr.upload.onprogress` to surface per-part bytes.
+ * - Caller (UploadZone) already has `numPages` precomputed — re-running
+ * `getPagesCount` here would duplicate the PDF parse for every batch.
+ * - Caller signals upload failure into per-file rejected lists, so a single
+ * throw fits its existing error handler without a fallback dance.
+ */
+
+const PART_SIZE = 10 * 1024 * 1024; // 10 MB
+const MAX_PARALLEL_PARTS = 5;
+const MULTIPART_ENDPOINT = "/api/file/s3/multipart";
+
+export type MultipartUploadResult = {
+ /** S3 object key — what `documentData.key` should be set to. */
+ key: string;
+ /** Slugified file name returned by the multipart endpoint. */
+ fileName: string;
+ fileType: string;
+ numPages: number;
+ fileSize: number;
+};
+
+export type MultipartUploadParams = {
+ file: File;
+ teamId: string;
+ numPages: number;
+ /** Pre-existing doc id; one is generated when omitted. */
+ docId?: string;
+ /** Override the `File`'s detected MIME (e.g. Firefox-fixed type). */
+ contentType?: string;
+ onProgress?: (bytesUploaded: number, bytesTotal: number) => void;
+ signal?: AbortSignal;
+};
+
+/** Threshold above which UploadZone should prefer multipart over TUS. */
+export const MULTIPART_SIZE_THRESHOLD = 100 * 1024 * 1024;
+
+export async function multipartUpload({
+ file,
+ teamId,
+ numPages,
+ docId,
+ contentType,
+ onProgress,
+ signal,
+}: MultipartUploadParams): Promise<MultipartUploadResult> {
+ const resolvedDocId = docId ?? newId("doc");
+ const resolvedContentType = contentType ?? file.type;
+ const baseUrl = process.env.NEXT_PUBLIC_BASE_URL ?? "";
+
+ const initiateBody: MultipartInitiateRequest = {
+ action: "initiate",
+ fileName: file.name,
+ contentType: resolvedContentType,
+ teamId,
+ docId: resolvedDocId,
+ };
+
+ const initiateResponse = await fetch(`${baseUrl}${MULTIPART_ENDPOINT}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(initiateBody),
+ signal,
+ });
+
+ if (!initiateResponse.ok) {
+ throw new Error(
+ `Failed to initiate multipart upload (${initiateResponse.status})`,
+ );
+ }
+
+ const { uploadId, key, fileName } = (await initiateResponse.json()) as {
+ uploadId: string;
+ key: string;
+ fileName: string;
+ };
+
+ const partUrlsBody: MultipartGetPartUrlsRequest = {
+ action: "get-part-urls",
+ fileName: file.name,
+ contentType: resolvedContentType,
+ teamId,
+ docId: resolvedDocId,
+ uploadId,
+ fileSize: file.size,
+ partSize: PART_SIZE,
+ };
+
+ const partUrlsResponse = await fetch(`${baseUrl}${MULTIPART_ENDPOINT}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(partUrlsBody),
+ signal,
+ });
+
+ if (!partUrlsResponse.ok) {
+ throw new Error(
+ `Failed to get multipart part URLs (${partUrlsResponse.status})`,
+ );
+ }
+
+ const { urls } = (await partUrlsResponse.json()) as {
+ urls: { partNumber: number; url: string }[];
+ };
+
+ // Aggregate progress across concurrently-uploading parts. Each part's XHR
+ // reports its own loaded bytes; we sum every part's latest snapshot to
+ // derive the file's total bytesUploaded.
+ const partBytes = new Map<number, number>();
+ const reportProgress = () => {
+ if (!onProgress) return;
+ let total = 0;
+ for (const v of partBytes.values()) total += v;
+ if (total > file.size) total = file.size;
+ onProgress(total, file.size);
+ };
+
+ const uploadPart = ({
+ partNumber,
+ url,
+ }: {
+ partNumber: number;
+ url: string;
+ }) =>
+ new Promise<{ PartNumber: number; ETag: string }>((resolve, reject) => {
+ const start = (partNumber - 1) * PART_SIZE;
+ const end = Math.min(start + PART_SIZE, file.size);
+ const chunk = file.slice(start, end);
+
+ const xhr = new XMLHttpRequest();
+ xhr.open("PUT", url, true);
+
+ xhr.upload.onprogress = (e) => {
+ if (e.lengthComputable) {
+ partBytes.set(partNumber, e.loaded);
+ reportProgress();
+ }
+ };
+ xhr.onload = () => {
+ if (xhr.status >= 200 && xhr.status < 300) {
+ const etag = xhr.getResponseHeader("ETag");
+ if (!etag) {
+ reject(new Error(`Missing ETag in response for part ${partNumber}`));
+ return;
+ }
+ // Force part to its full chunk size — onprogress can stop short of
+ // 100% on some browsers/networks even when the upload succeeded.
+ partBytes.set(partNumber, chunk.size);
+ reportProgress();
+ resolve({ PartNumber: partNumber, ETag: etag });
+ } else {
+ reject(
+ new Error(
+ `Failed to upload part ${partNumber} (status ${xhr.status})`,
+ ),
+ );
+ }
+ };
+ xhr.onerror = () =>
+ reject(new Error(`Network error while uploading part ${partNumber}`));
+ xhr.onabort = () =>
+ reject(new Error(`Upload of part ${partNumber} was aborted`));
+
+ if (signal) {
+ if (signal.aborted) {
+ xhr.abort();
+ } else {
+ signal.addEventListener("abort", () => xhr.abort(), { once: true });
+ }
+ }
+
+ xhr.send(chunk);
+ });
+
+ const parts: { PartNumber: number; ETag: string }[] = [];
+ for (let i = 0; i < urls.length; i += MAX_PARALLEL_PARTS) {
+ const batch = urls.slice(i, i + MAX_PARALLEL_PARTS);
+ const batchResults = await Promise.all(batch.map(uploadPart));
+ parts.push(...batchResults);
+ }
+
+ const completeBody: MultipartCompleteRequest = {
+ action: "complete",
+ fileName: file.name,
+ contentType: resolvedContentType,
+ teamId,
+ docId: resolvedDocId,
+ uploadId,
+ parts,
+ };
+
+ const completeResponse = await fetch(`${baseUrl}${MULTIPART_ENDPOINT}`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(completeBody),
+ signal,
+ });
+
+ if (!completeResponse.ok) {
+ throw new Error(
+ `Failed to complete multipart upload (${completeResponse.status})`,
+ );
+ }
+
+ // Final flush in case the last part didn't fire 100% before resolving.
+ if (onProgress) onProgress(file.size, file.size);
+
+ return {
+ key,
+ fileName,
+ fileType: resolvedContentType,
+ numPages,
+ fileSize: file.size,
+ };
+}
diff --git a/pages/api/file/s3/multipart.ts b/pages/api/file/s3/multipart.ts
index 63f9bbfc..62b5dc06 100644
--- a/pages/api/file/s3/multipart.ts
+++ b/pages/api/file/s3/multipart.ts
@@ -10,15 +10,30 @@ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { getServerSession } from "next-auth";
import path from "node:path";
-import { ONE_HOUR, ONE_SECOND } from "@/lib/constants";
+import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";
+import { getLimits } from "@/ee/limits/server";
+import {
+ FREE_PLAN_ACCEPTED_FILE_TYPES,
+ ONE_HOUR,
+ ONE_SECOND,
+ SUPPORTED_DOCUMENT_MIME_TYPES,
+} from "@/lib/constants";
import { getTeamS3ClientAndConfig } from "@/lib/files/aws-client";
import { buildContentDisposition, safeSlugify } from "@/lib/utils";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
+import {
+ getFileSizeLimit,
+ getFileSizeLimits,
+} from "@/lib/utils/get-file-size-limits";
import { MultipartUploadSchema } from "@/lib/zod/schemas/multipart";
import { authOptions } from "../../auth/[...nextauth]";
+const FREE_PLAN = "free";
+const FREE_TRIAL_PLAN = "free+drtrial";
+const BYTES_PER_MEGABYTE = 1024 * 1024;
+
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
@@ -48,24 +63,106 @@ export default async function handler(
const data = validationResult.data;
const { action, fileName, contentType, teamId, docId } = data;
+ const userId = (session.user as CustomUser).id;
- // Verify team access
+ // Verify team access (and grab `plan` for the upload-time plan/size gates
+ // applied below). `initiate` and `get-part-urls` are the points at which
+ // server resources (multipart upload id, pre-signed PUT URLs) are issued,
+ // so the gates run there; `complete` only ratifies an already-uploaded
+ // object and doesn't need to re-run them.
const team = await prisma.team.findUnique({
where: {
id: teamId,
users: {
some: {
- userId: (session.user as CustomUser).id,
+ userId,
},
},
},
- select: { id: true },
+ select: { id: true, plan: true },
});
if (!team) {
return res.status(403).end("Unauthorized to access this team");
}
+ if (action === "initiate" || action === "get-part-urls") {
+ const [limits, teamIsPaused] = await Promise.all([
+ getLimits({ teamId, userId }),
+ isTeamPausedById(teamId),
+ ]);
+
+ if (teamIsPaused) {
+ return res.status(403).json({
+ error:
+ "Team is currently paused. New document uploads are not available.",
+ });
+ }
+
+ const documentLimit = limits.documents;
+ if (
+ typeof documentLimit === "number" &&
+ Number.isFinite(documentLimit) &&
+ limits.usage.documents >= documentLimit
+ ) {
+ return res.status(403).json({
+ error: "You have reached the team document limit",
+ });
+ }
+
+ const isFree =
+ team.plan === FREE_PLAN || team.plan === FREE_TRIAL_PLAN;
+ const isTrial = team.plan.includes("drtrial");
+
+ // Plan-eligibility gate. The client-side dropzone enforces the same
+ // rule, but the folder picker bypasses dropzone and the multipart
+ // endpoint signs PUT URLs that S3 will accept independently of any
+ // later document-creation check — so we must re-enforce server-side.
+ if (!SUPPORTED_DOCUMENT_MIME_TYPES.includes(contentType)) {
+ return res.status(415).json({
+ error: `File type ${contentType} is not supported`,
+ });
+ }
+ if (
+ isFree &&
+ !isTrial &&
+ !(contentType in FREE_PLAN_ACCEPTED_FILE_TYPES)
+ ) {
+ return res.status(415).json({
+ error: `File type ${contentType} is not available on the free plan`,
+ });
+ }
+
+ if (action === "get-part-urls") {
+ const teamFileSizeLimitConfig: Parameters<
+ typeof getFileSizeLimits
+ >[0]["limits"] =
+ "fileSizeLimits" in limits &&
+ typeof limits.fileSizeLimits === "object" &&
+ limits.fileSizeLimits !== null
+ ? {
+ fileSizeLimits: limits.fileSizeLimits as Record<
+ string,
+ number | undefined
+ >,
+ }
+ : undefined;
+ const fileSizeLimits = getFileSizeLimits({
+ limits: teamFileSizeLimitConfig,
+ isFree,
+ isTrial,
+ });
+ const fileSizeLimitMb = getFileSizeLimit(contentType, fileSizeLimits);
+ const fileSizeLimitBytes = fileSizeLimitMb * BYTES_PER_MEGABYTE;
+
+ if (data.fileSize > fileSizeLimitBytes) {
+ return res.status(413).json({
+ error: `File size too big for ${contentType} (max. ${fileSizeLimitMb} MB)`,
+ });
+ }
+ }
+ }
+
// Get the basename and extension for the file
const { name, ext } = path.parse(fileName);
const slugifiedName = safeSlugify(name) + ext;
diff --git a/pages/datarooms/[id]/documents/[...name].tsx b/pages/datarooms/[id]/documents/[...name].tsx
index 260e911c..710f099a 100644
--- a/pages/datarooms/[id]/documents/[...name].tsx
+++ b/pages/datarooms/[id]/documents/[...name].tsx
@@ -3,7 +3,7 @@ import { useRouter } from "next/router";
import { useState } from "react";
import { useTeam } from "@/context/team-context";
-import { ArrowUpDownIcon, FolderPlusIcon, PlusIcon } from "lucide-react";
+import { ArrowUpDownIcon } from "lucide-react";
import {
useDataroom,
@@ -19,9 +19,8 @@ import { DataroomItemsList } from "@/components/datarooms/dataroom-items-list";
import { DataroomSearchResults } from "@/components/datarooms/dataroom-search-results";
import { SidebarFolderTree } from "@/components/datarooms/folders";
import { DataroomSortableList } from "@/components/datarooms/sortable/sortable-list";
-import { AddDocumentModal } from "@/components/documents/add-document-modal";
+import { AddDocumentDropdown } from "@/components/documents/add-document-dropdown";
import { LoadingDocuments } from "@/components/documents/loading-document";
-import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
import { SearchBoxPersisted } from "@/components/search-box";
import { Button } from "@/components/ui/button";
@@ -77,44 +76,11 @@ export default function Documents() {
</div>
<div className="flex shrink-0 items-center gap-x-2">
{!dataroom?.isFrozen && (
- <>
- <AddDocumentModal
- isDataroom={true}
- dataroomId={dataroom?.id}
- key={1}
- >
- <Button
- size="sm"
- className="group flex items-center justify-start gap-x-1 whitespace-nowrap px-2 text-left sm:gap-x-3 sm:px-3"
- title="Add Document"
- >
- <PlusIcon
- className="h-4 w-4 shrink-0 sm:h-5 sm:w-5"
- aria-hidden="true"
- />
- <span className="text-xs sm:text-sm">
- Add Document
- </span>
- </Button>
- </AddDocumentModal>
- <AddFolderModal
- isDataroom={true}
- dataroomId={dataroom?.id}
- key={2}
- >
- <Button
- size="sm"
- variant="outline"
- className="group flex shrink-0 items-center justify-start gap-x-3 whitespace-nowrap px-3 text-left"
- >
- <FolderPlusIcon
- className="h-5 w-5 shrink-0"
- aria-hidden="true"
- />
- <span>Add Folder</span>
- </Button>
- </AddFolderModal>
- </>
+ <AddDocumentDropdown
+ isDataroom={true}
+ dataroomId={dataroom?.id}
+ size="sm"
+ />
)}
<div id="dataroom-reordering-action" className="shrink-0">
{!isReordering && !dataroom?.isFrozen ? (
diff --git a/pages/datarooms/[id]/documents/index.tsx b/pages/datarooms/[id]/documents/index.tsx
index e656fbd4..8af29c02 100644
--- a/pages/datarooms/[id]/documents/index.tsx
+++ b/pages/datarooms/[id]/documents/index.tsx
@@ -3,12 +3,7 @@ import { useRouter } from "next/router";
import { useState } from "react";
import { useTeam } from "@/context/team-context";
-import {
- ArrowUpDownIcon,
- CircleHelpIcon,
- FolderPlusIcon,
- PlusIcon,
-} from "lucide-react";
+import { ArrowUpDownIcon, CircleHelpIcon } from "lucide-react";
import {
useDataroom,
@@ -23,12 +18,10 @@ import { DataroomItemsList } from "@/components/datarooms/dataroom-items-list";
import { DataroomSearchResults } from "@/components/datarooms/dataroom-search-results";
import { SidebarFolderTree } from "@/components/datarooms/folders";
import { DataroomSortableList } from "@/components/datarooms/sortable/sortable-list";
-import { AddDocumentModal } from "@/components/documents/add-document-modal";
+import { AddDocumentDropdown } from "@/components/documents/add-document-dropdown";
import { LoadingDocuments } from "@/components/documents/loading-document";
-import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
import { SearchBoxPersisted } from "@/components/search-box";
-import { Button } from "@/components/ui/button";
import { ResponsiveButton } from "@/components/ui/responsive-button";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { BadgeTooltip } from "@/components/ui/tooltip";
@@ -99,40 +92,11 @@ export default function Documents() {
</div>
<div className="flex shrink-0 items-center gap-x-2">
{!dataroom?.isFrozen && (
- <>
- <AddDocumentModal
- isDataroom={true}
- dataroomId={dataroom?.id}
- key={1}
- >
- <Button
- size="sm"
- className="group flex items-center justify-start gap-x-1 whitespace-nowrap px-2 text-left sm:gap-x-3 sm:px-3"
- title="Add Document"
- >
- <PlusIcon
- className="h-4 w-4 shrink-0 sm:h-5 sm:w-5"
- aria-hidden="true"
- />
- <span className="text-xs sm:text-sm">
- Add Document
- </span>
- </Button>
- </AddDocumentModal>
-
- <AddFolderModal
- isDataroom={true}
- dataroomId={dataroom?.id}
- key={2}
- >
- <ResponsiveButton
- icon={<FolderPlusIcon className="h-5 w-5 shrink-0" />}
- text="Add Folder"
- size="sm"
- variant="outline"
- />
- </AddFolderModal>
- </>
+ <AddDocumentDropdown
+ isDataroom={true}
+ dataroomId={dataroom?.id}
+ size="sm"
+ />
)}
<div id="dataroom-reordering-action" className="shrink-0">
{!isReordering && !dataroom?.isFrozen ? (
diff --git a/pages/documents/index.tsx b/pages/documents/index.tsx
index 1a0357bb..5105c093 100644
--- a/pages/documents/index.tsx
+++ b/pages/documents/index.tsx
@@ -3,16 +3,15 @@ import { useRouter } from "next/router";
import Link from "next/link";
import { useTeam } from "@/context/team-context";
-import { EyeOffIcon, FolderPlusIcon, PlusIcon } from "lucide-react";
+import { EyeOffIcon } from "lucide-react";
import useDocuments, { useHiddenDocuments, useRootFolders } from "@/lib/swr/use-documents";
import { handleInvitationStatus } from "@/lib/utils";
-import { AddDocumentModal } from "@/components/documents/add-document-modal";
+import { AddDocumentDropdown } from "@/components/documents/add-document-dropdown";
import { DocumentsList } from "@/components/documents/documents-list";
import SortButton from "@/components/documents/filters/sort-button";
import { Pagination } from "@/components/documents/pagination";
-import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
import { SearchBoxPersisted } from "@/components/search-box";
import { Button } from "@/components/ui/button";
@@ -76,27 +75,7 @@ export default function Documents() {
</p>
</div>
<div className="flex items-center gap-x-2">
- <AddDocumentModal>
- <Button
- className="group flex flex-1 items-center justify-start gap-x-1 whitespace-nowrap px-1 text-left sm:gap-x-3 sm:px-3"
- title="Add Document"
- >
- <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
- <span className="text-xs sm:text-base">Add Document</span>
- </Button>
- </AddDocumentModal>
- <AddFolderModal>
- <Button
- size="icon"
- variant="outline"
- className="border-gray-500 bg-gray-50 hover:bg-gray-200 dark:bg-black hover:dark:bg-muted"
- >
- <FolderPlusIcon
- className="h-5 w-5 shrink-0"
- aria-hidden="true"
- />
- </Button>
- </AddFolderModal>
+ <AddDocumentDropdown variant="split" />
</div>
</section>
diff --git a/pages/documents/tree/[...name].tsx b/pages/documents/tree/[...name].tsx
index bfa15d99..8f51c7e1 100644
--- a/pages/documents/tree/[...name].tsx
+++ b/pages/documents/tree/[...name].tsx
@@ -1,13 +1,10 @@
import { useRouter } from "next/router";
import { useTeam } from "@/context/team-context";
-import { FolderPlusIcon, PlusIcon } from "lucide-react";
-import { AddDocumentModal } from "@/components/documents/add-document-modal";
+import { AddDocumentDropdown } from "@/components/documents/add-document-dropdown";
import { DocumentsList } from "@/components/documents/documents-list";
-import { AddFolderModal } from "@/components/folders/add-folder-modal";
import AppLayout from "@/components/layouts/app";
-import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { useFolder, useFolderDocuments } from "@/lib/swr/use-documents";
@@ -33,25 +30,7 @@ export default function DocumentTreePage() {
</p>
</div>
<div className="flex items-center gap-x-2">
- <AddDocumentModal>
- <Button className="gap-x-3 px-3" title="Add Document">
- <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
- <span>Add Document</span>
- </Button>
- </AddDocumentModal>
- <AddFolderModal>
- <Button
- // size="icon"
- variant="outline"
- className="gap-x-3 px-3"
- >
- <FolderPlusIcon
- className="h-5 w-5 shrink-0"
- aria-hidden="true"
- />
- <span>Add Folder</span>
- </Button>
- </AddFolderModal>
+ <AddDocumentDropdown variant="split" />
</div>
</section>