@guardian/ophan-tracker-js 2.1.0-next.0 → 2.1.0-next.2

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.
@@ -0,0 +1,19 @@
1
+ import abd from './vendor/adBlockDetectionLib.js';
2
+
3
+ export default {
4
+ run() {
5
+ return new Promise((resolve, reject) => {
6
+ if (abd.init) {
7
+ try {
8
+ abd.init({
9
+ complete: resolve,
10
+ });
11
+ } catch (error) {
12
+ reject(error);
13
+ }
14
+ } else {
15
+ reject(new Error('Failed to initialise adblock detection'));
16
+ }
17
+ });
18
+ },
19
+ };
@@ -0,0 +1,160 @@
1
+ // Generated by CoffeeScript 2.7.0
2
+ import transmit from './transmit.js';
3
+
4
+ import components from './components.js';
5
+
6
+ // The upworthy definition of attention minutes, from
7
+ // http://upworthy.github.io/2014/06/implementing-attention-minutes-part-1/ :
8
+
9
+ // "We consider the page to have the user’s attention if
10
+ // 1. some activity is happening on the page. For our purposes this means:
11
+ // 1. the page currently has focus
12
+ // 2. and the user has interacted with the page within a certain timeout
13
+ // 2. or a video is playing on the page
14
+ // Attention Minutes, then, are the total number of minutes that a user has spent on
15
+ // a page where the above conditions have held true."
16
+
17
+ // our definition of "within a certain timeout" above:
18
+ const ATTENTIONDECAY = 5000;
19
+
20
+ // our definition of "the user has interacted with the page"
21
+ const EVENTS = [
22
+ 'focus',
23
+ 'click',
24
+ 'scroll',
25
+ 'mousemove',
26
+ 'touchstart',
27
+ 'touchend',
28
+ 'touchcancel',
29
+ 'touchleave',
30
+ 'touchmove',
31
+ 'keyup',
32
+ 'keydown',
33
+ ];
34
+
35
+ const REPORTINGINTERVAL = 10000;
36
+
37
+ // total attention time so far on this page
38
+ let totalAttentionMs = 0;
39
+
40
+ // the time elapsed since the time origin (https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)
41
+ // when the most recent period of attention (that is, attention
42
+ // which we haven't yet added to totalAttentionMs) began.
43
+ // null if we don't have attention.
44
+ let unrecordedAttentionStarted = null;
45
+
46
+ // the attention time we last reported to ophan
47
+ let reportedTotalAttentionMs = null; // setting null here forces a first report of attention time, even if it's only 0ms
48
+
49
+ // the decay timer if we've set one
50
+ let decayTimerId = null;
51
+
52
+ // is video currently playing?
53
+ let videoPlaying = false;
54
+
55
+ const cancelDecayTimer = () => {
56
+ if (decayTimerId != null) {
57
+ window.clearTimeout(decayTimerId);
58
+ }
59
+ decayTimerId = null;
60
+ };
61
+
62
+ const makeActive = () => {
63
+ if (unrecordedAttentionStarted == null) {
64
+ unrecordedAttentionStarted = performance.now();
65
+ }
66
+ components.startMonitoring();
67
+ cancelDecayTimer();
68
+ decayTimerId = window.setTimeout(() => {
69
+ if (!videoPlaying) {
70
+ makeInactive();
71
+ }
72
+ }, ATTENTIONDECAY);
73
+ };
74
+
75
+ const incrementTotalAttentionTimeByUnrecordedAmount = () => {
76
+ if (unrecordedAttentionStarted != null) {
77
+ const now = performance.now();
78
+ const unrecordedMs = Math.min(
79
+ now - unrecordedAttentionStarted,
80
+ REPORTINGINTERVAL,
81
+ );
82
+ totalAttentionMs += unrecordedMs;
83
+ unrecordedAttentionStarted = now;
84
+ }
85
+ };
86
+
87
+ const makeInactive = () => {
88
+ cancelDecayTimer();
89
+ components.stopMonitoring();
90
+ incrementTotalAttentionTimeByUnrecordedAmount();
91
+ unrecordedAttentionStarted = null;
92
+ };
93
+
94
+ const reporter = () => {
95
+ incrementTotalAttentionTimeByUnrecordedAmount();
96
+ if (totalAttentionMs !== reportedTotalAttentionMs) {
97
+ const report = {
98
+ attentionMs: Math.round(totalAttentionMs),
99
+ };
100
+ const componentAttentionTimes = components.getAttentionTimes();
101
+ if (Object.keys(componentAttentionTimes).length) {
102
+ report.componentAttentionMs = componentAttentionTimes;
103
+ }
104
+ transmit.sendMore(report);
105
+ reportedTotalAttentionMs = totalAttentionMs;
106
+ }
107
+ };
108
+
109
+ const initComponent = (name, el, visibilityThreshold = 0.5) => {
110
+ components.registerComponent(
111
+ name,
112
+ el,
113
+ visibilityThreshold,
114
+ REPORTINGINTERVAL,
115
+ );
116
+ };
117
+
118
+ const initAttention = (visibility) => {
119
+ EVENTS.forEach((event) => {
120
+ window.addEventListener(event, makeActive);
121
+ });
122
+
123
+ document.addEventListener(
124
+ visibility.changeEvent,
125
+ () => {
126
+ if (visibility.state() === 'visible') {
127
+ makeActive();
128
+ } else {
129
+ makeInactive();
130
+ }
131
+ },
132
+ false,
133
+ );
134
+
135
+ document.addEventListener('videoPlaying', () => {
136
+ videoPlaying = true;
137
+ makeActive();
138
+ });
139
+ document.addEventListener('videoEnded', () => {
140
+ videoPlaying = false;
141
+ makeInactive();
142
+ });
143
+ document.addEventListener('videoPause', () => {
144
+ videoPlaying = false;
145
+ makeInactive();
146
+ });
147
+
148
+ window.setTimeout(reporter, 100);
149
+ window.setInterval(reporter, REPORTINGINTERVAL);
150
+ };
151
+
152
+ const setEventEmitter = (emitter) => {
153
+ components.setEventEmitter(emitter);
154
+ };
155
+
156
+ export default {
157
+ init: initAttention,
158
+ initComponent: initComponent,
159
+ setEventEmitter: setEventEmitter,
160
+ };
@@ -0,0 +1,25 @@
1
+ // Generated by CoffeeScript 2.7.0
2
+ import transmit from './transmit.js';
3
+ import perf from './perf.js';
4
+
5
+ const start = perf?.timing?.domComplete ?? performance.now();
6
+
7
+ // DFP ads
8
+ if (typeof googletag !== 'undefined' && googletag !== null) {
9
+ googletag.cmd.push(() => {
10
+ googletag.pubads().addEventListener('slotRenderEnded', (event) => {
11
+ const slotId = event.slot.getSlotId().getDomId();
12
+ transmit.sendMore({
13
+ ads: [
14
+ {
15
+ slot: slotId,
16
+ campaignId: event.isEmpty ? '__empty__' : event.lineItemId,
17
+ creativeId: event.creativeId,
18
+ timeToRenderEnded: Math.round(performance.now() - start),
19
+ adServer: 'DFP',
20
+ },
21
+ ],
22
+ });
23
+ });
24
+ });
25
+ }
@@ -0,0 +1,80 @@
1
+ import ophan from './core.js';
2
+
3
+ import transmit from './transmit.js';
4
+
5
+ /**
6
+ * Finds the closest ancestor anchor (`<a>`) element of the given element.
7
+ *
8
+ * @param {Element} el - The element to start searching from.
9
+ * @returns {Element|null} The closest ancestor anchor element or null if none found.
10
+ */
11
+ export const validAncestorAnchorElement = (el) => {
12
+ if (!el || el.nodeName?.toLowerCase() === 'body') return null;
13
+ return el.nodeName.toLowerCase() === 'a'
14
+ ? el
15
+ : validAncestorAnchorElement(el.parentNode);
16
+ };
17
+
18
+ /**
19
+ * Retrieves the value of the `data-component` attribute from the closest ancestor.
20
+ *
21
+ * @param {Element} el - The element to start searching from.
22
+ * @returns {string|null} The `data-component` attribute value or null if not found.
23
+ */
24
+ export const getContainingComponent = (el) => {
25
+ if (!el || el.nodeName?.toLowerCase() === 'body') return null;
26
+ return (
27
+ el.getAttribute('data-component') || getContainingComponent(el.parentNode)
28
+ );
29
+ };
30
+
31
+ /**
32
+ * Collects all `data-link-name` attribute values from the ancestor elements.
33
+ *
34
+ * @param {Element} el - The element to start searching from.
35
+ * @param {string[]} dataLinkNames - Initial array of data link names (optional).
36
+ * @returns {string[]} Array of `data-link-name` values.
37
+ */
38
+ const getDataLinkNames = (el, dataLinkNames = []) => {
39
+ if (!el || el === document.body || el === document) return dataLinkNames;
40
+
41
+ const dataLinkName = el.getAttribute('data-link-name');
42
+ if (dataLinkName) dataLinkNames.push(dataLinkName);
43
+
44
+ return getDataLinkNames(el.parentNode, dataLinkNames);
45
+ };
46
+
47
+ if (typeof document.addEventListener === 'function') {
48
+ document.addEventListener(
49
+ 'click',
50
+ function (e) {
51
+ let anchorTarget, info;
52
+ anchorTarget = validAncestorAnchorElement(e.target);
53
+ info = {
54
+ from: [location.protocol, '//', location.host, location.pathname].join(
55
+ '',
56
+ ),
57
+ to: anchorTarget ? anchorTarget.href : void 0,
58
+ referringComponent: getContainingComponent(e.target),
59
+ referringDataLinkNames: getDataLinkNames(e.target),
60
+ refPlatform: ophan.servingPlatform(),
61
+ refViewId: ophan.viewId,
62
+ };
63
+ if (info.referringDataLinkNames != null) {
64
+ transmit.sendMore({
65
+ clickComponent: info.referringComponent,
66
+ clickLinkNames: info.referringDataLinkNames,
67
+ });
68
+ }
69
+ if (anchorTarget != null) {
70
+ // then we may be about to navigate away from this page, so store to send on next request
71
+ return ophan.storeDataToSendOnNextEvent(info);
72
+ }
73
+ },
74
+ false,
75
+ );
76
+ }
77
+
78
+ export default {
79
+ getDataLinkNames: getDataLinkNames,
80
+ };
@@ -0,0 +1,209 @@
1
+ /**
2
+ * @type {Component[]}
3
+ */
4
+ const components = [];
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+ /**
17
+ * theguardian.com uses a custom scroll event for performance reasons.
18
+ * We pass in the event emitter so that we can listen to this custom scroll event.
19
+ * If not on theguardian.com, we default to the native scroll event
20
+ * @type {Object|null}
21
+ */
22
+ let eventEmitter = null;
23
+
24
+ // Tracks attention time of elements on the page with data-component attributes.
25
+ // This should always be less than or equal to the page attention time.
26
+ // If the page does not have attention, no component has attention.
27
+ // If the page does have attention, a given component *may* also have
28
+ // attention, if it is within the viewport and not hidden.
29
+ class Component {
30
+ /**
31
+ * Component constructor.
32
+ * @param {string} name - The name of the component.
33
+ * @param {HTMLElement} element - The DOM element of the component.
34
+ * @param {number} visibilityThreshold1 -
35
+ * visibilityThreshold represents the fraction of each component that must
36
+ * be in the viewport before it is considered visible.
37
+ * e.g. 0.5 means that half the height or width must be in the viewport
38
+ * 1 means that the entire element must be in the viewport
39
+ * @param {number} reportingInterval1 - ??
40
+ */
41
+ constructor(name, element, visibilityThreshold1, reportingInterval1) {
42
+ this.name = name;
43
+ this.element = element;
44
+ this.visibilityThreshold = visibilityThreshold1;
45
+ this.reportingInterval = reportingInterval1;
46
+ this.visible = false;
47
+ // total attention time so far for this element
48
+ this.totalAttentionMs = 0;
49
+ // the time elapsed since the time origin (https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp#the_time_origin)
50
+ // when the most recent period of attention (that is, attention
51
+ // which we haven't yet added to totalAttentionMs) began.
52
+ // null if we don't have attention.
53
+ this.unrecordedAttentionStarted = null;
54
+ // the attention time when getAttentionTime() was last called
55
+ this.reportedTotalAttentionMs = 0;
56
+ this.usingEmitter = false;
57
+ this.visCheck = this.checkVisibility.bind(this);
58
+ if (eventEmitter != null) {
59
+ this.usingEmitter = true;
60
+ eventEmitter.on('window:throttledScroll', this.visCheck);
61
+ } else {
62
+ window.addEventListener('scroll', this.visCheck);
63
+ }
64
+ window.addEventListener('resize', this.visCheck);
65
+ }
66
+
67
+ isVisible(threshold = 1) {
68
+ if (!this.element.offsetParent) {
69
+ // exclude hidden elements
70
+ // will also exclude position: fixed elements but we don't care about these
71
+ // (because their attention time would always be the same as the whole page)
72
+ // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent
73
+ return false;
74
+ }
75
+
76
+ const box = this.element.getBoundingClientRect();
77
+ const width = box.width;
78
+ const height = box.height;
79
+ const windowHeight =
80
+ window.innerHeight || document.documentElement.clientHeight;
81
+ const windowWidth =
82
+ window.innerWidth || document.documentElement.clientWidth;
83
+
84
+ return (
85
+ box.left >= -(width * (1 - threshold)) &&
86
+ box.top >= -(height * (1 - threshold)) &&
87
+ box.right <= windowWidth + width * (1 - threshold) &&
88
+ box.bottom <= windowHeight + height * (1 - threshold)
89
+ );
90
+ }
91
+
92
+ visibilityHasChanged() {
93
+ const wasVisible = this.visible;
94
+ this.visible = this.isVisible(this.visibilityThreshold);
95
+ return wasVisible !== this.visible;
96
+ }
97
+
98
+ rebindToEventEmitter() {
99
+ if (!this.usingEmitter && eventEmitter != null) {
100
+ window.removeEventListener('scroll', this.visCheck);
101
+ this.usingEmitter = true;
102
+ return eventEmitter.on('window:throttledScroll', this.visCheck);
103
+ }
104
+ }
105
+
106
+ checkVisibility() {
107
+ this.rebindToEventEmitter();
108
+ if (this.visibilityHasChanged()) {
109
+ return this.visible ? this.makeActive() : this.makeInactive();
110
+ }
111
+ }
112
+
113
+ makeActive() {
114
+ // mark when the latest period of attention began,
115
+ // if we're not already in an attention period
116
+ return this.unrecordedAttentionStarted != null
117
+ ? this.unrecordedAttentionStarted
118
+ : (this.unrecordedAttentionStarted = performance.now());
119
+ }
120
+
121
+ makeInactive() {
122
+ this.incrementTotalAttentionTimeByUnrecordedAmount();
123
+ return (this.unrecordedAttentionStarted = null);
124
+ }
125
+
126
+ hadAttentionSinceLastGet() {
127
+ this.incrementTotalAttentionTimeByUnrecordedAmount();
128
+ return this.totalAttentionMs !== this.reportedTotalAttentionMs;
129
+ }
130
+
131
+ getAttentionTime() {
132
+ this.incrementTotalAttentionTimeByUnrecordedAmount();
133
+ this.reportedTotalAttentionMs = this.totalAttentionMs;
134
+ return this.totalAttentionMs;
135
+ }
136
+
137
+ incrementTotalAttentionTimeByUnrecordedAmount() {
138
+ if (this.unrecordedAttentionStarted != null) {
139
+ const now = performance.now();
140
+ // the Math.min here is to deal with occasions where we don't get an event indicating that the user
141
+ // has become inactive - this can happen e.g. due to users suspending their phone. Never send
142
+ // crazy big values!
143
+ const unrecordedMs = Math.min(
144
+ now - this.unrecordedAttentionStarted,
145
+ this.reportingInterval,
146
+ );
147
+ this.totalAttentionMs += unrecordedMs;
148
+ return (this.unrecordedAttentionStarted = now);
149
+ }
150
+ }
151
+ }
152
+
153
+ /**
154
+ * Begins monitoring the components on the page for attention time.
155
+ * @returns {Array} Array of results from makeActive() for each visible component.
156
+ */
157
+ const startMonitoring = () => {
158
+ return components
159
+ .filter((component) => component.isVisible())
160
+ .map((component) => component.makeActive());
161
+ };
162
+
163
+ /**
164
+ * Stops monitoring the components on the page for attention time.
165
+ * @returns {Array} Array of results from makeInactive() for each component.
166
+ */
167
+ const stopMonitoring = () => {
168
+ return components.map((component) => component.makeInactive());
169
+ };
170
+
171
+ /**
172
+ * Retrieves the attention times for all components.
173
+ * @returns {Object}
174
+ */
175
+ const getAttentionTimes = () => {
176
+ const obj = {};
177
+ for (const component of components) {
178
+ if (component.hadAttentionSinceLastGet()) {
179
+ // if there are duplicate component names, only the last one survives
180
+ obj[component.name] = Math.round(component.getAttentionTime());
181
+ }
182
+ }
183
+ return obj;
184
+ };
185
+
186
+ export default {
187
+ /**
188
+ * @param {Object} emitter - The event emitter to set.
189
+ * @returns {Object}
190
+ */
191
+ setEventEmitter: function (emitter) {
192
+ return (eventEmitter = emitter);
193
+ },
194
+ startMonitoring,
195
+ stopMonitoring,
196
+ getAttentionTimes,
197
+
198
+ /** @type {(...args: ConstructorParameters<typeof Component>) => void} */
199
+ registerComponent: function (
200
+ name,
201
+ el,
202
+ visibilityThreshold,
203
+ reportingInterval,
204
+ ) {
205
+ return components.push(
206
+ new Component(name, el, visibilityThreshold, reportingInterval),
207
+ );
208
+ },
209
+ };
@@ -0,0 +1,25 @@
1
+ // Generated by CoffeeScript 2.7.0
2
+ import core from './core.js';
3
+
4
+ import transmit from './transmit.js';
5
+
6
+ import attention from './attention.js';
7
+
8
+ import visibility from './visibility.js';
9
+
10
+ import './click-path-capture.js';
11
+
12
+ import './perf.js';
13
+
14
+ import './campaign.js';
15
+
16
+ core.init('contribution');
17
+
18
+ if (window.addEventListener != null) {
19
+ attention.init(visibility);
20
+ }
21
+
22
+ export default {
23
+ record: transmit.sendMore,
24
+ viewId: transmit.viewId,
25
+ };