Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
chore: cleanup link preview
Marc Seitz7f9736e6325d
diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex 98699cc0..c67d4d21 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -9,7 +9,7 @@ import { toast } from "sonner";import { useAnalytics } from "@/lib/analytics";import { useDisablePrint } from "@/lib/hooks/use-disable-print";-import { LinkWithDocument, NotionTheme, WatermarkConfig } from "@/lib/types";+import { LinkWithDocument, NotionTheme } from "@/lib/types";import LoadingSpinner from "@/components/ui/loading-spinner";import AccessForm, {@@ -18,8 +18,6 @@ import AccessForm, {} from "@/components/view/access-form";import EmailVerificationMessage from "./access-form/email-verification-form";-import LinkPreview from "./link-preview";-import { TNavData } from "./nav";import ViewData, { TViewDocumentData } from "./view-data";type RowData = { [key: string]: any };@@ -119,12 +117,6 @@ export default function DocumentView({);const [code, setCode] = useState<string | null>(null);const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);- const [linkOpened, setLinkOpened] = useState<boolean>(false);-- // Check if this is a link document- const isLinkDocument = document.type === "link";- // For link documents, get URL from viewData.file (from API) or fallback to document.file- const linkUrl = isLinkDocument ? viewData.file || document.file : null;const handleSubmission = async (): Promise<void> => {setIsLoading(true);@@ -172,22 +164,19 @@ export default function DocumentView({viewerId,} = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;- // For link documents, we don't track views here - only when the link is opened- if (!isLinkDocument) {- analytics.identify(- userEmail ?? verifiedEmail ?? data.email ?? undefined,- );- analytics.capture("Link Viewed", {- linkId: link.id,- documentId: document.id,- linkType: "DOCUMENT_LINK",- viewerId: viewId,- viewerEmail: data.email ?? verifiedEmail ?? userEmail,- isEmbedded,- isTeamMember,- teamId: link.teamId,- });- }+ analytics.identify(+ userEmail ?? verifiedEmail ?? data.email ?? undefined,+ );+ analytics.capture("Link Viewed", {+ linkId: link.id,+ documentId: document.id,+ linkType: "DOCUMENT_LINK",+ viewerId: viewId,+ viewerEmail: data.email ?? verifiedEmail ?? userEmail,+ isEmbedded,+ isTeamMember,+ teamId: link.teamId,+ });// set the verification token to the cookieif (verificationToken) {@@ -292,80 +281,6 @@ export default function DocumentView({);}- const handleLinkContinue = async () => {- // Use viewData.file or fallback to document.file- const finalLinkUrl = linkUrl || document.file;- if (!finalLinkUrl) {- console.error("Link URL not available", {- linkUrl,- documentFile: document.file,- viewDataFile: viewData.file,- });- return;- }-- // Track link open in analytics and record 100% completion (non-blocking)- if (viewData.viewId) {- // Record page view for page 1 to mark 100% completion- fetch("/api/record_view", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- linkId: link.id,- documentId: document.id,- viewId: viewData.viewId,- pageNumber: 1,- versionNumber: document.versions[0].versionNumber,- duration: 1000, // 1 second minimum duration- time: Date.now(),- }),- keepalive: true,- }).catch((error) => {- console.error("Failed to record page view:", error);- });-- // Track link open- fetch("/api/record_link_open", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- linkId: link.id,- documentId: document.id,- viewId: viewData.viewId,- linkUrl: finalLinkUrl,- viewerEmail: data.email ?? verifiedEmail ?? userEmail ?? undefined,- }),- }).catch((error) => {- console.error("Failed to track link open:", error);- });-- analytics.capture("Link Opened", {- linkId: link.id,- documentId: document.id,- linkType: "DOCUMENT_LINK",- viewerId: viewData.viewId,- viewerEmail: data.email ?? verifiedEmail ?? userEmail,- teamId: link.teamId,- });- }-- // Open link in new window/tab immediately- setLinkOpened(true);- const newWindow = window.open(- finalLinkUrl,- "_blank",- "noopener,noreferrer",- );- if (!newWindow) {- // If popup blocked, fallback to current window- window.location.href = finalLinkUrl;- }- };-if (isLoading) {return (<div className="flex h-screen items-center justify-center">@@ -374,40 +289,6 @@ export default function DocumentView({);}- // For link documents, show the preview page- if (submitted && isLinkDocument) {- const navData: TNavData = {- linkId: link.id,- documentId: document.id,- viewId: viewData.viewId,- isPreview: viewData.isPreview || false,- allowDownload: link.allowDownload || false,- brand: brand,- annotationsFeatureEnabled: annotationsEnabled || false,- };-- // Use viewData.file or fallback to document.file- const finalLinkUrl = linkUrl || document.file || "";-- return (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <LinkPreview- linkUrl={finalLinkUrl}- linkName={document.name}- brand={brand}- onContinue={handleLinkContinue}- navData={navData}- />- </div>- );- }-return (<divclassName="bg-gray-950"diff --git a/components/view/link-preview.tsx b/components/view/link-preview.tsxindex a2f473dd..dba29282 100644--- a/components/view/link-preview.tsx+++ b/components/view/link-preview.tsx@@ -1,49 +1,234 @@-import { useEffect, useState } from "react";+import { useRouter } from "next/router";++import { useEffect, useMemo, useRef } from "react";import { ExternalLink } from "lucide-react";-import { Brand } from "@prisma/client";+import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";+import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { Button } from "@/components/ui/button";import Nav, { TNavData } from "./nav";+import { AwayPoster } from "./viewer/away-poster";interface LinkPreviewProps {linkUrl: string;linkName: string;- brand?: Partial<Brand> | null;- onContinue: () => void;navData: TNavData;+ versionNumber: number;}export default function LinkPreview({linkUrl,linkName,- brand,- onContinue,navData,+ versionNumber,}: LinkPreviewProps) {- const [domain, setDomain] = useState<string>("");+ const router = useRouter();+ const startTimeRef = useRef(Date.now());+ const visibilityRef = useRef<boolean>(true);++ const domain = useMemo(() => {+ if (!linkUrl) return "";- useEffect(() => {- if (!linkUrl) {- console.warn("LinkPreview: linkUrl is missing", { linkUrl, linkName });- return;- }-try {const url = new URL(linkUrl);- setDomain(url.hostname.replace("www.", ""));+ return url.hostname.replace("www.", "");} catch (e) {// If URL parsing fails, try to extract domain from stringconst match = linkUrl.match(/https?:\/\/([^\/]+)/);if (match) {- setDomain(match[1].replace("www.", ""));+ return match[1].replace("www.", "");+ }+ return linkUrl.length > 50 ? linkUrl.substring(0, 50) + "..." : linkUrl;+ }+ }, [linkUrl]);++ const trackingOptions = getTrackingOptions();+ const {+ trackPageViewSafely,+ resetTrackingState,+ startIntervalTracking,+ stopIntervalTracking,+ getActiveDuration,+ isInactive,+ updateActivity,+ } = useSafePageViewTracker({+ ...trackingOptions,+ externalStartTimeRef: startTimeRef,+ });++ const { linkId, documentId, viewId, isPreview, dataroomId } = navData;++ useEffect(() => {+ // Remove token and email query parameters on component mount+ const removeQueryParams = (queries: string[]) => {+ const currentQuery = { ...router.query };+ const currentPath = router.asPath.split("?")[0];+ queries.map((query) => delete currentQuery[query]);++ router.replace(+ {+ pathname: currentPath,+ query: currentQuery,+ },+ undefined,+ { shallow: true },+ );+ };++ if (router.query.token) {+ removeQueryParams(["token", "email", "domain", "slug", "linkId"]);+ }+ }, []);++ useEffect(() => {+ const handleVisibilityChange = () => {+ if (document.visibilityState === "visible") {+ visibilityRef.current = true;+ resetTrackingState();++ // Restart interval tracking+ const trackingData = {+ linkId,+ documentId,+ viewId,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ };+ startIntervalTracking(trackingData);} else {- setDomain(linkUrl.length > 50 ? linkUrl.substring(0, 50) + "..." : linkUrl);+ visibilityRef.current = false;+ stopIntervalTracking();++ // Track final duration using activity-aware calculation+ const duration = getActiveDuration();+ trackPageViewSafely(+ {+ linkId,+ documentId,+ viewId,+ duration,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ },+ true,+ );}+ };++ document.addEventListener("visibilitychange", handleVisibilityChange);++ return () => {+ document.removeEventListener("visibilitychange", handleVisibilityChange);+ };+ }, [+ linkId,+ documentId,+ viewId,+ versionNumber,+ dataroomId,+ isPreview,+ trackPageViewSafely,+ resetTrackingState,+ startIntervalTracking,+ stopIntervalTracking,+ getActiveDuration,+ ]);++ useEffect(() => {+ const handleBeforeUnload = () => {+ stopIntervalTracking();+ const duration = getActiveDuration();+ trackPageViewSafely(+ {+ linkId,+ documentId,+ viewId,+ duration,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ },+ true,+ );+ };++ window.addEventListener("beforeunload", handleBeforeUnload);++ return () => {+ window.removeEventListener("beforeunload", handleBeforeUnload);+ };+ }, [+ linkId,+ documentId,+ viewId,+ versionNumber,+ dataroomId,+ isPreview,+ trackPageViewSafely,+ stopIntervalTracking,+ getActiveDuration,+ ]);++ useEffect(() => {+ const trackingData = {+ linkId,+ documentId,+ viewId,+ pageNumber: 1,+ versionNumber,+ dataroomId,+ isPreview,+ };++ startIntervalTracking(trackingData);++ return () => {+ stopIntervalTracking();+ };+ }, [+ linkId,+ documentId,+ viewId,+ versionNumber,+ dataroomId,+ isPreview,+ startIntervalTracking,+ stopIntervalTracking,+ ]);++ const handleLinkClick = () => {+ // Track the link click (non-blocking)+ if (!isPreview && viewId && linkUrl) {+ fetch("/api/record_click", {+ method: "POST",+ body: JSON.stringify({+ timestamp: new Date().toISOString(),+ sessionId: viewId,+ linkId,+ documentId,+ viewId,+ pageNumber: "1",+ href: linkUrl,+ versionNumber,+ dataroomId,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ }).catch(console.error);}- }, [linkUrl, linkName]);++ window.open(linkUrl, "_blank", "noopener,noreferrer");+ return;+ };return (<>@@ -60,18 +245,19 @@ export default function LinkPreview({{domain || linkName || "External Link"}</h2><p className="max-w-md text-sm text-gray-500 dark:text-gray-400">- You're leaving Papermark. If you trust this link, click to continue.+ You're leaving Papermark. If you trust this link, click to+ continue.</p>{linkUrl ? (<ahref={linkUrl}target="_blank"rel="noopener noreferrer"- className="block cursor-pointer break-all text-sm font-medium text-blue-600 hover:text-blue-700 underline transition-colors dark:text-blue-400 dark:hover:text-blue-300"+ className="block cursor-pointer break-all text-sm font-medium text-blue-600 underline transition-colors hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300"onClick={(e) => {e.preventDefault();e.stopPropagation();- onContinue();+ handleLinkClick();}}>{linkUrl}@@ -82,7 +268,7 @@ export default function LinkPreview({</p>)}<Button- onClick={onContinue}+ onClick={handleLinkClick}className="w-full max-w-md space-x-2"size="lg"disabled={!linkUrl}@@ -92,7 +278,11 @@ export default function LinkPreview({</Button></div></div>+ <AwayPoster+ isVisible={isInactive}+ inactivityThreshold={trackingOptions.inactivityThreshold}+ onDismiss={updateActivity}+ /></>);}-diff --git a/components/view/view-data.tsx b/components/view/view-data.tsxindex 7eb91b41..3bfb5ff7 100644--- a/components/view/view-data.tsx+++ b/components/view/view-data.tsx@@ -109,8 +109,6 @@ export default function ViewData({annotationsFeatureEnabled: annotationsEnabled,};- // Calculate allowDownload once for all components-// Check if agents are enabled (returned from views API after access is granted)const agentsEnabled ="agentsEnabled" in viewData ? viewData.agentsEnabled : false;@@ -131,8 +129,6 @@ export default function ViewData({linkId={link.id}viewId={viewData.viewId}viewerId={"viewerId" in viewData ? viewData.viewerId : undefined}- // focusedDocumentId={dataroomId ? document.id : undefined}- // focusedDocumentName={dataroomId ? document.name : undefined}><ViewerChatLayout>{notionData?.recordMap ? (@@ -147,62 +143,7 @@ export default function ViewData({<LinkPreviewlinkUrl={viewData.file || document.versions[0]?.file || ""}linkName={document.name}- brand={brand}- onContinue={async () => {- const url = viewData.file || document.versions[0]?.file;- if (!url) return;-- // Track link open in analytics and record 100% completion (non-blocking)- if (navData.viewId) {- // Record page view for page 1 to mark 100% completion- fetch("/api/record_view", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- linkId: navData.linkId,- documentId: navData.documentId,- viewId: navData.viewId,- pageNumber: 1,- versionNumber: document.versions[0]?.versionNumber || 1,- duration: 1000, // 1 second minimum duration- time: Date.now(),- }),- keepalive: true,- }).catch((error) => {- console.error("Failed to record page view:", error);- });-- // Track link open- fetch("/api/record_link_open", {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- linkId: navData.linkId,- documentId: navData.documentId,- viewId: navData.viewId,- linkUrl: url,- viewerEmail: viewerEmail,- }),- }).catch((error) => {- console.error("Failed to track link open:", error);- });- }-- // Open link in new window immediately- const newWindow = window.open(- url,- "_blank",- "noopener,noreferrer",- );- if (!newWindow) {- // If popup blocked, fallback to current window- window.location.href = url;- }- }}+ versionNumber={document.versions[0]?.versionNumber || 1}navData={navData}/>) : document.downloadOnly ? (diff --git a/pages/api/record_link_open.ts b/pages/api/record_link_open.tsdeleted file mode 100644index bc878822..00000000--- a/pages/api/record_link_open.ts+++ /dev/null@@ -1,127 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import { getGeoData, LOCALHOST_GEO_DATA, LOCALHOST_IP } from "@/lib/utils/geo";-import { recordLinkViewTB } from "@/lib/tinybird";-import { isBot, userAgentFromString } from "@/lib/utils/user-agent";-import { EU_COUNTRY_CODES } from "@/lib/constants";-import { capitalize, getDomainWithoutWWW, log } from "@/lib/utils";--type Geo = {- country?: string;- city?: string;- region?: string;- latitude?: string;- longitude?: string;-};--export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method !== "POST") {- res.status(405).json({ message: "Method Not Allowed" });- return;- }-- const {- linkId,- documentId,- viewId,- linkUrl,- viewerEmail,- } = req.body as {- linkId: string;- documentId: string;- viewId: string;- linkUrl: string;- viewerEmail?: string;- };-- if (!linkId || !documentId || !viewId || !linkUrl) {- res.status(400).json({ message: "Missing required fields" });- return;- }-- const geo: Geo =- process.env.VERCEL === "1" ? getGeoData(req.headers) : LOCALHOST_GEO_DATA;-- const referer = req.headers.referer;- const ua = userAgentFromString(req.headers["user-agent"] || "");-- const bot = isBot(ua.ua);-- // don't track clicks from bots- if (bot) {- return res.status(200).json({ success: true, skipped: true });- }-- const ip = process.env.VERCEL === "1"- ? (Array.isArray(req.headers["x-forwarded-for"])- ? req.headers["x-forwarded-for"][0]- : req.headers["x-forwarded-for"]) || req.headers["x-real-ip"]- : LOCALHOST_IP;-- // get continent, region & geolocation data- const { continent, region } =- process.env.VERCEL === "1"- ? {- continent: req.headers["x-vercel-ip-continent"] as string | undefined,- region: req.headers["x-vercel-ip-country-region"] as string | undefined,- }- : LOCALHOST_GEO_DATA;-- const isEuCountry = geo.country && EU_COUNTRY_CODES.includes(geo.country);-- const refererDomain = referer ? getDomainWithoutWWW(referer) : "(direct)";-- const clickId = `click_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;-- const clickData = {- timestamp: new Date(Date.now()).toISOString(),- click_id: clickId,- view_id: viewId,- link_id: linkId,- document_id: documentId,- dataroom_id: null,- continent: continent || "",- country: geo.country || "Unknown",- region: region || "Unknown",- city: geo.city || "Unknown",- latitude: geo.latitude || "Unknown",- longitude: geo.longitude || "Unknown",- device: ua.device.type ? capitalize(ua.device.type) : "Desktop",- device_vendor: ua.device.vendor || "Unknown",- device_model: ua.device.model || "Unknown",- browser: ua.browser.name || "Unknown",- browser_version: ua.browser.version || "Unknown",- engine: ua.engine.name || "Unknown",- engine_version: ua.engine.version || "Unknown",- os: ua.os.name || "Unknown",- os_version: ua.os.version || "Unknown",- cpu_architecture: ua.cpu?.architecture || "Unknown",- ua: ua.ua || "Unknown",- bot: ua.isBot,- referer: refererDomain,- referer_url: referer || "(direct)",- ip_address:- // only record IP if it's a valid IP and not from a EU country- typeof ip === "string" && ip.trim().length > 0 && !isEuCountry- ? ip- : null,- };-- // Record link open in Tinybird (notifications/webhooks are handled when view is created)- try {- await recordLinkViewTB(clickData);- } catch (error) {- log({- message: `Failed to record link open (tinybird) for ${linkId}. \n\n ${error}`,- type: "error",- mention: true,- });- // Still return success to not block the redirect- }-- return res.status(200).json({ success: true });-}-