nova-hooks 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +232 -0
- package/dist/index.es.js +213 -0
- package/dist/src/event-bus.d.ts +31 -0
- package/dist/src/hooks.d.ts +17 -0
- package/dist/src/index.d.ts +3 -0
- package/dist/src/socket.d.ts +12 -0
- package/package.json +52 -0
- package/readme.md +141 -0
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
let socket_io_client = require("socket.io-client");
|
|
3
|
+
let react = require("react");
|
|
4
|
+
//#region src/socket.ts
|
|
5
|
+
var socket;
|
|
6
|
+
var projectName;
|
|
7
|
+
/**
|
|
8
|
+
* Connects to the socket server and emits a connection event
|
|
9
|
+
* @param socketUrl The URL of the socket server to connect to
|
|
10
|
+
*/
|
|
11
|
+
var connectSocket = (socketUrl, project) => {
|
|
12
|
+
if (!socketUrl || socketUrl.trim() === "") throw new Error("Socket URL is required to connect.");
|
|
13
|
+
if (!project || project.trim() === "") throw new Error("Project name is required to connect.");
|
|
14
|
+
if (socket) return;
|
|
15
|
+
socket = (0, socket_io_client.io)(socketUrl);
|
|
16
|
+
projectName = project;
|
|
17
|
+
socket.on("connect", () => {
|
|
18
|
+
console.log("Nova socket connected");
|
|
19
|
+
});
|
|
20
|
+
socket.on("disconnect", () => {
|
|
21
|
+
console.log("Nova socket disconnected");
|
|
22
|
+
});
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Disconnects the socket server and cleans up the instance
|
|
26
|
+
*/
|
|
27
|
+
var disconnectSocket = () => {
|
|
28
|
+
if (socket) {
|
|
29
|
+
socket.disconnect();
|
|
30
|
+
socket = void 0;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
//#region src/event-bus.ts
|
|
35
|
+
var SimpleEventEmitter = class {
|
|
36
|
+
listeners = {};
|
|
37
|
+
on(event, callback) {
|
|
38
|
+
if (!this.listeners[event]) this.listeners[event] = [];
|
|
39
|
+
this.listeners[event].push(callback);
|
|
40
|
+
}
|
|
41
|
+
emit(event, data) {
|
|
42
|
+
if (this.listeners[event]) this.listeners[event].forEach((cb) => cb(data));
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var ActionType = {
|
|
46
|
+
Button: "Button",
|
|
47
|
+
Menu: "Menu",
|
|
48
|
+
Login: "Login",
|
|
49
|
+
Link: "Link"
|
|
50
|
+
};
|
|
51
|
+
var PageVisitAction = "Page Visit";
|
|
52
|
+
var APP_EVENT = "APP_EVENT";
|
|
53
|
+
var eventBus = new SimpleEventEmitter();
|
|
54
|
+
var NOVA_USER_ACTIVITY_EVENT = "nova-user-activity";
|
|
55
|
+
var pendingClicks = /* @__PURE__ */ new Map();
|
|
56
|
+
var batchTimer = null;
|
|
57
|
+
/**
|
|
58
|
+
* Event listener for APP_EVENT that processes and enriches event data
|
|
59
|
+
* Adds project name, timestamp, and page context before sending to server
|
|
60
|
+
*/
|
|
61
|
+
eventBus.on(APP_EVENT, (eventData) => {
|
|
62
|
+
if (!eventData) return;
|
|
63
|
+
try {
|
|
64
|
+
if (!socket) {
|
|
65
|
+
console.warn("Nova socket is not initialized. Please call connectSocket first.");
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const pageUrl = typeof window !== "undefined" ? window.location.pathname : "Unknown";
|
|
69
|
+
const pageTitle = typeof document !== "undefined" ? document.title : "Unknown";
|
|
70
|
+
const enrichedEvent = {
|
|
71
|
+
...eventData,
|
|
72
|
+
Project: projectName,
|
|
73
|
+
CreatedDate: (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", ""),
|
|
74
|
+
PageUrl: pageUrl,
|
|
75
|
+
PageTitle: pageTitle
|
|
76
|
+
};
|
|
77
|
+
if (enrichedEvent.ActionType !== "Page Visit") {
|
|
78
|
+
const key = `${enrichedEvent.ActionType}-${enrichedEvent.Action}-${enrichedEvent.PageUrl}`;
|
|
79
|
+
if (pendingClicks.has(key)) {
|
|
80
|
+
const existing = pendingClicks.get(key);
|
|
81
|
+
if ("Count" in existing && "Count" in enrichedEvent) existing.Count += enrichedEvent.Count || 1;
|
|
82
|
+
existing.CreatedDate = enrichedEvent.CreatedDate;
|
|
83
|
+
} else pendingClicks.set(key, enrichedEvent);
|
|
84
|
+
if (!batchTimer) batchTimer = setTimeout(() => {
|
|
85
|
+
pendingClicks.forEach((event) => {
|
|
86
|
+
socket?.emit(NOVA_USER_ACTIVITY_EVENT, event);
|
|
87
|
+
});
|
|
88
|
+
pendingClicks.clear();
|
|
89
|
+
batchTimer = null;
|
|
90
|
+
}, 1e3);
|
|
91
|
+
} else socket?.emit(NOVA_USER_ACTIVITY_EVENT, enrichedEvent);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
console.error("Nova Error: ", error);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
/**
|
|
97
|
+
* Emits an event with the provided event data and optionally executes a callback function
|
|
98
|
+
* @param eventData The event data to be emitted
|
|
99
|
+
* @param callback Optional callback function to be executed before emitting the event
|
|
100
|
+
*/
|
|
101
|
+
function withEvent(eventData, callback) {
|
|
102
|
+
if (callback && typeof callback === "function") callback();
|
|
103
|
+
eventBus.emit(APP_EVENT, eventData);
|
|
104
|
+
}
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/hooks.ts
|
|
107
|
+
var getCssPath = (el) => {
|
|
108
|
+
const path = [];
|
|
109
|
+
let current = el;
|
|
110
|
+
while (current && current.nodeType === Node.ELEMENT_NODE && current !== document.body) {
|
|
111
|
+
let selector = current.tagName.toLowerCase();
|
|
112
|
+
if (current.id) {
|
|
113
|
+
selector += `#${current.id}`;
|
|
114
|
+
path.unshift(selector);
|
|
115
|
+
break;
|
|
116
|
+
} else if (current.className && typeof current.className === "string") selector += `.${current.className.trim().split(/\s+/).join(".")}`;
|
|
117
|
+
path.unshift(selector);
|
|
118
|
+
current = current.parentElement;
|
|
119
|
+
}
|
|
120
|
+
return path.join(" > ");
|
|
121
|
+
};
|
|
122
|
+
/**
|
|
123
|
+
* Hook to track global click events and emit them to the server
|
|
124
|
+
* Listens for click events on the document and automatically captures button/link clicks
|
|
125
|
+
* @param empId Optional employee ID for tracking
|
|
126
|
+
* @param roleId Optional role ID for tracking
|
|
127
|
+
*/
|
|
128
|
+
var useGlobalClickTracker = (empId, roleId) => {
|
|
129
|
+
(0, react.useEffect)(() => {
|
|
130
|
+
if (typeof window === "undefined") return;
|
|
131
|
+
const handler = (e) => {
|
|
132
|
+
let target = e.target;
|
|
133
|
+
while (target && target !== document.body) {
|
|
134
|
+
let trackId = target.getAttribute("data-nova-track-id");
|
|
135
|
+
let actionType = target.getAttribute("data-nova-track-type");
|
|
136
|
+
if (!trackId) {
|
|
137
|
+
const tagName = target.tagName.toLowerCase();
|
|
138
|
+
const role = target.getAttribute("role");
|
|
139
|
+
const isButton = tagName === "button" || role === "button" || tagName === "input" && (target.type === "submit" || target.type === "button");
|
|
140
|
+
const isLink = tagName === "a";
|
|
141
|
+
const isInteractiveRole = role === "menuitem" || role === "tab" || role === "option";
|
|
142
|
+
const isClickableDiv = window.getComputedStyle(target).cursor === "pointer";
|
|
143
|
+
if (isButton || isLink || isInteractiveRole || isClickableDiv) {
|
|
144
|
+
trackId = target.innerText?.trim() || target.getAttribute("aria-label")?.trim() || target.title?.trim() || target.getAttribute("name")?.trim() || `[UI Path] ${getCssPath(target)}`;
|
|
145
|
+
actionType = isLink ? "Link" : isButton ? "Button" : "Menu";
|
|
146
|
+
if (trackId.length > 80) trackId = trackId.substring(0, 80) + "...";
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (trackId && actionType) {
|
|
150
|
+
withEvent({
|
|
151
|
+
Action: trackId,
|
|
152
|
+
ActionType: actionType,
|
|
153
|
+
EmpId: empId || "UNKNOWN",
|
|
154
|
+
EmpRole: roleId || "UNKNOWN",
|
|
155
|
+
Count: 1
|
|
156
|
+
});
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
target = target.parentElement;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
document.addEventListener("click", handler);
|
|
163
|
+
return () => {
|
|
164
|
+
document.removeEventListener("click", handler);
|
|
165
|
+
};
|
|
166
|
+
}, [empId, roleId]);
|
|
167
|
+
};
|
|
168
|
+
var DURATION_THRESHOLD = 5;
|
|
169
|
+
/**
|
|
170
|
+
* Hook to track accurate active page visit duration
|
|
171
|
+
* Uses Page Visibility API to only count time when the tab is actively visible
|
|
172
|
+
* @param action The action name for the page visit
|
|
173
|
+
* @param empId Optional employee ID for tracking
|
|
174
|
+
* @param empRole Optional employee role for tracking
|
|
175
|
+
*/
|
|
176
|
+
var usePageTimeTracker = (action, empId, empRole) => {
|
|
177
|
+
const activeTimeRef = (0, react.useRef)(0);
|
|
178
|
+
const lastVisibleTimeRef = (0, react.useRef)(Date.now());
|
|
179
|
+
const isVisibleRef = (0, react.useRef)(true);
|
|
180
|
+
(0, react.useEffect)(() => {
|
|
181
|
+
if (typeof window === "undefined") return;
|
|
182
|
+
lastVisibleTimeRef.current = Date.now();
|
|
183
|
+
isVisibleRef.current = document.visibilityState === "visible";
|
|
184
|
+
const handleVisibilityChange = () => {
|
|
185
|
+
if (document.visibilityState === "visible") {
|
|
186
|
+
lastVisibleTimeRef.current = Date.now();
|
|
187
|
+
isVisibleRef.current = true;
|
|
188
|
+
} else {
|
|
189
|
+
if (isVisibleRef.current) activeTimeRef.current += Date.now() - lastVisibleTimeRef.current;
|
|
190
|
+
isVisibleRef.current = false;
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
document.addEventListener("visibilitychange", handleVisibilityChange);
|
|
194
|
+
return () => {
|
|
195
|
+
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
|
196
|
+
let totalActiveTime = activeTimeRef.current;
|
|
197
|
+
if (isVisibleRef.current) totalActiveTime += Date.now() - lastVisibleTimeRef.current;
|
|
198
|
+
const duration = Math.round(totalActiveTime / 1e3);
|
|
199
|
+
if (duration > DURATION_THRESHOLD) withEvent({
|
|
200
|
+
Action: action,
|
|
201
|
+
ActionType: PageVisitAction,
|
|
202
|
+
EmpId: empId || "UNKNOWN",
|
|
203
|
+
EmpRole: empRole || "UNKNOWN",
|
|
204
|
+
Duration: duration
|
|
205
|
+
});
|
|
206
|
+
};
|
|
207
|
+
}, [
|
|
208
|
+
action,
|
|
209
|
+
empId,
|
|
210
|
+
empRole
|
|
211
|
+
]);
|
|
212
|
+
};
|
|
213
|
+
//#endregion
|
|
214
|
+
exports.ActionType = ActionType;
|
|
215
|
+
exports.PageVisitAction = PageVisitAction;
|
|
216
|
+
exports.connectSocket = connectSocket;
|
|
217
|
+
exports.disconnectSocket = disconnectSocket;
|
|
218
|
+
Object.defineProperty(exports, "projectName", {
|
|
219
|
+
enumerable: true,
|
|
220
|
+
get: function() {
|
|
221
|
+
return projectName;
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
Object.defineProperty(exports, "socket", {
|
|
225
|
+
enumerable: true,
|
|
226
|
+
get: function() {
|
|
227
|
+
return socket;
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
exports.useGlobalClickTracker = useGlobalClickTracker;
|
|
231
|
+
exports.usePageTimeTracker = usePageTimeTracker;
|
|
232
|
+
exports.withEvent = withEvent;
|
package/dist/index.es.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { io } from "socket.io-client";
|
|
2
|
+
import { useEffect, useRef } from "react";
|
|
3
|
+
//#region src/socket.ts
|
|
4
|
+
var socket;
|
|
5
|
+
var projectName;
|
|
6
|
+
/**
|
|
7
|
+
* Connects to the socket server and emits a connection event
|
|
8
|
+
* @param socketUrl The URL of the socket server to connect to
|
|
9
|
+
*/
|
|
10
|
+
var connectSocket = (socketUrl, project) => {
|
|
11
|
+
if (!socketUrl || socketUrl.trim() === "") throw new Error("Socket URL is required to connect.");
|
|
12
|
+
if (!project || project.trim() === "") throw new Error("Project name is required to connect.");
|
|
13
|
+
if (socket) return;
|
|
14
|
+
socket = io(socketUrl);
|
|
15
|
+
projectName = project;
|
|
16
|
+
socket.on("connect", () => {
|
|
17
|
+
console.log("Nova socket connected");
|
|
18
|
+
});
|
|
19
|
+
socket.on("disconnect", () => {
|
|
20
|
+
console.log("Nova socket disconnected");
|
|
21
|
+
});
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Disconnects the socket server and cleans up the instance
|
|
25
|
+
*/
|
|
26
|
+
var disconnectSocket = () => {
|
|
27
|
+
if (socket) {
|
|
28
|
+
socket.disconnect();
|
|
29
|
+
socket = void 0;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/event-bus.ts
|
|
34
|
+
var SimpleEventEmitter = class {
|
|
35
|
+
listeners = {};
|
|
36
|
+
on(event, callback) {
|
|
37
|
+
if (!this.listeners[event]) this.listeners[event] = [];
|
|
38
|
+
this.listeners[event].push(callback);
|
|
39
|
+
}
|
|
40
|
+
emit(event, data) {
|
|
41
|
+
if (this.listeners[event]) this.listeners[event].forEach((cb) => cb(data));
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
var ActionType = {
|
|
45
|
+
Button: "Button",
|
|
46
|
+
Menu: "Menu",
|
|
47
|
+
Login: "Login",
|
|
48
|
+
Link: "Link"
|
|
49
|
+
};
|
|
50
|
+
var PageVisitAction = "Page Visit";
|
|
51
|
+
var APP_EVENT = "APP_EVENT";
|
|
52
|
+
var eventBus = new SimpleEventEmitter();
|
|
53
|
+
var NOVA_USER_ACTIVITY_EVENT = "nova-user-activity";
|
|
54
|
+
var pendingClicks = /* @__PURE__ */ new Map();
|
|
55
|
+
var batchTimer = null;
|
|
56
|
+
/**
|
|
57
|
+
* Event listener for APP_EVENT that processes and enriches event data
|
|
58
|
+
* Adds project name, timestamp, and page context before sending to server
|
|
59
|
+
*/
|
|
60
|
+
eventBus.on(APP_EVENT, (eventData) => {
|
|
61
|
+
if (!eventData) return;
|
|
62
|
+
try {
|
|
63
|
+
if (!socket) {
|
|
64
|
+
console.warn("Nova socket is not initialized. Please call connectSocket first.");
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const pageUrl = typeof window !== "undefined" ? window.location.pathname : "Unknown";
|
|
68
|
+
const pageTitle = typeof document !== "undefined" ? document.title : "Unknown";
|
|
69
|
+
const enrichedEvent = {
|
|
70
|
+
...eventData,
|
|
71
|
+
Project: projectName,
|
|
72
|
+
CreatedDate: (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace("Z", ""),
|
|
73
|
+
PageUrl: pageUrl,
|
|
74
|
+
PageTitle: pageTitle
|
|
75
|
+
};
|
|
76
|
+
if (enrichedEvent.ActionType !== "Page Visit") {
|
|
77
|
+
const key = `${enrichedEvent.ActionType}-${enrichedEvent.Action}-${enrichedEvent.PageUrl}`;
|
|
78
|
+
if (pendingClicks.has(key)) {
|
|
79
|
+
const existing = pendingClicks.get(key);
|
|
80
|
+
if ("Count" in existing && "Count" in enrichedEvent) existing.Count += enrichedEvent.Count || 1;
|
|
81
|
+
existing.CreatedDate = enrichedEvent.CreatedDate;
|
|
82
|
+
} else pendingClicks.set(key, enrichedEvent);
|
|
83
|
+
if (!batchTimer) batchTimer = setTimeout(() => {
|
|
84
|
+
pendingClicks.forEach((event) => {
|
|
85
|
+
socket?.emit(NOVA_USER_ACTIVITY_EVENT, event);
|
|
86
|
+
});
|
|
87
|
+
pendingClicks.clear();
|
|
88
|
+
batchTimer = null;
|
|
89
|
+
}, 1e3);
|
|
90
|
+
} else socket?.emit(NOVA_USER_ACTIVITY_EVENT, enrichedEvent);
|
|
91
|
+
} catch (error) {
|
|
92
|
+
console.error("Nova Error: ", error);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
/**
|
|
96
|
+
* Emits an event with the provided event data and optionally executes a callback function
|
|
97
|
+
* @param eventData The event data to be emitted
|
|
98
|
+
* @param callback Optional callback function to be executed before emitting the event
|
|
99
|
+
*/
|
|
100
|
+
function withEvent(eventData, callback) {
|
|
101
|
+
if (callback && typeof callback === "function") callback();
|
|
102
|
+
eventBus.emit(APP_EVENT, eventData);
|
|
103
|
+
}
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/hooks.ts
|
|
106
|
+
var getCssPath = (el) => {
|
|
107
|
+
const path = [];
|
|
108
|
+
let current = el;
|
|
109
|
+
while (current && current.nodeType === Node.ELEMENT_NODE && current !== document.body) {
|
|
110
|
+
let selector = current.tagName.toLowerCase();
|
|
111
|
+
if (current.id) {
|
|
112
|
+
selector += `#${current.id}`;
|
|
113
|
+
path.unshift(selector);
|
|
114
|
+
break;
|
|
115
|
+
} else if (current.className && typeof current.className === "string") selector += `.${current.className.trim().split(/\s+/).join(".")}`;
|
|
116
|
+
path.unshift(selector);
|
|
117
|
+
current = current.parentElement;
|
|
118
|
+
}
|
|
119
|
+
return path.join(" > ");
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Hook to track global click events and emit them to the server
|
|
123
|
+
* Listens for click events on the document and automatically captures button/link clicks
|
|
124
|
+
* @param empId Optional employee ID for tracking
|
|
125
|
+
* @param roleId Optional role ID for tracking
|
|
126
|
+
*/
|
|
127
|
+
var useGlobalClickTracker = (empId, roleId) => {
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
if (typeof window === "undefined") return;
|
|
130
|
+
const handler = (e) => {
|
|
131
|
+
let target = e.target;
|
|
132
|
+
while (target && target !== document.body) {
|
|
133
|
+
let trackId = target.getAttribute("data-nova-track-id");
|
|
134
|
+
let actionType = target.getAttribute("data-nova-track-type");
|
|
135
|
+
if (!trackId) {
|
|
136
|
+
const tagName = target.tagName.toLowerCase();
|
|
137
|
+
const role = target.getAttribute("role");
|
|
138
|
+
const isButton = tagName === "button" || role === "button" || tagName === "input" && (target.type === "submit" || target.type === "button");
|
|
139
|
+
const isLink = tagName === "a";
|
|
140
|
+
const isInteractiveRole = role === "menuitem" || role === "tab" || role === "option";
|
|
141
|
+
const isClickableDiv = window.getComputedStyle(target).cursor === "pointer";
|
|
142
|
+
if (isButton || isLink || isInteractiveRole || isClickableDiv) {
|
|
143
|
+
trackId = target.innerText?.trim() || target.getAttribute("aria-label")?.trim() || target.title?.trim() || target.getAttribute("name")?.trim() || `[UI Path] ${getCssPath(target)}`;
|
|
144
|
+
actionType = isLink ? "Link" : isButton ? "Button" : "Menu";
|
|
145
|
+
if (trackId.length > 80) trackId = trackId.substring(0, 80) + "...";
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (trackId && actionType) {
|
|
149
|
+
withEvent({
|
|
150
|
+
Action: trackId,
|
|
151
|
+
ActionType: actionType,
|
|
152
|
+
EmpId: empId || "UNKNOWN",
|
|
153
|
+
EmpRole: roleId || "UNKNOWN",
|
|
154
|
+
Count: 1
|
|
155
|
+
});
|
|
156
|
+
break;
|
|
157
|
+
}
|
|
158
|
+
target = target.parentElement;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
document.addEventListener("click", handler);
|
|
162
|
+
return () => {
|
|
163
|
+
document.removeEventListener("click", handler);
|
|
164
|
+
};
|
|
165
|
+
}, [empId, roleId]);
|
|
166
|
+
};
|
|
167
|
+
var DURATION_THRESHOLD = 5;
|
|
168
|
+
/**
|
|
169
|
+
* Hook to track accurate active page visit duration
|
|
170
|
+
* Uses Page Visibility API to only count time when the tab is actively visible
|
|
171
|
+
* @param action The action name for the page visit
|
|
172
|
+
* @param empId Optional employee ID for tracking
|
|
173
|
+
* @param empRole Optional employee role for tracking
|
|
174
|
+
*/
|
|
175
|
+
var usePageTimeTracker = (action, empId, empRole) => {
|
|
176
|
+
const activeTimeRef = useRef(0);
|
|
177
|
+
const lastVisibleTimeRef = useRef(Date.now());
|
|
178
|
+
const isVisibleRef = useRef(true);
|
|
179
|
+
useEffect(() => {
|
|
180
|
+
if (typeof window === "undefined") return;
|
|
181
|
+
lastVisibleTimeRef.current = Date.now();
|
|
182
|
+
isVisibleRef.current = document.visibilityState === "visible";
|
|
183
|
+
const handleVisibilityChange = () => {
|
|
184
|
+
if (document.visibilityState === "visible") {
|
|
185
|
+
lastVisibleTimeRef.current = Date.now();
|
|
186
|
+
isVisibleRef.current = true;
|
|
187
|
+
} else {
|
|
188
|
+
if (isVisibleRef.current) activeTimeRef.current += Date.now() - lastVisibleTimeRef.current;
|
|
189
|
+
isVisibleRef.current = false;
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
document.addEventListener("visibilitychange", handleVisibilityChange);
|
|
193
|
+
return () => {
|
|
194
|
+
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
|
195
|
+
let totalActiveTime = activeTimeRef.current;
|
|
196
|
+
if (isVisibleRef.current) totalActiveTime += Date.now() - lastVisibleTimeRef.current;
|
|
197
|
+
const duration = Math.round(totalActiveTime / 1e3);
|
|
198
|
+
if (duration > DURATION_THRESHOLD) withEvent({
|
|
199
|
+
Action: action,
|
|
200
|
+
ActionType: PageVisitAction,
|
|
201
|
+
EmpId: empId || "UNKNOWN",
|
|
202
|
+
EmpRole: empRole || "UNKNOWN",
|
|
203
|
+
Duration: duration
|
|
204
|
+
});
|
|
205
|
+
};
|
|
206
|
+
}, [
|
|
207
|
+
action,
|
|
208
|
+
empId,
|
|
209
|
+
empRole
|
|
210
|
+
]);
|
|
211
|
+
};
|
|
212
|
+
//#endregion
|
|
213
|
+
export { ActionType, PageVisitAction, connectSocket, disconnectSocket, projectName, socket, useGlobalClickTracker, usePageTimeTracker, withEvent };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare const ActionType: {
|
|
2
|
+
readonly Button: "Button";
|
|
3
|
+
readonly Menu: "Menu";
|
|
4
|
+
readonly Login: "Login";
|
|
5
|
+
readonly Link: "Link";
|
|
6
|
+
};
|
|
7
|
+
export declare const PageVisitAction = "Page Visit";
|
|
8
|
+
/**
|
|
9
|
+
* Represents the structure of event data that can be emitted
|
|
10
|
+
* Can be either a click event (Button/Menu) with a count
|
|
11
|
+
* or a page visit event with duration in seconds
|
|
12
|
+
*/
|
|
13
|
+
export type EventData = {
|
|
14
|
+
ActionType: keyof typeof ActionType;
|
|
15
|
+
Action: string;
|
|
16
|
+
EmpId: string;
|
|
17
|
+
EmpRole: string;
|
|
18
|
+
Count: number;
|
|
19
|
+
} | {
|
|
20
|
+
ActionType: typeof PageVisitAction;
|
|
21
|
+
Action: string;
|
|
22
|
+
EmpId: string;
|
|
23
|
+
EmpRole: string;
|
|
24
|
+
Duration: number;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Emits an event with the provided event data and optionally executes a callback function
|
|
28
|
+
* @param eventData The event data to be emitted
|
|
29
|
+
* @param callback Optional callback function to be executed before emitting the event
|
|
30
|
+
*/
|
|
31
|
+
export declare function withEvent(eventData: EventData, callback?: () => void): void;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { EventData } from './event-bus';
|
|
2
|
+
/**
|
|
3
|
+
* Hook to track global click events and emit them to the server
|
|
4
|
+
* Listens for click events on the document and automatically captures button/link clicks
|
|
5
|
+
* @param empId Optional employee ID for tracking
|
|
6
|
+
* @param roleId Optional role ID for tracking
|
|
7
|
+
*/
|
|
8
|
+
declare const useGlobalClickTracker: (empId?: string, roleId?: string) => void;
|
|
9
|
+
/**
|
|
10
|
+
* Hook to track accurate active page visit duration
|
|
11
|
+
* Uses Page Visibility API to only count time when the tab is actively visible
|
|
12
|
+
* @param action The action name for the page visit
|
|
13
|
+
* @param empId Optional employee ID for tracking
|
|
14
|
+
* @param empRole Optional employee role for tracking
|
|
15
|
+
*/
|
|
16
|
+
declare const usePageTimeTracker: (action: EventData["Action"], empId?: EventData["EmpId"], empRole?: EventData["EmpRole"]) => void;
|
|
17
|
+
export { useGlobalClickTracker, usePageTimeTracker };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { io } from 'socket.io-client';
|
|
2
|
+
export declare let socket: ReturnType<typeof io> | undefined;
|
|
3
|
+
export declare let projectName: string | number;
|
|
4
|
+
/**
|
|
5
|
+
* Connects to the socket server and emits a connection event
|
|
6
|
+
* @param socketUrl The URL of the socket server to connect to
|
|
7
|
+
*/
|
|
8
|
+
export declare const connectSocket: (socketUrl: string, project: string) => void;
|
|
9
|
+
/**
|
|
10
|
+
* Disconnects the socket server and cleans up the instance
|
|
11
|
+
*/
|
|
12
|
+
export declare const disconnectSocket: () => void;
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "nova-hooks",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Nova hooks package",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"nova",
|
|
7
|
+
"hooks"
|
|
8
|
+
],
|
|
9
|
+
"homepage": "https://github.com/mjjabarullah/nova-hooks#readme",
|
|
10
|
+
"bugs": {
|
|
11
|
+
"url": "https://github.com/mjjabarullah/nova-hooks/issues"
|
|
12
|
+
},
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/mjjabarullah/nova-hooks.git"
|
|
16
|
+
},
|
|
17
|
+
"license": "ISC",
|
|
18
|
+
"author": "Mohamed Jabarullah",
|
|
19
|
+
"type": "module",
|
|
20
|
+
"main": "dist/index.cjs.js",
|
|
21
|
+
"module": "dist/index.es.js",
|
|
22
|
+
"types": "dist/index.d.ts",
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"scripts": {
|
|
27
|
+
"build": "vite build",
|
|
28
|
+
"prepare": "vite build",
|
|
29
|
+
"test": "vitest run",
|
|
30
|
+
"test:watch": "vitest",
|
|
31
|
+
"coverage": "vitest run --coverage"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"socket.io-client": "^4.8.3"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react": "^18.0.0 || ^19.0.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@testing-library/jest-dom": "^6.9.1",
|
|
41
|
+
"@testing-library/react": "^16.3.2",
|
|
42
|
+
"@types/node": "^25.6.2",
|
|
43
|
+
"@types/react": "^19.2.14",
|
|
44
|
+
"@types/react-dom": "^19.2.3",
|
|
45
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
46
|
+
"jsdom": "^27.0.1",
|
|
47
|
+
"typescript": "~6.0.3",
|
|
48
|
+
"vite": "^8.0.12",
|
|
49
|
+
"vite-plugin-dts": "^5.0.0",
|
|
50
|
+
"vitest": "^3.2.4"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/readme.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# nova-hooks
|
|
2
|
+
|
|
3
|
+
A highly-optimized, **zero-configuration** event tracking utility for capturing user interactions and page visits in React applications. Built with a custom, lightweight `EventBus` and `socket.io-client`.
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## ✨ Features
|
|
8
|
+
|
|
9
|
+
- **Zero-Config Tracking:** Automatically captures clicks on buttons, links, and interactive elements without needing manual attributes!
|
|
10
|
+
- **True Page Dwell Time:** Uses the native Page Visibility API to calculate the *actual* active time spent on a page (pauses when the user switches tabs).
|
|
11
|
+
- **Network Optimized:** Employs a built-in 1-second debouncing and click-batching mechanism to minimize network overhead.
|
|
12
|
+
- **Ultra-Lightweight:** Zero dependencies (other than `socket.io-client`). Fully framework-agnostic core logic.
|
|
13
|
+
- **Auto-Enriched Context:** Automatically attaches `PageUrl`, `PageTitle`, `Project`, and `CreatedDate` to every single event payload.
|
|
14
|
+
- **SSR Safe:** Fully compatible with Next.js and Remix.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## 🚀 Getting Started
|
|
19
|
+
|
|
20
|
+
### 1. Install
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
yarn add nova-hooks@https://github.com/mjjabarullah/nova-hooks.git#v2.0.0
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm i nova-hooks@https://github.com/mjjabarullah/nova-hooks.git#v2.0.0
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### 2. Initialization
|
|
31
|
+
|
|
32
|
+
> [!IMPORTANT]
|
|
33
|
+
> Ensure the socket connection is established at the root of your application using the `connectSocket` method.
|
|
34
|
+
|
|
35
|
+
```tsx
|
|
36
|
+
import { connectSocket } from "nova-hooks";
|
|
37
|
+
import { useEffect } from "react";
|
|
38
|
+
|
|
39
|
+
const App = () => {
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
connectSocket(import.meta.env.VITE_APP_SOCKET, "WolfPack");
|
|
42
|
+
}, []);
|
|
43
|
+
|
|
44
|
+
// app code...
|
|
45
|
+
};
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
## 🛠️ Usage Examples
|
|
51
|
+
|
|
52
|
+
### 1. Zero-Config Global Click Tracking
|
|
53
|
+
Place `useGlobalClickTracker` in your authenticated layout. It will automatically listen to the DOM and seamlessly track clicks on any `<button>`, `<a>`, or `cursor: pointer` element!
|
|
54
|
+
|
|
55
|
+
```tsx
|
|
56
|
+
import { useGlobalClickTracker } from "nova-hooks";
|
|
57
|
+
|
|
58
|
+
const ProtectedLayout = ({ children }) => {
|
|
59
|
+
const { user } = useAuth();
|
|
60
|
+
|
|
61
|
+
// Magic happens here! Tracks all UI clicks across the entire app.
|
|
62
|
+
useGlobalClickTracker(user?.empId, user?.roleId);
|
|
63
|
+
|
|
64
|
+
return <>{children}</>;
|
|
65
|
+
};
|
|
66
|
+
```
|
|
67
|
+
*Note: It will intelligently extract labels from `innerText`, `title`, `aria-label`, or auto-generate a fallback CSS Path!*
|
|
68
|
+
|
|
69
|
+
### 2. Explicit Tracking (Optional Overrides)
|
|
70
|
+
If you want to override the auto-detected name for a specific button, just attach the `data-nova-*` attributes:
|
|
71
|
+
|
|
72
|
+
```tsx
|
|
73
|
+
<button
|
|
74
|
+
data-nova-track-id="Custom Task Action"
|
|
75
|
+
data-nova-track-type={ActionType.Button}
|
|
76
|
+
>
|
|
77
|
+
Track Me Specifically
|
|
78
|
+
</button>
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### 3. Accurate Page Dwell Time
|
|
82
|
+
Track exactly how long a user actively stares at a specific page/component. The timer pauses if they switch tabs or minimize the browser!
|
|
83
|
+
|
|
84
|
+
```tsx
|
|
85
|
+
import { usePageTimeTracker } from "nova-hooks";
|
|
86
|
+
|
|
87
|
+
export const Dashboard = () => {
|
|
88
|
+
const { user } = useAuth();
|
|
89
|
+
|
|
90
|
+
// Tracks active dwell time and emits it automatically when the user leaves the page
|
|
91
|
+
usePageTimeTracker("Home Dashboard", user?.empId, user?.roleId);
|
|
92
|
+
|
|
93
|
+
return <div>Welcome to the Dashboard</div>;
|
|
94
|
+
};
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 4. Manual / Imperative Tracking
|
|
98
|
+
If you need to track events programmatically (like inside an API success callback), use the `withEvent` method:
|
|
99
|
+
|
|
100
|
+
```tsx
|
|
101
|
+
import { withEvent, ActionType } from "nova-hooks";
|
|
102
|
+
|
|
103
|
+
const doLogin = () => {
|
|
104
|
+
api.login()
|
|
105
|
+
.then(() => {
|
|
106
|
+
withEvent({
|
|
107
|
+
Action: "Login Success",
|
|
108
|
+
ActionType: ActionType.Login,
|
|
109
|
+
EmpId: "EMP-123",
|
|
110
|
+
EmpRole: "Admin",
|
|
111
|
+
Count: 1,
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## 📦 Exports & Types
|
|
120
|
+
|
|
121
|
+
| Name | Type | Description |
|
|
122
|
+
| ----------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
|
|
123
|
+
| `ActionType` | `object` | Predefined enum-like values: `"Button"`, `"Menu"`, `"Login"`, `"Link"` |
|
|
124
|
+
| `PageVisitAction` | `string` | Constant string `"Page Visit"` used for tracking page visits |
|
|
125
|
+
| `connectSocket` | `(socketUrl: string, project: string) => void` | Connects to the socket server and sets the project name. |
|
|
126
|
+
| `disconnectSocket` | `() => void` | Disconnects and cleans up the active socket connection. |
|
|
127
|
+
| `withEvent` | `(eventData: EventData, callback?: Function) => void` | Emits a structured event optionally after running a callback. |
|
|
128
|
+
| `useGlobalClickTracker` | `(empId?: string, roleId?: string) => void` | React hook to automatically track global click events. |
|
|
129
|
+
| `usePageTimeTracker` | `(action: string; empId?: string; empRole?: string) => void` | React hook to track active time spent on a page via the Visibility API. |
|
|
130
|
+
|
|
131
|
+
### EventData Structure
|
|
132
|
+
All events are automatically enriched with `Project`, `PageUrl`, `PageTitle`, and an ISO `CreatedDate`.
|
|
133
|
+
|
|
134
|
+
| Property | Type | Description |
|
|
135
|
+
| ------------ | ----------------------------------------------------------------- | ------------------------------------------------------------------- |
|
|
136
|
+
| `ActionType` | `keyof typeof ActionType` \| `typeof PageVisitAction` | Type of the action. |
|
|
137
|
+
| `Action` | `string` | Specific action performed (extracted from DOM or manually set). |
|
|
138
|
+
| `EmpId` | `string` | Unique identifier of the employee. |
|
|
139
|
+
| `EmpRole` | `string` | Role of the employee performing the action. |
|
|
140
|
+
| `Count` | `number` _(only when `ActionType` is from `ActionType`)_ | Number of rapid occurrences of the action (batched). |
|
|
141
|
+
| `Duration` | `number` _(seconds, only when `ActionType` is `PageVisitAction`)_ | Duration of the *active* visit in seconds. |
|