UNPKG

@dotcms/analytics

Version:

Official JavaScript library for Content Analytics with DotCMS.

68 lines (67 loc) 2.73 kB
import { ANALYTICS_WINDOWS_ACTIVE_KEY as a, ANALYTICS_WINDOWS_CLEANUP_KEY as o } from "../../../../uve/src/internal/constants.js"; import { DEFAULT_SESSION_TIMEOUT_MINUTES as r, ACTIVITY_EVENTS as l } from "../../shared/constants/dot-analytics.constants.js"; class v { constructor() { this.activityListeners = [], this.lastActivityTime = Date.now(), this.inactivityTimer = null, this.isThrottled = !1, this.config = null, this.ACTIVITY_THROTTLE_MS = 1e3; } // Throttle activity events to max 1 per second /** * Updates activity timestamp (throttled for performance) */ updateActivityTime() { this.lastActivityTime = Date.now(), this.inactivityTimer && clearTimeout(this.inactivityTimer), this.inactivityTimer = setTimeout( () => { var i; (i = this.config) != null && i.debug && console.warn("DotCMS Analytics [Activity]: User became inactive after timeout"), this.inactivityTimer = null; }, r * 60 * 1e3 ); } /** * Updates session activity with throttling */ updateSessionActivity() { this.isThrottled || (this.isThrottled = !0, this.updateActivityTime(), setTimeout(() => { this.isThrottled = !1; }, this.ACTIVITY_THROTTLE_MS)); } /** * Initializes activity tracking with event listeners */ initialize(i) { if (this.cleanup(), this.config = i, typeof window > "u") return; const s = () => this.updateSessionActivity(); l.forEach((c) => { window.addEventListener(c, s, { passive: !0 }), this.activityListeners.push( () => window.removeEventListener(c, s) ); }); const n = () => { document.visibilityState === "visible" && (this.updateSessionActivity(), i.debug && console.warn( "DotCMS Analytics [Activity]: User returned to tab, session reactivated" )); }; document.addEventListener("visibilitychange", n), this.activityListeners.push( () => document.removeEventListener("visibilitychange", n) ), this.updateActivityTime(), i.debug && console.warn("DotCMS Analytics [Activity]: Activity tracking initialized"); } /** * Cleans up all activity tracking listeners */ cleanup() { this.activityListeners.forEach((i) => i()), this.activityListeners = [], this.inactivityTimer && (clearTimeout(this.inactivityTimer), this.inactivityTimer = null), this.config = null; } } const t = new v(), d = () => { t.updateSessionActivity(); }, u = (e) => { t.initialize(e); }, y = () => { t.cleanup(), typeof window < "u" && (window[a] = !1, window[o] = void 0, window.dispatchEvent(new CustomEvent("dotcms:analytics:cleanup"))); }; export { y as cleanupActivityTracking, u as initializeActivityTracking, d as updateSessionActivity };