@dotcms/analytics 1.2.0-next.1 → 1.2.0-next.10

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.
Files changed (49) hide show
  1. package/README.md +197 -7
  2. package/lib/core/dot-analytics.content.js +63 -0
  3. package/lib/core/plugin/click/dot-analytics.click-tracker.d.ts +108 -0
  4. package/lib/core/plugin/click/dot-analytics.click-tracker.js +144 -0
  5. package/lib/core/plugin/click/dot-analytics.click.plugin.d.ts +36 -0
  6. package/lib/core/plugin/click/dot-analytics.click.plugin.js +27 -0
  7. package/lib/core/plugin/click/dot-analytics.click.utils.d.ts +12 -0
  8. package/lib/core/plugin/click/dot-analytics.click.utils.js +55 -0
  9. package/lib/core/plugin/enricher/dot-analytics.enricher.plugin.d.ts +14 -10
  10. package/lib/core/plugin/enricher/dot-analytics.enricher.plugin.js +26 -38
  11. package/lib/core/{shared/dot-content-analytics.activity-tracker.d.ts → plugin/identity/dot-analytics.identity.activity-tracker.d.ts} +2 -17
  12. package/lib/core/{shared/dot-content-analytics.activity-tracker.js → plugin/identity/dot-analytics.identity.activity-tracker.js} +17 -37
  13. package/lib/core/plugin/identity/dot-analytics.identity.plugin.d.ts +2 -20
  14. package/lib/core/plugin/identity/dot-analytics.identity.plugin.js +7 -7
  15. package/lib/core/plugin/identity/dot-analytics.identity.utils.d.ts +0 -16
  16. package/lib/core/plugin/impression/dot-analytics.impression-tracker.d.ts +62 -0
  17. package/lib/core/plugin/impression/dot-analytics.impression-tracker.js +200 -0
  18. package/lib/core/plugin/impression/dot-analytics.impression.plugin.d.ts +40 -0
  19. package/lib/core/plugin/impression/dot-analytics.impression.plugin.js +27 -0
  20. package/lib/core/plugin/impression/dot-analytics.impression.utils.d.ts +26 -0
  21. package/lib/core/plugin/impression/dot-analytics.impression.utils.js +27 -0
  22. package/lib/core/plugin/impression/index.d.ts +2 -0
  23. package/lib/core/plugin/main/dot-analytics.plugin.d.ts +46 -0
  24. package/lib/core/plugin/main/dot-analytics.plugin.js +114 -0
  25. package/lib/core/shared/constants/{dot-content-analytics.constants.d.ts → dot-analytics.constants.d.ts} +61 -0
  26. package/lib/core/shared/constants/dot-analytics.constants.js +52 -0
  27. package/lib/core/shared/constants/index.d.ts +1 -1
  28. package/lib/core/shared/dot-analytics.logger.d.ts +85 -0
  29. package/lib/core/shared/dot-analytics.logger.js +90 -0
  30. package/lib/core/shared/http/dot-analytics.http.d.ts +9 -0
  31. package/lib/core/shared/http/dot-analytics.http.js +34 -0
  32. package/lib/core/shared/models/data.model.d.ts +39 -1
  33. package/lib/core/shared/models/event.model.d.ts +74 -3
  34. package/lib/core/shared/models/library.model.d.ts +77 -25
  35. package/lib/core/shared/models/request.model.d.ts +17 -9
  36. package/lib/core/shared/queue/dot-analytics.queue.utils.js +44 -37
  37. package/lib/core/shared/{dot-content-analytics.utils.d.ts → utils/dot-analytics.utils.d.ts} +91 -3
  38. package/lib/core/shared/utils/dot-analytics.utils.js +202 -0
  39. package/lib/react/hook/useRouterTracker.js +4 -4
  40. package/lib/react/internal/utils.js +1 -1
  41. package/package.json +7 -6
  42. package/lib/core/dot-content-analytics.js +0 -46
  43. package/lib/core/plugin/dot-analytics.plugin.d.ts +0 -33
  44. package/lib/core/plugin/dot-analytics.plugin.js +0 -42
  45. package/lib/core/shared/constants/dot-content-analytics.constants.js +0 -34
  46. package/lib/core/shared/dot-content-analytics.http.d.ts +0 -17
  47. package/lib/core/shared/dot-content-analytics.http.js +0 -41
  48. package/lib/core/shared/dot-content-analytics.utils.js +0 -147
  49. /package/lib/core/{dot-content-analytics.d.ts → dot-analytics.content.d.ts} +0 -0
