Skip to content

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

Feat: Added 10-second record view and session stop functionality

Ashish Viradiya1757b68311c6
diff --git a/components/view/viewer/advanced-excel-viewer.tsx b/components/view/viewer/advanced-excel-viewer.tsx
index a7f9bbc3..b7da0566 100644
--- a/components/view/viewer/advanced-excel-viewer.tsx
+++ b/components/view/viewer/advanced-excel-viewer.tsx
@@ -1,8 +1,10 @@
import { useEffect, useRef } from "react";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
import Nav, { TNavData } from "../nav";
+import { AwayPoster } from "./away-poster";
export default function AdvancedExcelViewer({
file,
@@ -19,17 +21,67 @@ export default function AdvancedExcelViewer({
const startTimeRef = useRef(Date.now());
const visibilityRef = useRef<boolean>(true);
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...getTrackingOptions(),
+ externalStartTimeRef: startTimeRef,
+ });
+
+ // Start interval tracking when component mounts
+ useEffect(() => {
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ };
+
+ startIntervalTracking(trackingData);
+
+ return () => {
+ stopIntervalTracking();
+ };
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ pageNumber,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ startIntervalTracking,
+ stopIntervalTracking,
+ ]);
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
visibilityRef.current = true;
- startTimeRef.current = Date.now(); // Reset start time when page becomes visible
resetTrackingState();
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ };
+ startIntervalTracking(trackingData);
} else {
visibilityRef.current = false;
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+ const duration = getActiveDuration();
if (duration > 0) {
trackPageViewSafely(
{
@@ -49,7 +101,8 @@ export default function AdvancedExcelViewer({
};
const handleBeforeUnload = () => {
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+ const duration = getActiveDuration();
if (duration > 0) {
trackPageViewSafely(
{
@@ -74,7 +127,20 @@ export default function AdvancedExcelViewer({
document.removeEventListener("visibilitychange", handleVisibilityChange);
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, []);
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ pageNumber,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
return (
<>
@@ -93,6 +159,11 @@ export default function AdvancedExcelViewer({
background: brand?.accentColor || "rgb(3, 7, 18)",
}}
/>
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={getTrackingOptions().inactivityThreshold}
+ onDismiss={updateActivity}
+ />
</div>
</>
);
diff --git a/components/view/viewer/away-poster.tsx b/components/view/viewer/away-poster.tsx
new file mode 100644
index 00000000..7236b7e3
--- /dev/null
+++ b/components/view/viewer/away-poster.tsx
@@ -0,0 +1,76 @@
+import { Play } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
+
+interface AwayPosterProps {
+ isVisible: boolean;
+ inactivityThreshold: number;
+ onDismiss?: () => void;
+ className?: string;
+}
+
+export function AwayPoster({
+ isVisible,
+ inactivityThreshold,
+ onDismiss,
+ className,
+}: AwayPosterProps) {
+ const formatTime = (ms: number) => {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ return minutes > 0 ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
+ };
+
+ return (
+ <Dialog open={isVisible} onOpenChange={(open) => !open && onDismiss?.()}>
+ <DialogContent
+ className={cn(
+ "w-full max-w-sm rounded-md border bg-card p-4 text-card-foreground shadow-lg",
+ "absolute bottom-6 left-6",
+ "animate-in fade-in slide-in-from-bottom",
+ className,
+ )}
+ onInteractOutside={onDismiss}
+ >
+ <div className="space-y-5">
+ <div className="flex items-center justify-between">
+ <Badge
+ variant="outline"
+ className="border-orange-400 bg-orange-100 text-orange-600"
+ >
+ Auto-paused
+ </Badge>
+ <span className="mr-6 text-xs text-muted-foreground">
+ {formatTime(inactivityThreshold)} idle
+ </span>
+ </div>
+
+ <div className="space-y-2">
+ <h3 className="text-lg font-semibold">
+ We paused to protect your session
+ </h3>
+ <p className="text-sm text-muted-foreground">
+ You were inactive, so we paused the document preview to keep
+ session safe.
+ </p>
+ </div>
+
+ <div className="pt-2">
+ <Button onClick={onDismiss} className="w-full">
+ <Play className="mr-2 h-4 w-4" />
+ Continue where you left off
+ </Button>
+ </div>
+
+ <p className="text-center text-[11px] text-muted-foreground">
+ Or just move your mouse or press any key to continue
+ </p>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/components/view/viewer/download-only-viewer.tsx b/components/view/viewer/download-only-viewer.tsx
index 7664c100..1868e3ff 100644
--- a/components/view/viewer/download-only-viewer.tsx
+++ b/components/view/viewer/download-only-viewer.tsx
@@ -1,17 +1,25 @@
import { useRouter } from "next/router";
+
+
import { useEffect, useRef } from "react";
-import { Brand, DataroomBrand } from "@prisma/client";
+
+
import { Download } from "lucide-react";
import { toast } from "sonner";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
import { Button } from "@/components/ui/button";
-import { TDocumentData } from "../dataroom/dataroom-view";
+import { ScreenProtector } from "../ScreenProtection";
import Nav, { TNavData } from "../nav";
+import { PoweredBy } from "../powered-by";
+import { AwayPoster } from "./away-poster";
+
+import "@/styles/custom-viewer-styles.css";
export default function DownloadOnlyViewer({
versionNumber,
@@ -25,7 +33,20 @@ export default function DownloadOnlyViewer({
const router = useRouter();
const startTimeRef = useRef(Date.now());
const visibilityRef = useRef<boolean>(true);
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+
+ const trackingOptions = getTrackingOptions();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...trackingOptions,
+ externalStartTimeRef: startTimeRef,
+ });
const { linkId, documentId, viewId, isPreview, allowDownload, dataroomId } =
navData;
@@ -56,11 +77,25 @@ export default function DownloadOnlyViewer({
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
visibilityRef.current = true;
- startTimeRef.current = Date.now();
resetTrackingState();
+
+ // Restart interval tracking
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: 1,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ };
+ startIntervalTracking(trackingData);
} else {
visibilityRef.current = false;
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+
+ // Track final duration using activity-aware calculation
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -82,11 +117,24 @@ export default function DownloadOnlyViewer({
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, [documentId, linkId, viewId, versionNumber, dataroomId, isPreview]);
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
useEffect(() => {
const handleBeforeUnload = () => {
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -107,7 +155,44 @@ export default function DownloadOnlyViewer({
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, [documentId, linkId, viewId, versionNumber, dataroomId, isPreview]);
+ }, [
+ 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 downloadFile = async () => {
if (isPreview) {
@@ -161,6 +246,11 @@ export default function DownloadOnlyViewer({
)}
</div>
</div>
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={trackingOptions.inactivityThreshold || 20000}
+ onDismiss={updateActivity}
+ />
</>
);
-}
+}
\ No newline at end of file
diff --git a/components/view/viewer/excel-viewer.tsx b/components/view/viewer/excel-viewer.tsx
index f3ee56dd..46195dd1 100644
--- a/components/view/viewer/excel-viewer.tsx
+++ b/components/view/viewer/excel-viewer.tsx
@@ -5,6 +5,7 @@ import "@/public/vendor/handsontable/handsontable.full.min.css";
import { Brand, DataroomBrand } from "@prisma/client";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
@@ -12,6 +13,7 @@ import { Button } from "@/components/ui/button";
import { ScreenProtector } from "../ScreenProtection";
import { TDocumentData } from "../dataroom/dataroom-view";
import Nav, { TNavData } from "../nav";
+import { AwayPoster } from "./away-poster";
// Define the type for the JSON data
type RowData = { [key: string]: any };
@@ -21,8 +23,6 @@ type SheetData = {
rowData: RowData[];
};
-
-
export default function ExcelViewer({
versionNumber,
sheetData,
@@ -46,7 +46,18 @@ export default function ExcelViewer({
const startTimeRef = useRef(Date.now());
const visibilityRef = useRef<boolean>(true);
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...getTrackingOptions(),
+ externalStartTimeRef: startTimeRef,
+ });
useEffect(() => {
const script = document.createElement("script");
@@ -107,15 +118,57 @@ export default function ExcelViewer({
};
}, [screenshotProtectionEnabled]);
+ // Start interval tracking when component mounts
+ useEffect(() => {
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: selectedSheetIndex + 1,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ };
+
+ startIntervalTracking(trackingData);
+
+ return () => {
+ stopIntervalTracking();
+ };
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ startIntervalTracking,
+ stopIntervalTracking,
+ ]);
+
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
visibilityRef.current = true;
- startTimeRef.current = Date.now(); // Reset start time when page becomes visible
resetTrackingState();
+
+ // Restart interval tracking
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: selectedSheetIndex + 1,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ };
+ startIntervalTracking(trackingData);
} else {
visibilityRef.current = false;
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+
+ // Track final duration using activity-aware calculation
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -135,33 +188,27 @@ export default function ExcelViewer({
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
- if (visibilityRef.current) {
- const duration = Date.now() - startTimeRef.current;
- trackPageViewSafely(
- {
- linkId,
- documentId,
- viewId,
- duration,
- pageNumber: selectedSheetIndex + 1,
- versionNumber,
- dataroomId,
- isPreview,
- },
- true,
- ); // Also capture duration if component unmounts while visible
- startTimeRef.current = Date.now();
- }
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, [selectedSheetIndex]);
+ }, [
+ selectedSheetIndex,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
useEffect(() => {
const handleBeforeUnload = () => {
- if (!visibilityRef.current) return;
-
- // Only track if we haven't already tracked an unload event
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -182,7 +229,18 @@ export default function ExcelViewer({
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, [selectedSheetIndex]);
+ }, [
+ selectedSheetIndex,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
useEffect(() => {
if (handsontableLoaded && sheetData.length) {
@@ -255,6 +313,13 @@ export default function ExcelViewer({
))}
</div>
{screenshotProtectionEnabled ? <ScreenProtector /> : null}
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={
+ getTrackingOptions().inactivityThreshold || 20000
+ }
+ onDismiss={updateActivity}
+ />
</div>
</>
);
diff --git a/components/view/viewer/image-viewer.tsx b/components/view/viewer/image-viewer.tsx
index 0f36494e..ba0416d7 100644
--- a/components/view/viewer/image-viewer.tsx
+++ b/components/view/viewer/image-viewer.tsx
@@ -1,9 +1,14 @@
import { useRouter } from "next/router";
+
+
import { useEffect, useRef, useState } from "react";
import React from "react";
+
+
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
import { WatermarkConfig } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -11,6 +16,7 @@ import { ScreenProtector } from "../ScreenProtection";
import Nav, { TNavData } from "../nav";
import { PoweredBy } from "../powered-by";
import { SVGWatermark } from "../watermark-svg";
+import { AwayPoster } from "./away-poster";
import "@/styles/custom-viewer-styles.css";
@@ -50,7 +56,19 @@ export default function ImageViewer({
const containerRef = useRef<HTMLDivElement>(null);
const imageRefs = useRef<HTMLImageElement | null>(null);
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+ const trackingOptions = getTrackingOptions();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...trackingOptions,
+ externalStartTimeRef: startTimeRef,
+ });
const [imageDimensions, setImageDimensions] = useState<{
width: number;
@@ -112,11 +130,21 @@ export default function ImageViewer({
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
visibilityRef.current = true;
- startTimeRef.current = Date.now(); // Reset start time when the page becomes visible again
resetTrackingState();
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: pageNumber,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ };
+ startIntervalTracking(trackingData);
} else {
visibilityRef.current = false;
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -138,33 +166,24 @@ export default function ImageViewer({
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, []);
-
- useEffect(() => {
- startTimeRef.current = Date.now();
-
- if (visibilityRef.current) {
- const duration = Date.now() - startTimeRef.current;
- trackPageViewSafely(
- {
- linkId,
- documentId,
- viewId,
- duration,
- pageNumber: pageNumber,
- versionNumber,
- dataroomId,
- isPreview,
- },
- false,
- );
- }
- }, []);
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
useEffect(() => {
const handleBeforeUnload = () => {
- // Only track if we haven't already tracked an unload event
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -185,7 +204,17 @@ export default function ImageViewer({
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, []);
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
// Add this effect near your other useEffect hooks
useEffect(() => {
@@ -225,6 +254,34 @@ export default function ImageViewer({
}
}, []); // Run once on mount
+ // Start interval tracking when component mounts
+ useEffect(() => {
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: pageNumber,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ };
+ console.log("trackingData", trackingData);
+ startIntervalTracking(trackingData);
+
+ return () => {
+ stopIntervalTracking();
+ };
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ startIntervalTracking,
+ stopIntervalTracking,
+ ]);
+
return (
<>
<Nav
@@ -301,6 +358,11 @@ export default function ImageViewer({
{screenshotProtectionEnabled ? <ScreenProtector /> : null}
{showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}
</div>
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={trackingOptions.inactivityThreshold || 60000}
+ onDismiss={updateActivity}
+ />
</>
);
-}
+}
\ No newline at end of file
diff --git a/components/view/viewer/notion-page.tsx b/components/view/viewer/notion-page.tsx
index 73096ae1..bc01f879 100644
--- a/components/view/viewer/notion-page.tsx
+++ b/components/view/viewer/notion-page.tsx
@@ -11,6 +11,7 @@ import { NotionRenderer } from "react-notion-x";
import "react-notion-x/src/styles.css";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
import { NotionTheme } from "@/lib/types";
import { cn } from "@/lib/utils";
import { determineTextColor } from "@/lib/utils/determine-text-color";
@@ -25,6 +26,7 @@ import { Portal } from "@/components/ui/portal";
import { ScreenProtector } from "../../view/ScreenProtection";
import Nav, { TNavData } from "../../view/nav";
+import { AwayPoster } from "./away-poster";
// custom styles for notion
import "@/styles/custom-notion-styles.css";
@@ -69,7 +71,45 @@ export const NotionPage = ({
const startTimeRef = useRef(Date.now());
const pageNumberRef = useRef<number>(pageNumber);
const visibilityRef = useRef<boolean>(true);
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+ const trackingOptions = getTrackingOptions();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...trackingOptions,
+ externalStartTimeRef: startTimeRef,
+ });
+
+ // Start interval tracking when component mounts
+ useEffect(() => {
+ const trackingData = {
+ linkId: linkId,
+ documentId: documentId,
+ viewId: viewId,
+ pageNumber: pageNumberRef.current,
+ versionNumber: versionNumber,
+ isPreview: isPreview,
+ };
+
+ startIntervalTracking(trackingData);
+
+ return () => {
+ stopIntervalTracking();
+ };
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ isPreview,
+ startIntervalTracking,
+ stopIntervalTracking,
+ ]);
useEffect(() => {
const handleVisibilityChange = () => {
@@ -77,9 +117,23 @@ export const NotionPage = ({
visibilityRef.current = true;
startTimeRef.current = Date.now(); // Reset start time when page becomes visible
resetTrackingState();
+
+ // Restart interval tracking
+ const trackingData = {
+ linkId: linkId,
+ documentId: documentId,
+ viewId: viewId,
+ pageNumber: pageNumberRef.current,
+ versionNumber: versionNumber,
+ isPreview: isPreview,
+ };
+ startIntervalTracking(trackingData);
} else {
visibilityRef.current = false;
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+
+ // Track final duration using activity-aware calculation
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId: linkId,
@@ -89,6 +143,7 @@ export const NotionPage = ({
pageNumber: pageNumberRef.current,
versionNumber: versionNumber,
isPreview: isPreview,
+ dataroomId: navData?.dataroomId || undefined,
},
true,
);
@@ -100,7 +155,18 @@ export const NotionPage = ({
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, []);
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
// Add this effect near your other useEffect hooks
useEffect(() => {
@@ -181,7 +247,8 @@ export const NotionPage = ({
useEffect(() => {
const handleBeforeUnload = () => {
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId: linkId,
@@ -201,7 +268,16 @@ export const NotionPage = ({
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, [subPageId]);
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ isPreview,
+ trackPageViewSafely,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
// // Function to calculate scroll percentage
// const calculateScrollPercentage = () => {
@@ -380,6 +456,11 @@ export const NotionPage = ({
/>
</div>
{screenshotProtectionEnabled ? <ScreenProtector /> : null}
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={getTrackingOptions().inactivityThreshold}
+ onDismiss={updateActivity}
+ />
</div>
);
};
diff --git a/components/view/viewer/pages-horizontal-viewer.tsx b/components/view/viewer/pages-horizontal-viewer.tsx
index 31fe2953..83e061d4 100644
--- a/components/view/viewer/pages-horizontal-viewer.tsx
+++ b/components/view/viewer/pages-horizontal-viewer.tsx
@@ -7,6 +7,7 @@ import { ChevronLeftIcon, ChevronRightIcon } from "lucide-react";
import { useSession } from "next-auth/react";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
import { WatermarkConfig } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -17,12 +18,12 @@ import Question from "../question";
import Toolbar from "../toolbar";
import ViewDurationSummary from "../visitor-graph";
import { SVGWatermark } from "../watermark-svg";
+import { AwayPoster } from "./away-poster";
import "@/styles/custom-viewer-styles.css";
const DEFAULT_PRELOADED_IMAGES_NUM = 5;
-
export default function PagesHorizontalViewer({
pages,
feedbackEnabled,
@@ -115,7 +116,18 @@ export default function PagesHorizontalViewer({
const [imageDimensions, setImageDimensions] = useState<
Record<number, { width: number; height: number }>
>({});
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...getTrackingOptions(),
+ externalStartTimeRef: startTimeRef,
+ });
const scaleCoordinates = (coords: string, scaleFactor: number) => {
return coords
@@ -173,18 +185,66 @@ export default function PagesHorizontalViewer({
hasTrackedUpRef.current = false; // Reset tracking status on page number change
}, [pageNumber]);
+ // Start interval tracking when component mounts or page changes
+ useEffect(() => {
+ if (pageNumber <= numPages) {
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: pageNumber,
+ versionNumber,
+ dataroomId,
+ setViewedPages,
+ isPreview,
+ };
+
+ startIntervalTracking(trackingData);
+ }
+
+ return () => {
+ stopIntervalTracking();
+ };
+ }, [
+ pageNumber,
+ numPages,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ startIntervalTracking,
+ stopIntervalTracking,
+ ]);
+
useEffect(() => {
const handleVisibilityChange = () => {
if (pageNumber > numPages) return;
if (document.visibilityState === "visible") {
visibilityRef.current = true;
- startTimeRef.current = Date.now(); // Reset start time when the page becomes visible again
resetTrackingState();
+
+ // Restart interval tracking
+ if (pageNumber <= numPages) {
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: pageNumber,
+ versionNumber,
+ dataroomId,
+ setViewedPages,
+ isPreview,
+ };
+ startIntervalTracking(trackingData);
+ }
} else {
visibilityRef.current = false;
+ stopIntervalTracking();
if (pageNumber <= numPages) {
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -208,31 +268,27 @@ export default function PagesHorizontalViewer({
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, [pageNumber, numPages]);
-
- useEffect(() => {
- startTimeRef.current = Date.now();
-
- if (visibilityRef.current && pageNumber <= numPages) {
- const duration = Date.now() - startTimeRef.current;
- trackPageViewSafely({
- linkId,
- documentId,
- viewId,
- duration,
- pageNumber: pageNumber,
- versionNumber,
- dataroomId,
- setViewedPages,
- isPreview,
- });
- }
- }, [pageNumber, numPages]);
+ }, [
+ pageNumber,
+ numPages,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
useEffect(() => {
const handleBeforeUnload = () => {
+ stopIntervalTracking();
if (pageNumber <= numPages) {
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -255,7 +311,19 @@ export default function PagesHorizontalViewer({
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, [pageNumber, numPages]);
+ }, [
+ pageNumber,
+ numPages,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
// Add this effect near your other useEffect hooks
useEffect(() => {
@@ -329,7 +397,7 @@ export default function PagesHorizontalViewer({
// Preload previous pages every 4 pages in advanced
preloadImage(pageNumber - 4);
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely({
linkId,
documentId,
@@ -359,7 +427,7 @@ export default function PagesHorizontalViewer({
// Preload the next page every 2 pages in advanced
preloadImage(pageNumber + 2);
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely({
linkId,
documentId,
@@ -402,7 +470,7 @@ export default function PagesHorizontalViewer({
const targetPage = parseInt(pageMatch[1]);
if (targetPage >= 1 && targetPage <= numPages) {
// Track the current page before jumping
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely({
linkId,
documentId,
@@ -753,6 +821,13 @@ export default function PagesHorizontalViewer({
{screenshotProtectionEnabled ? <ScreenProtector /> : null}
{showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={
+ getTrackingOptions().inactivityThreshold
+ }
+ onDismiss={updateActivity}
+ />
</div>
</>
);
diff --git a/components/view/viewer/pages-vertical-viewer.tsx b/components/view/viewer/pages-vertical-viewer.tsx
index 3e1afd35..5560ce59 100644
--- a/components/view/viewer/pages-vertical-viewer.tsx
+++ b/components/view/viewer/pages-vertical-viewer.tsx
@@ -6,6 +6,7 @@ import React from "react";
import { ChevronDownIcon, ChevronUpIcon } from "lucide-react";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
import { WatermarkConfig } from "@/lib/types";
import { cn } from "@/lib/utils";
import { useMediaQuery } from "@/lib/utils/use-media-query";
@@ -16,6 +17,7 @@ import { PoweredBy } from "../powered-by";
import Question from "../question";
import Toolbar from "../toolbar";
import { SVGWatermark } from "../watermark-svg";
+import { AwayPoster } from "./away-poster";
import "@/styles/custom-viewer-styles.css";
@@ -189,7 +191,50 @@ export default function PagesVerticalViewer({
hasTrackedUpRef.current = false; // Reset tracking status on page number change
}, [pageNumber]);
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...getTrackingOptions(),
+ externalStartTimeRef: startTimeRef,
+ });
+
+ useEffect(() => {
+ if (pageNumber <= numPages) {
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: pageNumber,
+ versionNumber,
+ dataroomId,
+ setViewedPages,
+ isPreview,
+ };
+
+ startIntervalTracking(trackingData);
+ }
+
+ return () => {
+ stopIntervalTracking();
+ };
+ }, [
+ pageNumber,
+ numPages,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ startIntervalTracking,
+ stopIntervalTracking,
+ ]);
useEffect(() => {
const handleVisibilityChange = () => {
@@ -197,12 +242,28 @@ export default function PagesVerticalViewer({
if (document.visibilityState === "visible") {
visibilityRef.current = true;
- startTimeRef.current = Date.now(); // Reset start time when the page becomes visible again
resetTrackingState();
+
+ if (pageNumber <= numPages) {
+ const trackingData = {
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: pageNumber,
+ versionNumber,
+ dataroomId,
+ setViewedPages,
+ isPreview,
+ };
+ startIntervalTracking(trackingData);
+ }
} else {
visibilityRef.current = false;
+ stopIntervalTracking();
+
+ // Track final duration using activity-aware calculation
if (pageNumber <= numPages) {
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -226,32 +287,27 @@ export default function PagesVerticalViewer({
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, [pageNumber, numPages]);
-
- useEffect(() => {
- startTimeRef.current = Date.now();
-
- if (visibilityRef.current && pageNumber <= numPages) {
- const duration = Date.now() - startTimeRef.current;
- trackPageViewSafely({
- linkId,
- documentId,
- viewId,
- duration,
- pageNumber: pageNumber,
- versionNumber,
- dataroomId,
- setViewedPages,
- isPreview,
- });
- }
- }, [pageNumber, numPages]);
+ }, [
+ pageNumber,
+ numPages,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
useEffect(() => {
const handleBeforeUnload = () => {
+ stopIntervalTracking();
if (pageNumber <= numPages) {
- // Only track if we haven't already tracked an unload event
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId,
@@ -274,7 +330,19 @@ export default function PagesVerticalViewer({
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, [pageNumber, numPages]);
+ }, [
+ pageNumber,
+ numPages,
+ linkId,
+ documentId,
+ viewId,
+ versionNumber,
+ dataroomId,
+ isPreview,
+ trackPageViewSafely,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
// Add this effect near your other useEffect hooks
useEffect(() => {
@@ -378,7 +446,7 @@ export default function PagesVerticalViewer({
if (maxVisiblePage !== pageNumber) {
if (pageNumber <= numPages) {
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely({
linkId,
documentId,
@@ -432,7 +500,7 @@ export default function PagesVerticalViewer({
// Preload previous pages
preloadImage(pageNumber - 4);
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely({
linkId,
documentId,
@@ -479,7 +547,7 @@ export default function PagesVerticalViewer({
// Preload the next page
preloadImage(pageNumber + 2);
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely({
linkId,
documentId,
@@ -535,7 +603,7 @@ export default function PagesVerticalViewer({
const targetPage = parseInt(pageMatch[1]);
if (targetPage >= 1 && targetPage <= numPages) {
// Track the current page before jumping
- const duration = Date.now() - startTimeRef.current;
+ const duration = getActiveDuration();
trackPageViewSafely({
linkId,
documentId,
@@ -898,6 +966,13 @@ export default function PagesVerticalViewer({
{screenshotProtectionEnabled ? <ScreenProtector /> : null}
{showPoweredByBanner ? <PoweredBy linkId={linkId} /> : null}
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={
+ getTrackingOptions().inactivityThreshold || 20000
+ }
+ onDismiss={updateActivity}
+ />
</div>
</>
);
diff --git a/components/view/viewer/pdf-default-viewer.tsx b/components/view/viewer/pdf-default-viewer.tsx
index 0d0aaa92..02d5feb7 100644
--- a/components/view/viewer/pdf-default-viewer.tsx
+++ b/components/view/viewer/pdf-default-viewer.tsx
@@ -9,6 +9,7 @@ import { Document, Page, pdfjs } from "react-pdf";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
+import { getTrackingOptions } from "@/lib/tracking/tracking-config";
@@ -16,7 +17,7 @@ import Nav from "@/components/view/nav";
-
+import { AwayPoster } from "./away-poster";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;
@@ -32,43 +33,73 @@ export default function PDFViewer(props: any) {
const pageNumberRef = useRef<number>(pageNumber);
const visibilityRef = useRef<boolean>(true);
const teamInfo = useTeam();
- const { trackPageViewSafely, resetTrackingState } = useSafePageViewTracker();
+ const {
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ isInactive,
+ updateActivity,
+ } = useSafePageViewTracker({
+ ...getTrackingOptions(),
+ externalStartTimeRef: startTimeRef,
+ });
// Update the previous page number after the effect hook has run
useEffect(() => {
pageNumberRef.current = pageNumber;
}, [pageNumber]);
+ // Start interval tracking when component mounts or page changes
useEffect(() => {
- startTimeRef.current = Date.now(); // update the start time for the new page
+ const trackingData = {
+ linkId: linkId,
+ documentId: documentId,
+ viewId: viewId,
+ pageNumber: pageNumberRef.current,
+ versionNumber: props.versionNumber,
+ isPreview: isPreview,
+ };
+
+ startIntervalTracking(trackingData);
- // when component unmounts, calculate duration and track page view
return () => {
- const duration = Math.round(Date.now() - startTimeRef.current);
- trackPageViewSafely(
- {
- linkId: linkId,
- documentId: documentId,
- viewId: viewId,
- duration: duration,
- pageNumber: pageNumberRef.current,
- versionNumber: props.versionNumber,
- isPreview: isPreview,
- },
- false,
- );
+ stopIntervalTracking();
};
- }, [pageNumber]); // monitor pageNumber for changes
+ }, [
+ pageNumber,
+ linkId,
+ documentId,
+ viewId,
+ props.versionNumber,
+ isPreview,
+ startIntervalTracking,
+ stopIntervalTracking,
+ ]);
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === "visible") {
visibilityRef.current = true;
- startTimeRef.current = Date.now();
resetTrackingState();
+
+ // Restart interval tracking
+ const trackingData = {
+ linkId: linkId,
+ documentId: documentId,
+ viewId: viewId,
+ pageNumber: pageNumberRef.current,
+ versionNumber: props.versionNumber,
+ isPreview: isPreview,
+ };
+ startIntervalTracking(trackingData);
} else {
visibilityRef.current = false;
- const duration = Date.now() - startTimeRef.current;
+ stopIntervalTracking();
+
+ // Track final duration using activity-aware calculation
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId: linkId,
@@ -89,7 +120,19 @@ export default function PDFViewer(props: any) {
return () => {
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
- }, [pageNumber]);
+ }, [
+ pageNumber,
+ linkId,
+ documentId,
+ viewId,
+ props.versionNumber,
+ isPreview,
+ trackPageViewSafely,
+ resetTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
useEffect(() => {
if (numPages > 0) {
@@ -109,7 +152,8 @@ export default function PDFViewer(props: any) {
// duration is measured in milliseconds
useEffect(() => {
const handleBeforeUnload = () => {
- const duration = Math.round(Date.now() - startTimeRef.current);
+ stopIntervalTracking();
+ const duration = getActiveDuration();
trackPageViewSafely(
{
linkId: linkId,
@@ -119,6 +163,7 @@ export default function PDFViewer(props: any) {
pageNumber: pageNumberRef.current,
versionNumber: props.versionNumber,
isPreview: isPreview,
+ dataroomId: props?.navData?.dataroomId || undefined,
},
true,
);
@@ -129,7 +174,16 @@ export default function PDFViewer(props: any) {
return () => {
window.removeEventListener("beforeunload", handleBeforeUnload);
};
- }, []);
+ }, [
+ linkId,
+ documentId,
+ viewId,
+ props.versionNumber,
+ isPreview,
+ trackPageViewSafely,
+ stopIntervalTracking,
+ getActiveDuration,
+ ]);
function onPageLoadSuccess() {
setPageWidth(window.innerWidth);
@@ -263,6 +317,13 @@ export default function PDFViewer(props: any) {
/>
</Document>
</div>
+ <AwayPoster
+ isVisible={isInactive}
+ inactivityThreshold={
+ getTrackingOptions().inactivityThreshold
+ }
+ onDismiss={updateActivity}
+ />
</div>
</>
);
diff --git a/lib/tracking/safe-page-view-tracker.ts b/lib/tracking/safe-page-view-tracker.ts
index 38df60e8..d102502d 100644
--- a/lib/tracking/safe-page-view-tracker.ts
+++ b/lib/tracking/safe-page-view-tracker.ts
@@ -1,4 +1,4 @@
-import { useRef } from "react";
+import { useRef, useEffect, useCallback, useState } from "react";
import { trackPageViewReliably } from "../utils/reliable-tracking";
interface TrackingData {
@@ -15,11 +15,117 @@ interface TrackingData {
>;
}
-export function useSafePageViewTracker() {
+interface TrackingOptions {
+ intervalTracking?: boolean;
+ intervalDuration?: number; // in milliseconds, default 10 seconds
+ activityTracking?: boolean;
+ inactivityThreshold?: number; // in milliseconds, default 1 minute
+ enableActivityDetection?: boolean;
+ externalStartTimeRef?: React.MutableRefObject<number>; // Optional external start time ref
+}
+
+export function useSafePageViewTracker(options: TrackingOptions = {}) {
+ const {
+ intervalTracking = true,
+ intervalDuration = 10000, // 10 seconds
+ activityTracking = true,
+ inactivityThreshold = 60000, // 1 minute default
+ enableActivityDetection = true,
+ externalStartTimeRef,
+ } = options;
+
const hasTrackedUnloadRef = useRef<boolean>(false);
const isTrackingRef = useRef<boolean>(false);
- const trackPageViewSafely = async (
+ // Activity tracking refs
+ const lastActivityTimeRef = useRef<number>(Date.now());
+ const isActiveRef = useRef<boolean>(true);
+ const intervalIdRef = useRef<NodeJS.Timeout | null>(null);
+ const inactivityTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+ const accumulatedActiveTimeRef = useRef<number>(0);
+
+ // Add state for inactive UI display
+ const [isInactive, setIsInactive] = useState<boolean>(false);
+
+ // Use external start time ref if provided, otherwise create internal one
+ const internalStartTimeRef = useRef<number>(Date.now());
+ const startTimeRef = externalStartTimeRef || internalStartTimeRef;
+ const lastIntervalTimeRef = useRef<number>(startTimeRef.current);
+
+ // Activity detection
+ const updateActivity = useCallback(() => {
+ const now = Date.now();
+
+ if (!isActiveRef.current) {
+ // User became active again, reset tracking
+ isActiveRef.current = true;
+ lastIntervalTimeRef.current = now;
+ setIsInactive(false); // Clear inactive state
+ }
+
+ lastActivityTimeRef.current = now;
+
+ // Clear existing inactivity timeout
+ if (inactivityTimeoutRef.current) {
+ clearTimeout(inactivityTimeoutRef.current);
+ }
+
+ // Set new inactivity timeout
+ if (activityTracking) {
+ inactivityTimeoutRef.current = setTimeout(() => {
+ if (isActiveRef.current) {
+ // User became inactive, accumulate the active time
+ const activeTime = Date.now() - lastIntervalTimeRef.current;
+ accumulatedActiveTimeRef.current += activeTime;
+ isActiveRef.current = false;
+ setIsInactive(true); // Set inactive state for UI
+ }
+ }, inactivityThreshold);
+ }
+ }, [activityTracking, inactivityThreshold]);
+
+ // Start initial inactivity timeout
+ const startInactivityTimeout = useCallback(() => {
+ if (!activityTracking) return;
+
+ // Clear any existing timeout
+ if (inactivityTimeoutRef.current) {
+ clearTimeout(inactivityTimeoutRef.current);
+ }
+
+ // Set initial inactivity timeout
+ inactivityTimeoutRef.current = setTimeout(() => {
+ if (isActiveRef.current) {
+ // User became inactive, accumulate the active time
+ const activeTime = Date.now() - lastIntervalTimeRef.current;
+ accumulatedActiveTimeRef.current += activeTime;
+ isActiveRef.current = false;
+ setIsInactive(true); // Set inactive state for UI
+ }
+ }, inactivityThreshold);
+ }, [activityTracking, inactivityThreshold]);
+
+ // Setup activity listeners
+ useEffect(() => {
+ if (!enableActivityDetection) return;
+
+ const events = ['mousedown', 'mousemove', 'keydown', 'keyup', 'scroll', 'touchstart', 'click'];
+
+ events.forEach(event => {
+ document.addEventListener(event, updateActivity, true);
+ });
+
+ // Start the initial inactivity timeout when activity detection is enabled
+ startInactivityTimeout();
+
+ return () => {
+ events.forEach(event => {
+ document.removeEventListener(event, updateActivity, true);
+ });
+ };
+ }, [updateActivity, enableActivityDetection, startInactivityTimeout]);
+
+ const trackPageViewSafely = useCallback(async (
data: TrackingData,
useBeacon: boolean = false,
): Promise<void> => {
@@ -64,21 +170,117 @@ export function useSafePageViewTracker() {
} finally {
isTrackingRef.current = false;
}
- };
+ }, []);
- const resetTrackingState = () => {
+ const getActiveDuration = useCallback(() => {
+
+ if (!activityTracking) {
+ return Date.now() - startTimeRef.current;
+ }
+
+ let totalActiveTime = accumulatedActiveTimeRef.current;
+
+ if (isActiveRef.current) {
+ // Add current active session time
+ totalActiveTime += Date.now() - lastIntervalTimeRef.current;
+ }
+
+ return totalActiveTime;
+ }, [activityTracking]);
+
+ const startIntervalTracking = useCallback((trackingData: Omit<TrackingData, 'duration'>) => {
+ if (!intervalTracking) return;
+
+ // Clear any existing interval
+ if (intervalIdRef.current) {
+ clearInterval(intervalIdRef.current);
+ }
+
+ // Reset timing references
+ const now = Date.now();
+ startTimeRef.current = now;
+ lastIntervalTimeRef.current = now;
+ accumulatedActiveTimeRef.current = 0;
+ isActiveRef.current = true;
+
+ // Start the inactivity timeout for activity tracking
+ startInactivityTimeout();
+
+ intervalIdRef.current = setInterval(() => {
+ const activeDuration = getActiveDuration();
+
+ // Only track if there's meaningful active time (at least 1 second)
+ if (activeDuration >= 1000) {
+ trackPageViewSafely({
+ ...trackingData,
+ duration: activeDuration,
+ }, false);
+
+ // Reset counters for next interval
+ accumulatedActiveTimeRef.current = 0;
+ lastIntervalTimeRef.current = Date.now();
+ startTimeRef.current = Date.now();
+ }
+ }, intervalDuration);
+ }, [intervalTracking, intervalDuration, getActiveDuration, trackPageViewSafely, startInactivityTimeout]);
+
+ const stopIntervalTracking = useCallback(() => {
+ if (intervalIdRef.current) {
+ clearInterval(intervalIdRef.current);
+ intervalIdRef.current = null;
+ }
+ if (inactivityTimeoutRef.current) {
+ clearTimeout(inactivityTimeoutRef.current);
+ inactivityTimeoutRef.current = null;
+ }
+ }, []);
+
+ const resetTrackingState = useCallback(() => {
hasTrackedUnloadRef.current = false;
isTrackingRef.current = false;
- };
+ lastActivityTimeRef.current = Date.now();
+ isActiveRef.current = true;
+ accumulatedActiveTimeRef.current = 0;
+ setIsInactive(false); // Clear inactive state
+
+ const now = Date.now();
+ startTimeRef.current = now;
+ lastIntervalTimeRef.current = now;
+
+ // Clear timeouts
+ if (inactivityTimeoutRef.current) {
+ clearTimeout(inactivityTimeoutRef.current);
+ inactivityTimeoutRef.current = null;
+ }
+
+ // Restart inactivity timeout if activity tracking is enabled
+ startInactivityTimeout();
+ }, [startInactivityTimeout]);
+
+ // TODO: for debugging
+ // const getTrackingState = () => ({
+ // hasTrackedUnload: hasTrackedUnloadRef.current,
+ // isTracking: isTrackingRef.current,
+ // isActive: isActiveRef.current,
+ // lastActivityTime: lastActivityTimeRef.current,
+ // accumulatedActiveTime: accumulatedActiveTimeRef.current,
+ // });
- const getTrackingState = () => ({
- hasTrackedUnload: hasTrackedUnloadRef.current,
- isTracking: isTrackingRef.current,
- });
+ // Cleanup on unmount
+ useEffect(() => {
+ return () => {
+ stopIntervalTracking();
+ };
+ }, [stopIntervalTracking]);
return {
trackPageViewSafely,
resetTrackingState,
- getTrackingState,
+ // getTrackingState,
+ startIntervalTracking,
+ stopIntervalTracking,
+ getActiveDuration,
+ updateActivity,
+ isInactive,
};
}
\ No newline at end of file
diff --git a/lib/tracking/tracking-config.ts b/lib/tracking/tracking-config.ts
new file mode 100644
index 00000000..227ef9df
--- /dev/null
+++ b/lib/tracking/tracking-config.ts
@@ -0,0 +1,25 @@
+export const TRACKING_CONFIG = {
+ // Interval tracking settings
+ INTERVAL_TRACKING_ENABLED: true,
+ INTERVAL_DURATION: 10000, // 10 seconds (in milliseconds)
+
+ // Activity tracking settings
+ ACTIVITY_TRACKING_ENABLED: true,
+ INACTIVITY_THRESHOLD: 60000, // 1 minute (in milliseconds)
+
+ // Activity detection settings
+ ACTIVITY_DETECTION_ENABLED: true,
+
+ // Minimum duration to track (prevents very short sessions)
+ MIN_TRACKING_DURATION: 1000, // 1 second (in milliseconds)
+} as const;
+
+export function getTrackingOptions(overrides: Partial<typeof TRACKING_CONFIG> = {}) {
+ return {
+ intervalTracking: overrides.INTERVAL_TRACKING_ENABLED ?? TRACKING_CONFIG.INTERVAL_TRACKING_ENABLED,
+ intervalDuration: overrides.INTERVAL_DURATION ?? TRACKING_CONFIG.INTERVAL_DURATION,
+ activityTracking: overrides.ACTIVITY_TRACKING_ENABLED ?? TRACKING_CONFIG.ACTIVITY_TRACKING_ENABLED,
+ inactivityThreshold: overrides.INACTIVITY_THRESHOLD ?? TRACKING_CONFIG.INACTIVITY_THRESHOLD,
+ enableActivityDetection: overrides.ACTIVITY_DETECTION_ENABLED ?? TRACKING_CONFIG.ACTIVITY_DETECTION_ENABLED,
+ };
+}
\ No newline at end of file
diff --git a/lib/utils/reliable-tracking.ts b/lib/utils/reliable-tracking.ts
index ef1b2339..87945a1d 100644
--- a/lib/utils/reliable-tracking.ts
+++ b/lib/utils/reliable-tracking.ts
@@ -10,7 +10,6 @@ interface TrackingData {
}
interface TrackingOptions {
- useBeacon?: boolean;
retryAttempts?: number;
retryDelay?: number;
}