This commit is contained in:
Sam Potts 2018-08-01 00:56:44 +10:00
parent 13a54b5dbe
commit 2371619486
10 changed files with 253 additions and 869 deletions

View File

@ -2,5 +2,6 @@
"useTabs": false, "useTabs": false,
"tabWidth": 4, "tabWidth": 4,
"singleQuote": true, "singleQuote": true,
"trailingComma": "all" "trailingComma": "all",
"printWidth": 120
} }

View File

@ -12,9 +12,7 @@ import Raven from 'raven-js';
// Raven / Sentry // Raven / Sentry
// For demo site (https://plyr.io) only // For demo site (https://plyr.io) only
if (isLive) { if (isLive) {
Raven.config( Raven.config('https://d4ad9866ad834437a4754e23937071e4@sentry.io/305555').install();
'https://d4ad9866ad834437a4754e23937071e4@sentry.io/305555',
).install();
} }
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
@ -130,7 +128,7 @@ import Raven from 'raven-js';
google: 'AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c', google: 'AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c',
}, },
ads: { ads: {
// enabled: true, enabled: true,
publisherId: '918848828995742', publisherId: '918848828995742',
}, },
}); });
@ -174,47 +172,40 @@ import Raven from 'raven-js';
title: 'View From A Blue Moon', title: 'View From A Blue Moon',
sources: [ sources: [
{ {
src: src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4',
'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-576p.mp4',
type: 'video/mp4', type: 'video/mp4',
size: 576, size: 576,
}, },
{ {
src: src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4',
'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-720p.mp4',
type: 'video/mp4', type: 'video/mp4',
size: 720, size: 720,
}, },
{ {
src: src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-1080p.mp4',
'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-1080p.mp4',
type: 'video/mp4', type: 'video/mp4',
size: 1080, size: 1080,
}, },
{ {
src: src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-1440p.mp4',
'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-1440p.mp4',
type: 'video/mp4', type: 'video/mp4',
size: 1440, size: 1440,
}, },
], ],
poster: poster: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg',
'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg',
tracks: [ tracks: [
{ {
kind: 'captions', kind: 'captions',
label: 'English', label: 'English',
srclang: 'en', srclang: 'en',
src: src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',
'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',
default: true, default: true,
}, },
{ {
kind: 'captions', kind: 'captions',
label: 'French', label: 'French',
srclang: 'fr', srclang: 'fr',
src: src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt',
'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt',
}, },
], ],
}; };
@ -224,17 +215,14 @@ import Raven from 'raven-js';
case types.audio: case types.audio:
player.source = { player.source = {
type: 'audio', type: 'audio',
title: title: 'Kishi Bashi – “It All Began With A Burst”',
'Kishi Bashi – “It All Began With A Burst”',
sources: [ sources: [
{ {
src: src: 'https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3',
'https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.mp3',
type: 'audio/mp3', type: 'audio/mp3',
}, },
{ {
src: src: 'https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg',
'https://cdn.plyr.io/static/demo/Kishi_Bashi_-_It_All_Began_With_a_Burst.ogg',
type: 'audio/ogg', type: 'audio/ogg',
}, },
], ],
@ -247,8 +235,7 @@ import Raven from 'raven-js';
type: 'video', type: 'video',
sources: [ sources: [
{ {
src: src: 'https://youtube.com/watch?v=bTqVqk7FSmY',
'https://youtube.com/watch?v=bTqVqk7FSmY',
provider: 'youtube', provider: 'youtube',
}, },
], ],
@ -277,26 +264,16 @@ import Raven from 'raven-js';
currentType = type; currentType = type;
// Remove active classes // Remove active classes
Array.from(buttons).forEach(button => Array.from(buttons).forEach(button => toggleClass(button.parentElement, 'active', false));
toggleClass(button.parentElement, 'active', false),
);
// Set active on parent // Set active on parent
toggleClass( toggleClass(document.querySelector(`[data-source="${type}"]`), 'active', true);
document.querySelector(`[data-source="${type}"]`),
'active',
true,
);
// Show cite // Show cite
Array.from(document.querySelectorAll('.plyr__cite')).forEach( Array.from(document.querySelectorAll('.plyr__cite')).forEach(cite => {
cite => { cite.setAttribute('hidden', '');
cite.setAttribute('hidden', ''); });
}, document.querySelector(`.plyr__cite--${type}`).removeAttribute('hidden');
);
document
.querySelector(`.plyr__cite--${type}`)
.removeAttribute('hidden');
} }
// Bind to each button // Bind to each button
@ -364,13 +341,7 @@ import Raven from 'raven-js';
a.async = 1; a.async = 1;
a.src = g; a.src = g;
m.parentNode.insertBefore(a, m); m.parentNode.insertBefore(a, m);
})( })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
window,
document,
'script',
'https://www.google-analytics.com/analytics.js',
'ga',
);
window.ga('create', 'UA-40881672-11', 'auto'); window.ga('create', 'UA-40881672-11', 'auto');
window.ga('send', 'pageview'); window.ga('send', 'pageview');
} }

View File

