import '../polyfills/Fetch';
import InView from '../utils/classes/InView';
import customEvent from '../utils/customEvent';
import ImageContainer from './ImageContainer';
/**
* Load content via `fetch` when element with attribute `[data-load-content]` comes into view
*
* @example
* <div data-load-content="more-stories">
* [fetched content goes here]
* </div>
*
* @module LoadContent
* @prop {string} selector - targets elements on to set up dynamic loading
*/
const LoadContent = {
selector: '[data-load-content]:not([data-load-manually])',
/**
* Set's up `InView` listener on any `[data-load-content]` elements.
* Callback is fired when element comes into view.
*
* @method init
*/
init() {
const inViewWatcher = new InView({
selector: this.selector,
threshold: 0.1,
});
inViewWatcher.init();
const $targets = document.querySelectorAll( this.selector );
[].forEach.call( $targets, ( $target ) => {
$target.addEventListener( customEvent.IN_VIEW, ( event ) => {
if ( event && event.detail ) {
if ( event.detail.isInView ) {
this.load( $target );
}
}
});
});
},
/**
* Fetches content from the template specified by `[data-load-content]`.
* Inserts content onto page.
*
* @method load
* @param {element} $target - Container element for dynamically loaded content.
* @return {promise} - Fetch API promise instance.
*/
load( $target ) {
const template = 'loadContent' in $target.dataset ? `${$target.dataset.loadContent}/` : '';
const params = 'loadContentParams' in $target.dataset ? `${$target.dataset.loadContentParams}/` : '';
return fetch( `/gnca-ajax-redesign/${template}${params}` )
.then( response => response.text() )
.then( ( content ) => {
$target.innerHTML = content; // eslint-disable-line no-param-reassign
const $images = $target.querySelectorAll( ImageContainer.selector );
if ( $images && $images.length > 0 ) {
ImageContainer.init( $images );
}
/* global gn_monetize */
/* global gnAdSettings */
/* eslint-disable camelcase */
// Initialize ad slots when ad divs are found.
if ( 'undefined' !== typeof ( gn_monetize ) && 'undefined' !== typeof ( gn_monetize.Ads ) ) {
const $ads = $target.querySelectorAll( '.c-ad' );
const { isTesting } = gnAdSettings;
[].forEach.call( $ads, ( $ad ) => {
const $adUnit = $ad.querySelector( '.c-ad__unit' );
gn_monetize.Ads.create({
sizes: '[2,2]',
id: `${$adUnit.getAttribute( 'id' )}`,
lazy: true,
fluid: isTesting,
targeting: {
pos: `${$adUnit.dataset.adPos}`,
},
});
});
}
/* eslint-enable camelcase */
});
},
};
export default LoadContent;