package/README.md CHANGED
@@ -108,13 +108,15 @@ track(eventName: string, properties?: Record<string, unknown>): void
108
108
 
109
109
  ## ⚙️ Configuration Options
110
110
 
111
- | Option | Type | Required | Default | Description |
112
- | -------------- | --------- | -------- | ----------------------------------- | -------------------------------------- |
113
- | `siteAuth` | `string` | ✅ | - | Site auth from dotCMS Analytics app |
114
- | `server` | `string` | ✅ | - | Your dotCMS server URL |
115
- | `debug` | `boolean` | ❌ | `false` | Enable verbose logging |
116
- | `autoPageView` | `boolean` | ❌ | React: `true` / Standalone: `false` | Auto track page views on route changes |
117
- | `queueConfig` | `QueueConfig` | ❌ | See below | Event batching configuration |
111
+ | Option | Type | Required | Default | Description |
112
+ | -------------- | --------------------------- | -------- | ----------------------------------- | ---------------------------------------------------------------- |
113
+ | `siteAuth` | `string` | ✅ | - | Site auth from dotCMS Analytics app |
114
+ | `server` | `string` | ✅ | - | Your dotCMS server URL |
115
+ | `debug` | `boolean` | ❌ | `false` | Enable verbose logging |
116
+ | `autoPageView` | `boolean` | ❌ | React: `true` / Standalone: `false` | Auto track page views on route changes |
117
+ | `queueConfig` | `QueueConfig` | ❌ | See below | Event batching configuration |
118
+ | `impressions` | `ImpressionConfig\|boolean` | ❌ | `false` | Content impression tracking (disabled by default) |
119
+ | `clicks` | `boolean` | ❌ | `false` | Content click tracking with 300ms throttle (disabled by default) |
118
120
 
119
121
  ### Queue Configuration
120
122
 
@@ -168,6 +170,194 @@ const analytics = initializeContentAnalytics({
168
170
  });
