Formatting and “ad” badge

This commit is contained in:
Sam Potts 2018-01-19 20:24:15 +11:00
parent f33ca846f2
commit 5fad152cbf
10 changed files with 103 additions and 108 deletions

2
demo/dist/demo.css vendored

File diff suppressed because one or more lines are too long

2
demo/dist/demo.js vendored
View File

@ -1,3 +1,3 @@
document.addEventListener("DOMContentLoaded",function(){window.shr&&window.shr.setup({count:{classname:"button__count"}});var e="tab-focus";document.addEventListener("focusout",function(t){t.target.classList.remove(e)}),document.addEventListener("keydown",function(t){9===t.keyCode&&window.setTimeout(function(){document.activeElement.classList.add(e)},0)});var t=new window.Plyr("#player",{debug:!0,title:"View From A Blue Moon",iconUrl:"../dist/plyr.svg",keyboard:{global:!0},tooltips:{controls:!0},captions:{active:!0},keys:{google:"AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c"},ads:{tagUrl:"http://go.aniview.com/api/adserver6/vast/?AV_PUBLISHERID=58c25bb0073ef448b1087ad6&AV_CHANNELID=5a0458dc28a06145e4519d21&AV_URL=127.0.0.1:3000&cb=1&AV_WIDTH=640&AV_HEIGHT=480"}});window.player=t;var o=document.querySelectorAll("[data-source]"),i={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},r=window.location.hash.replace("#",""),a=window.history&&window.history.pushState;function n(e,t,o){e&&e.classList[o?"add":"remove"](t)}function s(e,a){if(e in i&&(a||e!==r)&&(r.length||e!==i.video)){switch(e){case i.video:t.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4",type:"video/mp4"}],poster:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg",tracks:[{kind:"captions",label:"English",srclang:"en",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt",default:!0},{kind:"captions",label:"French",srclang:"fr",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt"}]};break;case i.audio:t.source={type:"audio",title:"Kishi Bashi – “It All Began With A Burst”",sources:[{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3",type:"audio/mp3"},{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg",type:"audio/ogg"}]};break;case i.youtube:t.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://youtube.com/watch?v=bTqVqk7FSmY",provider:"youtube"}]};break;case i.vimeo:t.source={type:"video",sources:[{src:"https://vimeo.com/76979871",provider:"vimeo"}]}}r=e,Array.from(o).forEach(function(e){return n(e.parentElement,"active",!1)}),n(document.querySelector('[data-source="'+e+'"]'),"active",!0),Array.from(document.querySelectorAll(".plyr__cite")).forEach(function(e){e.setAttribute("hidden","")}),document.querySelector(".plyr__cite--"+e).removeAttribute("hidden")}}if(Array.from(o).forEach(function(e){e.addEventListener("click",function(){var t=e.getAttribute("data-source");s(t),a&&window.history.pushState({type:t},"","#"+t)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&s(e.state.type)}),a){var c=!r.length;c&&(r=i.video),r in i&&window.history.replaceState({type:r},"",c?"":"#"+r),r!==i.video&&s(r,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,r,a,n){e.GoogleAnalyticsObject="ga",e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,a=t.createElement("script"),n=t.getElementsByTagName("script")[0],a.async=1,a.src="//www.google-analytics.com/analytics.js",n.parentNode.insertBefore(a,n)}(window,document),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview")); document.addEventListener("DOMContentLoaded",function(){window.shr&&window.shr.setup({count:{classname:"button__count"}});document.addEventListener("focusout",function(e){e.target.classList.remove("tab-focus")}),document.addEventListener("keydown",function(e){9===e.keyCode&&window.setTimeout(function(){document.activeElement.classList.add("tab-focus")},0)});var e=new window.Plyr("#player",{debug:!0,title:"View From A Blue Moon",iconUrl:"../dist/plyr.svg",keyboard:{global:!0},tooltips:{controls:!0},captions:{active:!0},keys:{google:"AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c"},ads:{tagUrl:"http://go.aniview.com/api/adserver6/vast/?AV_PUBLISHERID=58c25bb0073ef448b1087ad6&AV_CHANNELID=5a0458dc28a06145e4519d21&AV_URL=127.0.0.1:3000&cb=1&AV_WIDTH=640&AV_HEIGHT=480"}});window.player=e;var t=document.querySelectorAll("[data-source]"),o={video:"video",audio:"audio",youtube:"youtube",vimeo:"vimeo"},i=window.location.hash.replace("#",""),a=window.history&&window.history.pushState;function r(e,t,o){e&&e.classList[o?"add":"remove"](t)}function n(a,n){if(a in o&&(n||a!==i)&&(i.length||a!==o.video)){switch(a){case o.video:e.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4",type:"video/mp4"}],poster:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg",tracks:[{kind:"captions",label:"English",srclang:"en",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt",default:!0},{kind:"captions",label:"French",srclang:"fr",src:"https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt"}]};break;case o.audio:e.source={type:"audio",title:"Kishi Bashi – “It All Began With A Burst”",sources:[{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3",type:"audio/mp3"},{src:"https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg",type:"audio/ogg"}]};break;case o.youtube:e.source={type:"video",title:"View From A Blue Moon",sources:[{src:"https://youtube.com/watch?v=bTqVqk7FSmY",provider:"youtube"}]};break;case o.vimeo:e.source={type:"video",sources:[{src:"https://vimeo.com/76979871",provider:"vimeo"}]}}i=a,Array.from(t).forEach(function(e){return r(e.parentElement,"active",!1)}),r(document.querySelector('[data-source="'+a+'"]'),"active",!0),Array.from(document.querySelectorAll(".plyr__cite")).forEach(function(e){e.setAttribute("hidden","")}),document.querySelector(".plyr__cite--"+a).removeAttribute("hidden")}}if(Array.from(t).forEach(function(e){e.addEventListener("click",function(){var t=e.getAttribute("data-source");n(t),a&&window.history.pushState({type:t},"","#"+t)})}),window.addEventListener("popstate",function(e){e.state&&"type"in e.state&&n(e.state.type)}),a){var s=!i.length;s&&(i=o.video),i in o&&window.history.replaceState({type:i},"",s?"":"#"+i),i!==o.video&&n(i,!0)}}),"plyr.io"===window.location.host&&(!function(e,t,o,i,a,r,n){e.GoogleAnalyticsObject="ga",e.ga=e.ga||function(){(e.ga.q=e.ga.q||[]).push(arguments)},e.ga.l=1*new Date,r=t.createElement("script"),n=t.getElementsByTagName("script")[0],r.async=1,r.src="//www.google-analytics.com/analytics.js",n.parentNode.insertBefore(r,n)}(window,document),window.ga("create","UA-40881672-11","auto"),window.ga("send","pageview"));
//# sourceMappingURL=demo.js.map //# sourceMappingURL=demo.js.map

File diff suppressed because one or more lines are too long

2
dist/plyr.css vendored

File diff suppressed because one or more lines are too long

2
dist/plyr.js vendored

File diff suppressed because one or more lines are too long

2
dist/plyr.js.map vendored

File diff suppressed because one or more lines are too long

View File

@ -176,6 +176,7 @@ const defaults = {
reset: 'Reset', reset: 'Reset',
none: 'None', none: 'None',
disabled: 'Disabled', disabled: 'Disabled',
advertisement: 'Advertisement',
}, },
// URLs // URLs

View File

@ -46,14 +46,14 @@ class Ads {
this.events = {}; this.events = {};
this.safetyTimer = null; this.safetyTimer = null;
// Set listeners on the Plyr instance. // Set listeners on the Plyr instance
this.setupListeners(); this.listeners();
// Start ticking our safety timer. If the whole advertisement // Start ticking our safety timer. If the whole advertisement
// thing doesn't resolve within our set time; we bail. // thing doesn't resolve within our set time; we bail
this.startSafetyTimer(12000, 'ready()'); this.startSafetyTimer(12000, 'ready()');
// Setup a simple promise to resolve if the IMA loader is ready. // Setup a simple promise to resolve if the IMA loader is ready
this.adsLoaderPromise = new Promise(resolve => { this.adsLoaderPromise = new Promise(resolve => {
this.on('ADS_LOADER_LOADED', () => resolve()); this.on('ADS_LOADER_LOADED', () => resolve());
}); });
@ -61,18 +61,18 @@ class Ads {
this.player.debug.log('Ads loader resolved!', this.adsLoader); this.player.debug.log('Ads loader resolved!', this.adsLoader);
}); });
// Setup a promise to resolve if the IMA manager is ready. // Setup a promise to resolve if the IMA manager is ready
this.adsManagerPromise = new Promise(resolve => { this.adsManagerPromise = new Promise(resolve => {
this.on('ADS_MANAGER_LOADED', () => resolve()); this.on('ADS_MANAGER_LOADED', () => resolve());
}); });
this.adsManagerPromise.then(() => { this.adsManagerPromise.then(() => {
this.player.debug.log('Ads manager resolved!', this.adsManager); this.player.debug.log('Ads manager resolved!', this.adsManager);
// Clear the safety timer. // Clear the safety timer
this.clearSafetyTimer('onAdsManagerLoaded()'); this.clearSafetyTimer('onAdsManagerLoaded()');
}); });
// Setup the IMA SDK. // Setup the IMA SDK
this.setupIMA(); this.setupIMA();
} }
@ -85,47 +85,49 @@ class Ads {
* mobile devices, this initialization is done as the result of a user action. * mobile devices, this initialization is done as the result of a user action.
*/ */
setupIMA() { setupIMA() {
// Create the container for our advertisements. // Create the container for our advertisements
this.adsContainer = utils.createElement('div', { this.adsContainer = utils.createElement('div', {
class: this.player.config.classNames.ads, class: this.player.config.classNames.ads,
'data-badge-text': this.player.config.i18n.advertisement,
hidden: '',
}); });
this.player.elements.container.appendChild(this.adsContainer); this.player.elements.container.appendChild(this.adsContainer);
// So we can run VPAID2. // So we can run VPAID2
google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED); google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
// Set language. // Set language
// Todo: Could make a config option out of this locale value. // Todo: Could make a config option out of this locale value.
google.ima.settings.setLocale('en'); google.ima.settings.setLocale('en');
// We assume the adContainer is the video container of the plyr element // We assume the adContainer is the video container of the plyr element
// that will house the ads. // that will house the ads
this.adDisplayContainer = new google.ima.AdDisplayContainer(this.adsContainer); this.adDisplayContainer = new google.ima.AdDisplayContainer(this.adsContainer);
// Request video ads to be pre-loaded. // Request video ads to be pre-loaded
this.requestAds(); this.requestAds();
} }
/** /**
* Request advertisements. * Request advertisements
*/ */
requestAds() { requestAds() {
const { container } = this.player.elements; const { container } = this.player.elements;
try { try {
// Create ads loader. // Create ads loader
this.adsLoader = new google.ima.AdsLoader(this.adDisplayContainer); this.adsLoader = new google.ima.AdsLoader(this.adDisplayContainer);
// Listen and respond to ads loaded and error events. // Listen and respond to ads loaded and error events
this.adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false); this.adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);
this.adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false); this.adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false);
// Request video ads. // Request video ads
const adsRequest = new google.ima.AdsRequest(); const adsRequest = new google.ima.AdsRequest();
adsRequest.adTagUrl = this.player.config.ads.tagUrl; adsRequest.adTagUrl = this.player.config.ads.tagUrl;
// Specify the linear and nonlinear slot sizes. This helps the SDK // Specify the linear and nonlinear slot sizes. This helps the SDK
// to select the correct creative if multiple are returned. // to select the correct creative if multiple are returned
adsRequest.linearAdSlotWidth = container.offsetWidth; adsRequest.linearAdSlotWidth = container.offsetWidth;
adsRequest.linearAdSlotHeight = container.offsetHeight; adsRequest.linearAdSlotHeight = container.offsetHeight;
adsRequest.nonLinearAdSlotWidth = container.offsetWidth; adsRequest.nonLinearAdSlotWidth = container.offsetWidth;
@ -143,25 +145,25 @@ class Ads {
} }
/** /**
* This method is called whenever the ads are ready inside the AdDisplayContainer. * This method is called whenever the ads are ready inside the AdDisplayContainer
* @param {Event} adsManagerLoadedEvent * @param {Event} adsManagerLoadedEvent
*/ */
onAdsManagerLoaded(adsManagerLoadedEvent) { onAdsManagerLoaded(adsManagerLoadedEvent) {
// Get the ads manager. // Get the ads manager
const settings = new google.ima.AdsRenderingSettings(); const settings = new google.ima.AdsRenderingSettings();
// Tell the SDK to save and restore content video state on our behalf. // Tell the SDK to save and restore content video state on our behalf
settings.restoreCustomPlaybackStateOnAdBreakComplete = true; settings.restoreCustomPlaybackStateOnAdBreakComplete = true;
settings.enablePreloading = true; settings.enablePreloading = true;
// The SDK is polling currentTime on the contentPlayback. And needs a duration // The SDK is polling currentTime on the contentPlayback. And needs a duration
// so it can determine when to start the mid- and post-roll. // so it can determine when to start the mid- and post-roll
this.adsManager = adsManagerLoadedEvent.getAdsManager(this.player, settings); this.adsManager = adsManagerLoadedEvent.getAdsManager(this.player, settings);
// Get the cue points for any mid-rolls by filtering out the pre- and post-roll. // Get the cue points for any mid-rolls by filtering out the pre- and post-roll
this.adsCuePoints = this.adsManager.getCuePoints(); this.adsCuePoints = this.adsManager.getCuePoints();
// Add advertisement cue's within the time line if available. // Add advertisement cue's within the time line if available
this.adsCuePoints.forEach(cuePoint => { this.adsCuePoints.forEach(cuePoint => {
if (cuePoint !== 0 && cuePoint !== -1) { if (cuePoint !== 0 && cuePoint !== -1) {
const seekElement = this.player.elements.progress; const seekElement = this.player.elements.progress;
@ -176,58 +178,38 @@ class Ads {
} }
}); });
// Add listeners to the required events. // Add listeners to the required events
// Advertisement error events. // Advertisement error events
this.adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error)); this.adsManager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error));
// Advertisement regular events. // Advertisement regular events
this.adsManager.addEventListener(google.ima.AdEvent.Type.AD_BREAK_READY, event => this.onAdEvent(event)); Object.keys(google.ima.AdEvent.Type).forEach(type => {
this.adsManager.addEventListener(google.ima.AdEvent.Type.AD_METADATA, event => this.onAdEvent(event)); this.adsManager.addEventListener(google.ima.AdEvent.Type[type], event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.ALL_ADS_COMPLETED, event => this.onAdEvent(event)); });
this.adsManager.addEventListener(google.ima.AdEvent.Type.CLICK, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.COMPLETE, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.LOADED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.STARTED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.DURATION_CHANGE, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.FIRST_QUARTILE, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.IMPRESSION, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.INTERACTION, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.LINEAR_CHANGED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.MIDPOINT, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.PAUSED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.RESUMED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.SKIPPABLE_STATE_CHANGED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.SKIPPED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.THIRD_QUARTILE, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.USER_CLOSE, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.VOLUME_CHANGED, event => this.onAdEvent(event));
this.adsManager.addEventListener(google.ima.AdEvent.Type.VOLUME_MUTED, event => this.onAdEvent(event));
// Resolve our adsManager. // Resolve our adsManager
this.handleEventListeners('ADS_MANAGER_LOADED'); this.handleEventListeners('ADS_MANAGER_LOADED');
} }
/** /**
* This is where all the event handling takes place. Retrieve the ad from the event. Some * This is where all the event handling takes place. Retrieve the ad from the event. Some
* events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated. * events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated
* @param {Event} event * @param {Event} event
*/ */
onAdEvent(event) { onAdEvent(event) {
const { container } = this.player.elements; const { container } = this.player.elements;
// Listen for events if debugging. // Listen for events if debugging
this.player.debug.log(`Ads event: ${event.type}`); this.player.debug.log(`Ads event: ${event.type}`);
// Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED) // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated. // don't have ad object associated
const ad = event.getAd(); const ad = event.getAd();
switch (event.type) { switch (event.type) {
case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
// All ads for the current videos are done. We can now request new advertisements // All ads for the current videos are done. We can now request new advertisements
// in case the video is re-played. // in case the video is re-played
this.handleEventListeners('ALL_ADS_COMPLETED'); this.handleEventListeners('ALL_ADS_COMPLETED');
// Todo: Example for what happens when a next video in a playlist would be loaded. // Todo: Example for what happens when a next video in a playlist would be loaded.
@ -251,32 +233,35 @@ class Ads {
// }; // };
// Todo: So there is still this thing where a video should only be allowed to start // Todo: So there is still this thing where a video should only be allowed to start
// playing when the IMA SDK is ready or has failed. // playing when the IMA SDK is ready or has failed
this.loadAds(); this.loadAds();
break; break;
case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED: case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
// This event indicates the ad has started - the video player can adjust the UI, // This event indicates the ad has started - the video player can adjust the UI,
// for example display a pause button and remaining time. Fired when content should // for example display a pause button and remaining time. Fired when content should
// be paused. This usually happens right before an ad is about to cover the content. // be paused. This usually happens right before an ad is about to cover the content
this.handleEventListeners('CONTENT_PAUSE_REQUESTED'); this.handleEventListeners('CONTENT_PAUSE_REQUESTED');
this.pauseContent(); this.pauseContent();
break; break;
case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED: case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
// This event indicates the ad has finished - the video player can perform // This event indicates the ad has finished - the video player can perform
// appropriate UI actions, such as removing the timer for remaining time detection. // appropriate UI actions, such as removing the timer for remaining time detection.
// Fired when content should be resumed. This usually happens when an ad finishes // Fired when content should be resumed. This usually happens when an ad finishes
// or collapses. // or collapses
this.handleEventListeners('CONTENT_RESUME_REQUESTED'); this.handleEventListeners('CONTENT_RESUME_REQUESTED');
this.resumeContent(); this.resumeContent();
break; break;
case google.ima.AdEvent.Type.LOADED: case google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to determine whether the // This is the first event sent for an ad - it is possible to determine whether the
// ad is a video ad or an overlay. // ad is a video ad or an overlay
this.handleEventListeners('LOADED'); this.handleEventListeners('LOADED');
if (!ad.isLinear()) { if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay. // Position AdDisplayContainer correctly for overlay
ad.width = container.offsetWidth; ad.width = container.offsetWidth;
ad.height = container.offsetHeight; ad.height = container.offsetHeight;
} }
@ -291,24 +276,24 @@ class Ads {
} }
/** /**
* Any ad error handling comes through here. * Any ad error handling comes through here
* @param {Event} adErrorEvent * @param {Event} event
*/ */
onAdError(adErrorEvent) { onAdError(event) {
this.cancel(); this.cancel();
this.player.debug.log('Ads error', adErrorEvent); this.player.debug.log('Ads error', event);
} }
/** /**
* Setup hooks for Plyr and window events. This ensures * Setup hooks for Plyr and window events. This ensures
* the mid- and post-roll launch at the correct time. And * the mid- and post-roll launch at the correct time. And
* resize the advertisement when the player resizes. * resize the advertisement when the player resizes
*/ */
setupListeners() { listeners() {
const { container } = this.player.elements; const { container } = this.player.elements;
let time; let time;
// Add listeners to the required events. // Add listeners to the required events
this.player.on('ended', () => { this.player.on('ended', () => {
this.adsLoader.contentComplete(); this.adsLoader.contentComplete();
}); });
@ -329,14 +314,14 @@ class Ads {
}); });
}); });
// Listen to the resizing of the window. And resize ad accordingly. // Listen to the resizing of the window. And resize ad accordingly
window.addEventListener('resize', () => { window.addEventListener('resize', () => {
this.adsManager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); this.adsManager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
}); });
} }
/** /**
* Initialize the adsManager and start playing advertisements. * Initialize the adsManager and start playing advertisements
*/ */
play() { play() {
const { container } = this.player.elements; const { container } = this.player.elements;
@ -345,25 +330,25 @@ class Ads {
return; return;
} }
// Play the requested advertisement whenever the adsManager is ready. // Play the requested advertisement whenever the adsManager is ready
this.adsManagerPromise.then(() => { this.adsManagerPromise.then(() => {
// Initialize the container. Must be done via a user action on mobile devices. // Initialize the container. Must be done via a user action on mobile devices
this.adDisplayContainer.initialize(); this.adDisplayContainer.initialize();
try { try {
if (!this.initialized) { if (!this.initialized) {
// Initialize the ads manager. Ad rules playlist will start at this time. // Initialize the ads manager. Ad rules playlist will start at this time
this.adsManager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL); this.adsManager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
// Call play to start showing the ad. Single video and overlay ads will // Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules. // start at this time; the call will be ignored for ad rules
this.adsManager.start(); this.adsManager.start();
} }
this.initialized = true; this.initialized = true;
} catch (adError) { } catch (adError) {
// An error may be thrown if there was a problem with the // An error may be thrown if there was a problem with the
// VAST response. // VAST response
this.onAdError(adError); this.onAdError(adError);
} }
}); });
@ -375,26 +360,26 @@ class Ads {
resumeContent() { resumeContent() {
this.player.debug.log('Resume video'); this.player.debug.log('Resume video');
// Hide our ad container. // Hide our ad container
this.adsContainer.style.display = 'none'; utils.toggleHidden(this.adsContainer, true);
// Ad is stopped. // Ad is stopped
this.playing = false; this.playing = false;
// Play our video. // Play our video
if (this.player.currentTime < this.player.duration) { if (this.player.currentTime < this.player.duration) {
this.player.play(); this.player.play();
} }
} }
/** /**
* Pause our video. * Pause our video
*/ */
pauseContent() { pauseContent() {
this.player.debug.log('Pause video'); this.player.debug.log('Pause video');
// Show our ad container. // Show our ad container.
this.adsContainer.style.display = 'block'; utils.toggleHidden(this.adsContainer, false);
// Ad is playing. // Ad is playing.
this.playing = true; this.playing = true;
@ -412,43 +397,43 @@ class Ads {
cancel() { cancel() {
this.player.debug.warn('Ad cancelled'); this.player.debug.warn('Ad cancelled');
// Pause our video. // Pause our video
this.resumeContent(); this.resumeContent();
// Tell our instance that we're done for now. // Tell our instance that we're done for now
this.handleEventListeners('ERROR'); this.handleEventListeners('ERROR');
// Re-create our adsManager. // Re-create our adsManager
this.loadAds(); this.loadAds();
} }
/** /**
* Re-create our adsManager. * Re-create our adsManager
*/ */
loadAds() { loadAds() {
// Tell our adsManager to go bye bye. // Tell our adsManager to go bye bye
this.adsManagerPromise.then(() => { this.adsManagerPromise.then(() => {
// Destroy our adsManager. // Destroy our adsManager
if (this.adsManager) { if (this.adsManager) {
this.adsManager.destroy(); this.adsManager.destroy();
} }
// Re-set our adsManager promises. // Re-set our adsManager promises
this.adsManagerPromise = new Promise(resolve => { this.adsManagerPromise = new Promise(resolve => {
this.on('ADS_MANAGER_LOADED', () => resolve()); this.on('ADS_MANAGER_LOADED', () => resolve());
this.player.debug.log(this.adsManager); this.player.debug.log(this.adsManager);
}); });
// Make sure we can re-call advertisements. // Make sure we can re-call advertisements
this.initialized = false; this.initialized = false;
// Now request some new advertisements. // Now request some new advertisements
this.requestAds(); this.requestAds();
}); });
} }
/** /**
* Handles callbacks after an ad event was invoked. * Handles callbacks after an ad event was invoked
* @param {string} event - Event type * @param {string} event - Event type
*/ */
handleEventListeners(event) { handleEventListeners(event) {
@ -472,7 +457,7 @@ class Ads {
* Setup a safety timer for when the ad network doesn't respond for whatever reason. * Setup a safety timer for when the ad network doesn't respond for whatever reason.
* The advertisement has 12 seconds to get its things together. We stop this timer when the * The advertisement has 12 seconds to get its things together. We stop this timer when the
* advertisement is playing, or when a user action is required to start, then we clear the * advertisement is playing, or when a user action is required to start, then we clear the
* timer on ad ready. * timer on ad ready
* @param {Number} time * @param {Number} time
* @param {String} from * @param {String} from
*/ */
@ -485,7 +470,7 @@ class Ads {
} }
/** /**
* Clear our safety timer(s). * Clear our safety timer(s)
* @param {String} from * @param {String} from
*/ */
clearSafetyTimer(from) { clearSafetyTimer(from) {

View File

@ -749,9 +749,9 @@ const utils = {
// Force repaint of element // Force repaint of element
repaint(element) { repaint(element) {
window.setTimeout(() => { window.setTimeout(() => {
element.setAttribute('hidden', ''); utils.toggleHidden(element, true);
element.offsetHeight; // eslint-disable-line element.offsetHeight; // eslint-disable-line
element.removeAttribute('hidden'); utils.toggleHidden(element, false);
}, 0); }, 0);
}, },
}; };

View File

@ -3,7 +3,6 @@
// ========================================================================== // ==========================================================================
.plyr__ads { .plyr__ads {
display: none; // Hide initially.
bottom: 0; bottom: 0;
cursor: pointer; cursor: pointer;
left: 0; left: 0;
@ -12,21 +11,31 @@
top: 0; top: 0;
z-index: 3; // Above the controls. z-index: 3; // Above the controls.
video { &::after {
left: 0; background: rgba($plyr-color-gunmetal, 0.8);
border-radius: 2px;
bottom: ($plyr-control-spacing * 2);
color: #fff;
content: attr(data-badge-text);
font-size: $plyr-font-size-captions-small;
padding: 2px 6px;
pointer-events: none;
position: absolute;
right: ($plyr-control-spacing * 2);
z-index: 3;
} }
} }
// Advertisement cue's for the progress bar. // Advertisement cue's for the progress bar.
.plyr__cues { .plyr__cues {
background: currentColor;
display: block; display: block;
position: absolute; height: $plyr-range-track-height;
z-index: 3; // Between progress and thumb.
top: 50%;
left: 0; left: 0;
margin: -($plyr-range-track-height / 2) 0 0; margin: -($plyr-range-track-height / 2) 0 0;
width: 3px;
height: $plyr-range-track-height;
background: currentColor;
opacity: 0.8; opacity: 0.8;
position: absolute;
top: 50%;
width: 3px;
z-index: 3; // Between progress and thumb.
} }