UNPKG

@asgerami/zemenay-blog

Version:

Plug-and-play blog system for Next.js - Get a fully functional blog running in minutes with zero configuration

81 lines (80 loc) 2.94 kB
"use strict"; "use client"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useAnalytics = useAnalytics; exports.useScrollTracking = useScrollTracking; const react_1 = require("react"); const analytics_1 = require("../lib/analytics"); /** * Hook to automatically track analytics for a blog post */ function useAnalytics(postId, options = {}) { const { trackViews = true, trackTimeOnPage: trackTime = true, sessionDuration = 30, } = options; const timeTrackingCleanup = (0, react_1.useRef)(null); const hasTrackedView = (0, react_1.useRef)(false); (0, react_1.useEffect)(() => { if (!postId) return; // Track page view if (trackViews && !hasTrackedView.current) { (0, analytics_1.trackPostView)(postId, { sessionDuration }) .then((result) => { if (result.success) { hasTrackedView.current = true; } }) .catch((error) => { console.error("Failed to track view:", error); }); } // Track time on page if (trackTime) { timeTrackingCleanup.current = (0, analytics_1.trackTimeOnPage)(postId); } // Cleanup function return () => { if (timeTrackingCleanup.current) { timeTrackingCleanup.current(); timeTrackingCleanup.current = null; } }; }, [postId, trackViews, trackTime, sessionDuration]); // Cleanup on unmount (0, react_1.useEffect)(() => { return () => { if (timeTrackingCleanup.current) { timeTrackingCleanup.current(); } }; }, []); } /** * Hook to track scroll depth */ function useScrollTracking(postId) { const scrollDepthTracked = (0, react_1.useRef)(new Set()); (0, react_1.useEffect)(() => { if (!postId) return; const handleScroll = () => { const scrollPercent = Math.round((window.scrollY / (document.documentElement.scrollHeight - window.innerHeight)) * 100); // Track at 25%, 50%, 75%, and 100% scroll depths const milestones = [25, 50, 75, 100]; for (const milestone of milestones) { if (scrollPercent >= milestone && !scrollDepthTracked.current.has(milestone)) { scrollDepthTracked.current.add(milestone); // Track the scroll depth console.log(`Scroll depth: ${milestone}% for post ${postId}`); // Note: We could track this to the database if needed } } }; window.addEventListener("scroll", handleScroll, { passive: true }); return () => { window.removeEventListener("scroll", handleScroll); }; }, [postId]); }