diff --git a/app/api/timeTracker.ts b/app/api/timeTracker.ts new file mode 100644 index 0000000..e65ae98 --- /dev/null +++ b/app/api/timeTracker.ts @@ -0,0 +1,47 @@ +"use client"; + +import { useEffect, useRef } from "react"; + +export function useTimeTracker(sectionId: string) { + const ref = useRef(null); + const startTime = useRef(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; +} \ No newline at end of file