169
171
  ```
170
172
 
173
+ ### Impression Tracking Configuration
174
+
175
+ The `impressions` option controls automatic tracking of content visibility:
176
+
177
+ - **`false` or `undefined` (default)**: Impression tracking disabled
178
+ - **`true`**: Enable tracking with default settings
179
+ - **`ImpressionConfig` object**: Enable tracking with custom settings
180
+
181
+ | Option | Type | Default | Description |
182
+ | --------------------- | -------- | ------- | ----------------------------------------- |
183
+ | `visibilityThreshold` | `number` | `0.5` | Min percentage visible (0.0 to 1.0) |
184
+ | `dwellMs` | `number` | `750` | Min time visible in milliseconds |
185
+ | `maxNodes` | `number` | `1000` | Max elements to track (performance limit) |
186
+
187
+ **How it works:**
188
+
189
+ - ✅ Tracks contentlets marked with `dotcms-analytics-contentlet` class and `data-dot-analytics-*` attributes
190
+ - ✅ Uses Intersection Observer API for high performance and battery efficiency
191
+ - ✅ Only fires when element is ≥50% visible for ≥750ms (configurable)
192
+ - ✅ Only tracks during active tab (respects page visibility)
193
+ - ✅ One impression per contentlet per session (no duplicates)
194
+ - ✅ Respects user consent settings
195
+ - ✅ Automatically disabled in dotCMS editor mode
196
+
197
+ **Example: Enable with defaults**
198
+
199
+ ```javascript
200
+ const analytics = initializeContentAnalytics({
201
+ siteAuth: 'abc123',
202
+ server: 'https://your-dotcms.com',
203
+ impressions: true // 50% visible, 750ms dwell, 1000 max nodes
204
+ });
205
+ ```
206
+
207
+ **Example: Custom thresholds**
208
+
209
+ ```javascript
210
+ const analytics = initializeContentAnalytics({
211
+ siteAuth: 'abc123',
212
+ server: 'https://your-dotcms.com',
213
+ impressions: {
214
+ visibilityThreshold: 0.7, // Require 70% visible
215
+ dwellMs: 1000, // Must be visible for 1 second
216
+ maxNodes: 500 // Track max 500 elements
217
+ }
218
+ });
219
+ ```
220
+
221
+ **Example: Disable tracking**
222
+
223
+ ```javascript
224
+ const analytics = initializeContentAnalytics({
225
+ siteAuth: 'abc123',
226
+ server: 'https://your-dotcms.com',
227
+ impressions: false // Explicitly disabled (also default if omitted)
228
+ });
229
+ ```
230
+
231
+ ### Click Tracking Configuration
232
+
233
+ The `clicks` option controls automatic tracking of user interactions with content elements:
234
+
235
+ - **`false` or `undefined` (default)**: Click tracking disabled
236
+ - **`true`**: Enable tracking with default settings (300ms throttle)
237
+
238
+ **How it works:**
239
+
240
+ - ✅ Tracks clicks on `<a>` and `<button>` elements within contentlets
241
+ - ✅ Contentlets must be marked with `dotcms-analytics-contentlet` class and `data-dot-analytics-*` attributes
242
+ - ✅ Captures semantic attributes (`href`, `aria-label`, `data-*`) and excludes CSS classes
243
+ - ✅ Throttles rapid clicks to prevent duplicate tracking (300ms fixed)
244
+ - ✅ One click event per interaction
245
+ - ✅ Respects user consent settings
246
+ - ✅ Automatically disabled in dotCMS editor mode
247
+
248
+ **Captured Data:**
249
+
250
+ For each click, the SDK captures:
251
+
252
+ - **Content Info**: `identifier`, `inode`, `title`, `content_type`
253
+ - **Element Info**:
254
+ - `text` - Button/link text (truncated to 100 chars)
255
+ - `type` - Element type (`a` or `button`)
256
+ - `id` - Element ID (required by backend, empty string if not present)
257
+ - `class` - Element CSS classes (required by backend, empty string if not present)
258
+ - `href` - Link destination as written in HTML (e.g., `/signup` not `http://...`, only for `<a>`, empty string for buttons)
259
+ - `attributes` - Additional useful attributes (see below)
260
+ - **Position Info**:
261
+ - `viewport_offset_pct` - Position relative to viewport (0-100%)
262
+ - `dom_index` - Element position in DOM
263
+
264
+ **Attributes Array:**
265
+
266
+ > **Note**: The `attributes` field is formatted as an array of `'key:value'` strings (e.g., `['data-category:primary-cta', 'aria-label:Sign up']`) for efficient serialization and backend parsing.
267
+
268
+ The `attributes` array captures additional semantic data in `'key:value'` string format:
269
+
270
+ ✅ **Included** (semantic/analytics value):
271
+
272
+ - `data-*` - Custom data attributes (e.g., `'data-category:primary-cta'`)
273
+ - `aria-*` - Accessibility attributes (e.g., `'aria-label:Sign up now'`)
274
+ - `title` - Element title
275
+ - `target` - Link target (e.g., `'target:_blank'`)
276
+ - Any other standard HTML attributes
277
+
278
+ ❌ **Excluded** (to avoid duplication):
279
+
280
+ - `class` - Already captured as top-level property
281
+ - `id` - Already captured as top-level property
282
+ - `href` - Already captured as top-level property
283
+ - `data-dot-analytics-*` - Internal SDK attributes
284
+
285
+ **Example: Enable click tracking**
286
+
287
+ ```javascript
288
+ const analytics = initializeContentAnalytics({
289
+ siteAuth: 'abc123',
290
+ server: 'https://your-dotcms.com',
291
+ clicks: true // Enable with 300ms throttle (fixed)
292
+ });
293
+ ```
294
+
295
+ **Example: Adding Custom Analytics Metadata**
296
+
297
+ Use `data-*` attributes to enrich click tracking with custom metadata:
298
+
299
+ ```html
300
+ <!-- Primary CTA with category -->
301
+ <a
302
+ href="/signup"
303
+ id="cta-signup"
304
+ data-category="primary-cta"
305
+ data-campaign="summer-sale"
306
+ aria-label="Sign up for free trial">
307
+ Start Free Trial →
308
+ </a>
309
+
310
+ <!-- Product link with metadata -->
311
+ <a href="/products/123" data-product-id="123" data-product-name="Premium Plan" data-price="29.99">
312
+ View Product
313
+ </a>
314
+
315
+ <!-- Button with custom tracking -->
316
+ <button data-action="download" data-file-type="pdf" data-category="lead-magnet">
317
+ Download Whitepaper
318
+ </button>
319
+ ```
320
+
321
+ **Resulting Click Event:**
322
+
323
+ ```json
324
+ {
325
+ "content": {
326
+ "identifier": "abc123",
327
+ "inode": "xyz789",
328
+ "title": "Product Page",
329
+ "content_type": "Page"
330
+ },
331
+ "element": {
332
+ "text": "Start Free Trial →",
333
+ "type": "a",
334
+ "id": "cta-signup",
335
+ "class": "btn btn-primary text-white",
336
+ "href": "/signup",
337
+ "attributes": [
338
+ "data-category:primary-cta",
339
+ "data-campaign:summer-sale",
340
+ "aria-label:Sign up for free trial",
341
+ "target:_blank"
342
+ ]
343
+ },
344
+ "position": {
345
+ "viewport_offset_pct": 45.2,
346
+ "dom_index": 2
347
+ }
348
+ }
349
+ ```
350
+
351
+ **Example: Disable tracking**
352
+
353
+ ```javascript
354
+ const analytics = initializeContentAnalytics({
355
+ siteAuth: 'abc123',
356
+ server: 'https://your-dotcms.com',
357
+ clicks: false // Explicitly disabled (also default if omitted)
358
+ });
359
+ ```
360
+
171
361
  ## 🛠️ Usage Examples
