Skip to content

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

feat: add performance indexes

Marc Seitz36165c037b70
diff --git a/components/documents/document-stats-placeholder.tsx b/components/documents/document-stats-placeholder.tsx
new file mode 100644
index 00000000..675272ce
--- /dev/null
+++ b/components/documents/document-stats-placeholder.tsx
@@ -0,0 +1,71 @@
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+import { Switch } from "@/components/ui/switch";
+
+import StatsCard from "./stats-card";
+import StatsChartDummy from "./stats-chart-dummy";
+
+interface DocumentStatsPlaceholderProps {
+ numPages: number;
+ onCreateLink: () => void;
+}
+
+export default function DocumentStatsPlaceholder({
+ numPages,
+ onCreateLink,
+}: DocumentStatsPlaceholderProps) {
+ // Mock stats data for placeholder
+ const mockStatsData = {
+ stats: undefined,
+ loading: false,
+ error: null,
+ };
+
+ return (
+ <>
+ <div className="flex items-center justify-end space-x-2">
+ <Switch disabled={true} id="toggle-stats-placeholder" checked={false} />
+ <Label
+ htmlFor="toggle-stats-placeholder"
+ className="text-muted-foreground"
+ >
+ Exclude internal visits
+ </Label>
+ </div>
+
+ {/* Stats Chart Placeholder */}
+ <StatsChartDummy totalPagesMax={numPages} />
+
+ {/* Stats Card Placeholder */}
+ <div className="grid grid-cols-1 space-y-2 border-foreground/5 sm:grid-cols-3 sm:space-x-2 sm:space-y-0 lg:grid-cols-3 lg:space-x-3">
+ {[
+ { name: "Number of visits", value: "0", active: false },
+ { name: "Number of reactions", value: "0", active: false },
+ {
+ name: "Total average view duration",
+ value: "0",
+ unit: "seconds",
+ active: false,
+ },
+ ].map((stat, statIdx) => (
+ <div
+ key={statIdx}
+ className="rounded-lg border border-foreground/5 px-4 py-6 sm:px-6 lg:px-8"
+ >
+ <dt className="text-sm font-medium text-gray-500">{stat.name}</dt>
+ <dd className="mt-1 flex items-baseline justify-between md:block lg:flex">
+ <div className="flex items-baseline text-2xl font-semibold text-gray-400">
+ {stat.value}
+ {stat.unit && (
+ <span className="ml-2 text-sm font-medium text-gray-300">
+ {stat.unit}
+ </span>
+ )}
+ </div>
+ </dd>
+ </div>
+ ))}
+ </div>
+ </>
+ );
+}
diff --git a/components/documents/video-stats-placeholder.tsx b/components/documents/video-stats-placeholder.tsx
new file mode 100644
index 00000000..62a51d2f
--- /dev/null
+++ b/components/documents/video-stats-placeholder.tsx
@@ -0,0 +1,68 @@
+import { Button } from "@/components/ui/button";
+
+import VideoChartPlaceholder from "./video-chart-placeholder";
+
+interface VideoStatsPlaceholderProps {
+ length: number;
+ onCreateLink: () => void;
+}
+
+export default function VideoStatsPlaceholder({
+ length,
+ onCreateLink,
+}: VideoStatsPlaceholderProps) {
+ const formatTime = (seconds: number) => {
+ const minutes = Math.floor(seconds / 60);
+ const remainingSeconds = Math.floor(seconds % 60);
+ return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`;
+ };
+
+ const mockStats = [
+ {
+ name: "Total visits",
+ value: "0",
+ active: false,
+ },
+ {
+ name: "Watch time",
+ value: "0:00",
+ unit: "minutes",
+ active: false,
+ },
+ {
+ name: "Average view duration",
+ value: "0:00",
+ unit: "minutes",
+ active: false,
+ },
+ ];
+
+ return (
+ <div className="space-y-4">
+ {/* Video Chart Placeholder */}
+ <VideoChartPlaceholder length={length} />
+
+ {/* Stats Cards */}
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
+ {mockStats.map((stat, index) => (
+ <div
+ key={stat.name}
+ className="rounded-lg border border-foreground/5 px-4 py-6 sm:px-6 lg:px-8"
+ >
+ <dt className="text-sm font-medium text-gray-500">{stat.name}</dt>
+ <dd className="mt-1 flex items-baseline justify-between md:block lg:flex">
+ <div className="flex items-baseline text-2xl font-semibold text-gray-400">
+ {stat.value}
+ {stat.unit && (
+ <span className="ml-2 text-sm font-medium text-gray-300">
+ {stat.unit}
+ </span>
+ )}
+ </div>
+ </dd>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/lib/swr/use-document-overview.ts b/lib/swr/use-document-overview.ts
new file mode 100644
index 00000000..8fbf08c3
--- /dev/null
+++ b/lib/swr/use-document-overview.ts
@@ -0,0 +1,77 @@
+import { useRouter } from "next/router";
+
+import { useTeam } from "@/context/team-context";
+import useSWR from "swr";
+
+import { DocumentWithVersion } from "@/lib/types";
+import { fetcher } from "@/lib/utils";
+
+interface DocumentOverview {
+ document: DocumentWithVersion & {
+ hasPageLinks: boolean;
+ isEmpty: boolean;
+ primaryVersion: any;
+ };
+ limits: {
+ canAddLinks: boolean;
+ canAddDocuments: boolean;
+ canAddUsers: boolean;
+ };
+ featureFlags: {
+ annotations: boolean;
+ };
+ team: {
+ plan: string;
+ isTrial: boolean;
+ };
+ counts: {
+ links: number;
+ views: number;
+ };
+}
+
+export function useDocumentOverview() {
+ const router = useRouter();
+ const teamInfo = useTeam();
+
+ const { id } = router.query as {
+ id: string;
+ };
+
+ const { data, error, mutate } = useSWR<DocumentOverview>(
+ teamInfo?.currentTeam?.id &&
+ id &&
+ `/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(
+ id,
+ )}/overview`,
+ fetcher,
+ {
+ // Aggressive caching for fast loads
+ dedupingInterval: 30000,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ revalidateIfStale: false,
+ // Enable fast refresh for critical data
+ refreshInterval: 0,
+ onError: (err) => {
+ if (err.status === 404) {
+ router.replace("/documents");
+ }
+ },
+ },
+ );
+
+ return {
+ data,
+ document: data?.document,
+ primaryVersion: data?.document?.primaryVersion,
+ limits: data?.limits,
+ featureFlags: data?.featureFlags,
+ team: data?.team,
+ counts: data?.counts,
+ isEmpty: data?.document?.isEmpty || false,
+ loading: !error && !data,
+ error,
+ mutate,
+ };
+}
diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.ts
index f3ab8ccd..caa015d9 100644
--- a/lib/swr/use-document.ts
+++ b/lib/swr/use-document.ts
@@ -62,7 +62,11 @@ export function useDocumentLinks() {
id: string;
};
- const { data: links, error } = useSWR<LinkWithViews[]>(
+ const {
+ data: links,
+ error,
+ mutate,
+ } = useSWR<LinkWithViews[]>(
teamInfo?.currentTeam?.id &&
id &&
`/api/teams/${teamInfo?.currentTeam?.id}/documents/${encodeURIComponent(
@@ -78,6 +82,7 @@ export function useDocumentLinks() {
links,
loading: !error && !links,
error,
+ mutate,
};
}
diff --git a/pages/api/teams/[teamId]/documents/[id]/links.ts b/pages/api/teams/[teamId]/documents/[id]/links.ts
index 46d59846..a27e99f3 100644
--- a/pages/api/teams/[teamId]/documents/[id]/links.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/links.ts
@@ -26,54 +26,84 @@ export default async function handle(
const userId = (session.user as CustomUser).id;
try {
- const { document } = await getTeamWithUsersAndDocument({
- teamId,
- userId,
- docId,
- checkOwner: true,
- options: {
- select: {
- ownerId: true,
- id: true,
- links: {
- orderBy: {
- createdAt: "desc",
- },
- include: {
- views: {
- orderBy: {
- viewedAt: "desc",
- },
+ // First check if document has any links to avoid expensive query
+ const document = await prisma.document.findUnique({
+ where: {
+ id: docId,
+ teamId,
+ },
+ select: {
+ id: true,
+ ownerId: true,
+ _count: {
+ select: {
+ links: { where: { isArchived: false } },
+ },
+ },
+ },
+ });
+
+ if (!document) {
+ return res.status(404).json({ error: "Document not found" });
+ }
+
+ // Early return for documents with no links
+ if (document._count.links === 0) {
+ return res.status(200).json([]);
+ }
+
+ // Only fetch full link data if we have links
+ const { document: documentWithLinks } = await getTeamWithUsersAndDocument(
+ {
+ teamId,
+ userId,
+ docId,
+ checkOwner: true,
+ options: {
+ select: {
+ ownerId: true,
+ id: true,
+ links: {
+ where: { isArchived: false },
+ orderBy: {
+ createdAt: "desc",
},
- feedback: {
- select: {
- id: true,
- data: true,
+ include: {
+ views: {
+ orderBy: {
+ viewedAt: "desc",
+ },
},
- },
- customFields: {
- select: {
- orderIndex: true,
- label: true,
- identifier: true,
- placeholder: true,
- type: true,
- required: true,
+ feedback: {
+ select: {
+ id: true,
+ data: true,
+ },
},
- orderBy: {
- orderIndex: "asc",
+ customFields: {
+ select: {
+ orderIndex: true,
+ label: true,
+ identifier: true,
+ placeholder: true,
+ type: true,
+ required: true,
+ },
+ orderBy: {
+ orderIndex: "asc",
+ },
+ },
+ _count: {
+ select: { views: true },
},
- },
- _count: {
- select: { views: true },
},
},
},
},
},
- });
+ );
- let links = document!.links;
+ let links = documentWithLinks!.links;
// Decrypt the password for each link
if (links && links.length > 0) {
diff --git a/pages/api/teams/[teamId]/documents/[id]/overview.ts b/pages/api/teams/[teamId]/documents/[id]/overview.ts
new file mode 100644
index 00000000..99ff7c90
--- /dev/null
+++ b/pages/api/teams/[teamId]/documents/[id]/overview.ts
@@ -0,0 +1,210 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { getLimits } from "@/ee/limits/server";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import { getFeatureFlags } from "@/lib/featureFlags";
+import prisma from "@/lib/prisma";
+import { usePlan } from "@/lib/swr/use-billing";
+import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
+import { CustomUser } from "@/lib/types";
+
+// Helper function to serialize BigInt values to strings
+function serializeBigInt(obj: any): any {
+ if (obj === null || obj === undefined) {
+ return obj;
+ }
+
+ if (typeof obj === "bigint") {
+ return obj.toString();
+ }
+
+ if (Array.isArray(obj)) {
+ return obj.map(serializeBigInt);
+ }
+
+ if (typeof obj === "object") {
+ const serialized: any = {};
+ for (const key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ serialized[key] = serializeBigInt(obj[key]);
+ }
+ }
+ return serialized;
+ }
+
+ return obj;
+}
+
+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).end("Unauthorized");
+ }
+
+ const { teamId, id: docId } = req.query as {
+ teamId: string;
+ id: string;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ // First verify user has access to the team
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: { plan: true },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ // Parallel fetch of core data
+ const [document, limits, featureFlags] = await Promise.all([
+ prisma.document.findUnique({
+ where: {
+ id: docId,
+ teamId,
+ },
+ select: {
+ id: true,
+ name: true,
+ description: true,
+ file: true,
+ originalFile: true,
+ type: true,
+ contentType: true,
+ storageType: true,
+ numPages: true,
+ ownerId: true,
+ teamId: true,
+ assistantEnabled: true,
+ advancedExcelEnabled: true,
+ downloadOnly: true,
+ createdAt: true,
+ updatedAt: true,
+ folderId: true,
+ isExternalUpload: true,
+ versions: {
+ where: { isPrimary: true },
+ orderBy: { createdAt: "desc" },
+ take: 1,
+ },
+ folder: {
+ select: {
+ name: true,
+ path: true,
+ },
+ },
+ datarooms: {
+ select: {
+ dataroom: {
+ select: {
+ id: true,
+ name: true,
+ },
+ },
+ folder: {
+ select: {
+ id: true,
+ name: true,
+ path: true,
+ },
+ },
+ },
+ },
+ // Get counts without fetching full records
+ _count: {
+ select: {
+ links: { where: { isArchived: false } },
+ views: { where: { isArchived: false } },
+ },
+ },
+ },
+ }),
+ getLimits({ teamId, userId }),
+ getFeatureFlags({ teamId }),
+ ]);
+
+ if (!document || !document.versions || document.versions.length === 0) {
+ return res.status(404).json({
+ error: "Not Found",
+ message: "The requested document does not exist",
+ });
+ }
+
+ const primaryVersion = document.versions[0];
+ const hasLinks = document._count.links > 0;
+ const hasViews = document._count.views > 0;
+
+ // Check for page links only if needed
+ let hasPageLinks = false;
+ if (primaryVersion) {
+ const pageLinksCount = await prisma.documentPage.count({
+ where: {
+ versionId: primaryVersion.id,
+ pageLinks: {
+ not: "null" as any,
+ },
+ },
+ });
+ hasPageLinks = pageLinksCount > 0;
+ }
+
+ // Basic response for instant loading
+ const response = {
+ document: {
+ ...serializeBigInt(document),
+ primaryVersion: serializeBigInt(primaryVersion),
+ hasPageLinks,
+ isEmpty: !hasLinks && !hasViews, // Flag for empty state optimization
+ },
+ limits: {
+ canAddLinks: limits?.links
+ ? document._count.links < limits.links
+ : true,
+ canAddDocuments: limits?.documents ? true : true, // Simplified for this context
+ canAddUsers: limits?.users ? true : true,
+ },
+ featureFlags: {
+ annotations: featureFlags.annotations,
+ },
+ team: {
+ plan: team?.plan || "free",
+ isTrial: team?.plan.includes("drtrial") || false,
+ },
+ counts: {
+ links: document._count.links,
+ views: document._count.views,
+ },
+ };
+
+ // Set cache headers for faster subsequent loads
+ res.setHeader(
+ "Cache-Control",
+ "private, max-age=60, stale-while-revalidate=300",
+ );
+
+ return res.status(200).json(response);
+ } catch (error) {
+ console.error("Document overview error:", error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+}
diff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.ts
index ce2f45b0..7598be92 100644
--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts
@@ -1,5 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { View } from "@prisma/client";
import { getServerSession } from "next-auth/next";
@@ -11,8 +12,6 @@ import {
} from "@/lib/tinybird";
import { CustomUser } from "@/lib/types";
-import { authOptions } from "../../../../auth/[...nextauth]";
-
export default async function handle(
req: NextApiRequest,
res: NextApiResponse,
@@ -37,46 +36,66 @@ export default async function handle(
const userId = (session.user as CustomUser).id;
try {
+ // First check if document exists and get basic info
const document = await prisma.document.findUnique({
where: {
id: docId,
teamId,
},
- include: {
- views: true,
+ select: {
+ id: true,
+ teamId: true,
team: {
select: {
plan: true,
},
},
- },
- });
-
- const users = await prisma.user.findMany({
- where: {
- teams: {
- some: {
- teamId: teamId,
+ _count: {
+ select: {
+ views: { where: { isArchived: false } },
},
},
},
- select: {
- email: true,
- },
});
- const views = document?.views;
+ if (!document) {
+ return res.status(404).json({ error: "Document not found" });
+ }
- // if there are no views, return an empty array
- if (!views) {
+ // Early return for documents with no views - avoid expensive queries
+ if (document._count.views === 0) {
return res.status(200).json({
views: [],
duration: { data: [] },
total_duration: 0,
groupedReactions: [],
+ totalViews: 0,
});
}
+ // Only fetch views and users if we have views
+ const [views, users] = await Promise.all([
+ prisma.view.findMany({
+ where: {
+ documentId: docId,
+ },
+ }),
+ excludeTeamMembers
+ ? prisma.user.findMany({
+ where: {
+ teams: {
+ some: {
+ teamId: teamId,
+ },
+ },
+ },
+ select: {
+ email: true,
+ },
+ })
+ : Promise.resolve([]),
+ ]);
+
const activeViews = views.filter((view) => !view.isArchived);
const archivedViews = views.filter((view) => view.isArchived);
diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.ts
index 51ec7c43..91293e77 100644
--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts
@@ -230,6 +230,22 @@ export default async function handle(
return res.status(404).end("Document not found");
}
+ // Check if document has any views first to avoid expensive query
+ const viewCount = await prisma.view.count({
+ where: {
+ documentId: docId,
+ isArchived: false,
+ },
+ });
+
+ if (viewCount === 0) {
+ return res.status(200).json({
+ viewsWithDuration: [],
+ hiddenViewCount: 0,
+ totalViews: 0,
+ });
+ }
+
const views = await prisma.view.findMany({
skip: offset,
take: limit,
diff --git a/pages/documents/[id]/index.tsx b/pages/documents/[id]/index.tsx
index c2cbad91..d3809de1 100644
--- a/pages/documents/[id]/index.tsx
+++ b/pages/documents/[id]/index.tsx
@@ -1,62 +1,104 @@
+// Lazy load heavy components for better performance
+import dynamic from "next/dynamic";
import ErrorPage from "next/error";
-import { useState } from "react";
+import { Suspense, useState } from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
-import useSWR from "swr";
-import { usePlan } from "@/lib/swr/use-billing";
-import { useDocument, useDocumentLinks } from "@/lib/swr/use-document";
-import useLimits from "@/lib/swr/use-limits";
-import { fetcher } from "@/lib/utils";
+import { useDocumentLinks } from "@/lib/swr/use-document";
+import { useDocumentOverview } from "@/lib/swr/use-document-overview";
import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";
import { AnnotationSheet } from "@/components/documents/annotations/annotation-sheet";
import DocumentHeader from "@/components/documents/document-header";
import { DocumentPreviewButton } from "@/components/documents/document-preview-button";
+// Import placeholder components
+import DocumentStatsPlaceholder from "@/components/documents/document-stats-placeholder";
import NotionAccessibilityIndicator from "@/components/documents/notion-accessibility-indicator";
-import { StatsComponent } from "@/components/documents/stats";
-import VideoAnalytics from "@/components/documents/video-analytics";
+import VideoStatsPlaceholder from "@/components/documents/video-stats-placeholder";
import AppLayout from "@/components/layouts/app";
import LinkSheet from "@/components/links/link-sheet";
import LinksTable from "@/components/links/links-table";
import { Button } from "@/components/ui/button";
import LoadingSpinner from "@/components/ui/loading-spinner";
-import VisitorsTable from "@/components/visitors/visitors-table";
+
+const StatsComponent = dynamic(
+ () =>
+ import("@/components/documents/stats").then((mod) => ({
+ default: mod.StatsComponent,
+ })),
+ {
+ loading: () => (
+ <div className="flex h-48 animate-pulse items-center justify-center rounded-lg bg-gray-100">
+ <LoadingSpinner className="h-6 w-6" />
+ </div>
+ ),
+ ssr: false,
+ },
+);
+
+const VideoAnalytics = dynamic(
+ () => import("@/components/documents/video-analytics"),
+ {
+ loading: () => (
+ <div className="flex h-48 animate-pulse items-center justify-center rounded-lg bg-gray-100">
+ <LoadingSpinner className="h-6 w-6" />
+ </div>
+ ),
+ ssr: false,
+ },
+);
+
+const VisitorsTable = dynamic(
+ () => import("@/components/visitors/visitors-table"),
+ {
+ loading: () => (
+ <div className="flex h-64 animate-pulse items-center justify-center rounded-lg bg-gray-100">
+ <LoadingSpinner className="h-6 w-6" />
+ </div>
+ ),
+ ssr: false,
+ },
+);
export default function DocumentPage() {
const {
+ data: overview,
document: prismaDocument,
primaryVersion,
+ limits,
+ featureFlags,
+ team,
+ counts,
+ isEmpty,
+ loading: overviewLoading,
error,
- mutate: mutateDocument,
- } = useDocument();
- const { links } = useDocumentLinks();
- const teamInfo = useTeam();
- const { isTrial } = usePlan();
+ mutate: mutateOverview,
+ } = useDocumentOverview();
- const { canAddLinks } = useLimits();
-
- // Get feature flags
- const { data: featureFlags } = useSWR<{ annotations: boolean }>(
- teamInfo?.currentTeam?.id
- ? `/api/feature-flags?teamId=${teamInfo.currentTeam.id}`
- : null,
- fetcher,
- );
+ // Always fetch links to show empty states properly
+ const { links, error: linksError, mutate: mutateLinks } = useDocumentLinks();
+ const teamInfo = useTeam();
const [isLinkSheetOpen, setIsLinkSheetOpen] = useState<boolean>(false);
+ // Mutate function that updates both overview and links
+ const mutateDocument = () => {
+ mutateOverview();
+ mutateLinks();
+ };
+
if (error && error.status === 400) {
return <ErrorPage statusCode={400} />;
}
const AddLinkButton = () => {
- if (!canAddLinks) {
+ if (!limits?.canAddLinks) {
return (
<UpgradePlanModal
- clickedPlan={isTrial ? PlanEnum.Business : PlanEnum.Pro}
+ clickedPlan={team?.isTrial ? PlanEnum.Business : PlanEnum.Pro}
trigger={"limit_add_link"}
>
<Button className="flex h-8 whitespace-nowrap text-xs lg:h-9 lg:text-sm">
@@ -76,63 +118,105 @@ export default function DocumentPage() {
}
};
+ // Show loading only for the initial overview load
+ if (overviewLoading) {
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <div className="flex h-screen items-center justify-center">
+ <LoadingSpinner className="mr-1 h-20 w-20" />
+ </div>
+ </main>
+ </AppLayout>
+ );
+ }
+
+ if (!prismaDocument || !primaryVersion) {
+ return (
+ <AppLayout>
+ <main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
+ <div className="flex h-screen items-center justify-center">
+ <LoadingSpinner className="mr-1 h-20 w-20" />
+ </div>
+ </main>
+ </AppLayout>
+ );
+ }
+
return (
<AppLayout>
<main className="relative mx-2 mb-10 mt-4 space-y-8 overflow-hidden px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">
- {prismaDocument && primaryVersion ? (
- <>
- {/* Action Header */}
- <DocumentHeader
+ {/* Action Header - Shows immediately */}
+ <DocumentHeader
+ primaryVersion={primaryVersion}
+ prismaDocument={prismaDocument}
+ teamId={teamInfo?.currentTeam?.id!}
+ actions={[
+ <NotionAccessibilityIndicator
+ key={"notion-status"}
+ documentId={prismaDocument.id}
primaryVersion={primaryVersion}
- prismaDocument={prismaDocument}
- teamId={teamInfo?.currentTeam?.id!}
- actions={[
- <NotionAccessibilityIndicator
- key={"notion-status"}
+ onUrlUpdate={mutateDocument}
+ />,
+ <>
+ {featureFlags?.annotations && (
+ <AnnotationSheet
documentId={prismaDocument.id}
- primaryVersion={primaryVersion}
- onUrlUpdate={mutateDocument}
- />,
- <>
- {featureFlags?.annotations && (
- <AnnotationSheet
- documentId={prismaDocument.id}
- teamId={teamInfo?.currentTeam?.id!}
- numPages={primaryVersion.numPages || 1}
- />
- )}
- </>,
- <DocumentPreviewButton
- key={"preview"}
+ teamId={teamInfo?.currentTeam?.id!}
+ numPages={primaryVersion.numPages || 1}
+ />
+ )}
+ </>,
+ <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"} />,
+ ]}
+ />
+
+ {/* Progressive Loading: Always show components, but optimize for empty states */}
+ <Suspense
+ fallback={
+ <div className="h-48 animate-pulse rounded-lg bg-gray-100" />
+ }
+ >
+ <>
+ {/* Document Analytics - Always show, lazy loaded if not empty */}
+ {primaryVersion.type !== "video" &&
+ (isEmpty ? (
+ <DocumentStatsPlaceholder
+ numPages={primaryVersion.numPages || 1}
+ onCreateLink={() => setIsLinkSheetOpen(true)}
+ />
+ ) : (
+ <StatsComponent
+ documentId={prismaDocument.id}
+ numPages={primaryVersion.numPages!}
+ />
+ ))}
+
+ {/* Video Analytics - Always show, lazy loaded if not empty */}
+ {primaryVersion.type === "video" &&
+ (isEmpty ? (
+ <VideoStatsPlaceholder
+ length={primaryVersion.length || 51}
+ onCreateLink={() => setIsLinkSheetOpen(true)}
+ />
+ ) : (
+ <VideoAnalytics
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"} />,
- ]}
- />
+ teamId={teamInfo?.currentTeam?.id!}
+ />
+ ))}
- {/* Document Analytics */}
- {primaryVersion.type !== "video" && (
- <StatsComponent
- documentId={prismaDocument.id}
- numPages={primaryVersion.numPages!}
- />
- )}
-
- {/* Video Analytics */}
- {primaryVersion.type === "video" && (
- <VideoAnalytics
- documentId={prismaDocument.id}
- primaryVersion={primaryVersion}
- teamId={teamInfo?.currentTeam?.id!}
- />
- )}
-
- {/* Links */}
+ {/* Links - Always show */}
<LinksTable
links={links}
targetType={"DOCUMENT"}
@@ -140,24 +224,20 @@ export default function DocumentPage() {
mutateDocument={mutateDocument}
/>
- {/* Visitors */}
+ {/* Visitors - Always show */}
<VisitorsTable
primaryVersion={primaryVersion}
isVideo={primaryVersion.type === "video"}
/>
-
- <LinkSheet
- isOpen={isLinkSheetOpen}
- linkType="DOCUMENT_LINK"
- setIsOpen={setIsLinkSheetOpen}
- existingLinks={links}
- />
</>
- ) : (
- <div className="flex h-screen items-center justify-center">
- <LoadingSpinner className="mr-1 h-20 w-20" />
- </div>
- )}
+ </Suspense>
+
+ <LinkSheet
+ isOpen={isLinkSheetOpen}
+ linkType="DOCUMENT_LINK"
+ setIsOpen={setIsLinkSheetOpen}
+ existingLinks={links}
+ />
</main>
</AppLayout>
);
diff --git a/prisma/migrations/20250915000000_add_performance_indexes/migration.sql b/prisma/migrations/20250915000000_add_performance_indexes/migration.sql
new file mode 100644
index 00000000..2da726b0
--- /dev/null
+++ b/prisma/migrations/20250915000000_add_performance_indexes/migration.sql
@@ -0,0 +1,27 @@
+-- CreateIndex
+CREATE INDEX "Document_teamId_folderId_idx" ON "Document"("teamId" ASC, "folderId" ASC);
+
+-- CreateIndex
+CREATE INDEX "Document_teamId_name_idx" ON "Document"("teamId" ASC, "name" ASC);
+
+-- CreateIndex
+CREATE INDEX "DocumentVersion_documentId_createdAt_idx" ON "DocumentVersion"("documentId" ASC, "createdAt" DESC);
+
+-- CreateIndex
+CREATE INDEX "DocumentVersion_documentId_isPrimary_idx" ON "DocumentVersion"("documentId" ASC, "isPrimary" ASC);
+
+-- CreateIndex
+CREATE INDEX "Link_documentId_isArchived_idx" ON "Link"("documentId" ASC, "isArchived" ASC);
+
+-- CreateIndex
+CREATE INDEX "Reaction_viewId_type_idx" ON "Reaction"("viewId" ASC, "type" ASC);
+
+-- CreateIndex
+CREATE INDEX "View_documentId_isArchived_idx" ON "View"("documentId" ASC, "isArchived" ASC);
+
+-- CreateIndex
+CREATE INDEX "View_documentId_viewedAt_idx" ON "View"("documentId" ASC, "viewedAt" DESC);
+
+-- CreateIndex
+CREATE INDEX "View_viewerEmail_idx" ON "View"("viewerEmail" ASC);
+
diff --git a/prisma/schema/document.prisma b/prisma/schema/document.prisma
index 73d2512b..2aac298f 100644
--- a/prisma/schema/document.prisma
+++ b/prisma/schema/document.prisma
@@ -36,6 +36,8 @@ model Document {
@@index([ownerId])
@@index([teamId])
@@index([folderId])
+ @@index([teamId, folderId]) // Performance optimization for document filtering by team and folder
+ @@index([teamId, name]) // Performance optimization for document search by name
}
model DocumentVersion {
@@ -61,6 +63,8 @@ model DocumentVersion {
@@unique([versionNumber, documentId])
@@index([documentId])
+ @@index([documentId, isPrimary]) // Performance optimization for primary version queries
+ @@index([documentId, createdAt(sort: Desc)]) // Partial index for primary versions
}
model DocumentPage {
diff --git a/prisma/schema/link.prisma b/prisma/schema/link.prisma
index 891fbf2a..13e8a483 100644
--- a/prisma/schema/link.prisma
+++ b/prisma/schema/link.prisma
@@ -86,6 +86,7 @@ model Link {
@@unique([domainSlug, slug])
@@index([documentId])
@@index([teamId])
+ @@index([documentId, isArchived]) // Performance optimization for active links filtering
}
model LinkPreset {
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index 57f89f17..f7c3d6aa 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -152,6 +152,9 @@ model View {
@@index([teamId])
@@index([viewedAt(sort: Desc)]) // Performance optimization for date aggregations
@@index([viewerId, documentId]) // Performance optimization for joins with filtering
+ @@index([viewerEmail]) // Performance optimization for viewer email filtering
+ @@index([documentId, isArchived]) // Performance optimization for active views filtering
+ @@index([documentId, viewedAt(sort: Desc)]) // Performance optimization for latest views queries
}
enum ViewType {
@@ -195,6 +198,7 @@ model Reaction {
createdAt DateTime @default(now())
@@index([viewId])
+ @@index([viewId, type]) // Performance optimization for reaction grouping
}
model Invitation {