@guardian/ophan-tracker-js 2.1.1-next.1 → 2.1.2-next.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.
Files changed (96) hide show
  1. package/package.json +15 -8
  2. package/readme.md +9 -9
  3. package/dist/assets/adblock-detection.d.ts +0 -5
  4. package/dist/assets/adblock-detection.js +0 -20
  5. package/dist/assets/attention.d.ts +0 -10
  6. package/dist/assets/attention.js +0 -126
  7. package/dist/assets/campaign.d.ts +0 -2
  8. package/dist/assets/campaign.js +0 -23
  9. package/dist/assets/click-path-capture.d.ts +0 -15
  10. package/dist/assets/click-path-capture.js +0 -68
  11. package/dist/assets/components.d.ts +0 -61
  12. package/dist/assets/components.js +0 -168
  13. package/dist/assets/contribution.d.ts +0 -6
  14. package/dist/assets/contribution.js +0 -16
  15. package/dist/assets/core.d.ts +0 -65
  16. package/dist/assets/core.js +0 -230
  17. package/dist/assets/embed.d.ts +0 -6
  18. package/dist/assets/embed.js +0 -8
  19. package/dist/assets/fb-instant.d.ts +0 -5
  20. package/dist/assets/fb-instant.js +0 -7
  21. package/dist/assets/heatmap.d.ts +0 -6
  22. package/dist/assets/heatmap.js +0 -34
  23. package/dist/assets/holidays.d.ts +0 -6
  24. package/dist/assets/holidays.js +0 -8
  25. package/dist/assets/http-status.d.ts +0 -6
  26. package/dist/assets/http-status.js +0 -11
  27. package/dist/assets/iframe-tracking.d.ts +0 -2
  28. package/dist/assets/iframe-tracking.js +0 -80
  29. package/dist/assets/interactive.d.ts +0 -2
  30. package/dist/assets/interactive.js +0 -17
  31. package/dist/assets/jobs-courses.d.ts +0 -6
  32. package/dist/assets/jobs-courses.js +0 -8
  33. package/dist/assets/jobs.d.ts +0 -6
  34. package/dist/assets/jobs.js +0 -8
  35. package/dist/assets/manage-my-account.d.ts +0 -8
  36. package/dist/assets/manage-my-account.js +0 -29
  37. package/dist/assets/membership.d.ts +0 -6
  38. package/dist/assets/membership.js +0 -16
  39. package/dist/assets/ng.d.ts +0 -25
  40. package/dist/assets/ng.js +0 -53
  41. package/dist/assets/perf.d.ts +0 -3
  42. package/dist/assets/perf.js +0 -36
  43. package/dist/assets/privatebrowsing.d.ts +0 -7
  44. package/dist/assets/privatebrowsing.js +0 -66
  45. package/dist/assets/r2.d.ts +0 -5
  46. package/dist/assets/r2.js +0 -15
  47. package/dist/assets/smart-news.d.ts +0 -6
  48. package/dist/assets/smart-news.js +0 -13
  49. package/dist/assets/support.d.ts +0 -10
  50. package/dist/assets/support.js +0 -28
  51. package/dist/assets/tests/click-path-capture.test.d.ts +0 -2
  52. package/dist/assets/tests/click-path-capture.test.js +0 -44
  53. package/dist/assets/tests/components.test.d.ts +0 -2
  54. package/dist/assets/tests/components.test.js +0 -47
  55. package/dist/assets/tests/core.test.d.ts +0 -2
  56. package/dist/assets/tests/core.test.js +0 -161
  57. package/dist/assets/tests/heatmap.test.d.ts +0 -2
  58. package/dist/assets/tests/heatmap.test.js +0 -45
  59. package/dist/assets/tests/transmit.test.d.ts +0 -2
  60. package/dist/assets/tests/transmit.test.js +0 -118
  61. package/dist/assets/transmit.d.ts +0 -54
  62. package/dist/assets/transmit.js +0 -130
  63. package/dist/assets/vendor/adBlockDetectionLib.d.ts +0 -5
  64. package/dist/assets/vendor/adBlockDetectionLib.js +0 -312
  65. package/dist/assets/visibility.d.ts +0 -6
  66. package/dist/assets/visibility.js +0 -22
  67. package/dist/assets/witness.d.ts +0 -6
  68. package/dist/assets/witness.js +0 -8
  69. package/dist/types/abtest.d.ts +0 -29
  70. package/dist/types/abtest.js +0 -0
  71. package/dist/types/acquisition.d.ts +0 -148
  72. package/dist/types/acquisition.js +0 -35
  73. package/dist/types/component-event.d.ts +0 -92
  74. package/dist/types/component-event.js +0 -67
  75. package/dist/types/component-type.d.ts +0 -58
  76. package/dist/types/component-type.js +0 -56
  77. package/dist/types/consent.d.ts +0 -47
  78. package/dist/types/consent.js +0 -15
  79. package/dist/types/event.d.ts +0 -115
  80. package/dist/types/event.js +0 -7
  81. package/dist/types/inpageclick.d.ts +0 -12
  82. package/dist/types/inpageclick.js +0 -0
  83. package/dist/types/interaction.d.ts +0 -18
  84. package/dist/types/interaction.js +0 -0
  85. package/dist/types/link.d.ts +0 -15
  86. package/dist/types/link.js +0 -0
  87. package/dist/types/media.d.ts +0 -103
  88. package/dist/types/media.js +0 -70
  89. package/dist/types/platform.d.ts +0 -33
  90. package/dist/types/platform.js +0 -33
  91. package/dist/types/printproduct.d.ts +0 -54
  92. package/dist/types/printproduct.js +0 -39
  93. package/dist/types/product.d.ts +0 -56
  94. package/dist/types/product.js +0 -54
  95. package/dist/types/subscription.d.ts +0 -65
  96. package/dist/types/subscription.js +0 -63
