Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
replicate folder structure from Data Room to all documents
Ashish Viradiya5f0fc8f2bf84
diff --git a/components/upload-zone.tsx b/components/upload-zone.tsxindex 85d50557..e60cb789 100644--- a/components/upload-zone.tsx+++ b/components/upload-zone.tsx@@ -1,7 +1,11 @@import { useRouter } from "next/router";++import { useCallback, useMemo, useRef, useState } from "react";++import { useTeam } from "@/context/team-context";import { DocumentStorageType } from "@prisma/client";import { useSession } from "next-auth/react";@@ -9,21 +13,25 @@ import { DropEvent, FileRejection, useDropzone } from "react-dropzone";import { toast } from "sonner";import { mutate } from "swr";++import { useAnalytics } from "@/lib/analytics";import { SUPPORTED_DOCUMENT_MIME_TYPES } from "@/lib/constants";import { DocumentData, createDocument } from "@/lib/documents/create-document";import { resumableUpload } from "@/lib/files/tus-upload";+import { createFolderInBoth, createFolderInMainDocs, isSystemFile } from "@/lib/folders/create-folder";import { usePlan } from "@/lib/swr/use-billing";import useLimits from "@/lib/swr/use-limits";import { CustomUser } from "@/lib/types";import { cn } from "@/lib/utils";import { getSupportedContentType } from "@/lib/utils/get-content-type";-import {- getFileSizeLimit,- getFileSizeLimits,-} from "@/lib/utils/get-file-size-limits";+import { getFileSizeLimit, getFileSizeLimits } from "@/lib/utils/get-file-size-limits";import { getPagesCount } from "@/lib/utils/get-page-number-count";++++// Originally these mime values were directly used in the dropzone hook.// There was a solid reason to take them out of the scope, primarily to solve a browser compatibility issue to determine the file type when user dropped a folder.// you will figure out how this change helped to fix the compatibility issue once you have went through reading of `getFilesFromDropEvent` and `traverseFolder`@@ -433,6 +441,10 @@ export default function UploadZone({let files: FileWithPaths[] = [];+ if (isSystemFile(entry.name)) {+ return files;+ }+if (entry.isDirectory) {/*** Let's create the folder.@@ -463,55 +475,48 @@ export default function UploadZone({throw new Error("No team found");}- const response = await fetch(- `/api/teams/${teamInfo.currentTeam.id}/${endpointTargetType}`,- {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- name: entry.name, // as folderName- path: parentPathOfThisEntry ?? folderPathName,- }),- },- );-- if (!response.ok) {- const { message } = await response.json();- setRejectedFiles((prev) => [- {- fileName: entry.name,- message: message,- },- ...prev,- ]);- } else {- let {- parentFolderPath: parentFolderPath,- path: slugifiedPathNameOfThisEntryAfterFolderCreation,- } = await response.json();-- if (- slugifiedPathNameOfThisEntryAfterFolderCreation?.startsWith("/")- ) {- // Reason "/" is removed because our `createDocument` API needs `path` to not start with "/"- slugifiedPathNameOfThisEntryAfterFolderCreation =- slugifiedPathNameOfThisEntryAfterFolderCreation.slice(1);- }+ // Create folder in main documents if not in dataroom+ if (!dataroomId) {+ // Create folder in main documents only+ const { path: folderPath } = await createFolderInMainDocs({+ teamId: teamInfo.currentTeam.id,+ name: entry.name,+ path: parentPathOfThisEntry ?? folderPathName,+ });analytics.capture("Folder Added", { folderName: entry.name });- mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}?root=true`,- );- mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}`,++ const dirReader = (+ entry as FileSystemDirectoryEntry+ ).createReader();+ const subEntries = await new Promise<FileSystemEntry[]>(+ (resolve) => dirReader.readEntries(resolve),);- mutate(- `/api/teams/${teamInfo?.currentTeam?.id}/${endpointTargetType}${parentFolderPath}`,++ const filteredSubEntries = subEntries.filter(+ (subEntry) => !isSystemFile(subEntry.name),);+ for (const subEntry of filteredSubEntries) {+ files.push(+ ...(await traverseFolder(+ subEntry,+ folderPath.startsWith("/")+ ? folderPath.slice(1)+ : folderPath,+ )),+ );+ }+ } else {+ // Create folder in both dataroom and main documents+ const { dataroomPath } = await createFolderInBoth({+ teamId: teamInfo.currentTeam.id,+ dataroomId,+ name: entry.name,+ path: parentPathOfThisEntry ?? folderPathName,+ setRejectedFiles,+ analytics,+ });- // Now we are sure that folder is created at the backend and we can continue to traverse its child folders/files.const dirReader = (entry as FileSystemDirectoryEntry).createReader();@@ -519,16 +524,26 @@ export default function UploadZone({(resolve) => dirReader.readEntries(resolve),);- for (const subEntry of subEntries) {+ const filteredSubEntries = subEntries.filter(+ (subEntry) => !isSystemFile(subEntry.name),+ );++ for (const subEntry of filteredSubEntries) {files.push(...(await traverseFolder(subEntry,- slugifiedPathNameOfThisEntryAfterFolderCreation,+ dataroomPath.startsWith("/")+ ? dataroomPath.slice(1)+ : dataroomPath,)),);}}} catch (error) {+ console.error(+ "An error occurred while creating the folder: ",+ error,+ );setRejectedFiles((prev) => [{fileName: entry.name,@@ -538,6 +553,10 @@ export default function UploadZone({]);}} else if (entry.isFile) {+ if (isSystemFile(entry.name)) {+ return files;+ }+let file = await new Promise<FileWithPaths>((resolve) =>(entry as FileSystemFileEntry).file(resolve),);@@ -668,4 +687,4 @@ export default function UploadZone({{children}</div>);-}+}\ No newline at end of filediff --git a/lib/constants.ts b/lib/constants.tsindex 93c47776..0ea9a41a 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -412,3 +412,96 @@ export const EU_COUNTRY_CODES = ["SI","SK",];++++export const SYSTEM_FILES = [+ '.DS_Store',+ 'Thumbs.db',+ '.git',+ '.gitignore',+ '.svn',+ '.idea',+ '.vscode',+ 'node_modules',+ 'package-lock.json',+ 'yarn.lock',+ 'package.json',+ 'tsconfig.json',+ 'README.md',+ 'LICENSE',+ '.env',+ '.env.local',+ '.env.development',+ '.env.production',+ '.env.test',+ '.npmrc',+ '.yarnrc',+ '.editorconfig',+ '.prettierrc',+ '.eslintrc',+ '.babelrc',+ '.travis.yml',+ 'docker-compose.yml',+ 'Dockerfile',+ 'dockerfile',+ '.dockerignore',+ '.gitattributes',+ '.gitmodules',+ '.gitkeep',+ '.gitlab-ci.yml',+ '.circleci',+ '.github',+ '.husky',+ '.lintstagedrc',+ '.npmignore',+ '.yarn',+ '.pnp.js',+ '.pnp.cjs',+ '.pnp.mjs',+ '.pnp.loader.js',+ '.pnp.loader.cjs',+ '.pnp.loader.mjs',+ '.pnp.loader.json',+ '.pnp.loader.yaml',+ '.pnp.loader.yml',+ '.pnp.loader.toml',+ '.pnp.loader.ini',+ '.pnp.loader.jsx',+ '.pnp.loader.ts',+ '.pnp.loader.tsx',+ '.pnp.loader.vue',+ '.pnp.loader.svelte',+ '.pnp.loader.astro',+ '.pnp.loader.mdx',+ '.pnp.loader.md',+ '.pnp.loader.html',+ '.pnp.loader.css',+ '.pnp.loader.scss',+ '.pnp.loader.sass',+ '.pnp.loader.less',+ '.pnp.loader.styl',+ '.pnp.loader.stylus',+ '.pnp.loader.postcss',+ '.pnp.loader.json',+ '.pnp.loader.yaml',+ '.pnp.loader.yml',+ '.pnp.loader.toml',+ '.pnp.loader.ini',+ '.pnp.loader.jsx',+ '.pnp.loader.ts',+ '.pnp.loader.tsx',+ '.pnp.loader.vue',+ '.pnp.loader.svelte',+ '.pnp.loader.astro',+ '.pnp.loader.mdx',+ '.pnp.loader.md',+ '.pnp.loader.html',+ '.pnp.loader.css',+ '.pnp.loader.scss',+ '.pnp.loader.sass',+ '.pnp.loader.less',+ '.pnp.loader.styl',+ '.pnp.loader.stylus',+ '.pnp.loader.postcss',+];\ No newline at end of filediff --git a/lib/folders/create-folder.ts b/lib/folders/create-folder.tsnew file mode 100644index 00000000..036c86ab--- /dev/null+++ b/lib/folders/create-folder.ts@@ -0,0 +1,119 @@+import { mutate } from "swr";+import { SYSTEM_FILES } from "../constants";++export function isSystemFile(name: string): boolean {+ return SYSTEM_FILES.includes(name) || name.startsWith('.');+}++interface CreateFolderResponse {+ path: string;+ parentFolderPath?: string;+}++export async function createFolderInDataroom({+ teamId,+ dataroomId,+ name,+ path,+}: {+ teamId: string;+ dataroomId: string;+ name: string;+ path?: string;+}): Promise<CreateFolderResponse> {+ const response = await fetch(+ `/api/teams/${teamId}/datarooms/${dataroomId}/folders`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name,+ path,+ }),+ },+ );++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.message || "Failed to create folder in dataroom");+ }++ return response.json();+}++export async function createFolderInMainDocs({+ teamId,+ name,+ path,+}: {+ teamId: string;+ name: string;+ path?: string;+}): Promise<CreateFolderResponse> {+ const response = await fetch(`/api/teams/${teamId}/folders`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name,+ path,+ }),+ });++ if (!response.ok) {+ const error = await response.json();+ throw new Error(error.message || "Failed to create folder in main documents");+ }++ return response.json();+}++export async function createFolderInBoth({+ teamId,+ dataroomId,+ name,+ path,+ setRejectedFiles,+ analytics,+}: {+ teamId: string;+ dataroomId: string;+ name: string;+ path?: string;+ setRejectedFiles: (files: { fileName: string; message: string }[]) => void;+ analytics: any;+}): Promise<{ dataroomPath: string; mainDocsPath: string }> {+ try {+ const [dataroomResponse, mainDocsResponse] = await Promise.all([+ createFolderInDataroom({ teamId, dataroomId, name, path }),+ createFolderInMainDocs({ teamId, name, path }),+ ]);++ // Track analytics+ analytics.capture("Folder Added in dataroom", {+ folderName: name,+ });++ // Mutate dataroom folders+ mutate(`/api/teams/${teamId}/datarooms/${dataroomId}/folders?root=true`);+ mutate(`/api/teams/${teamId}/datarooms/${dataroomId}/folders`);+ mutate(`/api/teams/${teamId}/datarooms/${dataroomId}/folders/${dataroomResponse.path}`);++ return {+ dataroomPath: dataroomResponse.path,+ mainDocsPath: mainDocsResponse.path,+ };+ } catch (error) {+ console.error("An error occurred while creating the folder: ", error);+ setRejectedFiles([+ {+ fileName: name,+ message: error instanceof Error ? error.message : "Failed to create folder",+ },+ ]);+ throw error;+ }+}\ No newline at end of file