Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions app/api/timeTracker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"use client";

import { useEffect, useRef } from "react";

export function useTimeTracker(sectionId: string) {
const ref = useRef<HTMLDivElement>(null);
const startTime = useRef<number | null>(null);

useEffect(() => {
if (!ref.current) return;

const observer = new IntersectionObserver(([entry]) => {
if (entry.isIntersecting) {
if (startTime.current === null) {
startTime.current = Date.now();
}
} else {
if (startTime.current !== null) {
const durationMs = Date.now() - startTime.current;

void fetch("/api/track", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
event_type: "component_view",
payload: {
sectionId,
durationMs,
},
}),
keepalive: true,
});

startTime.current = null;
}
}
}, { threshold: 0 }); //start when feature first appears

observer.observe(ref.current);

return () => {
observer.disconnect();
};
}, [sectionId]);

return ref;
}