package/package.json CHANGED
@@ -1,33 +1,40 @@
1
1
  {
2
2
  "name": "@guardian/ophan-tracker-js",
3
- "version": "2.1.1-next.1",
3
+ "version": "2.1.2-next.0",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=16"
7
7
  },
8
8
  "files": [
9
- "dist/**/*.js",
10
- "dist/**/*.d.ts"
9
+ "NPM-dist/**/*.js",
10
+ "NPM-dist/**/*.d.ts"
11
11
  ],
12
- "main": "dist/assets/ng.js",
12
+ "main": "NPM-dist/ng.js",
13
+ "types": "NPM-dist/types/ng.d.ts",
13
14
  "devDependencies": {
14
- "@babel/preset-env": "7.22.10",
15
+ "@babel/preset-env": "^7.22.10",
16
+ "@babel/preset-typescript": "^7.24.7",
15
17
  "@changesets/cli": "^2.26.2",
16
18
  "@guardian/prettier": "^7.0.0",
17
19
  "@rollup/plugin-babel": "6.0.3",
18
20
  "@rollup/plugin-terser": "0.4.3",
19
21
  "@rollup/plugin-typescript": "^11.1.6",
22
+ "@types/jest": "^29.5.12",
23
+ "babel-jest": "^29.7.0",
20
24
  "jest": "^29.7.0",
21
25
  "jest-environment-jsdom": "^29.7.0",
22
26
  "rollup": "3.28.0",
23
27
  "rollup-jest": "^3.1.0",
28
+ "ts-jest": "^29.1.4",
24
29
  "typescript": "^5.4.4"
25
30
  },
26
31
  "scripts": {
27
- "build": "NODE_ENV=production npx rollup -c",
28
- "build:test": "NODE_ENV=test npx rollup -c",
29
- "build-types": "tsc",
32
+ "build-for-cdn": "NODE_ENV=production npx rollup -c",
33
+ "build-for-npm": "tsc",
30
34
  "test": "jest",
31
35
  "format": "npx prettier --write ."
36
+ },
37
+ "dependencies": {
38
+ "@guardian/tsconfig": "^1.0.0"
32
39
  }
33
40
  }
