diff options
Diffstat (limited to 'src/js/controls.js')
-rw-r--r-- | src/js/controls.js | 975 |
1 files changed, 663 insertions, 312 deletions
diff --git a/src/js/controls.js b/src/js/controls.js index c01e3584..d0e6874d 100644 --- a/src/js/controls.js +++ b/src/js/controls.js @@ -1,5 +1,6 @@ // ========================================================================== // Plyr controls +// TODO: This needs to be split into smaller files and cleaned up // ========================================================================== import captions from './captions'; @@ -9,19 +10,7 @@ import support from './support'; import { repaint, transitionEndEvent } from './utils/animation'; import { dedupe } from './utils/arrays'; import browser from './utils/browser'; -import { - createElement, - emptyElement, - getAttributesFromSelector, - getElement, - getElements, - hasClass, - matches, - removeElement, - setAttributes, - toggleClass, - toggleHidden, -} from './utils/elements'; +import { createElement, emptyElement, getAttributesFromSelector, getElement, getElements, hasClass, matches, removeElement, setAttributes, setFocus, toggleClass, toggleHidden } from './utils/elements'; import { off, on } from './utils/events'; import is from './utils/is'; import loadSprite from './utils/loadSprite'; @@ -34,7 +23,9 @@ const controls = { // Get icon URL getIconUrl() { const url = new URL(this.config.iconUrl, window.location); - const cors = url.host !== window.location.host || (browser.isIE && !window.svg4everybody); + const cors = + url.host !== window.location.host || + (browser.isIE && !window.svg4everybody); return { url: this.config.iconUrl, @@ -45,37 +36,82 @@ const controls = { // Find the UI controls findElements() { try { - this.elements.controls = getElement.call(this, this.config.selectors.controls.wrapper); + this.elements.controls = getElement.call( + this, + this.config.selectors.controls.wrapper, + ); // Buttons this.elements.buttons = { - play: getElements.call(this, this.config.selectors.buttons.play), - pause: getElement.call(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), + play: getElements.call( + this, + this.config.selectors.buttons.play, + ), + pause: getElement.call( + 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), pip: getElement.call(this, this.config.selectors.buttons.pip), - airplay: getElement.call(this, this.config.selectors.buttons.airplay), - 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), + airplay: getElement.call( + this, + this.config.selectors.buttons.airplay, + ), + 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 - this.elements.progress = getElement.call(this, this.config.selectors.progress); + this.elements.progress = getElement.call( + this, + this.config.selectors.progress, + ); // Inputs this.elements.inputs = { seek: getElement.call(this, this.config.selectors.inputs.seek), - volume: getElement.call(this, this.config.selectors.inputs.volume), + volume: getElement.call( + this, + this.config.selectors.inputs.volume, + ), }; // Display this.elements.display = { - buffer: getElement.call(this, this.config.selectors.display.buffer), - currentTime: getElement.call(this, this.config.selectors.display.currentTime), - duration: getElement.call(this, this.config.selectors.display.duration), + buffer: getElement.call( + this, + this.config.selectors.display.buffer, + ), + currentTime: getElement.call( + this, + this.config.selectors.display.currentTime, + ), + duration: getElement.call( + this, + this.config.selectors.display.duration, + ), }; // Seek tooltip @@ -88,7 +124,10 @@ const controls = { return true; } catch (error) { // Log it - this.debug.warn('It looks like there is a problem with your custom controls HTML', error); + this.debug.warn( + 'It looks like there is a problem with your custom controls HTML', + error, + ); // Restore native video controls this.toggleNativeControls(true); @@ -101,7 +140,9 @@ const controls = { createIcon(type, attributes) { const namespace = 'http://www.w3.org/2000/svg'; const iconUrl = controls.getIconUrl.call(this); - const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${this.config.iconPrefix}`; + const iconPath = `${!iconUrl.cors ? iconUrl.url : ''}#${ + this.config.iconPrefix + }`; // Create <svg> const icon = document.createElementNS(namespace, 'svg'); @@ -123,7 +164,11 @@ const controls = { if ('href' in use) { use.setAttributeNS('http://www.w3.org/1999/xlink', 'href', path); } else { - use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', path); + use.setAttributeNS( + 'http://www.w3.org/1999/xlink', + 'xlink:href', + path, + ); } // Add <use> to <svg> @@ -142,7 +187,9 @@ const controls = { const text = universals[type] || i18n.get(type, this.config); const attributes = Object.assign({}, attr, { - class: [attr.class, this.config.classNames.hidden].filter(Boolean).join(' '), + class: [attr.class, this.config.classNames.hidden] + .filter(Boolean) + .join(' '), }); return createElement('span', attributes, text); }, @@ -229,7 +276,9 @@ const controls = { break; case 'play-large': - attributes.class += ` ${this.config.classNames.control}--overlaid`; + attributes.class += ` ${ + this.config.classNames.control + }--overlaid`; type = 'play'; label = 'play'; icon = 'play'; @@ -243,19 +292,41 @@ const controls = { // Setup toggle icon and labels if (toggle) { // Icon - button.appendChild(controls.createIcon.call(this, iconPressed, { class: 'icon--pressed' })); - button.appendChild(controls.createIcon.call(this, icon, { class: 'icon--not-pressed' })); + button.appendChild( + controls.createIcon.call(this, iconPressed, { + class: 'icon--pressed', + }), + ); + button.appendChild( + controls.createIcon.call(this, icon, { + class: 'icon--not-pressed', + }), + ); // Label/Tooltip - button.appendChild(controls.createLabel.call(this, labelPressed, { class: 'label--pressed' })); - button.appendChild(controls.createLabel.call(this, label, { class: 'label--not-pressed' })); + button.appendChild( + controls.createLabel.call(this, labelPressed, { + class: 'label--pressed', + }), + ); + button.appendChild( + controls.createLabel.call(this, label, { + class: 'label--not-pressed', + }), + ); } else { button.appendChild(controls.createIcon.call(this, icon)); button.appendChild(controls.createLabel.call(this, label)); } // Merge attributes - extend(attributes, getAttributesFromSelector(this.config.selectors.buttons[type], attributes)); + extend( + attributes, + getAttributesFromSelector( + this.config.selectors.buttons[type], + attributes, + ), + ); setAttributes(button, attributes); @@ -355,12 +426,16 @@ const controls = { // Create time display createTime(type) { - const attributes = getAttributesFromSelector(this.config.selectors.display[type]); + const attributes = getAttributesFromSelector( + this.config.selectors.display[type], + ); const container = createElement( 'div', extend(attributes, { - class: `plyr__time ${attributes.class}`, + class: `${this.config.classNames.display.time} ${ + attributes.class ? attributes.class : '' + }`.trim(), 'aria-label': i18n.get(type, this.config), }), '00:00', @@ -372,37 +447,169 @@ const controls = { return container; }, - // Create a settings menu item - createMenuItem({ value, list, type, title, badge = null, checked = false }) { - const item = createElement('li'); + // Bind keyboard shortcuts for a menu item + // We have to bind to keyup otherwise Firefox triggers a click when a keydown event handler shifts focus + // https://bugzilla.mozilla.org/show_bug.cgi?id=1220143 + bindMenuItemShortcuts(menuItem, type) { + // Handle space or -> to open menu + on( + menuItem, + 'keydown keyup', + event => { + // We only care about space and ⬆️ ⬇️️ ➡️ + if (![32, 38, 39, 40].includes(event.which)) { + return; + } - const label = createElement('label', { - class: this.config.classNames.control, - }); + // Prevent play / seek + event.preventDefault(); + event.stopPropagation(); - const radio = createElement( - 'input', - extend(getAttributesFromSelector(this.config.selectors.inputs[type]), { - type: 'radio', - name: `plyr-${type}`, + // We're just here to prevent the keydown bubbling + if (event.type === 'keydown') { + return; + } + + const isRadioButton = matches( + menuItem, + '[role="menuitemradio"]', + ); + + // Show the respective menu + if (!isRadioButton && [32, 39].includes(event.which)) { + controls.showMenuPanel.call(this, type, true); + } else { + let target; + + if (event.which !== 32) { + if ( + event.which === 40 || + (isRadioButton && event.which === 39) + ) { + target = menuItem.nextElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.firstElementChild; + } + } else { + target = menuItem.previousElementSibling; + + if (!is.element(target)) { + target = menuItem.parentNode.lastElementChild; + } + } + + setFocus.call(this, target, true); + } + } + }, + false, + ); + }, + + // Create a settings menu item + createMenuItem({ + value, + list, + type, + title, + badge = null, + checked = false, + }) { + const attributes = getAttributesFromSelector( + this.config.selectors.inputs[type], + ); + + const menuItem = createElement( + 'button', + extend(attributes, { + type: 'button', + role: 'menuitemradio', + class: `${this.config.classNames.control} ${ + attributes.class ? attributes.class : '' + }`.trim(), + 'aria-checked': checked, value, - checked, - class: 'plyr__sr-only', }), ); - const faux = createElement('span', { hidden: '' }); + const flex = createElement('span'); - label.appendChild(radio); - label.appendChild(faux); - label.insertAdjacentHTML('beforeend', title); + // We have to set as HTML incase of special characters + flex.innerHTML = title; if (is.element(badge)) { - label.appendChild(badge); + flex.appendChild(badge); } - item.appendChild(label); - list.appendChild(item); + menuItem.appendChild(flex); + + // Replicate radio button behaviour + Object.defineProperty(menuItem, 'checked', { + enumerable: true, + get() { + return menuItem.getAttribute('aria-checked') === 'true'; + }, + set(checked) { + // Ensure exclusivity + if (checked) { + Array.from(menuItem.parentNode.children) + .filter(node => matches(node, '[role="menuitemradio"]')) + .forEach(node => + node.setAttribute('aria-checked', 'false'), + ); + } + + menuItem.setAttribute( + 'aria-checked', + checked ? 'true' : 'false', + ); + }, + }); + + this.listeners.bind( + menuItem, + 'click keyup', + event => { + if (event.type === 'keyup' && event.which !== 32) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + + menuItem.checked = true; + + switch (type) { + case 'language': + this.currentTrack = Number(value); + break; + + case 'quality': + this.quality = value; + break; + + case 'speed': + this.speed = parseFloat(value); + break; + + default: + break; + } + + controls.showMenuPanel.call( + this, + 'home', + event.type === 'keyup', + ); + }, + type, + false, + ); + + controls.bindMenuItemShortcuts.call(this, menuItem, type); + + list.appendChild(menuItem); }, // Format a time for display @@ -437,12 +644,17 @@ const controls = { // Update range if (is.element(this.elements.inputs.volume)) { - controls.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume); + controls.setRange.call( + this, + this.elements.inputs.volume, + this.muted ? 0 : this.volume, + ); } // Update mute state if (is.element(this.elements.buttons.mute)) { - this.elements.buttons.mute.pressed = this.muted || this.volume === 0; + this.elements.buttons.mute.pressed = + this.muted || this.volume === 0; } }, @@ -469,7 +681,9 @@ const controls = { const setProgress = (target, input) => { const value = is.number(input) ? input : 0; - const progress = is.element(target) ? target : this.elements.display.buffer; + const progress = is.element(target) + ? target + : this.elements.display.buffer; // Update value and label if (is.element(progress)) { @@ -493,7 +707,11 @@ const controls = { // Set seek range value only if it's a 'natural' time event if (event.type === 'timeupdate') { - controls.setRange.call(this, this.elements.inputs.seek, value); + controls.setRange.call( + this, + this.elements.inputs.seek, + value, + ); } break; @@ -501,7 +719,10 @@ const controls = { // Check buffer status case 'playing': case 'progress': - setProgress(this.elements.display.buffer, this.buffered * 100); + setProgress( + this.elements.display.buffer, + this.buffered * 100, + ); break; @@ -529,7 +750,9 @@ const controls = { const format = i18n.get('seekLabel', this.config); range.setAttribute( 'aria-valuetext', - format.replace('{currentTime}', currentTime).replace('{duration}', duration), + format + .replace('{currentTime}', currentTime) + .replace('{duration}', duration), ); } else if (matches(range, this.config.selectors.inputs.volume)) { const percent = range.value * 100; @@ -579,7 +802,10 @@ const controls = { if (is.event(event)) { percent = 100 / clientRect.width * (event.pageX - clientRect.left); } else if (hasClass(this.elements.display.seekTooltip, visible)) { - percent = parseFloat(this.elements.display.seekTooltip.style.left, 10); + percent = parseFloat( + this.elements.display.seekTooltip.style.left, + 10, + ); } else { return; } @@ -592,14 +818,21 @@ const controls = { } // Display the time a click would seek to - controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent); + controls.updateTimeDisplay.call( + this, + this.elements.display.seekTooltip, + this.duration / 100 * percent, + ); // Set position this.elements.display.seekTooltip.style.left = `${percent}%`; // Show/hide the tooltip // If the event is a moues in/out and percentage is inside bounds - if (is.event(event) && ['mouseenter', 'mouseleave'].includes(event.type)) { + if ( + is.event(event) && + ['mouseenter', 'mouseleave'].includes(event.type) + ) { toggle(event.type === 'mouseenter'); } }, @@ -607,7 +840,9 @@ const controls = { // Handle time change event timeUpdate(event) { // Only invert if only one time element is displayed and used for both duration and currentTime - const invert = !is.element(this.elements.display.duration) && this.config.invertTime; + const invert = + !is.element(this.elements.display.duration) && + this.config.invertTime; // Duration controls.updateTimeDisplay.call( @@ -629,7 +864,10 @@ const controls = { // Show the duration on metadataloaded or durationchange events durationUpdate() { // Bail if no UI or durationchange event triggered after playing/seek when invertTime is false - if (!this.supported.ui || (!this.config.invertTime && this.currentTime)) { + if ( + !this.supported.ui || + (!this.config.invertTime && this.currentTime) + ) { return; } @@ -637,7 +875,7 @@ const controls = { // https://github.com/video-dev/hls.js/blob/5820d29d3c4c8a46e8b75f1e3afa3e68c1a9a2db/src/controller/buffer-controller.js#L415 // https://github.com/google/shaka-player/blob/4d889054631f4e1cf0fbd80ddd2b71887c02e232/lib/media/streaming_engine.js#L1062 // https://github.com/Dash-Industry-Forum/dash.js/blob/69859f51b969645b234666800d4cb596d89c602d/src/dash/models/DashManifestModel.js#L338 - if (this.duration >= 2**32) { + if (this.duration >= 2 ** 32) { toggleHidden(this.elements.display.currentTime, true); toggleHidden(this.elements.progress, true); return; @@ -645,7 +883,10 @@ const controls = { // Update ARIA values if (is.element(this.elements.inputs.seek)) { - this.elements.inputs.seek.setAttribute('aria-valuemax', this.duration); + this.elements.inputs.seek.setAttribute( + 'aria-valuemax', + this.duration, + ); } // If there's a spot to display duration @@ -653,12 +894,20 @@ const controls = { // If there's only one time display, display duration there if (!hasDuration && this.config.displayDuration && this.paused) { - controls.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration); + controls.updateTimeDisplay.call( + this, + this.elements.display.currentTime, + this.duration, + ); } // If there's a duration element, update content if (hasDuration) { - controls.updateTimeDisplay.call(this, this.elements.display.duration, this.duration); + controls.updateTimeDisplay.call( + this, + this.elements.display.duration, + this.duration, + ); } // Update the tooltip (if visible) @@ -666,28 +915,126 @@ const controls = { }, // Hide/show a tab - toggleTab(setting, toggle) { - toggleHidden(this.elements.settings.tabs[setting], !toggle); + toggleMenuButton(setting, toggle) { + toggleHidden(this.elements.settings.buttons[setting], !toggle); + }, + + // Update the selected setting + updateSetting(setting, container, input) { + const pane = this.elements.settings.panels[setting]; + let value = null; + let list = container; + + if (setting === 'captions') { + value = this.currentTrack; + } else { + value = !is.empty(input) ? input : this[setting]; + + // Get default + if (is.empty(value)) { + value = this.config[setting].default; + } + + // Unsupported value + if ( + !is.empty(this.options[setting]) && + !this.options[setting].includes(value) + ) { + this.debug.warn( + `Unsupported value of '${value}' for ${setting}`, + ); + return; + } + + // Disabled value + if (!this.config[setting].options.includes(value)) { + this.debug.warn(`Disabled value of '${value}' for ${setting}`); + return; + } + } + + // Get the list if we need to + if (!is.element(list)) { + list = pane && pane.querySelector('[role="menu"]'); + } + + // If there's no list it means it's not been rendered... + if (!is.element(list)) { + return; + } + + // Update the label + const label = this.elements.settings.buttons[setting].querySelector( + `.${this.config.classNames.menu.value}`, + ); + label.innerHTML = controls.getLabel.call(this, setting, value); + + // Find the radio option and check it + const target = list && list.querySelector(`[value="${value}"]`); + + if (is.element(target)) { + target.checked = true; + } + }, + + // Translate a value into a nice label + getLabel(setting, value) { + switch (setting) { + case 'speed': + return value === 1 + ? i18n.get('normal', this.config) + : `${value}×`; + + case 'quality': + if (is.number(value)) { + const label = i18n.get( + `qualityLabel.${value}`, + this.config, + ); + + if (!label.length) { + return `${value}p`; + } + + return label; + } + + return toTitleCase(value); + + case 'captions': + return captions.getLabel.call(this); + + default: + return null; + } }, // Set the quality menu setQualityMenu(options) { // Menu required - if (!is.element(this.elements.settings.panes.quality)) { + if (!is.element(this.elements.settings.panels.quality)) { return; } const type = 'quality'; - const list = this.elements.settings.panes.quality.querySelector('ul'); + const list = this.elements.settings.panels.quality.querySelector( + '[role="menu"]', + ); // Set options if passed and filter based on uniqueness and config if (is.array(options)) { - this.options.quality = dedupe(options).filter(quality => this.config.quality.options.includes(quality)); + this.options.quality = dedupe(options).filter(quality => + this.config.quality.options.includes(quality), + ); } // Toggle the pane and tab - const toggle = !is.empty(this.options.quality) && this.options.quality.length > 1; - controls.toggleTab.call(this, type, toggle); + const toggle = + !is.empty(this.options.quality) && this.options.quality.length > 1; + controls.toggleMenuButton.call(this, type, toggle); + + // Empty the menu + emptyElement(list); // Check if we need to toggle the parent controls.checkMenu.call(this); @@ -697,9 +1044,6 @@ const controls = { return; } - // Empty the menu - emptyElement(list); - // Get the badge HTML for HD, 4K etc const getBadge = quality => { const label = i18n.get(`qualityBadge.${quality}`, this.config); @@ -730,101 +1074,23 @@ const controls = { controls.updateSetting.call(this, type, list); }, - // Translate a value into a nice label - getLabel(setting, value) { - switch (setting) { - case 'speed': - return value === 1 ? i18n.get('normal', this.config) : `${value}×`; - - case 'quality': - if (is.number(value)) { - const label = i18n.get(`qualityLabel.${value}`, this.config); - - if (!label.length) { - return `${value}p`; - } - - return label; - } - - return toTitleCase(value); - - case 'captions': - return captions.getLabel.call(this); - - default: - return null; - } - }, - - // Update the selected setting - updateSetting(setting, container, input) { - const pane = this.elements.settings.panes[setting]; - let value = null; - let list = container; - - if (setting === 'captions') { - value = this.currentTrack; - } else { - value = !is.empty(input) ? input : this[setting]; - - // Get default - if (is.empty(value)) { - value = this.config[setting].default; - } - - // Unsupported value - if (!is.empty(this.options[setting]) && !this.options[setting].includes(value)) { - this.debug.warn(`Unsupported value of '${value}' for ${setting}`); - return; - } - - // Disabled value - if (!this.config[setting].options.includes(value)) { - this.debug.warn(`Disabled value of '${value}' for ${setting}`); - return; - } - } - - // Get the list if we need to - if (!is.element(list)) { - list = pane && pane.querySelector('ul'); - } - - // If there's no list it means it's not been rendered... - if (!is.element(list)) { - return; - } - - // Update the label - const label = this.elements.settings.tabs[setting].querySelector(`.${this.config.classNames.menu.value}`); - label.innerHTML = controls.getLabel.call(this, setting, value); - - // Find the radio option and check it - const target = list && list.querySelector(`input[value="${value}"]`); - - if (is.element(target)) { - target.checked = true; - } - }, - // Set the looping options /* setLoopMenu() { // Menu required - if (!is.element(this.elements.settings.panes.loop)) { + if (!is.element(this.elements.settings.panels.loop)) { return; } const options = ['start', 'end', 'all', 'reset']; - const list = this.elements.settings.panes.loop.querySelector('ul'); + const list = this.elements.settings.panels.loop.querySelector('[role="menu"]'); // Show the pane and tab - toggleHidden(this.elements.settings.tabs.loop, false); - toggleHidden(this.elements.settings.panes.loop, false); + toggleHidden(this.elements.settings.buttons.loop, false); + toggleHidden(this.elements.settings.panels.loop, false); // Toggle the pane and tab const toggle = !is.empty(this.loop.options); - controls.toggleTab.call(this, 'loop', toggle); + controls.toggleMenuButton.call(this, 'loop', toggle); // Empty the menu emptyElement(list); @@ -857,13 +1123,21 @@ const controls = { // Set a list of available captions languages setCaptionsMenu() { + // Menu required + if (!is.element(this.elements.settings.panels.captions)) { + return; + } + // TODO: Captions or language? Currently it's mixed const type = 'captions'; - const list = this.elements.settings.panes.captions.querySelector('ul'); + const list = this.elements.settings.panels.captions.querySelector( + '[role="menu"]', + ); const tracks = captions.getTracks.call(this); + const toggle = Boolean(tracks.length); // Toggle the pane and tab - controls.toggleTab.call(this, type, tracks.length); + controls.toggleMenuButton.call(this, type, toggle); // Empty the menu emptyElement(list); @@ -872,7 +1146,7 @@ const controls = { controls.checkMenu.call(this); // If there's no captions, bail - if (!tracks.length) { + if (!toggle) { return; } @@ -881,7 +1155,9 @@ const controls = { value, checked: this.captions.toggled && this.currentTrack === value, title: captions.getLabel.call(this, track), - badge: track.language && controls.createBadge.call(this, track.language.toUpperCase()), + badge: + track.language && + controls.createBadge.call(this, track.language.toUpperCase()), list, type: 'language', })); @@ -903,17 +1179,15 @@ const controls = { // Set a list of available captions languages setSpeedMenu(options) { - // Do nothing if not selected - if (!this.config.controls.includes('settings') || !this.config.settings.includes('speed')) { - return; - } - // Menu required - if (!is.element(this.elements.settings.panes.speed)) { + if (!is.element(this.elements.settings.panels.speed)) { return; } const type = 'speed'; + const list = this.elements.settings.panels.speed.querySelector( + '[role="menu"]', + ); // Set the speed options if (is.array(options)) { @@ -923,11 +1197,17 @@ const controls = { } // Set options if passed and filter based on config - this.options.speed = this.options.speed.filter(speed => this.config.speed.options.includes(speed)); + this.options.speed = this.options.speed.filter(speed => + this.config.speed.options.includes(speed), + ); // Toggle the pane and tab - const toggle = !is.empty(this.options.speed) && this.options.speed.length > 1; - controls.toggleTab.call(this, type, toggle); + const toggle = + !is.empty(this.options.speed) && this.options.speed.length > 1; + controls.toggleMenuButton.call(this, type, toggle); + + // Empty the menu + emptyElement(list); // Check if we need to toggle the parent controls.checkMenu.call(this); @@ -937,12 +1217,6 @@ const controls = { return; } - // Get the list to populate - const list = this.elements.settings.panes.speed.querySelector('ul'); - - // Empty the menu - emptyElement(list); - // Create items this.options.speed.forEach(speed => { controls.createMenuItem.call(this, { @@ -958,27 +1232,32 @@ const controls = { // Check if we need to hide/show the settings menu checkMenu() { - const { tabs } = this.elements.settings; - const visible = !is.empty(tabs) && Object.values(tabs).some(tab => !tab.hidden); + const { buttons } = this.elements.settings; + const visible = + !is.empty(buttons) && + Object.values(buttons).some(button => !button.hidden); toggleHidden(this.elements.settings.menu, !visible); }, // Show/hide menu - toggleMenu(event) { - const { form } = this.elements.settings; + toggleMenu(input) { + const { popup } = this.elements.settings; const button = this.elements.buttons.settings; // Menu and button are required - if (!is.element(form) || !is.element(button)) { + if (!is.element(popup) || !is.element(button)) { return; } - const show = is.boolean(event) ? event : is.element(form) && form.hasAttribute('hidden'); + const show = is.boolean(input) + ? input + : is.element(popup) && popup.hasAttribute('hidden'); - if (is.event(event)) { - const isMenuItem = is.element(form) && form.contains(event.target); - const isButton = event.target === this.elements.buttons.settings; + if (is.event(input)) { + const isMenuItem = + is.element(popup) && popup.contains(input.target); + const isButton = input.target === this.elements.buttons.settings; // If the click was inside the form or if the click // wasn't the button or menu item and we're trying to @@ -989,7 +1268,7 @@ const controls = { // Prevent the toggle being caught by the doc listener if (isButton) { - event.stopPropagation(); + input.stopPropagation(); } } @@ -998,31 +1277,35 @@ const controls = { button.setAttribute('aria-expanded', show); } - if (is.element(form)) { - toggleHidden(form, !show); - toggleClass(this.elements.container, this.config.classNames.menu.open, show); + // Show the actual popup + if (is.element(popup)) { + toggleHidden(popup, !show); + + toggleClass( + this.elements.container, + this.config.classNames.menu.open, + show, + ); + + // Focus the first item if key interaction + if (show && is.event(input) && input.type === 'keyup') { + const pane = Object.values(this.elements.settings.panels).find( + pane => !pane.hidden, + ); + const firstItem = pane.querySelector('[role^="menuitem"]'); - if (show) { - form.removeAttribute('tabindex'); - } else { - form.setAttribute('tabindex', -1); + setFocus.call(this, firstItem, true); } } }, - // Get the natural size of a tab - getTabSize(tab) { + // Get the natural size of a menu panel + getMenuSize(tab) { const clone = tab.cloneNode(true); clone.style.position = 'absolute'; clone.style.opacity = 0; clone.removeAttribute('hidden'); - // Prevent input's being unchecked due to the name being identical - Array.from(clone.querySelectorAll('input[name]')).forEach(input => { - const name = input.getAttribute('name'); - input.setAttribute('name', `${name}-clone`); - }); - // Append to parent so we get the "real" size tab.parentNode.appendChild(clone); @@ -1039,31 +1322,22 @@ const controls = { }; }, - // Toggle Menu - showTab(target = '') { - const { menu } = this.elements.settings; - const pane = document.getElementById(target); + // Show a panel in the menu + showMenuPanel(type = '', tabFocus = false) { + const target = document.getElementById( + `plyr-settings-${this.id}-${type}`, + ); // Nothing to show, bail - if (!is.element(pane)) { - return; - } - - // Are we targeting a tab? If not, bail - const isTab = pane.getAttribute('role') === 'tabpanel'; - if (!isTab) { + if (!is.element(target)) { return; } - // Hide all other tabs - // Get other tabs - const current = menu.querySelector('[role="tabpanel"]:not([hidden])'); - const container = current.parentNode; - - // Set other toggles to be expanded false - Array.from(menu.querySelectorAll(`[aria-controls="${current.getAttribute('id')}"]`)).forEach(toggle => { - toggle.setAttribute('aria-expanded', false); - }); + // Hide all other panels + const container = target.parentNode; + const current = Array.from(container.children).find( + node => !node.hidden, + ); // If we can do fancy animations, we'll animate the height/width if (support.transitions && !support.reducedMotion) { @@ -1072,12 +1346,15 @@ const controls = { container.style.height = `${current.scrollHeight}px`; // Get potential sizes - const size = controls.getTabSize.call(this, pane); + const size = controls.getMenuSize.call(this, target); // Restore auto height/width - const restore = e => { + const restore = event => { // We're only bothered about height and width on the container - if (e.target !== container || !['width', 'height'].includes(e.propertyName)) { + if ( + event.target !== container || + !['width', 'height'].includes(event.propertyName) + ) { return; } @@ -1099,26 +1376,23 @@ const controls = { // Set attributes on current tab toggleHidden(current, true); - current.setAttribute('tabindex', -1); // Set attributes on target - toggleHidden(pane, false); - - const tabs = getElements.call(this, `[aria-controls="${target}"]`); - Array.from(tabs).forEach(tab => { - tab.setAttribute('aria-expanded', true); - }); - pane.removeAttribute('tabindex'); + toggleHidden(target, false); // Focus the first item - pane.querySelectorAll('button:not(:disabled), input:not(:disabled), [tabindex]')[0].focus(); + const firstItem = target.querySelector('[role^="menuitem"]'); + setFocus.call(this, firstItem, tabFocus); }, // Build the default HTML // TODO: Set order based on order in the config.controls array? create(data) { // Create the container - const container = createElement('div', getAttributesFromSelector(this.config.selectors.controls.wrapper)); + const container = createElement( + 'div', + getAttributesFromSelector(this.config.selectors.controls.wrapper), + ); // Restart button if (this.config.controls.includes('restart')) { @@ -1137,12 +1411,17 @@ const controls = { // Fast forward button if (this.config.controls.includes('fast-forward')) { - container.appendChild(controls.createButton.call(this, 'fast-forward')); + container.appendChild( + controls.createButton.call(this, 'fast-forward'), + ); } // Progress if (this.config.controls.includes('progress')) { - const progress = createElement('div', getAttributesFromSelector(this.config.selectors.progress)); + const progress = createElement( + 'div', + getAttributesFromSelector(this.config.selectors.progress), + ); // Seek range slider progress.appendChild( @@ -1176,7 +1455,9 @@ const controls = { // Media current time display if (this.config.controls.includes('current-time')) { - container.appendChild(controls.createTime.call(this, 'currentTime')); + container.appendChild( + controls.createTime.call(this, 'currentTime'), + ); } // Media duration display @@ -1224,13 +1505,16 @@ const controls = { } // Settings button / menu - if (this.config.controls.includes('settings') && !is.empty(this.config.settings)) { - const menu = createElement('div', { + if ( + this.config.controls.includes('settings') && + !is.empty(this.config.settings) + ) { + const control = createElement('div', { class: 'plyr__menu', hidden: '', }); - menu.appendChild( + control.appendChild( controls.createButton.call(this, 'settings', { id: `plyr-settings-toggle-${data.id}`, 'aria-haspopup': true, @@ -1239,45 +1523,60 @@ const controls = { }), ); - const form = createElement('form', { + const popup = createElement('div', { class: 'plyr__menu__container', id: `plyr-settings-${data.id}`, hidden: '', 'aria-labelled-by': `plyr-settings-toggle-${data.id}`, - role: 'tablist', - tabindex: -1, }); const inner = createElement('div'); const home = createElement('div', { id: `plyr-settings-${data.id}-home`, - 'aria-labelled-by': `plyr-settings-toggle-${data.id}`, - role: 'tabpanel', }); - // Create the tab list - const tabs = createElement('ul', { - role: 'tablist', + // Create the menu + const menu = createElement('div', { + role: 'menu', }); - // Build the tabs + home.appendChild(menu); + inner.appendChild(home); + this.elements.settings.panels.home = home; + + // Build the menu items this.config.settings.forEach(type => { - const tab = createElement('li', { - role: 'tab', - hidden: '', + // TODO: bundle this with the createMenuItem helper and bindings + const menuItem = createElement( + 'button', + extend( + getAttributesFromSelector( + this.config.selectors.buttons.settings, + ), + { + type: 'button', + class: `${this.config.classNames.control} ${ + this.config.classNames.control + }--forward`, + role: 'menuitem', + 'aria-haspopup': true, + hidden: '', + }, + ), + ); + + // Bind menu shortcuts for keyboard users + controls.bindMenuItemShortcuts.call(this, menuItem, type); + + // Show menu on click + on(menuItem, 'click', () => { + controls.showMenuPanel.call(this, type, false); }); - const button = createElement( - 'button', - extend(getAttributesFromSelector(this.config.selectors.buttons.settings), { - type: 'button', - class: `${this.config.classNames.control} ${this.config.classNames.control}--forward`, - id: `plyr-settings-${data.id}-${type}-tab`, - 'aria-haspopup': true, - 'aria-controls': `plyr-settings-${data.id}-${type}`, - 'aria-expanded': false, - }), + const flex = createElement( + 'span', + null, i18n.get(type, this.config), ); @@ -1288,54 +1587,93 @@ const controls = { // Speed contains HTML entities value.innerHTML = data[type]; - button.appendChild(value); - tab.appendChild(button); - tabs.appendChild(tab); + flex.appendChild(value); + menuItem.appendChild(flex); + menu.appendChild(menuItem); - this.elements.settings.tabs[type] = tab; - }); - - home.appendChild(tabs); - inner.appendChild(home); - - // Build the panes - this.config.settings.forEach(type => { + // Build the panes const pane = createElement('div', { id: `plyr-settings-${data.id}-${type}`, hidden: '', - 'aria-labelled-by': `plyr-settings-${data.id}-${type}-tab`, - role: 'tabpanel', - tabindex: -1, }); - const back = createElement( - 'button', - { - type: 'button', - class: `${this.config.classNames.control} ${this.config.classNames.control}--back`, - 'aria-haspopup': true, - 'aria-controls': `plyr-settings-${data.id}-home`, - 'aria-expanded': false, + // Back button + const backButton = createElement('button', { + type: 'button', + class: `${this.config.classNames.control} ${ + this.config.classNames.control + }--back`, + }); + + // Visible label + backButton.appendChild( + createElement( + 'span', + { + 'aria-hidden': true, + }, + i18n.get(type, this.config), + ), + ); + + // Screen reader label + backButton.appendChild( + createElement( + 'span', + { + class: this.config.classNames.hidden, + }, + i18n.get('menuBack', this.config), + ), + ); + + // Go back via keyboard + on( + pane, + 'keydown', + event => { + // We only care about <- + if (event.which !== 37) { + return; + } + + // Prevent seek + event.preventDefault(); + event.stopPropagation(); + + // Show the respective menu + controls.showMenuPanel.call(this, 'home', true); }, - i18n.get(type, this.config), + false, ); - pane.appendChild(back); + // Go back via button click + on(backButton, 'click', () => { + controls.showMenuPanel.call(this, 'home', false); + }); - const options = createElement('ul'); + // Add to pane + pane.appendChild(backButton); + + // Menu + pane.appendChild( + createElement('div', { + role: 'menu', + }), + ); - pane.appendChild(options); inner.appendChild(pane); - this.elements.settings.panes[type] = pane; + this.elements.settings.buttons[type] = menuItem; + this.elements.settings.panels[type] = pane; }); - form.appendChild(inner); - menu.appendChild(form); - container.appendChild(menu); + popup.appendChild(inner); + control.appendChild(popup); + container.appendChild(control); - this.elements.settings.form = form; - this.elements.settings.menu = menu; + this.elements.settings.popup = popup; + this.elements.settings.menu = control; } // Picture in picture button @@ -1350,18 +1688,25 @@ const controls = { // Toggle fullscreen button if (this.config.controls.includes('fullscreen')) { - container.appendChild(controls.createButton.call(this, 'fullscreen')); + container.appendChild( + controls.createButton.call(this, 'fullscreen'), + ); } // Larger overlaid play button if (this.config.controls.includes('play-large')) { - this.elements.container.appendChild(controls.createButton.call(this, 'play-large')); + this.elements.container.appendChild( + controls.createButton.call(this, 'play-large'), + ); } this.elements.controls = container; if (this.isHTML5) { - controls.setQualityMenu.call(this, html5.getQualityOptions.call(this)); + controls.setQualityMenu.call( + this, + html5.getQualityOptions.call(this), + ); } controls.setSpeedMenu.call(this); @@ -1448,7 +1793,9 @@ const controls = { // Inject to custom location if (is.string(this.config.selectors.controls.container)) { - target = document.querySelector(this.config.selectors.controls.container); + target = document.querySelector( + this.config.selectors.controls.container, + ); } // Inject into the container by default @@ -1457,7 +1804,9 @@ const controls = { } // Inject controls HTML (needs to be before captions, hence "afterbegin") - const insertMethod = is.element(container) ? 'insertAdjacentElement' : 'insertAdjacentHTML'; + const insertMethod = is.element(container) + ? 'insertAdjacentElement' + : 'insertAdjacentHTML'; target[insertMethod]('afterbegin', container); // Find the elements if need be @@ -1473,7 +1822,9 @@ const controls = { // Setup tooltips if (this.config.tooltips.controls) { const { classNames, selectors } = this.config; - const selector = `${selectors.controls.wrapper} ${selectors.labels} .${classNames.hidden}`; + const selector = `${selectors.controls.wrapper} ${ + selectors.labels + } .${classNames.hidden}`; const labels = getElements.call(this, selector); Array.from(labels).forEach(label => { |