UNPKG

@financial-times/o-ads

Version:

This package contains the core functionality used by the FT in providing ads across all of its sites. This includes ft.com, howtospendit.com, ftadviser.com and other specialist titles.

433 lines (338 loc) 12.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _index = _interopRequireDefault(require("./utils/index.js")); var _config = _interopRequireDefault(require("./config.js")); var _slot = _interopRequireDefault(require("./slot.js")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* eslint no-inner-declarations: 1 */ var 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) { var slots = []; names = names || Object.keys(this); /* istanbul ignore else */ if (_index.default.isNonEmptyString(names)) { slots.push(names); } else if (_index.default.isArray(names)) { slots = names; } slots.forEach(run.bind(null, this, method)); if (_index.default.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) { var slot = slots[name]; if (slot) { if (_index.default.isFunction(slot[action])) { slot[action](); } else { if (_index.default.isFunction(slot.fire)) { slot.fire(action); } else { _index.default.log.warn('Attempted to %s on a non-slot %s', action, name); } } } else { _index.default.log.warn('Attempted to %s non-existant slot %s', action, name); } } function findFormatBySize(size) { if (!size) { return false; } var formats = (0, _config.default)('formats'); for (var prop in formats) { /* istanbul ignore else */ if (formats.hasOwnProperty(prop)) { var sizes = formats[prop].sizes; sizes = _index.default.isArray(sizes[0]) ? sizes : [sizes]; var 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 (_index.default.isString(container)) { container = document.getElementById(container) || document.querySelector("[data-o-ads-name=\"".concat(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 (!_index.default.isElement(container)) { _index.default.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 var slot = new _slot.default(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]) { _index.default.log.error('slot %s is already defined!', slot.name); } return slot; }; Slots.prototype.initRefresh = function () { if ((0, _config.default)('flags').refresh && (0, _config.default)('refresh')) { var data = (0, _config.default)('refresh'); this.refreshCount = 0; /* istanbul ignore else */ if (data.time && !data.inview) { var 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 () { _index.default.on('slotRenderStart', function (slots, event) { var slot = slots[event.detail.name]; /* istanbul ignore else */ if (slot) { _index.default.extend(slot[slot.server], event.detail[slot.server]); var size = event.detail.gpt.size; var 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 () { var breakpoints = (0, _config.default)('responsive'); /* istanbul ignore else */ if (_index.default.isObject(breakpoints)) { screensize = _index.default.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 */ var isCurrentlyResponsive = slot.container && slot.container.getAttribute('data-o-ads-loaded') === 'Responsive'; var 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) { var data = _index.default.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))) { var type = data.type.replace('oAds.', ''); // Make sure the message is coming from an identified ad slot var slotName = _index.default.iframeToSlotName(event.source.window); var slot = slots[slotName] || false; if (!slot) { _index.default.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'); } else if (type === 'slotClass' && data.slotClass) { slot.addClass(data.slotClass); } // Received message to Collapse ad slot. else if (type === 'collapse') { slot.fire('slotCollapsed'); slot.collapse(); } // Received touch events from ad slot iframe /* istanbul ignore else*/ else if (/^touch/.test(data.type)) { slot.fire('touch', data); } else { _index.default.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) { var lazyLoadingConfig = (0, _config.default)('lazyLoad') || slotConfig | {}; this.lazyLoadingObservers = this.lazyLoadingObservers || []; this.flushLazyLoading(); // find any pre-existing observers var 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 => { var 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)) { var 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 => { var slot = this[name]; /* istanbul ignore else */ if (slot instanceof _slot.default) { 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 () { var log = _index.default.log; var data = []; this.forEach(function (slot) { var 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: _index.default.isArray(slot.gpt.size) && slot.gpt.size.join('×') || slot.gpt.isEmpty && 'empty' || 'N/A', sizes: _index.default.isArray(slot.sizes) && slot.sizes.map(function (item) { return item.join('×'); }).join(', ') || 'responsive slot', targeting: Object.keys(slot.targeting).map(function (param) { return "".concat(param, "=").concat(slot.targeting[param]); }).join(', ') }; data.push(row); }); log.start('Creatives'); log.table(data); log.end(); }; var _default = new Slots(); exports.default = _default;