package/readme.md CHANGED
@@ -42,15 +42,15 @@ You can see example usage of the library on theguardian.com [here](https://githu
42
42
 
43
43
  ### Usage with Typescript
44
44
 
45
- Refer to the type definitions within the library for the structure of valid tracking events. The `ophan.record()` function accepts a type of `EventPayload` found [here](linktotypes).
45
+ Refer to the type definitions within the library for the structure of valid tracking events. The `ophan.record()` function accepts a type of `EventPayload` found [here]("./types/event.ts#L95").
46
46
 
47
47
  #### Example Usage
48
48
 
49
49
  ```typescript
50
- import ophan, { Product, ComponentEvent, ComponentType } from '@guardian/ophan-tracker-js';
51
- import type { TProduct, AbTest } from '@guardian/ophan-tracker-js';
50
+ import ophan, { Product, ComponentEvent } from '@guardian/ophan-tracker-js';
51
+ import type { AbTest } from '@guardian/ophan-tracker-js';
52
52
 
53
- const exampleProduct: TProduct = Product.APP_PREMIUM_TIER;
53
+ const exampleProduct: TProduct = "APP_PREMIUM_TIER";
54
54
  const exampleAbTest: AbTest = {
55
55
  name: "myAbTest",
56
56
  variant: "variant",
@@ -58,7 +58,7 @@ const exampleAbTest: AbTest = {
58
58
  };
59
59
 
60
60
  const componentV2 = {
61
- componentType: ComponentType.ACQUISITIONS_BUTTON,
61
+ componentType: "ACQUISITIONS_BUTTON",
62
62
  id: "component-id",
63
63
  products: new Set([exampleProduct]),
64
64
  campaignCode: "campaign-code",
@@ -89,16 +89,16 @@ The backend of tracker exposes two endpoints, `img/1` which takes in page view e
89
89
 
90
90
  # Developing Ophan Tracker JS
91
91
 
92
- The library is implemented using both Javascript and TypeScript, with the source code located in the `assets` directory and its subdirectories. The project is set up to include both TypeScript (.ts) and JavaScript (.js) files, allowing for a mix of both languages in the library's implementation.
92
+ The library is implemented using both Javascript and TypeScript, with the source code located in the `src` directory and its subdirectories. The project is set up to include both TypeScript (.ts) and JavaScript (.js) files, allowing for a mix of both languages in the library's implementation.
93
93
 
94
- Typescript interfaces and types can be developed in the `types` folder. These can then be imported into the Javascript source code and used to type certain functions or re-exported for consumers. This means we don't have to maintain separate types for each function in the JS source code. Please refer to `ng.js` for an example of how to do this.
94
+ Typescript interfaces and types are developed in the `types` folder.
95
95
 
96
96
  The TypeScript compiler is configured to generate compiled JavaScript files and corresponding declaration files (.d.ts) in the ./dist directory. The declaration files provide type information for the library's public API. The compiler also generates source map files for the declaration files.
97
97
 
98
98
  ## Compile
99
99
 
100
100
  ```
101
- .../ophan/tracker-js $ npm run build-types
101
+ .../ophan/tracker-js $ npm run build-for-npm
102
102
  ```
103
103
 
104
104
  #### Proxy tracker-js:
@@ -153,4 +153,4 @@ We use `changesets` for automated publishing of the NPM package:
153
153
 
154
154
  ##### Rollup
155
155
 
156
- The generated files from Rollup (using the `build` script in `package.json`) are only used for publishing to the CDN to use SystemJS / AMD
156
+ The generated files from Rollup (using the `build-for-cdn` script in `package.json`) are only used for publishing to the CDN to use SystemJS / AMD
@@ -1,5 +0,0 @@
1
- declare namespace _default {
2
- function run(): Promise<any>;
3
- }
4
- export default _default;
5
- //# sourceMappingURL=adblock-detection.d.ts.map
@@ -1,20 +0,0 @@
1
- import abd from './vendor/adBlockDetectionLib.js';
2
- export default {
3
- run() {
4
- return new Promise((resolve, reject) => {
5
- if (abd.init) {
6
- try {
7
- abd.init({
8
- complete: resolve,
9
- });
10
- }
11
- catch (error) {
12
- reject(error);
13
- }
14
- }
15
- else {
16
- reject(new Error('Failed to initialise adblock detection'));
17
- }
18
- });
19
- },
20
- };
@@ -1,10 +0,0 @@
1
- declare namespace _default {
2
- export { initAttention as init };
3
- export { initComponent };
4
- export { setEventEmitter };
5
- }
6
- export default _default;
7
- declare function initAttention(visibility: any): void;
8
- declare function initComponent(name: any, el: any, visibilityThreshold?: number): void;
9
- declare function setEventEmitter(emitter: any): void;
10
- //# sourceMappingURL=attention.d.ts.map
@@ -1,126 +0,0 @@
1
- // Generated by CoffeeScript 2.7.0
2
- import transmit from './transmit.js';
3
- import components from './components.js';
4
- // The upworthy definition of attention minutes, from
5
- // http://upworthy.github.io/2014/06/implementing-attention-minutes-part-1/ :
6
- // "We consider the page to have the user’s attention if
7
- // 1. some activity is happening on the page. For our purposes this means:
8
- // 1. the page currently has focus
9
- // 2. and the user has interacted with the page within a certain timeout
10
- // 2. or a video is playing on the page
11
- // Attention Minutes, then, are the total number of minutes that a user has spent on
12
- // a page where the above conditions have held true."
13
- // our definition of "within a certain timeout" above:
14
- const ATTENTIONDECAY = 5000;
15
- // our definition of "the user has interacted with the page"
16
- const EVENTS = [
17
- 'focus',
18
- 'click',
19
- 'scroll',
20
- 'mousemove',
21
- 'touchstart',
22
- 'touchend',
23
- 'touchcancel',
24
- 'touchleave',
25
- 'touchmove',
26
- 'keyup',
27
- 'keydown',
28
- ];
29
- const REPORTINGINTERVAL = 10000;
30
- // total attention time so far on this page
31
- let totalAttentionMs = 0;
32
- // the time elapsed since the time origin (https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)
33
- // when the most recent period of attention (that is, attention
34
- // which we haven't yet added to totalAttentionMs) began.
35
- // null if we don't have attention.
36
- let unrecordedAttentionStarted = null;
37
- // the attention time we last reported to ophan
38
- let reportedTotalAttentionMs = null; // setting null here forces a first report of attention time, even if it's only 0ms
39
- // the decay timer if we've set one
40
- let decayTimerId = null;
41
- // is video currently playing?
42
- let videoPlaying = false;
43
- const cancelDecayTimer = () => {
44
- if (decayTimerId != null) {
45
- window.clearTimeout(decayTimerId);
46
- }
47
- decayTimerId = null;
48
- };
49
- const makeActive = () => {
50
- if (unrecordedAttentionStarted == null) {
51
- unrecordedAttentionStarted = performance.now();
52
- }
53
- components.startMonitoring();
54
- cancelDecayTimer();
55
- decayTimerId = window.setTimeout(() => {
56
- if (!videoPlaying) {
57
- makeInactive();
58
- }
59
- }, ATTENTIONDECAY);
60
- };
61
- const incrementTotalAttentionTimeByUnrecordedAmount = () => {
62
- if (unrecordedAttentionStarted != null) {
63
- const now = performance.now();
64
- const unrecordedMs = Math.min(now - unrecordedAttentionStarted, REPORTINGINTERVAL);
65
- totalAttentionMs += unrecordedMs;
66
- unrecordedAttentionStarted = now;
67
- }
68
- };
69
- const makeInactive = () => {
70
- cancelDecayTimer();
71
- components.stopMonitoring();
72
- incrementTotalAttentionTimeByUnrecordedAmount();
73
- unrecordedAttentionStarted = null;
74
- };
75
- const reporter = () => {
76
- incrementTotalAttentionTimeByUnrecordedAmount();
77
- if (totalAttentionMs !== reportedTotalAttentionMs) {
78
- const report = {
79
- attentionMs: Math.round(totalAttentionMs),
80
- };
81
- const componentAttentionTimes = components.getAttentionTimes();
82
- if (Object.keys(componentAttentionTimes).length) {
83
- report.componentAttentionMs = componentAttentionTimes;
84
- }
85
- transmit.sendMore(report);
86
- reportedTotalAttentionMs = totalAttentionMs;
87
- }
88
- };
89
- const initComponent = (name, el, visibilityThreshold = 0.5) => {
90
- components.registerComponent(name, el, visibilityThreshold, REPORTINGINTERVAL);
91
- };
92
- const initAttention = (visibility) => {
93
- EVENTS.forEach((event) => {
94
- window.addEventListener(event, makeActive);
95
- });
96
- document.addEventListener(visibility.changeEvent, () => {
97
- if (visibility.state() === 'visible') {
98
- makeActive();
99
- }
100
- else {
101
- makeInactive();
102
- }
103
- }, false);
104
- document.addEventListener('videoPlaying', () => {
105
- videoPlaying = true;
106
- makeActive();
107
- });
108
- document.addEventListener('videoEnded', () => {
109
- videoPlaying = false;
110
- makeInactive();
111
- });
112
- document.addEventListener('videoPause', () => {
113
- videoPlaying = false;
114
- makeInactive();
115
- });
116
- window.setTimeout(reporter, 100);
117
- window.setInterval(reporter, REPORTINGINTERVAL);
118
- };
119
- const setEventEmitter = (emitter) => {
120
- components.setEventEmitter(emitter);
121
- };
122
- export default {
123
- init: initAttention,
124
- initComponent: initComponent,
125
- setEventEmitter: setEventEmitter,
126
- };
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=campaign.d.ts.map
@@ -1,23 +0,0 @@
1
- // Generated by CoffeeScript 2.7.0
2
- import transmit from './transmit.js';
3
- import perf from './perf.js';
4
- const start = perf?.timing?.domComplete ?? performance.now();
5
- // DFP ads
6
- if (typeof googletag !== 'undefined' && googletag !== null) {
7
- googletag.cmd.push(() => {
8
- googletag.pubads().addEventListener('slotRenderEnded', (event) => {
9
- const slotId = event.slot.getSlotId().getDomId();
10
- transmit.sendMore({
11
- ads: [
12
- {
13
- slot: slotId,
14
- campaignId: event.isEmpty ? '__empty__' : event.lineItemId,
15
- creativeId: event.creativeId,
16
- timeToRenderEnded: Math.round(performance.now() - start),
17
- adServer: 'DFP',
18
- },
19
- ],
20
- });
21
- });
22
- });
23
- }
@@ -1,15 +0,0 @@
1
- export function validAncestorAnchorElement(el: Element): Element | null;
2
- export function getContainingComponent(el: Element): string | null;
3
- declare namespace _default {
4
- export { getDataLinkNames };
5
- }
6
- export default _default;
7
- /**
8
- * Collects all `data-link-name` attribute values from the ancestor elements.
9
- *
10
- * @param {Element} el - The element to start searching from.
11
- * @param {string[]} dataLinkNames - Initial array of data link names (optional).
12
- * @returns {string[]} Array of `data-link-name` values.
13
- */
14
- declare function getDataLinkNames(el: Element, dataLinkNames?: string[]): string[];
15
- //# sourceMappingURL=click-path-capture.d.ts.map
@@ -1,68 +0,0 @@
1
- import ophan from './core.js';
2
- import transmit from './transmit.js';
3
- /**
4
- * Finds the closest ancestor anchor (`<a>`) element of the given element.
5
- *
6
- * @param {Element} el - The element to start searching from.
7
- * @returns {Element|null} The closest ancestor anchor element or null if none found.
8
- */
9
- export const validAncestorAnchorElement = (el) => {
10
- if (!el || el.nodeName?.toLowerCase() === 'body')
11
- return null;
12
- return el.nodeName.toLowerCase() === 'a'
13
- ? el
14
- : validAncestorAnchorElement(el.parentNode);
15
- };
16
- /**
17
- * Retrieves the value of the `data-component` attribute from the closest ancestor.
18
- *
19
- * @param {Element} el - The element to start searching from.
20
- * @returns {string|null} The `data-component` attribute value or null if not found.
21
- */
22
- export const getContainingComponent = (el) => {
23
- if (!el || el.nodeName?.toLowerCase() === 'body')
24
- return null;
25
- return (el.getAttribute('data-component') || getContainingComponent(el.parentNode));
26
- };
27
- /**
28
- * Collects all `data-link-name` attribute values from the ancestor elements.
29
- *
30
- * @param {Element} el - The element to start searching from.
31
- * @param {string[]} dataLinkNames - Initial array of data link names (optional).
32
- * @returns {string[]} Array of `data-link-name` values.
33
- */
34
- const getDataLinkNames = (el, dataLinkNames = []) => {
35
- if (!el || el === document.body || el === document)
36
- return dataLinkNames;
37
- const dataLinkName = el.getAttribute('data-link-name');
38
- if (dataLinkName)
39
- dataLinkNames.push(dataLinkName);
40
- return getDataLinkNames(el.parentNode, dataLinkNames);
41
- };
42
- if (typeof document.addEventListener === 'function') {
43
- document.addEventListener('click', function (e) {
44
- let anchorTarget, info;
45
- anchorTarget = validAncestorAnchorElement(e.target);
46
- info = {
47
- from: [location.protocol, '//', location.host, location.pathname].join(''),
48
- to: anchorTarget ? anchorTarget.href : void 0,
49
- referringComponent: getContainingComponent(e.target),
50
- referringDataLinkNames: getDataLinkNames(e.target),
51
- refPlatform: ophan.servingPlatform(),
52
- refViewId: ophan.viewId,
53
- };
54
- if (info.referringDataLinkNames != null) {
55
- transmit.sendMore({
56
- clickComponent: info.referringComponent,
57
- clickLinkNames: info.referringDataLinkNames,
58
- });
59
- }
60
- if (anchorTarget != null) {
61
- // then we may be about to navigate away from this page, so store to send on next request
62
- return ophan.storeDataToSendOnNextEvent(info);
63
- }
64
- }, false);
65
- }
66
- export default {
67
- getDataLinkNames: getDataLinkNames,
68
- };
@@ -1,61 +0,0 @@
1
- /**
2
- * @type {Component[]}
3
- */
4
- export const components: Component[];
5
- declare namespace _default {
6
- export function setEventEmitter(emitter: Object): Object;
7
- export { startMonitoring };
8
- export { stopMonitoring };
9
- export { getAttentionTimes };
10
- export let registerComponent: (...args: [name: string, element: HTMLElement, visibilityThreshold1: number, reportingInterval1: number]) => void;
11
- }
12
- export default _default;
13
- declare class Component {
14
- /**
15
- * Component constructor.
16
- * @param {string} name - The name of the component.
17
- * @param {HTMLElement} element - The DOM element of the component.
18
- * @param {number} visibilityThreshold1 -
19
- * visibilityThreshold represents the fraction of each component that must
20
- * be in the viewport before it is considered visible.
21
- * e.g. 0.5 means that half the height or width must be in the viewport
22
- * 1 means that the entire element must be in the viewport
23
- * @param {number} reportingInterval1 - ??
24
- */
25
- constructor(name: string, element: HTMLElement, visibilityThreshold1: number, reportingInterval1: number);
26
- name: string;
27
- element: HTMLElement;
28
- visibilityThreshold: number;
29
- reportingInterval: number;
30
- visible: boolean;
31
- totalAttentionMs: number;
32
- unrecordedAttentionStarted: number | null;
33
- reportedTotalAttentionMs: number;
34
- usingEmitter: boolean;
35
- visCheck: () => number | null | undefined;
36
- isVisible(threshold?: number): boolean;
37
- visibilityHasChanged(): boolean;
38
- rebindToEventEmitter(): any;
39
- checkVisibility(): number | null | undefined;
40
- makeActive(): number;
41
- makeInactive(): null;
42
- hadAttentionSinceLastGet(): boolean;
43
- getAttentionTime(): number;
44
- incrementTotalAttentionTimeByUnrecordedAmount(): number | undefined;
45
- }
46
- /**
47
- * Begins monitoring the components on the page for attention time.
48
- * @returns {Array} Array of results from makeActive() for each visible component.
49
- */
50
- declare function startMonitoring(): any[];
51
- /**
52
- * Stops monitoring the components on the page for attention time.
53
- * @returns {Array} Array of results from makeInactive() for each component.
54
- */
55
- declare function stopMonitoring(): any[];
56
- /**
57
- * Retrieves the attention times for all components.
58
- * @returns {Object}
59
- */
60
- declare function getAttentionTimes(): Object;
61
- //# sourceMappingURL=components.d.ts.map
@@ -1,168 +0,0 @@
1
- /**
2
- * @type {Component[]}
3
- */
4
- export const components = [];
5
- /**
6
- * theguardian.com uses a custom scroll event for performance reasons.
7
- * We pass in the event emitter so that we can listen to this custom scroll event.
8
- * If not on theguardian.com, we default to the native scroll event
9
- * @type {Object|null}
10
- */
11
- let eventEmitter = null;
12
- // Tracks attention time of elements on the page with data-component attributes.
13
- // This should always be less than or equal to the page attention time.
14
- // If the page does not have attention, no component has attention.
15
- // If the page does have attention, a given component *may* also have
16
- // attention, if it is within the viewport and not hidden.
17
- class Component {
18
- /**
19
- * Component constructor.
20
- * @param {string} name - The name of the component.
21
- * @param {HTMLElement} element - The DOM element of the component.
22
- * @param {number} visibilityThreshold1 -
23
- * visibilityThreshold represents the fraction of each component that must
24
- * be in the viewport before it is considered visible.
25
- * e.g. 0.5 means that half the height or width must be in the viewport
26
- * 1 means that the entire element must be in the viewport
27
- * @param {number} reportingInterval1 - ??
28
- */
29
- constructor(name, element, visibilityThreshold1, reportingInterval1) {
30
- this.name = name;
31
- this.element = element;
32
- this.visibilityThreshold = visibilityThreshold1;
33
- this.reportingInterval = reportingInterval1;
34
- this.visible = false;
35
- // total attention time so far for this element
36
- this.totalAttentionMs = 0;
37
- // the time elapsed since the time origin (https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)
38
- // when the most recent period of attention (that is, attention
39
- // which we haven't yet added to totalAttentionMs) began.
40
- // null if we don't have attention.
41
- this.unrecordedAttentionStarted = null;
42
- // the attention time when getAttentionTime() was last called
43
- this.reportedTotalAttentionMs = 0;
44
- this.usingEmitter = false;
45
- this.visCheck = this.checkVisibility.bind(this);
46
- if (eventEmitter != null) {
47
- this.usingEmitter = true;
48
- eventEmitter.on('window:throttledScroll', this.visCheck);
49
- }
50
- else {
51
- window.addEventListener('scroll', this.visCheck);
52
- }
53
- window.addEventListener('resize', this.visCheck);
54
- }
55
- isVisible(threshold = 1) {
56
- if (!this.element.offsetParent) {
57
- // exclude hidden elements
58
- // will also exclude position: fixed elements but we don't care about these
59
- // (because their attention time would always be the same as the whole page)
60
- // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
61
- return false;
62
- }
63
- const box = this.element.getBoundingClientRect();
64
- const width = box.width;
65
- const height = box.height;
66
- const windowHeight = window.innerHeight || document.documentElement.clientHeight;
67
- const windowWidth = window.innerWidth || document.documentElement.clientWidth;
68
- return (box.left >= -(width * (1 - threshold)) &&
69
- box.top >= -(height * (1 - threshold)) &&
70
- box.right <= windowWidth + width * (1 - threshold) &&
71
- box.bottom <= windowHeight + height * (1 - threshold));
72
- }
73
- visibilityHasChanged() {
74
- const wasVisible = this.visible;
75
- this.visible = this.isVisible(this.visibilityThreshold);
76
- return wasVisible !== this.visible;
77
- }
78
- rebindToEventEmitter() {
79
- if (!this.usingEmitter && eventEmitter != null) {
80
- window.removeEventListener('scroll', this.visCheck);
81
- this.usingEmitter = true;
82
- return eventEmitter.on('window:throttledScroll', this.visCheck);
83
- }
84
- }
85
- checkVisibility() {
86
- this.rebindToEventEmitter();
87
- if (this.visibilityHasChanged()) {
88
- return this.visible ? this.makeActive() : this.makeInactive();
89
- }
90
- }
91
- makeActive() {
92
- // mark when the latest period of attention began,
93
- // if we're not already in an attention period
94
- return this.unrecordedAttentionStarted != null
95
- ? this.unrecordedAttentionStarted
96
- : (this.unrecordedAttentionStarted = performance.now());
97
- }
98
- makeInactive() {
99
- this.incrementTotalAttentionTimeByUnrecordedAmount();
100
- return (this.unrecordedAttentionStarted = null);
101
- }
102
- hadAttentionSinceLastGet() {
103
- this.incrementTotalAttentionTimeByUnrecordedAmount();
104
- return this.totalAttentionMs !== this.reportedTotalAttentionMs;
105
- }
106
- getAttentionTime() {
107
- this.incrementTotalAttentionTimeByUnrecordedAmount();
108
- this.reportedTotalAttentionMs = this.totalAttentionMs;
109
- return this.totalAttentionMs;
110
- }
111
- incrementTotalAttentionTimeByUnrecordedAmount() {
112
- if (this.unrecordedAttentionStarted != null) {
113
- const now = performance.now();
114
- // the Math.min here is to deal with occasions where we don't get an event indicating that the user
115
- // has become inactive - this can happen e.g. due to users suspending their phone. Never send
116
- // crazy big values!
117
- const unrecordedMs = Math.min(now - this.unrecordedAttentionStarted, this.reportingInterval);
118
- this.totalAttentionMs += unrecordedMs;
119
- return (this.unrecordedAttentionStarted = now);
120
- }
121
- }
122
- }
123
- /**
124
- * Begins monitoring the components on the page for attention time.
125
- * @returns {Array} Array of results from makeActive() for each visible component.
126
- */
127
- const startMonitoring = () => {
128
- return components
129
- .filter((component) => component.isVisible())
130
- .map((component) => component.makeActive());
131
- };
132
- /**
133
- * Stops monitoring the components on the page for attention time.
134
- * @returns {Array} Array of results from makeInactive() for each component.
135
- */
136
- const stopMonitoring = () => {
137
- return components.map((component) => component.makeInactive());
138
- };
139
- /**
140
- * Retrieves the attention times for all components.
141
- * @returns {Object}
142
- */
143
- const getAttentionTimes = () => {
144
- const obj = {};
145
- for (const component of components) {
146
- if (component.hadAttentionSinceLastGet()) {
147
- // if there are duplicate component names, only the last one survives
148
- obj[component.name] = Math.round(component.getAttentionTime());
149
- }
150
- }
151
- return obj;
152
- };
153
- export default {
154
- /**
155
- * @param {Object} emitter - The event emitter to set.
156
- * @returns {Object}
157
- */
158
- setEventEmitter: function (emitter) {
159
- return (eventEmitter = emitter);
160
- },
161
- startMonitoring,
162
- stopMonitoring,
163
- getAttentionTimes,
164
- /** @type {(...args: ConstructorParameters<typeof Component>) => void} */
165
- registerComponent: function (name, el, visibilityThreshold, reportingInterval) {
166
- return components.push(new Component(name, el, visibilityThreshold, reportingInterval));
167
- },
168
- };
@@ -1,6 +0,0 @@
1
- declare namespace _default {
2
- let record: (obj: import("../types/event.js").EventPayload, f?: Function | undefined) => void;
3
- let viewId: any;
4
- }
5
- export default _default;
6
- //# sourceMappingURL=contribution.d.ts.map
@@ -1,16 +0,0 @@
1
- // Generated by CoffeeScript 2.7.0
2
- import core from './core.js';
3
- import transmit from './transmit.js';
4
- import attention from './attention.js';
5
- import visibility from './visibility.js';
6
- import './click-path-capture.js';
7
- import './perf.js';
8
- import './campaign.js';
9
- core.init('contribution');
10
- if (window.addEventListener != null) {
11
- attention.init(visibility);
12
- }
13
- export default {
14
- record: transmit.sendMore,
15
- viewId: transmit.viewId,
16
- };