172
362
 
173
363
  ### Vanilla JavaScript
@@ -0,0 +1,63 @@
1
+ import { Analytics as c } from "analytics";
2
+ import { ANALYTICS_WINDOWS_ACTIVE_KEY as r, ANALYTICS_WINDOWS_CLEANUP_KEY as l } from "../../uve/src/internal/constants.js";
3
+ import { dotAnalyticsClickPlugin as d } from "./plugin/click/dot-analytics.click.plugin.js";
4
+ import { dotAnalyticsEnricherPlugin as m } from "./plugin/enricher/dot-analytics.enricher.plugin.js";
5
+ import { dotAnalyticsIdentityPlugin as u } from "./plugin/identity/dot-analytics.identity.plugin.js";
6
+ import { dotAnalyticsImpressionPlugin as p } from "./plugin/impression/dot-analytics.impression.plugin.js";
7
+ import { dotAnalytics as y } from "./plugin/main/dot-analytics.plugin.js";
8
+ import { validateAnalyticsConfig as A, getEnhancedTrackingPlugins as f } from "./shared/utils/dot-analytics.utils.js";
9
+ import { cleanupActivityTracking as w } from "./plugin/identity/dot-analytics.identity.activity-tracker.js";
10
+ const v = (n) => {
11
+ const o = A(n);
12
+ if (o)
13
+ return console.error(
14
+ `DotCMS Analytics [Core]: Missing ${o.join(" and ")} in configuration`
15
+ ), typeof window < "u" && (window[r] = !1), null;
16
+ const a = f(
17
+ n,
18
+ p,
19
+ d
20
+ ), i = c({
21
+ app: "dotAnalytics",
22
+ debug: n.debug,
23
+ plugins: [
24
+ u(n),
25
+ // Inject identity context
26
+ ...a,
27
+ //Track content impressions & clicks (conditionally loaded)
28
+ m(),
29
+ // Enrich and clean payload with page, device, utm data and custom data
30
+ y(n)
31
+ // Send events to server
32
+ ]
33
+ }), e = () => w();
34
+ return typeof window < "u" && (window.addEventListener("beforeunload", e), window[l] = e, window[r] = !0, window.dispatchEvent(new CustomEvent("dotcms:analytics:ready"))), {
35
+ /**
36
+ * Track a page view.
37
+ * Session activity is automatically updated by the identity plugin.
38
+ * @param payload - Optional custom data to include with the page view (any valid JSON object)
39
+ */
40
+ pageView: (t = {}) => {
41
+ if (!i) {
42
+ console.warn("DotCMS Analytics [Core]: Analytics instance not initialized");
43
+ return;
44
+ }
45
+ i.page(t);
46
+ },
47
+ /**
48
+ * Track a custom event.
49
+ * @param eventName - The name of the event to track
50
+ * @param payload - Custom data to include with the event (any valid JSON object)
51
+ */
52
+ track: (t, s = {}) => {
53
+ if (!i) {
54
+ console.warn("DotCMS Analytics [Core]: Analytics instance not initialized");
55
+ return;
56
+ }
57
+ i.track(t, s);
58
+ }
59
+ };
60
+ };
61
+ export {
62
+ v as initializeContentAnalytics
63
+ };
@@ -0,0 +1,108 @@
1
+ import { DotCMSAnalyticsConfig, DotCMSContentClickPayload } from '../../shared/models';
2
+ /** Callback function for click events */
3
+ export type ClickCallback = (eventName: string, payload: DotCMSContentClickPayload) => void;
4
+ /** Subscription object with unsubscribe method */
5
+ export interface ClickSubscription {
6
+ unsubscribe: () => void;
7
+ }
8
+ /**
9
+ * Tracks content clicks using event listeners on contentlet containers.
10
+ * Detects clicks on <a> and <button> elements inside contentlets and fires events.
11
+ *
12
+ * Features:
13
+ * - Attaches event listeners to contentlet containers
14
+ * - Tracks clicks on anchor and button elements only
15
+ * - Uses MutationObserver to detect dynamically added content
16
+ * - Throttles rapid clicks to prevent duplicates (300ms)
17
+ * - Subscription-based event system for decoupling
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * const tracker = new DotCMSClickTracker(config);
22
+ * const subscription = tracker.onClick((eventName, payload) => {
23
+ * console.log('Click detected:', payload);
24
+ * });
25
+ * tracker.initialize();
26
+ * // Later: subscription.unsubscribe();
27
+ * ```
28
+ */
29
+ export declare class DotCMSClickTracker {
30
+ private config;
31
+ private mutationObserver;
32
+ private lastClickTime;
33
+ private logger;
34
+ private subscribers;
35
+ private trackedElements;
36
+ private elementHandlers;
37
+ constructor(config: DotCMSAnalyticsConfig);
38
+ /**
39
+ * Subscribe to click events
40
+ * @param callback - Function called when click is detected
41
+ * @returns Subscription object with unsubscribe method
42
+ */
43
+ onClick(callback: ClickCallback): ClickSubscription;
44
+ /**
45
+ * Notifies all subscribers of a click event
46
+ * @param eventName - Name of the event (e.g., 'content_click')
47
+ * @param payload - Click event payload with content and element data
48
+ */
49
+ private notifySubscribers;
50
+ /**
51
+ * Initialize click tracking system
52
+ *
53
+ * Performs the following:
54
+ * - Validates browser environment
55
+ * - Scans for existing contentlets after a delay (100ms)
56
+ * - Sets up MutationObserver for dynamic content
57
+ *
58
+ * The delay allows React/Next.js to finish initial rendering
59
+ * before attaching listeners.
60
+ */
61
+ initialize(): void;
62
+ /**
63
+ * Attach click listener to a contentlet container
64
+ *
65
+ * Skips if element already has a listener attached.
66
+ * The listener delegates to handleContentletClick which:
67
+ * - Finds clicked anchor/button elements
68
+ * - Extracts contentlet and element data
69
+ * - Applies throttling (300ms)
70
+ * - Notifies subscribers
71
+ *
72
+ * @param element - Contentlet container element to track
73
+ */
74
+ private attachClickListener;
75
+ /**
76
+ * Find and attach listeners to all contentlet elements in the DOM
77
+ *
78
+ * Scans the entire document for elements with the
79
+ * `.dotcms-analytics-contentlet` class and attaches click
80
+ * listeners if not already tracked.
81
+ *
82
+ * Called during initialization and whenever DOM mutations are detected.
83
+ */
84
+ private findAndAttachListeners;
85
+ /**
86
+ * Initialize MutationObserver to detect new contentlet containers
87
+ * Uses same simple strategy as impression tracker - no complex filtering
88
+ */
89
+ private initializeMutationObserver;
90
+ /**
91
+ * Remove all click listeners from tracked contentlets
92
+ *
93
+ * Iterates through all contentlet elements and removes their
94
+ * click event handlers, cleaning up WeakMap references.
95
+ */
96
+ private removeAllListeners;
97
+ /**
98
+ * Cleanup all resources used by the click tracker
99
+ *
100
+ * Performs:
101
+ * - Removes all event listeners from contentlets
102
+ * - Disconnects MutationObserver
103
+ * - Clears internal references
104
+ *
105
+ * Should be called when the plugin is disabled or on page unload.
106
+ */
107
+ cleanup(): void;
108
+ }
@@ -0,0 +1,144 @@
1
+ import { handleContentletClick as c } from "./dot-analytics.click.utils.js";
2
+ import { DEFAULT_CLICK_THROTTLE_MS as d } from "../../shared/constants/dot-analytics.constants.js";
3
+ import { createPluginLogger as h, isBrowser as l, INITIAL_SCAN_DELAY_MS as g, findContentlets as r, createContentletObserver as u } from "../../shared/utils/dot-analytics.utils.js";
4
+ class C {
5
+ constructor(t) {
6
+ this.config = t, this.mutationObserver = null, this.lastClickTime = { value: 0 }, this.subscribers = /* @__PURE__ */ new Set(), this.trackedElements = /* @__PURE__ */ new WeakSet(), this.elementHandlers = /* @__PURE__ */ new WeakMap(), this.logger = h("Click", t);
7
+ }
8
+ /**
9
+ * Subscribe to click events
10
+ * @param callback - Function called when click is detected
11
+ * @returns Subscription object with unsubscribe method
12
+ */
13
+ onClick(t) {
14
+ return this.subscribers.add(t), {
15
+ unsubscribe: () => {
16
+ this.subscribers.delete(t);
17
+ }
18
+ };
19
+ }
20
+ /**
21
+ * Notifies all subscribers of a click event
22
+ * @param eventName - Name of the event (e.g., 'content_click')
23
+ * @param payload - Click event payload with content and element data
24
+ */
25
+ notifySubscribers(t, e) {
26
+ this.subscribers.forEach((i) => i(t, e));
27
+ }
28
+ /**
29
+ * Initialize click tracking system
30
+ *
31
+ * Performs the following:
32
+ * - Validates browser environment
33
+ * - Scans for existing contentlets after a delay (100ms)
34
+ * - Sets up MutationObserver for dynamic content
35
+ *
36
+ * The delay allows React/Next.js to finish initial rendering
37
+ * before attaching listeners.
38
+ */
39
+ initialize() {
40
+ if (!l()) {
41
+ this.logger.warn("No document, skipping");
42
+ return;
43
+ }
44
+ this.logger.debug("Plugin initializing"), typeof window < "u" && setTimeout(() => {
45
+ this.logger.debug("Running initial scan after timeout..."), this.findAndAttachListeners();
46
+ }, g), this.initializeMutationObserver(), this.logger.info("Plugin initialized");
47
+ }
48
+ /**
49
+ * Attach click listener to a contentlet container
50
+ *
51
+ * Skips if element already has a listener attached.
52
+ * The listener delegates to handleContentletClick which:
53
+ * - Finds clicked anchor/button elements
54
+ * - Extracts contentlet and element data
55
+ * - Applies throttling (300ms)
56
+ * - Notifies subscribers
57
+ *
58
+ * @param element - Contentlet container element to track
59
+ */
60
+ attachClickListener(t) {
61
+ if (this.trackedElements.has(t)) {
62
+ const n = t.dataset.dotAnalyticsIdentifier || "unknown";
63
+ this.logger.debug(`Element ${n} already has listener, skipping`);
64
+ return;
65
+ }
66
+ if (!t.dataset.dotAnalyticsDomIndex) {
67
+ const n = r();
68
+ t.dataset.dotAnalyticsDomIndex = String(n.indexOf(t));
69
+ }
70
+ const e = (n) => {
71
+ this.logger.debug("Click handler triggered on contentlet"), c(
72
+ n,
73
+ t,
74
+ (a, s) => {
75
+ const o = Date.now();
76
+ o - this.lastClickTime.value < d || (this.lastClickTime.value = o, this.notifySubscribers(a, s), this.logger.info(
77
+ `Fired click event for ${s.content.identifier}`,
78
+ s
79
+ ));
80
+ },
81
+ this.logger
82
+ );
83
+ };
84
+ t.addEventListener("click", e), this.trackedElements.add(t), this.elementHandlers.set(t, e);
85
+ const i = t.dataset.dotAnalyticsIdentifier || "unknown";
86
+ this.logger.log(`Attached listener to contentlet ${i}`, t);
87
+ }
88
+ /**
89
+ * Find and attach listeners to all contentlet elements in the DOM
90
+ *
91
+ * Scans the entire document for elements with the
92
+ * `.dotcms-analytics-contentlet` class and attaches click
93
+ * listeners if not already tracked.
94
+ *
95
+ * Called during initialization and whenever DOM mutations are detected.
96
+ */
97
+ findAndAttachListeners() {
98
+ this.logger.debug("findAndAttachListeners called");
99
+ const t = r();
100
+ this.logger.debug(`Scanning... found ${t.length} contentlets`);
101
+ let e = 0;
102
+ t.forEach((i) => {
103
+ const n = !this.trackedElements.has(i);
104
+ this.attachClickListener(i), n && this.trackedElements.has(i) && e++;
105
+ }), e > 0 && this.logger.info(`Attached ${e} new click listeners`);
106
+ }
107
+ /**
108
+ * Initialize MutationObserver to detect new contentlet containers
109
+ * Uses same simple strategy as impression tracker - no complex filtering
110
+ */
111
+ initializeMutationObserver() {
112
+ l() && (this.mutationObserver = u(() => {
113
+ this.findAndAttachListeners();
114
+ }), this.logger.info("MutationObserver enabled for click tracking"));
115
+ }
116
+ /**
117
+ * Remove all click listeners from tracked contentlets
118
+ *
119
+ * Iterates through all contentlet elements and removes their
120
+ * click event handlers, cleaning up WeakMap references.
121
+ */
122
+ removeAllListeners() {
123
+ r().forEach((e) => {
124
+ const i = this.elementHandlers.get(e);
125
+ i && (e.removeEventListener("click", i), this.elementHandlers.delete(e));
126
+ });
127
+ }
128
+ /**
129
+ * Cleanup all resources used by the click tracker
130
+ *
131
+ * Performs:
132
+ * - Removes all event listeners from contentlets
133
+ * - Disconnects MutationObserver
134
+ * - Clears internal references
135
+ *
136
+ * Should be called when the plugin is disabled or on page unload.
137
+ */
138
+ cleanup() {
139
+ this.removeAllListeners(), this.mutationObserver && (this.mutationObserver.disconnect(), this.mutationObserver = null), this.logger.info("Click tracking cleaned up");
140
+ }
141
+ }
142
+ export {
143
+ C as DotCMSClickTracker
144
+ };
@@ -0,0 +1,36 @@
1
+ import { AnalyticsInstance } from 'analytics';
2
+ import { DotCMSAnalyticsConfig } from '../../shared/models';
3
+ /**
4
+ * Click Plugin for DotAnalytics
5
+ * Handles automatic tracking of clicks on content elements.
6
+ *
7
+ * This plugin initializes the click tracker which:
8
+ * - Uses MutationObserver to detect contentlet containers
9
+ * - Attaches click listeners to each .dotcms-analytics-contentlet element
10
+ * - Filters for clicks on <a> or <button> elements inside tracked contentlets
11
+ * - Extracts contentlet data and element metadata
12
+ * - Throttles clicks to prevent duplicates
13
+ * - Fires 'content_click' events via subscription callback
14
+ *
15
+ * Note: This plugin is only registered if config.clicks is enabled.
16
+ * See getEnhancedTrackingPlugins() for conditional loading logic.
17
+ *
18
+ * @param {DotCMSAnalyticsConfig} config - Configuration with clicks settings
19
+ * @returns {Object} Plugin object with lifecycle methods
20
+ */
21
+ export declare const dotAnalyticsClickPlugin: (config: DotCMSAnalyticsConfig) => {
22
+ name: string;
23
+ /**
24
+ * Initialize click tracking
25
+ * Called when Analytics.js initializes the plugin with instance context
26
+ * @param instance - Analytics.js instance with track method
27
+ */
28
+ initialize: ({ instance }: {
29
+ instance: AnalyticsInstance;
30
+ }) => Promise<void>;
31
+ /**
32
+ * Setup cleanup handlers when plugin is loaded
33
+ * Called after Analytics.js completes plugin loading
34
+ */
35
+ loaded: () => boolean;
36
+ };
@@ -0,0 +1,27 @@
1
+ import { DotCMSClickTracker as o } from "./dot-analytics.click-tracker.js";
2
+ import { createPluginLogger as u, isBrowser as a, setupPluginCleanup as s } from "../../shared/utils/dot-analytics.utils.js";
3
+ const g = (n) => {
4
+ let i = null, l = null;
5
+ const e = u("Click", n);
6
+ return {
7
+ name: "dot-analytics-click",
8
+ /**
9
+ * Initialize click tracking
10
+ * Called when Analytics.js initializes the plugin with instance context
11
+ * @param instance - Analytics.js instance with track method
12
+ */
13
+ initialize: ({ instance: r }) => (i = new o(n), l = i.onClick((c, t) => {
14
+ r.track(c, t);
15
+ }), i.initialize(), e.info("Click tracking plugin initialized"), Promise.resolve()),
16
+ /**
17
+ * Setup cleanup handlers when plugin is loaded
18
+ * Called after Analytics.js completes plugin loading
19
+ */
20
+ loaded: () => (a() && i && s(() => {
21
+ l && (l.unsubscribe(), l = null), i && (i.cleanup(), i = null, e.info("Click tracking cleaned up on page unload"));
22
+ }), !0)
23
+ };
24
+ };
25
+ export {
26
+ g as dotAnalyticsClickPlugin
27
+ };
@@ -0,0 +1,12 @@
1
+ import { DotCMSContentClickPayload } from '../../shared/models';
2
+ import { createPluginLogger } from '../../shared/utils/dot-analytics.utils';
3
+ /**
4
+ * Handles click events on elements within a contentlet.
5
+ * The contentlet element is already known since we attach listeners to contentlets.
6
+ *
7
+ * @param event - The mouse event
8
+ * @param contentletElement - The contentlet container element
9
+ * @param trackCallback - Callback to execute if the click is valid
10
+ * @param logger - Logger instance for debug messages
11
+ */
12
+ export declare const handleContentletClick: (event: MouseEvent, contentletElement: HTMLElement, trackCallback: (eventName: string, payload: DotCMSContentClickPayload) => void, logger: ReturnType<typeof createPluginLogger>) => void;
@@ -0,0 +1,55 @@
1
+ import { CLICKABLE_ELEMENTS_SELECTOR as l, CLICK_EVENT_TYPE as m } from "../../shared/constants/dot-analytics.constants.js";
2
+ import { extractContentletData as p } from "../../shared/utils/dot-analytics.utils.js";
3
+ import { getViewportMetrics as b } from "../impression/dot-analytics.impression.utils.js";
4
+ const _ = (r, o, c, e) => {
5
+ const a = r.target;
6
+ e.debug("Click detected on:", a);
7
+ const t = a.closest(l);
8
+ if (!t) {
9
+ e.debug("No <a> or <button> found in click path");
10
+ return;
11
+ }
12
+ if (!o.contains(t)) {
13
+ e.debug("Click was outside contentlet boundary");
14
+ return;
15
+ }
16
+ e.debug("Found clickable element:", t);
17
+ const n = p(o);
18
+ if (!n.identifier) {
19
+ e.debug("Contentlet has no identifier");
20
+ return;
21
+ }
22
+ e.debug("Contentlet data:", n);
23
+ const d = b(o), s = [];
24
+ for (const i of t.attributes)
25
+ !i.name.startsWith("data-dot-analytics") && i.name !== "class" && i.name !== "id" && i.name !== "href" && s.push(`${i.name}:${i.value}`);
26
+ const f = parseInt(o.dataset.dotAnalyticsDomIndex || "-1", 10), u = {
27
+ content: {
28
+ identifier: n.identifier,
29
+ inode: n.inode,
30
+ title: n.title,
31
+ content_type: n.contentType
32
+ },
33
+ position: {
34
+ viewport_offset_pct: d.offsetPercentage,
35
+ dom_index: f
36
+ },
37
+ element: {
38
+ text: (t.innerText || t.textContent || "").trim().substring(0, 100),
39
+ // Limit length
40
+ type: t.tagName.toLowerCase(),
41
+ id: t.id || "",
42
+ // Required by backend, empty string if not present
43
+ class: t.className || "",
44
+ // Required by backend, empty string if not present
45
+ href: t.getAttribute("href") || "",
46
+ // Path as written in HTML (relative), empty string for buttons
47
+ attributes: s
48
+ // Additional attributes (data-*, aria-*, target, etc.)
49
+ }
50
+ };
51
+ c(m, u);
52
+ };
53
+ export {
54
+ _ as handleContentletClick
55
+ };