@dotcms/analytics
Version:
Official JavaScript library for Content Analytics with DotCMS.
87 lines (86 loc) • 2.85 kB
JavaScript
import { DEFAULT_SESSION_TIMEOUT_MINUTES as c, ACTIVITY_EVENTS as r } from "./dot-content-analytics.constants.js";
class o {
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: User became inactive after timeout"), this.inactivityTimer = null;
},
c * 60 * 1e3
);
}
/**
* Checks if user has been inactive
*/
isUserInactive() {
const i = c * 60 * 1e3;
return Date.now() - this.lastActivityTime > i;
}
/**
* Gets last activity time
*/
getLastActivity() {
return this.lastActivityTime;
}
/**
* 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();
r.forEach((a) => {
window.addEventListener(a, s, { passive: !0 }), this.activityListeners.push(
() => window.removeEventListener(a, s)
);
});
const n = () => {
document.visibilityState === "visible" && (this.updateSessionActivity(), i.debug && console.warn("DotCMS Analytics: 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 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;
}
/**
* Gets session information for debugging
*/
getSessionInfo() {
return {
lastActivity: this.getLastActivity(),
isActive: !this.isUserInactive()
};
}
}
const t = new o(), h = () => {
t.updateSessionActivity();
}, l = (e) => {
t.initialize(e);
}, T = () => {
t.cleanup();
};
export {
T as cleanupActivityTracking,
l as initializeActivityTracking,
h as updateSessionActivity
};