@ -1,6 +1,6 @@
{ {
"name": "plyr", "name": "plyr",
"version": "3.3.23", "version": "3.4.0-beta.1",
"description": "description":
"A simple, accessible and customizable HTML5, YouTube and Vimeo media player", "A simple, accessible and customizable HTML5, YouTube and Vimeo media player",
"homepage": "https://plyr.io", "homepage": "https://plyr.io",

View File

@ -84,7 +84,9 @@ const captions = {
// * toggled: The real captions state // * toggled: The real captions state
const languages = dedupe( const languages = dedupe(
Array.from(navigator.languages || navigator.language || navigator.userLanguage).map(language => language.split('-')[0]), Array.from(navigator.languages || navigator.language || navigator.userLanguage).map(
language => language.split('-')[0],
),
); );
let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase(); let language = (this.storage.get('language') || this.config.captions.language || 'auto').toLowerCase();

395
src/js/controls.js vendored
View File

@ -23,9 +23,7 @@ const controls = {
// Get icon URL // Get icon URL
getIconUrl() { getIconUrl() {
const url = new URL(this.config.iconUrl, window.location); const url = new URL(this.config.iconUrl, window.location);
const cors = const cors = url.host !== window.location.host || (browser.isIE && !window.svg4everybody);
url.host !== window.location.host ||
(browser.isIE && !window.svg4everybody);
return { return {
url: this.config.iconUrl, url: this.config.iconUrl,
@ -36,82 +34,37 @@ const controls = {
// Find the UI controls // Find the UI controls
findElements() { findElements() {
try { try {
this.elements.controls = getElement.call( this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper);
this,
this.config.selectors.controls.wrapper,
);
// Buttons // Buttons
this.elements.buttons = { this.elements.buttons = {
play: getElements.call( play: getElements.call(this, this.config.selectors.buttons.play),
this, pause: getElement.call(this, this.config.selectors.buttons.pause),
this.config.selectors.buttons.play, restart: getElement.call(this, this.config.selectors.buttons.restart),
), rewind: getElement.call(this, this.config.selectors.buttons.rewind),
pause: getElement.call( fastForward: getElement.call(this, this.config.selectors.buttons.fastForward),
this,
this.config.selectors.buttons.pause,
),
restart: getElement.call(
this,
this.config.selectors.buttons.restart,
),
rewind: getElement.call(
this,
this.config.selectors.buttons.rewind,
),
fastForward: getElement.call(
this,
this.config.selectors.buttons.fastForward,
),
mute: getElement.call(this, this.config.selectors.buttons.mute), mute: getElement.call(this, this.config.selectors.buttons.mute),
pip: getElement.call(this, this.config.selectors.buttons.pip), pip: getElement.call(this, this.config.selectors.buttons.pip),
airplay: getElement.call( airplay: getElement.call(this, this.config.selectors.buttons.airplay),
this, settings: getElement.call(this, this.config.selectors.buttons.settings),
this.config.selectors.buttons.airplay, captions: getElement.call(this, this.config.selectors.buttons.captions),
), fullscreen: getElement.call(this, this.config.selectors.buttons.fullscreen),
settings: getElement.call(
this,
this.config.selectors.buttons.settings,
),
captions: getElement.call(
this,
this.config.selectors.buttons.captions,
),
fullscreen: getElement.call(
this,
this.config.selectors.buttons.fullscreen,
),
}; };
// Progress // Progress
this.elements.progress = getElement.call( this.elements.progress = getElement.call(this, this.config.selectors.progress);
this,
this.config.selectors.progress,
);
// Inputs // Inputs
this.elements.inputs = { this.elements.inputs = {
seek: getElement.call(this, this.config.selectors.inputs.seek), seek: getElement.call(this, this.config.selectors.inputs.seek),
volume: getElement.call( volume: getElement.call(this, this.config.selectors.inputs.volume),
this,
this.config.selectors.inputs.volume,
),
}; };
// Display // Display
this.elements.display = { this.elements.display = {
buffer: getElement.call( buffer: getElement.call(this, this.config.selectors.display.buffer),
this, currentTime: getElement.call(this, this.config.selectors.display.currentTime),
this.config.selectors.display.buffer, duration: getElement.call(this, this.config.selectors.display.duration),
),
currentTime: getElement.call(
this,
this.config.selectors.display.currentTime,
),
duration: getElement.call(
this,
this.config.selectors.display.duration,
),
}; };
// Seek tooltip // Seek tooltip
@ -124,10 +77,7 @@ const controls = {
return true; return true;
} catch (error) { } catch (error) {
// Log it // Log it
this.debug.warn( this.debug.warn('It looks like there is a problem with your custom controls HTML', error);
'It looks like there is a problem with your custom controls HTML',
error,
);
// Restore native video controls // Restore native video controls
this.toggleNativeControls(true); this.toggleNativeControls(true);
@ -140,9 +90,7 @@ const controls = {
createIcon(type, attributes) { createIcon(type, attributes) {
const namespace = 'http://www.w3.org/2000/svg'; const namespace = 'http://www.w3.org/2000/svg';
const iconUrl = controls.getIconUrl.call(this); const iconUrl = controls.getIconUrl.call(this);
const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${ const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`;
this.config.iconPrefix
}`;
// Create <svg> // Create <svg>
const icon = document.createElementNS(namespace, 'svg'); const icon = document.createElementNS(namespace, 'svg');
@ -164,11 +112,7 @@ const controls = {
if ('href' in use) { if ('href' in use) {
use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path); use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path);
} else { } else {
use.setAttributeNS( use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path);
'http://www.w3.org/1999/xlink',
'xlink:href',
path,
);
} }
// Add <use> to <svg> // Add <use> to <svg>
@ -187,9 +131,7 @@ const controls = {
const text = universals[type] || i18n.get(type, this.config); const text = universals[type] || i18n.get(type, this.config);
const attributes = Object.assign({}, attr, { const attributes = Object.assign({}, attr, {
class: [attr.class, this.config.classNames.hidden] class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' '),
.filter(Boolean)
.join(' '),
}); });
return createElement('span', attributes, text); return createElement('span', attributes, text);
}, },
@ -276,9 +218,7 @@ const controls = {
break; break;
case 'play-large': case 'play-large':
attributes.class += ` ${ attributes.class += ` ${this.config.classNames.control}--overlaid`;
this.config.classNames.control
}--overlaid`;
type = 'play'; type = 'play';
label = 'play'; label = 'play';
icon = 'play'; icon = 'play';
@ -320,13 +260,7 @@ const controls = {
} }
// Merge attributes // Merge attributes
extend( extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes));
attributes,
getAttributesFromSelector(
this.config.selectors.buttons[type],
attributes,
),
);
setAttributes(button, attributes); setAttributes(button, attributes);
@ -426,16 +360,12 @@ const controls = {
// Create time display // Create time display
createTime(type) { createTime(type) {
const attributes = getAttributesFromSelector( const attributes = getAttributesFromSelector(this.config.selectors.display[type]);
this.config.selectors.display[type],
);
const container = createElement( const container = createElement(
'div', 'div',
extend(attributes, { extend(attributes, {
class: `${this.config.classNames.display.time} ${ class: `${this.config.classNames.display.time} ${attributes.class ? attributes.class : ''}`.trim(),
attributes.class ? attributes.class : ''
}`.trim(),
'aria-label': i18n.get(type, this.config), 'aria-label': i18n.get(type, this.config),
}), }),
'00:00', '00:00',
@ -470,10 +400,7 @@ const controls = {
return; return;
} }
const isRadioButton = matches( const isRadioButton = matches(menuItem, '[role="menuitemradio"]');
menuItem,
'[role="menuitemradio"]',
);
// Show the respective menu // Show the respective menu
if (!isRadioButton && [32, 39].includes(event.which)) { if (!isRadioButton && [32, 39].includes(event.which)) {
@ -482,10 +409,7 @@ const controls = {
let target; let target;
if (event.which !== 32) { if (event.which !== 32) {
if ( if (event.which === 40 || (isRadioButton && event.which === 39)) {
event.which === 40 ||
(isRadioButton && event.which === 39)
) {
target = menuItem.nextElementSibling; target = menuItem.nextElementSibling;
if (!is.element(target)) { if (!is.element(target)) {
@ -508,26 +432,15 @@ const controls = {
}, },
// Create a settings menu item // Create a settings menu item
createMenuItem({ createMenuItem({ value, list, type, title, badge = null, checked = false }) {
value, const attributes = getAttributesFromSelector(this.config.selectors.inputs[type]);
list,
type,
title,
badge = null,
checked = false,
}) {
const attributes = getAttributesFromSelector(
this.config.selectors.inputs[type],
);
const menuItem = createElement( const menuItem = createElement(
'button', 'button',
extend(attributes, { extend(attributes, {
type: 'button', type: 'button',
role: 'menuitemradio', role: 'menuitemradio',
class: `${this.config.classNames.control} ${ class: `${this.config.classNames.control} ${attributes.class ? attributes.class : ''}`.trim(),
attributes.class ? attributes.class : ''
}`.trim(),
'aria-checked': checked, 'aria-checked': checked,
value, value,
}), }),
@ -555,15 +468,10 @@ const controls = {
if (checked) { if (checked) {
Array.from(menuItem.parentNode.children) Array.from(menuItem.parentNode.children)
.filter(node => matches(node, '[role="menuitemradio"]')) .filter(node => matches(node, '[role="menuitemradio"]'))
.forEach(node => .forEach(node => node.setAttribute('aria-checked', 'false'));
node.setAttribute('aria-checked', 'false'),
);
} }
menuItem.setAttribute( menuItem.setAttribute('aria-checked', checked ? 'true' : 'false');
'aria-checked',
checked ? 'true' : 'false',
);
}, },
}); });
@ -597,11 +505,7 @@ const controls = {
break; break;
} }
controls.showMenuPanel.call( controls.showMenuPanel.call(this, 'home', event.type === 'keyup');
this,
'home',
event.type === 'keyup',
);
}, },
type, type,
false, false,
@ -644,17 +548,12 @@ const controls = {
// Update range // Update range
if (is.element(this.elements.inputs.volume)) { if (is.element(this.elements.inputs.volume)) {
controls.setRange.call( controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);
this,
this.elements.inputs.volume,
this.muted ? 0 : this.volume,
);
} }
// Update mute state // Update mute state
if (is.element(this.elements.buttons.mute)) { if (is.element(this.elements.buttons.mute)) {
this.elements.buttons.mute.pressed = this.elements.buttons.mute.pressed = this.muted || this.volume === 0;
this.muted || this.volume === 0;
} }
}, },
@ -681,9 +580,7 @@ const controls = {
const setProgress = (target, input) => { const setProgress = (target, input) => {
const value = is.number(input) ? input : 0; const value = is.number(input) ? input : 0;
const progress = is.element(target) const progress = is.element(target) ? target : this.elements.display.buffer;
? target
: this.elements.display.buffer;
// Update value and label // Update value and label
if (is.element(progress)) { if (is.element(progress)) {
@ -707,11 +604,7 @@ const controls = {
// Set seek range value only if it's a 'natural' time event // Set seek range value only if it's a 'natural' time event
if (event.type === 'timeupdate') { if (event.type === 'timeupdate') {
controls.setRange.call( controls.setRange.call(this, this.elements.inputs.seek, value);
this,
this.elements.inputs.seek,
value,
);
} }
break; break;
@ -719,10 +612,7 @@ const controls = {
// Check buffer status // Check buffer status
case 'playing': case 'playing':
case 'progress': case 'progress':
setProgress( setProgress(this.elements.display.buffer, this.buffered * 100);
this.elements.display.buffer,
this.buffered * 100,
);
break; break;
@ -750,9 +640,7 @@ const controls = {
const format = i18n.get('seekLabel', this.config); const format = i18n.get('seekLabel', this.config);
range.setAttribute( range.setAttribute(
'aria-valuetext', 'aria-valuetext',
format format.replace('{currentTime}', currentTime).replace('{duration}', duration),
.replace('{currentTime}', currentTime)
.replace('{duration}', duration),
); );
} else if (matches(range, this.config.selectors.inputs.volume)) { } else if (matches(range, this.config.selectors.inputs.volume)) {
const percent = range.value * 100; const percent = range.value * 100;
@ -802,10 +690,7 @@ const controls = {
if (is.event(event)) { if (is.event(event)) {
percent = 100 / clientRect.width * (event.pageX - clientRect.left); percent = 100 / clientRect.width * (event.pageX - clientRect.left);
} else if (hasClass(this.elements.display.seekTooltip, visible)) { } else if (hasClass(this.elements.display.seekTooltip, visible)) {
percent = parseFloat( percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);
this.elements.display.seekTooltip.style.left,
10,
);
} else { } else {
return; return;
} }
@ -818,21 +703,14 @@ const controls = {
} }
// Display the time a click would seek to // Display the time a click would seek to
controls.updateTimeDisplay.call( controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent);
this,
this.elements.display.seekTooltip,
this.duration / 100 * percent,
);
// Set position // Set position
this.elements.display.seekTooltip.style.left = `${percent}%`; this.elements.display.seekTooltip.style.left = `${percent}%`;
// Show/hide the tooltip // Show/hide the tooltip
// If the event is a moues in/out and percentage is inside bounds // If the event is a moues in/out and percentage is inside bounds
if ( if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) {
is.event(event) &&
['mouseenter', 'mouseleave'].includes(event.type)
) {
toggle(event.type === 'mouseenter'); toggle(event.type === 'mouseenter');
} }
}, },
@ -840,9 +718,7 @@ const controls = {
// Handle time change event // Handle time change event
timeUpdate(event) { timeUpdate(event) {
// Only invert if only one time element is displayed and used for both duration and currentTime // Only invert if only one time element is displayed and used for both duration and currentTime
const invert = const invert = !is.element(this.elements.display.duration) && this.config.invertTime;
!is.element(this.elements.display.duration) &&
this.config.invertTime;
// Duration // Duration
controls.updateTimeDisplay.call( controls.updateTimeDisplay.call(
@ -864,10 +740,7 @@ const controls = {
// Show the duration on metadataloaded or durationchange events // Show the duration on metadataloaded or durationchange events
durationUpdate() { durationUpdate() {
// Bail if no UI or durationchange event triggered after playing/seek when invertTime is false // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false
if ( if (!this.supported.ui || (!this.config.invertTime && this.currentTime)) {
!this.supported.ui ||
(!this.config.invertTime && this.currentTime)
) {
return; return;
} }
@ -883,10 +756,7 @@ const controls = {
// Update ARIA values // Update ARIA values
if (is.element(this.elements.inputs.seek)) { if (is.element(this.elements.inputs.seek)) {
this.elements.inputs.seek.setAttribute( this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration);
'aria-valuemax',
this.duration,
);
} }
// If there's a spot to display duration // If there's a spot to display duration
@ -894,20 +764,12 @@ const controls = {
// If there's only one time display, display duration there // If there's only one time display, display duration there
if (!hasDuration && this.config.displayDuration && this.paused) { if (!hasDuration && this.config.displayDuration && this.paused) {
controls.updateTimeDisplay.call( controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);
this,
this.elements.display.currentTime,
this.duration,
);
} }
// If there's a duration element, update content // If there's a duration element, update content
if (hasDuration) { if (hasDuration) {
controls.updateTimeDisplay.call( controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);
this,
this.elements.display.duration,
this.duration,
);
} }
// Update the tooltip (if visible) // Update the tooltip (if visible)
@ -936,13 +798,8 @@ const controls = {
} }
// Unsupported value // Unsupported value
if ( if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) {
!is.empty(this.options[setting]) && this.debug.warn(`Unsupported value of '${value}' for ${setting}`);
!this.options[setting].includes(value)
) {
this.debug.warn(
`Unsupported value of '${value}' for ${setting}`,
);
return; return;
} }
@ -964,9 +821,7 @@ const controls = {
} }
// Update the label // Update the label
const label = this.elements.settings.buttons[setting].querySelector( const label = this.elements.settings.buttons[setting].querySelector(`.${this.config.classNames.menu.value}`);
`.${this.config.classNames.menu.value}`,
);
label.innerHTML = controls.getLabel.call(this, setting, value); label.innerHTML = controls.getLabel.call(this, setting, value);
// Find the radio option and check it // Find the radio option and check it
@ -981,16 +836,11 @@ const controls = {
getLabel(setting, value) { getLabel(setting, value) {
switch (setting) { switch (setting) {
case 'speed': case 'speed':
return value === 1 return value === 1 ? i18n.get('normal', this.config) : `${value}&times;`;
? i18n.get('normal', this.config)
: `${value}&times;`;
case 'quality': case 'quality':
if (is.number(value)) { if (is.number(value)) {
const label = i18n.get( const label = i18n.get(`qualityLabel.${value}`, this.config);
`qualityLabel.${value}`,
this.config,
);
if (!label.length) { if (!label.length) {
return `${value}p`; return `${value}p`;
@ -1017,20 +867,15 @@ const controls = {
} }
const type = 'quality'; const type = 'quality';
const list = this.elements.settings.panels.quality.querySelector( const list = this.elements.settings.panels.quality.querySelector('[role="menu"]');
'[role="menu"]',
);
// Set options if passed and filter based on uniqueness and config // Set options if passed and filter based on uniqueness and config
if (is.array(options)) { if (is.array(options)) {
this.options.quality = dedupe(options).filter(quality => this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality));
this.config.quality.options.includes(quality),
);
} }
// Toggle the pane and tab // Toggle the pane and tab
const toggle = const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1;
!is.empty(this.options.quality) && this.options.quality.length > 1;
controls.toggleMenuButton.call(this, type, toggle); controls.toggleMenuButton.call(this, type, toggle);
// Empty the menu // Empty the menu
@ -1130,9 +975,7 @@ const controls = {
// TODO: Captions or language? Currently it's mixed // TODO: Captions or language? Currently it's mixed
const type = 'captions'; const type = 'captions';
const list = this.elements.settings.panels.captions.querySelector( const list = this.elements.settings.panels.captions.querySelector('[role="menu"]');
'[role="menu"]',
);
const tracks = captions.getTracks.call(this); const tracks = captions.getTracks.call(this);
const toggle = Boolean(tracks.length); const toggle = Boolean(tracks.length);
@ -1155,9 +998,7 @@ const controls = {
value, value,
checked: this.captions.toggled && this.currentTrack === value, checked: this.captions.toggled && this.currentTrack === value,
title: captions.getLabel.call(this, track), title: captions.getLabel.call(this, track),
badge: badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()),
track.language &&
controls.createBadge.call(this, track.language.toUpperCase()),
list, list,
type: 'language', type: 'language',
})); }));
@ -1185,9 +1026,7 @@ const controls = {
} }
const type = 'speed'; const type = 'speed';
const list = this.elements.settings.panels.speed.querySelector( const list = this.elements.settings.panels.speed.querySelector('[role="menu"]');
'[role="menu"]',
);
// Set the speed options // Set the speed options
if (is.array(options)) { if (is.array(options)) {
@ -1197,13 +1036,10 @@ const controls = {
} }
// Set options if passed and filter based on config // Set options if passed and filter based on config
this.options.speed = this.options.speed.filter(speed => this.options.speed = this.options.speed.filter(speed => this.config.speed.options.includes(speed));
this.config.speed.options.includes(speed),
);
// Toggle the pane and tab // Toggle the pane and tab
const toggle = const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1;
!is.empty(this.options.speed) && this.options.speed.length > 1;
controls.toggleMenuButton.call(this, type, toggle); controls.toggleMenuButton.call(this, type, toggle);
// Empty the menu // Empty the menu
@ -1233,9 +1069,7 @@ const controls = {
// Check if we need to hide/show the settings menu // Check if we need to hide/show the settings menu
checkMenu() { checkMenu() {
const { buttons } = this.elements.settings; const { buttons } = this.elements.settings;
const visible = const visible = !is.empty(buttons) && Object.values(buttons).some(button => !button.hidden);
!is.empty(buttons) &&
Object.values(buttons).some(button => !button.hidden);
toggleHidden(this.elements.settings.menu, !visible); toggleHidden(this.elements.settings.menu, !visible);
}, },
@ -1250,13 +1084,10 @@ const controls = {
return; return;
} }
const show = is.boolean(input) const show = is.boolean(input) ? input : is.element(popup) && popup.hasAttribute('hidden');
? input
: is.element(popup) && popup.hasAttribute('hidden');
if (is.event(input)) { if (is.event(input)) {
const isMenuItem = const isMenuItem = is.element(popup) && popup.contains(input.target);
is.element(popup) && popup.contains(input.target);
const isButton = input.target === this.elements.buttons.settings; const isButton = input.target === this.elements.buttons.settings;
// If the click was inside the form or if the click // If the click was inside the form or if the click
@ -1281,17 +1112,11 @@ const controls = {
if (is.element(popup)) { if (is.element(popup)) {
toggleHidden(popup, !show); toggleHidden(popup, !show);
toggleClass( toggleClass(this.elements.container, this.config.classNames.menu.open, show);
this.elements.container,
this.config.classNames.menu.open,
show,
);
// Focus the first item if key interaction // Focus the first item if key interaction
if (show && is.event(input) && input.type === 'keyup') { if (show && is.event(input) && input.type === 'keyup') {
const pane = Object.values(this.elements.settings.panels).find( const pane = Object.values(this.elements.settings.panels).find(pane => !pane.hidden);
pane => !pane.hidden,
);
const firstItem = pane.querySelector('[role^="menuitem"]'); const firstItem = pane.querySelector('[role^="menuitem"]');
setFocus.call(this, firstItem, true); setFocus.call(this, firstItem, true);
@ -1324,9 +1149,7 @@ const controls = {
// Show a panel in the menu // Show a panel in the menu
showMenuPanel(type = '', tabFocus = false) { showMenuPanel(type = '', tabFocus = false) {
const target = document.getElementById( const target = document.getElementById(`plyr-settings-${this.id}-${type}`);
`plyr-settings-${this.id}-${type}`,
);
// Nothing to show, bail // Nothing to show, bail
if (!is.element(target)) { if (!is.element(target)) {
@ -1335,9 +1158,7 @@ const controls = {
// Hide all other panels // Hide all other panels
const container = target.parentNode; const container = target.parentNode;
const current = Array.from(container.children).find( const current = Array.from(container.children).find(node => !node.hidden);
node => !node.hidden,
);
// If we can do fancy animations, we'll animate the height/width // If we can do fancy animations, we'll animate the height/width
if (support.transitions && !support.reducedMotion) { if (support.transitions && !support.reducedMotion) {
@ -1351,10 +1172,7 @@ const controls = {
// Restore auto height/width // Restore auto height/width
const restore = event => { const restore = event => {
// We're only bothered about height and width on the container // We're only bothered about height and width on the container
if ( if (event.target !== container || !['width', 'height'].includes(event.propertyName)) {
event.target !== container ||
!['width', 'height'].includes(event.propertyName)
) {
return; return;
} }
@ -1389,10 +1207,7 @@ const controls = {
// TODO: Set order based on order in the config.controls array? // TODO: Set order based on order in the config.controls array?
create(data) { create(data) {
// Create the container // Create the container
const container = createElement( const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper));
'div',
getAttributesFromSelector(this.config.selectors.controls.wrapper),
);
// Restart button // Restart button
if (this.config.controls.includes('restart')) { if (this.config.controls.includes('restart')) {
@ -1411,17 +1226,12 @@ const controls = {
// Fast forward button // Fast forward button
if (this.config.controls.includes('fast-forward')) { if (this.config.controls.includes('fast-forward')) {
container.appendChild( container.appendChild(controls.createButton.call(this, 'fast-forward'));
controls.createButton.call(this, 'fast-forward'),
);
} }
// Progress // Progress
if (this.config.controls.includes('progress')) { if (this.config.controls.includes('progress')) {
const progress = createElement( const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress));
'div',
getAttributesFromSelector(this.config.selectors.progress),
);
// Seek range slider // Seek range slider
progress.appendChild( progress.appendChild(
@ -1455,9 +1265,7 @@ const controls = {
// Media current time display // Media current time display
if (this.config.controls.includes('current-time')) { if (this.config.controls.includes('current-time')) {
container.appendChild( container.appendChild(controls.createTime.call(this, 'currentTime'));
controls.createTime.call(this, 'currentTime'),
);
} }
// Media duration display // Media duration display
@ -1505,10 +1313,7 @@ const controls = {
} }
// Settings button / menu // Settings button / menu
if ( if (this.config.controls.includes('settings') && !is.empty(this.config.settings)) {
this.config.controls.includes('settings') &&
!is.empty(this.config.settings)
) {
const control = createElement('div', { const control = createElement('div', {
class: 'plyr__menu', class: 'plyr__menu',
hidden: '', hidden: '',
@ -1550,20 +1355,13 @@ const controls = {
// TODO: bundle this with the createMenuItem helper and bindings // TODO: bundle this with the createMenuItem helper and bindings
const menuItem = createElement( const menuItem = createElement(
'button', 'button',
extend( extend(getAttributesFromSelector(this.config.selectors.buttons.settings), {
getAttributesFromSelector( type: 'button',
this.config.selectors.buttons.settings, class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`,
), role: 'menuitem',
{ 'aria-haspopup': true,
type: 'button', hidden: '',
class: `${this.config.classNames.control} ${ }),
this.config.classNames.control
}--forward`,
role: 'menuitem',
'aria-haspopup': true,
hidden: '',
},
),
); );
// Bind menu shortcuts for keyboard users // Bind menu shortcuts for keyboard users
@ -1574,11 +1372,7 @@ const controls = {
controls.showMenuPanel.call(this, type, false); controls.showMenuPanel.call(this, type, false);
}); });
const flex = createElement( const flex = createElement('span', null, i18n.get(type, this.config));
'span',
null,
i18n.get(type, this.config),
);
const value = createElement('span', { const value = createElement('span', {
class: this.config.classNames.menu.value, class: this.config.classNames.menu.value,
@ -1600,9 +1394,7 @@ const controls = {
// Back button // Back button
const backButton = createElement('button', { const backButton = createElement('button', {
type: 'button', type: 'button',
class: `${this.config.classNames.control} ${ class: `${this.config.classNames.control} ${this.config.classNames.control}--back`,
this.config.classNames.control
}--back`,
}); });
// Visible label // Visible label
@ -1688,25 +1480,18 @@ const controls = {
// Toggle fullscreen button // Toggle fullscreen button
if (this.config.controls.includes('fullscreen')) { if (this.config.controls.includes('fullscreen')) {
container.appendChild( container.appendChild(controls.createButton.call(this, 'fullscreen'));
controls.createButton.call(this, 'fullscreen'),
);
} }
// Larger overlaid play button // Larger overlaid play button
if (this.config.controls.includes('play-large')) { if (this.config.controls.includes('play-large')) {
this.elements.container.appendChild( this.elements.container.appendChild(controls.createButton.call(this, 'play-large'));
controls.createButton.call(this, 'play-large'),
);
} }
this.elements.controls = container; this.elements.controls = container;
if (this.isHTML5) { if (this.isHTML5) {
controls.setQualityMenu.call( controls.setQualityMenu.call(this, html5.getQualityOptions.call(this));
this,
html5.getQualityOptions.call(this),
);
} }
controls.setSpeedMenu.call(this); controls.setSpeedMenu.call(this);
@ -1793,9 +1578,7 @@ const controls = {
// Inject to custom location // Inject to custom location
if (is.string(this.config.selectors.controls.container)) { if (is.string(this.config.selectors.controls.container)) {
target = document.querySelector( target = document.querySelector(this.config.selectors.controls.container);
this.config.selectors.controls.container,
);
} }
// Inject into the container by default // Inject into the container by default
@ -1804,9 +1587,7 @@ const controls = {
} }
// Inject controls HTML (needs to be before captions, hence "afterbegin") // Inject controls HTML (needs to be before captions, hence "afterbegin")
const insertMethod = is.element(container) const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML';
? 'insertAdjacentElement'
: 'insertAdjacentHTML';
target[insertMethod]('afterbegin', container); target[insertMethod]('afterbegin', container);
// Find the elements if need be // Find the elements if need be
@ -1822,9 +1603,7 @@ const controls = {
// Setup tooltips // Setup tooltips
if (this.config.tooltips.controls) { if (this.config.tooltips.controls) {
const { classNames, selectors } = this.config; const { classNames, selectors } = this.config;
const selector = `${selectors.controls.wrapper} ${ const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`;
selectors.labels
} .${classNames.hidden}`;
const labels = getElements.call(this, selector); const labels = getElements.call(this, selector);
Array.from(labels).forEach(label => { Array.from(labels).forEach(label => {

View File

@ -6,14 +6,7 @@ import controls from './controls';
import ui from './ui'; import ui from './ui';
import { repaint } from './utils/animation'; import { repaint } from './utils/animation';
import browser from './utils/browser'; import browser from './utils/browser';
import { import { getElement, getElements, hasClass, matches, toggleClass, toggleHidden } from './utils/elements';
getElement,
getElements,
hasClass,
matches,
toggleClass,
toggleHidden,
} from './utils/elements';
import { on, once, toggleListener, triggerEvent } from './utils/events'; import { on, once, toggleListener, triggerEvent } from './utils/events';
import is from './utils/is'; import is from './utils/is';
@ -69,38 +62,13 @@ class Listeners {
return; return;
} }
if ( if (event.which === 32 && matches(focused, 'button, [role^="menuitem"]')) {
event.which === 32 &&
matches(focused, 'button, [role^="menuitem"]')
) {
return; return;
} }
} }
// Which keycodes should we prevent default // Which keycodes should we prevent default
const preventDefault = [ const preventDefault = [32, 37, 38, 39, 40, 48, 49, 50, 51, 52, 53, 54, 56, 57, 67, 70, 73, 75, 76, 77, 79];
32,
37,
38,
39,
40,
48,
49,
50,
51,
52,
53,
54,
56,
57,
67,
70,
73,
75,
76,
77,
79,
];
// If the code is found prevent default (e.g. prevent scrolling for arrows) // If the code is found prevent default (e.g. prevent scrolling for arrows)
if (preventDefault.includes(code)) { if (preventDefault.includes(code)) {
@ -195,11 +163,7 @@ class Listeners {
// Escape is handle natively when in full screen // Escape is handle natively when in full screen
// So we only need to worry about non native // So we only need to worry about non native
if ( if (!player.fullscreen.enabled && player.fullscreen.active && code === 27) {
!player.fullscreen.enabled &&
player.fullscreen.active &&
code === 27
) {
player.fullscreen.toggle(); player.fullscreen.toggle();
} }
@ -222,11 +186,7 @@ class Listeners {
player.touch = true; player.touch = true;
// Add touch class // Add touch class
toggleClass( toggleClass(player.elements.container, player.config.classNames.isTouch, true);
player.elements.container,
player.config.classNames.isTouch,
true,
);
} }
setTabFocus(event) { setTabFocus(event) {
@ -272,11 +232,7 @@ class Listeners {
return; return;
} }
toggleClass( toggleClass(document.activeElement, player.config.classNames.tabFocus, true);
document.activeElement,
player.config.classNames.tabFocus,
true,
);
}, 10); }, 10);
} }
@ -286,38 +242,17 @@ class Listeners {
// Keyboard shortcuts // Keyboard shortcuts
if (player.config.keyboard.global) { if (player.config.keyboard.global) {
toggleListener.call( toggleListener.call(player, window, 'keydown keyup', this.handleKey, toggle, false);
player,
window,
'keydown keyup',
this.handleKey,
toggle,
false,
);
} }
// Click anywhere closes menu // Click anywhere closes menu
toggleListener.call( toggleListener.call(player, document.body, 'click', this.toggleMenu, toggle);
player,
document.body,
'click',
this.toggleMenu,
toggle,
);
// Detect touch by events // Detect touch by events
once.call(player, document.body, 'touchstart', this.firstTouch); once.call(player, document.body, 'touchstart', this.firstTouch);
// Tab focus detection // Tab focus detection
toggleListener.call( toggleListener.call(player, document.body, 'keydown focus blur', this.setTabFocus, toggle, false, true);
player,
document.body,
'keydown focus blur',
this.setTabFocus,
toggle,
false,
true,
);
} }
// Container listeners // Container listeners
@ -326,13 +261,7 @@ class Listeners {
// Keyboard shortcuts // Keyboard shortcuts
if (!player.config.keyboard.global && player.config.keyboard.focused) { if (!player.config.keyboard.global && player.config.keyboard.focused) {
on.call( on.call(player, player.elements.container, 'keydown keyup', this.handleKey, false);
player,
player.elements.container,
'keydown keyup',
this.handleKey,
false,
);
} }
// Toggle controls on mouse events and entering fullscreen // Toggle controls on mouse events and entering fullscreen
@ -350,9 +279,7 @@ class Listeners {
} }
// Show, then hide after a timeout unless another control event occurs // Show, then hide after a timeout unless another control event occurs
const show = ['touchstart', 'touchmove', 'mousemove'].includes( const show = ['touchstart', 'touchmove', 'mousemove'].includes(event.type);
event.type,
);
let delay = 0; let delay = 0;
@ -366,10 +293,7 @@ class Listeners {
clearTimeout(player.timers.controls); clearTimeout(player.timers.controls);
// Set new timer to prevent flicker when seeking // Set new timer to prevent flicker when seeking
player.timers.controls = setTimeout( player.timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);
() => ui.toggleControls.call(player, false),
delay,
);
}, },
); );
} }
@ -379,16 +303,11 @@ class Listeners {
const { player } = this; const { player } = this;
// Time change on media // Time change on media
on.call(player, player.media, 'timeupdate seeking seeked', event => on.call(player, player.media, 'timeupdate seeking seeked', event => controls.timeUpdate.call(player, event));
controls.timeUpdate.call(player, event),
);
// Display duration // Display duration
on.call( on.call(player, player.media, 'durationchange loadeddata loadedmetadata', event =>
player, controls.durationUpdate.call(player, event),
player.media,
'durationchange loadeddata loadedmetadata',
event => controls.durationUpdate.call(player, event),
); );
// Check for audio tracks on load // Check for audio tracks on load
@ -408,30 +327,20 @@ class Listeners {
}); });
// Check for buffer progress // Check for buffer progress
on.call( on.call(player, player.media, 'progress playing seeking seeked', event =>
player, controls.updateProgress.call(player, event),
player.media,
'progress playing seeking seeked',
event => controls.updateProgress.call(player, event),
); );
// Handle volume changes // Handle volume changes
on.call(player, player.media, 'volumechange', event => on.call(player, player.media, 'volumechange', event => controls.updateVolume.call(player, event));
controls.updateVolume.call(player, event),
);
// Handle play/pause // Handle play/pause
on.call( on.call(player, player.media, 'playing play pause ended emptied timeupdate', event =>
player, ui.checkPlaying.call(player, event),
player.media,
'playing play pause ended emptied timeupdate',
event => ui.checkPlaying.call(player, event),
); );
// Loading state // Loading state
on.call(player, player.media, 'waiting canplay seeked playing', event => on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event));
ui.checkLoading.call(player, event),
);
// If autoplay, then load advertisement if required // If autoplay, then load advertisement if required
// TODO: Show some sort of loading state while the ad manager loads else there's a delay before ad shows // TODO: Show some sort of loading state while the ad manager loads else there's a delay before ad shows
@ -443,23 +352,14 @@ class Listeners {
// If ads are enabled, wait for them first // If ads are enabled, wait for them first
if (player.ads.enabled && !player.ads.initialized) { if (player.ads.enabled && !player.ads.initialized) {
// Wait for manager response // Wait for manager response
player.ads.managerPromise player.ads.managerPromise.then(() => player.ads.play()).catch(() => player.play());
.then(() => player.ads.play())
.catch(() => player.play());
} }
}); });
// Click video // Click video
if ( if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {
player.supported.ui &&
player.config.clickToPlay &&
!player.isAudio
) {
// Re-fetch the wrapper // Re-fetch the wrapper
const wrapper = getElement.call( const wrapper = getElement.call(player, `.${player.config.classNames.video}`);
player,
`.${player.config.classNames.video}`,
);
// Bail if there's no wrapper (this should never happen) // Bail if there's no wrapper (this should never happen)
if (!is.element(wrapper)) { if (!is.element(wrapper)) {
@ -467,42 +367,31 @@ class Listeners {
} }
// On click play, pause ore restart // On click play, pause ore restart
on.call( on.call(player, player.elements.container, 'click touchstart', event => {
player, const targets = [player.elements.container, wrapper];
player.elements.container,
'click touchstart',
event => {
const targets = [player.elements.container, wrapper];
// Ignore if click if not container or in video wrapper // Ignore if click if not container or in video wrapper
if ( if (!targets.includes(event.target) && !wrapper.contains(event.target)) {
!targets.includes(event.target) && return;
!wrapper.contains(event.target) }
) {
return;
}
// First touch on touch devices will just show controls (if we're hiding controls) // First touch on touch devices will just show controls (if we're hiding controls)
// If controls are shown then it'll toggle like a pointer device // If controls are shown then it'll toggle like a pointer device
if ( if (
player.config.hideControls && player.config.hideControls &&
player.touch && player.touch &&
hasClass( hasClass(player.elements.container, player.config.classNames.hideControls)
player.elements.container, ) {
player.config.classNames.hideControls, return;
) }
) {
return;
}
if (player.ended) { if (player.ended) {
player.restart(); player.restart();
player.play(); player.play();
} else { } else {
player.togglePlay(); player.togglePlay();
} }
}, });
);
} }
// Disable right click // Disable right click
@ -545,19 +434,12 @@ class Listeners {
// Quality change // Quality change
on.call(player, player.media, 'qualitychange', event => { on.call(player, player.media, 'qualitychange', event => {
// Update UI // Update UI
controls.updateSetting.call( controls.updateSetting.call(player, 'quality', null, event.detail.quality);
player,
'quality',
null,
event.detail.quality,
);
}); });
// Proxy events to container // Proxy events to container
// Bubble up key events for Edge // Bubble up key events for Edge
const proxyEvents = player.config.events const proxyEvents = player.config.events.concat(['keyup', 'keydown']).join(' ');
.concat(['keyup', 'keydown'])
.join(' ');
on.call(player, player.media, proxyEvents, event => { on.call(player, player.media, proxyEvents, event => {
let { detail = {} } = event; let { detail = {} } = event;
@ -567,13 +449,7 @@ class Listeners {
detail = player.media.error; detail = player.media.error;
} }
triggerEvent.call( triggerEvent.call(player, player.elements.container, event.type, true, detail);
player,
player.elements.container,
event.type,
true,
detail,
);
}); });
} }
@ -625,28 +501,13 @@ class Listeners {
} }
// Pause // Pause
this.bind( this.bind(player.elements.buttons.restart, 'click', player.restart, 'restart');
player.elements.buttons.restart,
'click',
player.restart,
'restart',
);
// Rewind // Rewind
this.bind( this.bind(player.elements.buttons.rewind, 'click', player.rewind, 'rewind');
player.elements.buttons.rewind,
'click',
player.rewind,
'rewind',
);
// Rewind // Rewind
this.bind( this.bind(player.elements.buttons.fastForward, 'click', player.forward, 'fastForward');
player.elements.buttons.fastForward,
'click',
player.forward,
'fastForward',
);
// Mute toggle // Mute toggle
this.bind( this.bind(
@ -659,9 +520,7 @@ class Listeners {
); );
// Captions toggle // Captions toggle
this.bind(player.elements.buttons.captions, 'click', () => this.bind(player.elements.buttons.captions, 'click', () => player.toggleCaptions());
player.toggleCaptions(),
);
// Fullscreen toggle // Fullscreen toggle
this.bind( this.bind(
@ -684,12 +543,7 @@ class Listeners {
); );
// Airplay // Airplay
this.bind( this.bind(player.elements.buttons.airplay, 'click', player.airplay, 'airplay');
player.elements.buttons.airplay,
'click',
player.airplay,
'airplay',
);
// Settings menu - click toggle // Settings menu - click toggle
this.bind(player.elements.buttons.settings, 'click', event => { this.bind(player.elements.buttons.settings, 'click', event => {
@ -731,39 +585,30 @@ class Listeners {
}); });
// Pause while seeking // Pause while seeking
this.bind( this.bind(player.elements.inputs.seek, 'mousedown mouseup keydown keyup touchstart touchend', event => {
player.elements.inputs.seek, const seek = event.currentTarget;
'mousedown mouseup keydown keyup touchstart touchend', const code = event.keyCode ? event.keyCode : event.which;
event => { const eventType = event.type;
const seek = event.currentTarget; const attribute = 'play-on-seeked';
const code = event.keyCode ? event.keyCode : event.which;
const eventType = event.type;
const attribute = 'play-on-seeked';
if ( if ((eventType === 'keydown' || eventType === 'keyup') && (code !== 39 && code !== 37)) {
(eventType === 'keydown' || eventType === 'keyup') && return;
(code !== 39 && code !== 37) }
) { // Was playing before?
return; const play = seek.hasAttribute(attribute);
}
// Was playing before?
const play = seek.hasAttribute(attribute);
// Done seeking // Done seeking
const done = ['mouseup', 'touchend', 'keyup'].includes( const done = ['mouseup', 'touchend', 'keyup'].includes(event.type);
event.type,
);
// If we're done seeking and it was playing, resume playback // If we're done seeking and it was playing, resume playback
if (play && done) { if (play && done) {
seek.removeAttribute(attribute); seek.removeAttribute(attribute);
player.play(); player.play();
} else if (!done && player.playing) { } else if (!done && player.playing) {
seek.setAttribute(attribute, ''); seek.setAttribute(attribute, '');
player.pause(); player.pause();
} }
}, });
);
// Fix range inputs on iOS // Fix range inputs on iOS
// Super weird iOS bug where after you interact with an <input type="range">, // Super weird iOS bug where after you interact with an <input type="range">,
@ -771,9 +616,7 @@ class Listeners {
if (browser.isIos) { if (browser.isIos) {
const inputs = getElements.call(player, 'input[type="range"]'); const inputs = getElements.call(player, 'input[type="range"]');
Array.from(inputs).forEach(input => Array.from(inputs).forEach(input => this.bind(input, inputEvent, event => repaint(event.target)));
this.bind(input, inputEvent, event => repaint(event.target)),
);
} }
// Seek // Seek
@ -799,10 +642,7 @@ class Listeners {
// Current time invert // Current time invert
// Only if one time element is used for both currentTime and duration // Only if one time element is used for both currentTime and duration
if ( if (player.config.toggleInvert && !is.element(player.elements.display.duration)) {
player.config.toggleInvert &&
!is.element(player.elements.display.duration)
) {
this.bind(player.elements.display.currentTime, 'click', () => { this.bind(player.elements.display.currentTime, 'click', () => {
// Do nothing if we're at the start // Do nothing if we're at the start
if (player.currentTime === 0) { if (player.currentTime === 0) {
@ -827,39 +667,25 @@ class Listeners {
// Polyfill for lower fill in <input type="range"> for webkit // Polyfill for lower fill in <input type="range"> for webkit
if (browser.isWebkit) { if (browser.isWebkit) {
Array.from(getElements.call(player, 'input[type="range"]')).forEach( Array.from(getElements.call(player, 'input[type="range"]')).forEach(element => {
element => { this.bind(element, 'input', event => controls.updateRangeFill.call(player, event.target));
this.bind(element, 'input', event => });
controls.updateRangeFill.call(player, event.target),
);
},
);
} }
// Seek tooltip // Seek tooltip
this.bind( this.bind(player.elements.progress, 'mouseenter mouseleave mousemove', event =>
player.elements.progress, controls.updateSeekTooltip.call(player, event),
'mouseenter mouseleave mousemove',
event => controls.updateSeekTooltip.call(player, event),
); );
// Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting) // Update controls.hover state (used for ui.toggleControls to avoid hiding when interacting)
this.bind(player.elements.controls, 'mouseenter mouseleave', event => { this.bind(player.elements.controls, 'mouseenter mouseleave', event => {
player.elements.controls.hover = player.elements.controls.hover = !player.touch && event.type === 'mouseenter';
!player.touch && event.type === 'mouseenter';
}); });
// Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting) // Update controls.pressed state (used for ui.toggleControls to avoid hiding when interacting)
this.bind( this.bind(player.elements.controls, 'mousedown mouseup touchstart touchend touchcancel', event => {
player.elements.controls, player.elements.controls.pressed = ['mousedown', 'touchstart'].includes(event.type);
'mousedown mouseup touchstart touchend touchcancel', });
event => {
player.elements.controls.pressed = [
'mousedown',
'touchstart',
].includes(event.type);
},
);
// Focus in/out on controls // Focus in/out on controls
this.bind(player.elements.controls, 'focusin focusout', event => { this.bind(player.elements.controls, 'focusin focusout', event => {
@ -867,11 +693,7 @@ class Listeners {
const isFocusIn = event.type === 'focusin'; const isFocusIn = event.type === 'focusin';
// Skip transition to prevent focus from scrolling the parent element // Skip transition to prevent focus from scrolling the parent element
toggleClass( toggleClass(elements.controls, config.classNames.noTransition, isFocusIn);
elements.controls,
config.classNames.noTransition,
isFocusIn,
);
// Toggle // Toggle
ui.toggleControls.call(player, isFocusIn); ui.toggleControls.call(player, isFocusIn);
@ -880,11 +702,7 @@ class Listeners {
if (isFocusIn) { if (isFocusIn) {
// Restore transition // Restore transition
setTimeout(() => { setTimeout(() => {
toggleClass( toggleClass(elements.controls, config.classNames.noTransition, false);
elements.controls,
config.classNames.noTransition,
false,
);
}, 0); }, 0);
// Delay a little more for keyboard users // Delay a little more for keyboard users
@ -894,10 +712,7 @@ class Listeners {
clearTimeout(timers.controls); clearTimeout(timers.controls);
// Hide // Hide
timers.controls = setTimeout( timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);
() => ui.toggleControls.call(player, false),
delay,
);
} }
}); });
@ -911,9 +726,7 @@ class Listeners {
const inverted = event.webkitDirectionInvertedFromDevice; const inverted = event.webkitDirectionInvertedFromDevice;
// Get delta from event. Invert if `inverted` is true // Get delta from event. Invert if `inverted` is true
const [x, y] = [event.deltaX, -event.deltaY].map( const [x, y] = [event.deltaX, -event.deltaY].map(value => (inverted ? -value : value));
value => (inverted ? -value : value),
);
// Using the biggest delta, normalize to 1 or -1 (or 0 if no delta) // Using the biggest delta, normalize to 1 or -1 (or 0 if no delta)
const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y); const direction = Math.sign(Math.abs(x) > Math.abs(y) ? x : y);
@ -923,10 +736,7 @@ class Listeners {
// Don't break page scrolling at max and min // Don't break page scrolling at max and min
const { volume } = player.media; const { volume } = player.media;
if ( if ((direction === 1 && volume < 1) || (direction === -1 && volume > 0)) {
(direction === 1 && volume < 1) ||
(direction === -1 && volume > 0)
) {
event.preventDefault(); event.preventDefault();
} }
}, },

View File

@ -52,11 +52,7 @@ class Plyr {
} }
// jQuery, NodeList or Array passed, use first element // jQuery, NodeList or Array passed, use first element
if ( if ((window.jQuery && this.media instanceof jQuery) || is.nodeList(this.media) || is.array(this.media)) {
(window.jQuery && this.media instanceof jQuery) ||
is.nodeList(this.media) ||
is.array(this.media)
) {
// eslint-disable-next-line // eslint-disable-next-line
this.media = this.media[0]; this.media = this.media[0];
} }
@ -69,9 +65,7 @@ class Plyr {
options || {}, options || {},
(() => { (() => {
try { try {
return JSON.parse( return JSON.parse(this.media.getAttribute('data-plyr-config'));
this.media.getAttribute('data-plyr-config'),
);
} catch (e) { } catch (e) {
return {}; return {};
} }
@ -199,21 +193,14 @@ class Plyr {
} }
} else { } else {
// <div> with attributes // <div> with attributes
this.provider = this.media.getAttribute( this.provider = this.media.getAttribute(this.config.attributes.embed.provider);
this.config.attributes.embed.provider,
);
// Remove attribute // Remove attribute
this.media.removeAttribute( this.media.removeAttribute(this.config.attributes.embed.provider);
this.config.attributes.embed.provider,
);
} }
// Unsupported or missing provider // Unsupported or missing provider
if ( if (is.empty(this.provider) || !Object.keys(providers).includes(this.provider)) {
is.empty(this.provider) ||
!Object.keys(providers).includes(this.provider)
) {
this.debug.error('Setup failed: Invalid provider'); this.debug.error('Setup failed: Invalid provider');
return; return;
} }
@ -235,10 +222,7 @@ class Plyr {
if (this.media.hasAttribute('autoplay')) { if (this.media.hasAttribute('autoplay')) {
this.config.autoplay = true; this.config.autoplay = true;
} }
if ( if (this.media.hasAttribute('playsinline') || this.media.hasAttribute('webkit-playsinline')) {
this.media.hasAttribute('playsinline') ||
this.media.hasAttribute('webkit-playsinline')
) {
this.config.playsinline = true; this.config.playsinline = true;
} }
if (this.media.hasAttribute('muted')) { if (this.media.hasAttribute('muted')) {
@ -256,11 +240,7 @@ class Plyr {
} }
// Check for support again but with type // Check for support again but with type
this.supported = support.check( this.supported = support.check(this.type, this.provider, this.config.playsinline);
this.type,
this.provider,
this.config.playsinline,
);
// If no support for even API, bail // If no support for even API, bail
if (!this.supported.api) { if (!this.supported.api) {
@ -293,14 +273,9 @@ class Plyr {
// Listen for events if debugging // Listen for events if debugging
if (this.config.debug) { if (this.config.debug) {
on.call( on.call(this, this.elements.container, this.config.events.join(' '), event => {
this, this.debug.log(`event: ${event.type}`);
this.elements.container, });
this.config.events.join(' '),
event => {
this.debug.log(`event: ${event.type}`);
},
);
} }
// Setup interface // Setup interface
@ -450,9 +425,7 @@ class Plyr {
* @param {number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime * @param {number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime
*/ */
rewind(seekTime) { rewind(seekTime) {
this.currentTime = this.currentTime = this.currentTime - (is.number(seekTime) ? seekTime : this.config.seekTime);
this.currentTime -
(is.number(seekTime) ? seekTime : this.config.seekTime);
} }
/** /**
@ -460,9 +433,7 @@ class Plyr {
* @param {number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime * @param {number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime
*/ */
forward(seekTime) { forward(seekTime) {
this.currentTime = this.currentTime = this.currentTime + (is.number(seekTime) ? seekTime : this.config.seekTime);
this.currentTime +
(is.number(seekTime) ? seekTime : this.config.seekTime);
} }
/** /**
@ -479,9 +450,7 @@ class Plyr {
const inputIsValid = is.number(input) && input > 0; const inputIsValid = is.number(input) && input > 0;
// Set // Set
this.media.currentTime = inputIsValid this.media.currentTime = inputIsValid ? Math.min(input, this.duration) : 0;
? Math.min(input, this.duration)
: 0;
// Logging // Logging
this.debug.log(`Seeking to ${this.currentTime} seconds`); this.debug.log(`Seeking to ${this.currentTime} seconds`);
@ -531,10 +500,7 @@ class Plyr {
// Media duration can be NaN or Infinity before the media has loaded // Media duration can be NaN or Infinity before the media has loaded
const realDuration = (this.media || {}).duration; const realDuration = (this.media || {}).duration;
const duration = const duration = !is.number(realDuration) || realDuration === Infinity ? 0 : realDuration;
!is.number(realDuration) || realDuration === Infinity
? 0
: realDuration;
// If config duration is funky, use regular duration // If config duration is funky, use regular duration
return fauxDuration || duration; return fauxDuration || duration;
@ -728,9 +694,7 @@ class Plyr {
if (!options.includes(quality)) { if (!options.includes(quality)) {
const value = closest(options, quality); const value = closest(options, quality);
this.debug.warn( this.debug.warn(`Unsupported quality option: ${quality}, using ${value} instead`);
`Unsupported quality option: ${quality}, using ${value} instead`,
);
quality = value; quality = value;
} }
@ -929,9 +893,7 @@ class Plyr {
const toggle = is.boolean(input) ? input : this.pip === states.inline; const toggle = is.boolean(input) ? input : this.pip === states.inline;
// Toggle based on current state // Toggle based on current state
this.media.webkitSetPresentationMode( this.media.webkitSetPresentationMode(toggle ? states.pip : states.inline);
toggle ? states.pip : states.inline,
);
} }
/** /**
@ -964,27 +926,16 @@ class Plyr {
// Don't toggle if missing UI support or if it's audio // Don't toggle if missing UI support or if it's audio
if (this.supported.ui && !this.isAudio) { if (this.supported.ui && !this.isAudio) {
// Get state before change // Get state before change
const isHidden = hasClass( const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls);
this.elements.container,
this.config.classNames.hideControls,
);
// Negate the argument if not undefined since adding the class to hides the controls // Negate the argument if not undefined since adding the class to hides the controls
const force = typeof toggle === 'undefined' ? undefined : !toggle; const force = typeof toggle === 'undefined' ? undefined : !toggle;
// Apply and get updated state // Apply and get updated state
const hiding = toggleClass( const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force);
this.elements.container,
this.config.classNames.hideControls,
force,
);
// Close menu // Close menu
if ( if (hiding && this.config.controls.includes('settings') && !is.empty(this.config.settings)) {
hiding &&
this.config.controls.includes('settings') &&
!is.empty(this.config.settings)
) {
controls.toggleMenu.call(this, false); controls.toggleMenu.call(this, false);
} }
@ -1074,12 +1025,7 @@ class Plyr {
replaceElement(this.elements.original, this.elements.container); replaceElement(this.elements.original, this.elements.container);
// Event // Event
triggerEvent.call( triggerEvent.call(this, this.elements.original, 'destroyed', true);
this,
this.elements.original,
'destroyed',
true,
);
// Callback // Callback
if (is.function(callback)) { if (is.function(callback)) {

View File

@ -25,13 +25,9 @@ const support = {
// Check for support // Check for support
// Basic functionality vs full UI // Basic functionality vs full UI
check(type, provider, playsinline) { check(type, provider, playsinline) {
const canPlayInline = const canPlayInline = browser.isIPhone && playsinline && support.playsinline;
browser.isIPhone && playsinline && support.playsinline;
const api = support[type] || provider !== 'html5'; const api = support[type] || provider !== 'html5';
const ui = const ui = api && support.rangeInput && (type !== 'video' || !browser.isIPhone || canPlayInline);
api &&
support.rangeInput &&
(type !== 'video' || !browser.isIPhone || canPlayInline);
return { return {
api, api,
@ -41,9 +37,7 @@ const support = {
// Picture-in-picture support // Picture-in-picture support
// Safari only currently // Safari only currently
pip: (() => pip: (() => !browser.isIPhone && is.function(createElement('video').webkitSetPresentationMode))(),
!browser.isIPhone &&
is.function(createElement('video').webkitSetPresentationMode))(),
// Airplay support // Airplay support
// Safari only currently // Safari only currently
@ -75,9 +69,7 @@ const support = {
} }
try { try {
return Boolean( return Boolean(type && this.media.canPlayType(type).replace(/no/, ''));
type && this.media.canPlayType(type).replace(/no/, ''),
);
} catch (err) { } catch (err) {
return false; return false;
} }
@ -102,9 +94,7 @@ const support = {
// Reduced motion iOS & MacOS setting // Reduced motion iOS & MacOS setting
// https://webkit.org/blog/7551/responsive-design-for-motion/ // https://webkit.org/blog/7551/responsive-design-for-motion/
reducedMotion: reducedMotion: 'matchMedia' in window && window.matchMedia('(prefers-reduced-motion)').matches,
'matchMedia' in window &&
window.matchMedia('(prefers-reduced-motion)').matches,
}; };
export default support; export default support;

View File

@ -14,16 +14,8 @@ import loadImage from './utils/loadImage';
const ui = { const ui = {
addStyleHook() { addStyleHook() {
toggleClass( toggleClass(this.elements.container, this.config.selectors.container.replace('.', ''), true);
this.elements.container, toggleClass(this.elements.container, this.config.classNames.uiSupported, this.supported.ui);
this.config.selectors.container.replace('.', ''),
true,
);
toggleClass(
this.elements.container,
this.config.classNames.uiSupported,
this.supported.ui,
);
}, },
// Toggle native HTML5 media controls // Toggle native HTML5 media controls
@ -43,9 +35,7 @@ const ui = {
// Don't setup interface if no support // Don't setup interface if no support
if (!this.supported.ui) { if (!this.supported.ui) {
this.debug.warn( this.debug.warn(`Basic support only for ${this.provider} ${this.type}`);
`Basic support only for ${this.provider} ${this.type}`,
);
// Restore native controls // Restore native controls
ui.toggleNativeControls.call(this, true); ui.toggleNativeControls.call(this, true);
@ -103,25 +93,13 @@ const ui = {
); );
// Check for airplay support // Check for airplay support
toggleClass( toggleClass(this.elements.container, this.config.classNames.airplay.supported, support.airplay && this.isHTML5);
this.elements.container,
this.config.classNames.airplay.supported,
support.airplay && this.isHTML5,
);
// Add iOS class // Add iOS class
toggleClass( toggleClass(this.elements.container, this.config.classNames.isIos, browser.isIos);
this.elements.container,
this.config.classNames.isIos,
browser.isIos,
);
// Add touch class // Add touch class
toggleClass( toggleClass(this.elements.container, this.config.classNames.isTouch, this.touch);
this.elements.container,
this.config.classNames.isTouch,
this.touch,
);
// Ready for API calls // Ready for API calls
this.ready = true; this.ready = true;
@ -171,9 +149,7 @@ const ui = {
} }
// Default to media type // Default to media type
const title = !is.empty(this.config.title) const title = !is.empty(this.config.title) ? this.config.title : 'video';
? this.config.title
: 'video';
const format = i18n.get('frameTitle', this.config); const format = i18n.get('frameTitle', this.config);
iframe.setAttribute('title', format.replace('{title}', title)); iframe.setAttribute('title', format.replace('{title}', title));
@ -182,11 +158,7 @@ const ui = {
// Toggle poster // Toggle poster
togglePoster(enable) { togglePoster(enable) {
toggleClass( toggleClass(this.elements.container, this.config.classNames.posterEnabled, enable);
this.elements.container,
this.config.classNames.posterEnabled,
enable,
);
}, },
// Set the poster image (async) // Set the poster image (async)
@ -217,9 +189,7 @@ const ui = {
.then(() => { .then(() => {
// Prevent race conditions // Prevent race conditions
if (poster !== this.poster) { if (poster !== this.poster) {
throw new Error( throw new Error('setPoster cancelled by later call to setPoster');
'setPoster cancelled by later call to setPoster',
);
} }
}) })
.then(() => { .then(() => {
@ -237,21 +207,9 @@ const ui = {
// Check playing state // Check playing state
checkPlaying(event) { checkPlaying(event) {
// Class hooks // Class hooks
toggleClass( toggleClass(this.elements.container, this.config.classNames.playing, this.playing);
this.elements.container, toggleClass(this.elements.container, this.config.classNames.paused, this.paused);
this.config.classNames.playing, toggleClass(this.elements.container, this.config.classNames.stopped, this.stopped);
this.playing,
);
toggleClass(
this.elements.container,
this.config.classNames.paused,
this.paused,
);
toggleClass(
this.elements.container,
this.config.classNames.stopped,
this.stopped,
);
// Set state // Set state
Array.from(this.elements.buttons.play || []).forEach(target => { Array.from(this.elements.buttons.play || []).forEach(target => {
@ -277,11 +235,7 @@ const ui = {
// Timer to prevent flicker when seeking // Timer to prevent flicker when seeking
this.timers.loading = setTimeout(() => { this.timers.loading = setTimeout(() => {
// Update progress bar loading class state // Update progress bar loading class state
toggleClass( toggleClass(this.elements.container, this.config.classNames.loading, this.loading);
this.elements.container,
this.config.classNames.loading,
this.loading,
);
// Update controls visibility // Update controls visibility
ui.toggleControls.call(this); ui.toggleControls.call(this);
@ -294,15 +248,7 @@ const ui = {
if (controls && this.config.hideControls) { if (controls && this.config.hideControls) {
// Show controls if force, loading, paused, or button interaction, otherwise hide // Show controls if force, loading, paused, or button interaction, otherwise hide
this.toggleControls( this.toggleControls(Boolean(force || this.loading || this.paused || controls.pressed || controls.hover));
Boolean(
force ||
this.loading ||
this.paused ||
controls.pressed ||
controls.hover,
),
);
} }
}, },
}; };

View File

@ -27,21 +27,9 @@ const supportsPassiveListeners = (() => {
})(); })();
// Toggle event listener // Toggle event listener
export function toggleListener( export function toggleListener(element, event, callback, toggle = false, passive = true, capture = false) {
element,
event,
callback,
toggle = false,
passive = true,
capture = false,
) {
// Bail if no element, event, or callback // Bail if no element, event, or callback
if ( if (!element || !('addEventListener' in element) || is.empty(event) || !is.function(callback)) {
!element ||
!('addEventListener' in element) ||
is.empty(event) ||
!is.function(callback)
) {
return; return;
} }
@ -69,74 +57,28 @@ export function toggleListener(
this.eventListeners.push({ element, type, callback, options }); this.eventListeners.push({ element, type, callback, options });
} }
element[toggle ? 'addEventListener' : 'removeEventListener']( element[toggle ? 'addEventListener' : 'removeEventListener'](type, callback, options);
type,
callback,
options,
);
}); });
} }
// Bind event handler // Bind event handler
export function on( export function on(element, events = '', callback, passive = true, capture = false) {
element, toggleListener.call(this, element, events, callback, true, passive, capture);
events = '',
callback,
passive = true,
capture = false,
) {
toggleListener.call(
this,
element,
events,
callback,
true,
passive,
capture,
);
} }
// Unbind event handler // Unbind event handler
export function off( export function off(element, events = '', callback, passive = true, capture = false) {
element, toggleListener.call(this, element, events, callback, false, passive, capture);
events = '',
callback,
passive = true,
capture = false,
) {
toggleListener.call(
this,
element,
events,
callback,
false,
passive,
capture,
);
} }
// Bind once-only event handler // Bind once-only event handler
export function once( export function once(element, events = '', callback, passive = true, capture = false) {
element,
events = '',
callback,
passive = true,
capture = false,
) {
function onceCallback(...args) { function onceCallback(...args) {
off(element, events, onceCallback, passive, capture); off(element, events, onceCallback, passive, capture);
callback.apply(this, args); callback.apply(this, args);
} }
toggleListener.call( toggleListener.call(this, element, events, onceCallback, true, passive, capture);
this,
element,
events,
onceCallback,
true,
passive,
capture,
);
} }
// Trigger event // Trigger event
@ -173,9 +115,6 @@ export function unbindListeners() {
// Run method when / if player is ready // Run method when / if player is ready
export function ready() { export function ready() {
return new Promise( return new Promise(
resolve => resolve => (this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)),
this.ready
? setTimeout(resolve, 0)
: on.call(this, this.elements.container, 'ready', resolve),
).then(() => {}); ).then(() => {});
} }