This repository has been archived by the owner on Mar 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
slots.js
382 lines (336 loc) · 11.1 KB
/
slots.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/* eslint no-inner-declarations: 1 */
import utils from './utils';
import config from './config';
import Slot from './slot';
let screensize = null;
/**
* The Slots instance tracks all ad slots on the page
* configures global page events used by a slot and
* provides utlity methods that act on all slots
* @constructor
*/
function Slots() { //eslint-disable-line no-empty
}
function invokeMethodOnSlots(names, method, callback) {
let slots = [];
names = names || Object.keys(this);
/* istanbul ignore else */
if (utils.isNonEmptyString(names)) {
slots.push(names);
} else if (utils.isArray(names)) {
slots = names;
}
slots.forEach(run.bind(null, this, method));
if(utils.isFunction(callback)){
callback.call(this, slots);
}
return this;
}
/*
* Either run a method or fire an event on the named slot.
* @private
* @param slots the slots object
*/
function run(slots, action, name) {
const slot = slots[name];
if (slot) {
if (utils.isFunction(slot[action])) {
slot[action]();
} else {
if(utils.isFunction(slot.fire)){
slot.fire(action);
} else {
utils.log.warn('Attempted to %s on a non-slot %s', action, name);
}
}
} else {
utils.log.warn('Attempted to %s non-existant slot %s', action, name);
}
}
function findFormatBySize(size) {
if(!size) {
return false;
}
const formats = config('formats');
for(const prop in formats) {
/* istanbul ignore else */
if(formats.hasOwnProperty(prop)) {
let sizes = formats[prop].sizes;
sizes = utils.isArray(sizes[0]) ? sizes : [sizes];
const match = sizes.filter(function(s) {
return s[0] === parseInt(size[0], 10) && s[1] === parseInt(size[1], 10);
});
if(match.length) {
return prop;
}
}
}
}
/**
* Given a slot name or an array of slot names will collapse the slots using the collapse method on the slot
*/
Slots.prototype.collapse = function(names) {
return invokeMethodOnSlots.call(this, names, 'collapse');
};
/**
* Given a slot name or an array of slot names will uncollapse the slots using the uncollapse method on the slot
*/
Slots.prototype.uncollapse = function(names) {
return invokeMethodOnSlots.call(this, names, 'uncollapse');
};
/**
* Given a slot name or an array of slot names of slotnames will refresh the slots using the refresh method on the slot
*/
Slots.prototype.refresh = function(names) {
return invokeMethodOnSlots.call(this, names, 'refresh');
};
/**
* Given a slot name or an array of slot names will clear the slots using the clear method on the slot
*/
Slots.prototype.clear = function(names) {
return invokeMethodOnSlots.call(this, names, 'clear');
};
/**
* Given a slot name or an array of slot names will destroy the slots using the destroySlot method on the slot and remove the reference to the slot
*/
Slots.prototype.destroy = function(names) {
return invokeMethodOnSlots.call(this, names, 'destroy', function(names){
names.forEach(name => {
this[name] = null;
delete this[name];
});
});
};
/**
* Given a slot name will submit a delayed impression for the slot
*/
Slots.prototype.submitImpression = function(name) {
return invokeMethodOnSlots.call(this, name, 'submitImpression');
};
/**
* Confirms a container in the page exists and creates a Slot object
*/
Slots.prototype.initSlot = function(container) {
// if container is a string this is a legacy implementation using ids
// find the element and remove the ID in favour of a data attribute
if (utils.isString(container)) {
container = document.getElementById(container) || document.querySelector(`[data-o-ads-name="${container}"]`);
if (container && container.id) {
container.setAttribute('data-o-ads-name', container.id);
container.removeAttribute('id');
}
}
// if not an element or we can't find it in the DOM exit
if (!utils.isElement(container)) {
utils.log.error('slot container must be an element!', container);
return false;
}
// add the aria hidden attribute
container.setAttribute('aria-hidden', 'true');
// pass the method to retrieve or create the single IntersectionObserver instance
const slot = new Slot(container, screensize, this.initLazyLoading.bind(this));
/* istanbul ignore else */
if (slot && !this[slot.name]) {
this[slot.name] = slot;
slot.fire('slotReady');
} else if (this[slot.name]) {
utils.log.error('slot %s is already defined!', slot.name);
}
return slot;
};
Slots.prototype.initRefresh = function() {
if (config('flags').refresh && config('refresh')) {
const data = config('refresh');
this.refreshCount = 0;
/* istanbul ignore else */
if (data.time && !data.inview) {
const refresh = () => {
/* istanbul ignore else */
if(!data.max || this.refreshCount++ < data.max) {
this.refresh();
} else if (this.refreshCount >= data.max) {
clearInterval(refresh);
}
};
setInterval(refresh, (parseFloat(data.time) || 1) * 1000);
}
}
return this;
};
/*
* listens for the rendered event from a slot and fires the slotExpand event,
* after extending the slot with information from the server.
*/
Slots.prototype.initRendered = function() {
utils.on('slotRenderStart', function(slots, event) {
const slot = slots[event.detail.name];
/* istanbul ignore else */
if (slot) {
utils.extend(slot[slot.server], event.detail[slot.server]);
const size = event.detail.gpt.size;
const format = findFormatBySize(size);
slot.setFormatLoaded(format);
slot.maximise(size);
slot.fire('slotExpand', event.detail);
}
}.bind(null, this));
return this;
};
/*
* if responsive configuration exists listen for breakpoint changes
*/
Slots.prototype.initResponsive = function() {
const breakpoints = config('responsive');
/* istanbul ignore else */
if (utils.isObject(breakpoints)) {
screensize = utils.responsive(breakpoints, onBreakpointChange.bind(null, this));
}
return this;
};
/*
* called when a responsive breakpoint is crossed though window resizing or orientation change.
*/
function onBreakpointChange(slots, screensize) {
slots.forEach(function(slot) {
/* istanbul ignore else */
if (slot) {
// ADS-766 if format name is Responsive then we have requested a responsive creative and do not want to request new ads at different breakpoints
/* istanbul ignore else */
const isCurrentlyResponsive = slot.container && slot.container.getAttribute('data-o-ads-loaded') === 'Responsive';
const stillWantsResponsive = slot.sizes[screensize] && slot.sizes[screensize].filter(size => findFormatBySize(size) === 'Responsive').length > 0;
if (isCurrentlyResponsive && stillWantsResponsive) {
return false;
}
slot.screensize = screensize;
slot.fire('breakpoint', { screensize: screensize });
}
});
}
/*
* Initialise the postMessage API
*/
Slots.prototype.initPostMessage = function() {
// Listen for messages coming from ads
window.addEventListener('message', pmHandler.bind(null, this), false);
function pmHandler(slots, event) {
const data = utils.messenger.parse(event.data);
/* istanbul ignore else don't process messages with a non oAds type*/
if (data.type && (/^oAds\./.test(data.type) || /^touch/.test(data.type))) {
const type = data.type.replace('oAds\.', '');
// Make sure the message is coming from an identified ad slot
const slotName = utils.iframeToSlotName(event.source.window);
const slot = slots[slotName] || false;
if (!slot) {
utils.log.error('Message received from unidentified slot');
return;
}
// TODO: Remove adIframeLoaded once we can tag onto GPTs `slotRenderEnded` event
if(type === 'adIframeLoaded') {
slot.fire('slotRenderEnded');
}
// Received message to Collapse ad slot.
else if (type === 'collapse') {
slot.collapse();
}
// Received touch events from ad slot iframe
/* istanbul ignore else*/
else if (/^touch/.test(data.type)) {
slot.fire('touch', data);
}
else {
utils.log.error('Unknown message received from o-ads-embed');
}
}
}
};
// remove any observers tied to elements no longer in the DOM
// e.g. app page has been swiped out from the gallery
Slots.prototype.flushLazyLoading = function() {
this.lazyLoadingObservers = this.lazyLoadingObservers.filter(observer => {
return Boolean(!observer.root || document.contains(observer.root));
});
};
Slots.prototype.initLazyLoading = function(slotConfig) {
const lazyLoadingConfig = config('lazyLoad') || slotConfig | {};
this.lazyLoadingObservers = this.lazyLoadingObservers || [];
this.flushLazyLoading();
// find any pre-existing observers
let lazyLoadingObserver = this.lazyLoadingObservers.find(observer => {
// deliberately double-equals to match null and undefined where the viewport is being observed
return lazyLoadingConfig.root == observer.root; // eslint-disable-line eqeqeq
});
function onChange(changes) {
//Execute the changes in the order they appear on the page. This is because the top slot often determines what the lower slots display.
/* istanbul ignore next */
changes
.filter(a => a.intersectionRect.height || a.intersectionRect.width || a.intersectionRect.top || a.intersectionRect.left)
.sort((a,b) => a.intersectionRect.top - b.intersectionRect.top)
.forEach((change) => {
const slotName = change.target.getAttribute('data-o-ads-name');
/* istanbul ignore else */
if(slotName) {
invokeMethodOnSlots.call(this, slotName, 'render');
}
});
}
// If we don't already have an instance of the observer, and it is enabled globally or on a slot (force), then create one.
/* istanbul ignore else */
if('IntersectionObserver' in window && !lazyLoadingObserver && Boolean(lazyLoadingConfig)) {
const options = {};
/* istanbul ignore else */
if(typeof lazyLoadingConfig === 'object') {
/* istanbul ignore else */
if(lazyLoadingConfig.viewportMargin){
options.rootMargin = lazyLoadingConfig.viewportMargin;
}
/* istanbul ignore else */
if(lazyLoadingConfig.threshold) {
options.threshold = lazyLoadingConfig.threshold;
}
options.root = lazyLoadingConfig.root || null;
}
lazyLoadingObserver = new IntersectionObserver(onChange.bind(this), options);
this.lazyLoadingObservers.push(lazyLoadingObserver);
}
return lazyLoadingObserver;
};
Slots.prototype.forEach = function(fn) {
Object.keys(this).forEach(name => {
const slot = this[name];
/* istanbul ignore else */
if (slot instanceof Slot) {
fn.call(this, slot);
}
});
return this;
};
/*
* Initialise slots
*/
Slots.prototype.init = function() {
this.initRefresh();
this.initRendered();
this.initResponsive();
this.initPostMessage();
this.initLazyLoading();
};
Slots.prototype.debug = function (){
const log = utils.log;
const data = [];
this.forEach(function (slot) {
const row = {
name: slot.name,
'unit name': slot.gpt.unitName,
'creative id': slot.gpt.creativeId || 'N/A',
'line item id': slot.gpt.lineItemId || 'N/A',
size: utils.isArray(slot.gpt.size) && slot.gpt.size.join('×') || slot.gpt.isEmpty && 'empty' || 'N/A',
sizes: utils.isArray(slot.sizes) && slot.sizes.map(function(item){ return item.join('×'); }).join(', ') || 'responsive slot',
targeting: Object.keys(slot.targeting).map(function (param) { return `${param}=${slot.targeting[param]}`;} ).join(', ')
};
data.push(row);
});
log.start('Creatives');
log.table(data);
log.end();
};
export default new Slots();