diff options
Diffstat (limited to 'dist/plyr.js')
-rw-r--r-- | dist/plyr.js | 1028 |
1 files changed, 929 insertions, 99 deletions
diff --git a/dist/plyr.js b/dist/plyr.js index 4cc8a6c1..9eba00fa 100644 --- a/dist/plyr.js +++ b/dist/plyr.js @@ -675,6 +675,7 @@ typeof navigator === "object" && (function (global, factory) { isIE: /* @cc_on!@ */ !!document.documentMode, + isEdge: window.navigator.userAgent.includes('Edge'), isWebkit: 'WebkitAppearance' in document.documentElement.style && !/Edge/.test(navigator.userAgent), isIPhone: /(iPhone|iPod)/gi.test(navigator.platform), isIos: /(iPad|iPhone|iPod)/gi.test(navigator.platform) @@ -733,12 +734,16 @@ typeof navigator === "object" && (function (global, factory) { // Check for mime type support against a player instance // Credits: http://diveintohtml5.info/everything.html // Related: http://www.leanbackplayer.com/test/h5mt.html - mime: function mime(inputType) { - var _inputType$split = inputType.split('/'), - _inputType$split2 = _slicedToArray(_inputType$split, 1), - mediaType = _inputType$split2[0]; + mime: function mime(input) { + if (is.empty(input)) { + return false; + } + + var _input$split = input.split('/'), + _input$split2 = _slicedToArray(_input$split, 1), + mediaType = _input$split2[0]; - var type = inputType; // Verify we're using HTML5 and there's no media type mismatch + var type = input; // Verify we're using HTML5 and there's no media type mismatch if (!this.isHTML5 || mediaType !== this.type) { return false; @@ -746,7 +751,7 @@ typeof navigator === "object" && (function (global, factory) { if (Object.keys(defaultCodecs).includes(type)) { - type += "; codecs=\"".concat(defaultCodecs[inputType], "\""); + type += "; codecs=\"".concat(defaultCodecs[input], "\""); } try { @@ -782,10 +787,16 @@ typeof navigator === "object" && (function (global, factory) { return []; } - var sources = Array.from(this.media.querySelectorAll('source')); // Filter out unsupported sources + var sources = Array.from(this.media.querySelectorAll('source')); // Filter out unsupported sources (if type is specified) return sources.filter(function (source) { - return support.mime.call(_this, source.getAttribute('type')); + var type = source.getAttribute('type'); + + if (is.empty(type)) { + return true; + } + + return support.mime.call(_this, type); }); }, // Get quality levels @@ -1238,13 +1249,13 @@ typeof navigator === "object" && (function (global, factory) { // ========================================================================== var getHours = function getHours(value) { - return parseInt(value / 60 / 60 % 60, 10); + return Math.trunc(value / 60 / 60 % 60, 10); }; var getMinutes = function getMinutes(value) { - return parseInt(value / 60 % 60, 10); + return Math.trunc(value / 60 % 60, 10); }; var getSeconds = function getSeconds(value) { - return parseInt(value % 60, 10); + return Math.trunc(value % 60, 10); }; // Format time to UI friendly string function formatTime() { @@ -2622,7 +2633,7 @@ typeof navigator === "object" && (function (global, factory) { var update = true; // If function, run it and use output if (is.function(this.config.controls)) { - this.config.controls = this.config.controls.call(this.props); + this.config.controls = this.config.controls.call(this, props); } // Convert falsy controls to empty array (primarily for empty strings) @@ -2713,10 +2724,10 @@ typeof navigator === "object" && (function (global, factory) { addProperty(button); } }); - } // Edge sometimes doesn't finish the paint so force a redraw + } // Edge sometimes doesn't finish the paint so force a repaint - if (window.navigator.userAgent.includes('Edge')) { + if (browser.isEdge) { repaint(target); } // Setup tooltips @@ -3227,7 +3238,7 @@ typeof navigator === "object" && (function (global, factory) { enabled: true, // Allow fullscreen? fallback: true, - // Fallback for vintage browsers + // Fallback using full viewport/window iosNative: false // Use the native fullscreen in iOS (disables custom controls) }, @@ -3428,7 +3439,12 @@ typeof navigator === "object" && (function (global, factory) { supported: 'plyr--airplay-supported', active: 'plyr--airplay-active' }, - tabFocus: 'plyr__tab-focus' + tabFocus: 'plyr__tab-focus', + previewThumbnails: { + thumbnailContainer: 'plyr__preview-thumbnail-container', + scrubbingContainer: 'plyr__preview-scrubbing-container', + timeTextContainer: 'plyr__preview-time-text-container' + } }, // Embed attributes attributes: { @@ -3446,6 +3462,12 @@ typeof navigator === "object" && (function (global, factory) { ads: { enabled: false, publisherId: '' + }, + // YouTube nocookies mode + noCookie: false, + // Preview Thumbnails plugin + previewThumbnails: { + enabled: false } }; @@ -3476,7 +3498,7 @@ typeof navigator === "object" && (function (global, factory) { function getProviderByUrl(url) { // YouTube - if (/^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$/.test(url)) { + if (/^(https?:\/\/)?(www\.)?(youtube\.com|youtube-nocookie\.com|youtu\.?be)\/.+$/.test(url)) { return providers.youtube; } // Vimeo @@ -3622,7 +3644,9 @@ typeof navigator === "object" && (function (global, factory) { this.scrollPosition = { x: 0, y: 0 - }; // Register event listeners + }; // Force the use of 'full window/browser' rather than fullscreen + + this.forceFallback = player.config.fullscreen.fallback === 'force'; // Register event listeners // Handle event (incase user presses escape etc) on.call(this.player, document, this.prefix === 'ms' ? 'MSFullscreenChange' : "".concat(this.prefix, "fullscreenchange"), function () { @@ -3648,7 +3672,17 @@ typeof navigator === "object" && (function (global, factory) { // Update UI value: function update() { if (this.enabled) { - this.player.debug.log("".concat(Fullscreen.native ? 'Native' : 'Fallback', " fullscreen enabled")); + var mode; + + if (this.forceFallback) { + mode = 'Fallback (forced)'; + } else if (Fullscreen.native) { + mode = 'Native'; + } else { + mode = 'Fallback'; + } + + this.player.debug.log("".concat(mode, " fullscreen enabled")); } else { this.player.debug.log('Fullscreen not supported and fallback disabled'); } // Add styling hook to show button @@ -3667,7 +3701,7 @@ typeof navigator === "object" && (function (global, factory) { if (browser.isIos && this.player.config.fullscreen.iosNative) { this.target.webkitEnterFullscreen(); - } else if (!Fullscreen.native) { + } else if (!Fullscreen.native || this.forceFallback) { toggleFallback.call(this, true); } else if (!this.prefix) { this.target.requestFullscreen(); @@ -3687,7 +3721,7 @@ typeof navigator === "object" && (function (global, factory) { if (browser.isIos && this.player.config.fullscreen.iosNative) { this.target.webkitExitFullscreen(); this.player.play(); - } else if (!Fullscreen.native) { + } else if (!Fullscreen.native || this.forceFallback) { toggleFallback.call(this, false); } else if (!this.prefix) { (document.cancelFullScreen || document.exitFullscreen).call(document); @@ -3707,6 +3741,13 @@ typeof navigator === "object" && (function (global, factory) { } } }, { + key: "usingNative", + // If we're actually using native + get: function get() { + return Fullscreen.native && !this.forceFallback; + } // Get the prefix for handlers + + }, { key: "enabled", // Determine if fullscreen is enabled get: function get() { @@ -3721,7 +3762,7 @@ typeof navigator === "object" && (function (global, factory) { } // Fallback using classname - if (!Fullscreen.native) { + if (!Fullscreen.native || this.forceFallback) { return hasClass(this.target, this.player.config.classNames.fullscreen.fallback); } @@ -3738,8 +3779,7 @@ typeof navigator === "object" && (function (global, factory) { key: "native", get: function get() { return !!(document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled); - } // Get the prefix for handlers - + } }, { key: "prefix", get: function get() { @@ -4006,6 +4046,44 @@ typeof navigator === "object" && (function (global, factory) { } }; + /* function reduceAspectRatio(width, height) { + const getRatio = (w, h) => (h === 0 ? w : getRatio(h, w % h)); + const ratio = getRatio(width, height); + return `${width / ratio}:${height / ratio}`; + } */ + // Set aspect ratio for responsive container + + function setAspectRatio(input) { + var ratio = input; + + if (!is.string(ratio) && !is.nullOrUndefined(this.embed)) { + ratio = this.embed.ratio; + } + + if (!is.string(ratio)) { + ratio = this.config.ratio; + } + + var _ratio$split$map = ratio.split(':').map(Number), + _ratio$split$map2 = _slicedToArray(_ratio$split$map, 2), + x = _ratio$split$map2[0], + y = _ratio$split$map2[1]; + + var padding = 100 / x * y; + this.elements.wrapper.style.paddingBottom = "".concat(padding, "%"); // For Vimeo we have an extra <div> to hide the standard controls and UI + + if (this.isVimeo && this.supported.ui) { + var height = 240; + var offset = (height - padding) / (height / 50); + this.media.style.transform = "translateY(-".concat(offset, "%)"); + } + + return { + padding: padding, + ratio: ratio + }; + } + var Listeners = /*#__PURE__*/ function () { @@ -4166,7 +4244,7 @@ typeof navigator === "object" && (function (global, factory) { // So we only need to worry about non native - if (!player.fullscreen.enabled && player.fullscreen.active && code === 27) { + if (code === 27 && !player.fullscreen.usingNative && player.fullscreen.active) { player.fullscreen.toggle(); } // Store last code for next cycle @@ -4259,9 +4337,11 @@ typeof navigator === "object" && (function (global, factory) { key: "container", value: function container() { var player = this.player; - var elements = player.elements; // Keyboard shortcuts + var config = player.config, + elements = player.elements, + timers = player.timers; // Keyboard shortcuts - if (!player.config.keyboard.global && player.config.keyboard.focused) { + if (!config.keyboard.global && config.keyboard.focused) { on.call(player, elements.container, 'keydown keyup', this.handleKey, false); } // Toggle controls on mouse events and entering fullscreen @@ -4285,17 +4365,92 @@ typeof navigator === "object" && (function (global, factory) { } // Clear timer - clearTimeout(player.timers.controls); // Set new timer to prevent flicker when seeking + clearTimeout(timers.controls); // Set new timer to prevent flicker when seeking - player.timers.controls = setTimeout(function () { + timers.controls = setTimeout(function () { return ui.toggleControls.call(player, false); }, delay); + }); // Force edge to repaint on exit fullscreen + // TODO: Fix weird bug where Edge doesn't re-draw when exiting fullscreen + + /* if (browser.isEdge) { + on.call(player, elements.container, 'exitfullscreen', () => { + setTimeout(() => repaint(elements.container), 100); + }); + } */ + // Set a gutter for Vimeo + + var setGutter = function setGutter(ratio, padding, toggle) { + if (!player.isVimeo) { + return; + } + + var target = player.elements.wrapper.firstChild; + + var _ratio$split$map = ratio.split(':').map(Number), + _ratio$split$map2 = _slicedToArray(_ratio$split$map, 2), + height = _ratio$split$map2[1]; + + var _player$embed$ratio$s = player.embed.ratio.split(':').map(Number), + _player$embed$ratio$s2 = _slicedToArray(_player$embed$ratio$s, 2), + videoWidth = _player$embed$ratio$s2[0], + videoHeight = _player$embed$ratio$s2[1]; + + target.style.maxWidth = toggle ? "".concat(height / videoHeight * videoWidth, "px") : null; + target.style.margin = toggle ? '0 auto' : null; + }; // Resize on fullscreen change + + + var setPlayerSize = function setPlayerSize(measure) { + // If we don't need to measure the viewport + if (!measure) { + return setAspectRatio.call(player); + } + + var rect = elements.container.getBoundingClientRect(); + var width = rect.width, + height = rect.height; + return setAspectRatio.call(player, "".concat(width, ":").concat(height)); + }; + + var resized = function resized() { + window.clearTimeout(timers.resized); + timers.resized = window.setTimeout(setPlayerSize, 50); + }; + + on.call(player, elements.container, 'enterfullscreen exitfullscreen', function (event) { + var _player$fullscreen = player.fullscreen, + target = _player$fullscreen.target, + usingNative = _player$fullscreen.usingNative; // Ignore for iOS native + + if (!player.isEmbed || target !== elements.container) { + return; + } + + var isEnter = event.type === 'enterfullscreen'; // Set the player size when entering fullscreen to viewport size + + var _setPlayerSize = setPlayerSize(isEnter), + padding = _setPlayerSize.padding, + ratio = _setPlayerSize.ratio; // Set Vimeo gutter + + + setGutter(ratio, padding, isEnter); // If not using native fullscreen, we need to check for resizes of viewport + + if (!usingNative) { + if (isEnter) { + on.call(player, window, 'resize', resized); + } else { + off.call(player, window, 'resize', resized); + } + } }); } // Listen for media events }, { key: "media", value: function media() { + var _this = this; + var player = this.player; var elements = player.elements; // Time change on media @@ -4376,10 +4531,11 @@ typeof navigator === "object" && (function (global, factory) { } if (player.ended) { - player.restart(); - player.play(); + _this.proxy(event, player.restart, 'restart'); + + _this.proxy(event, player.play, 'play'); } else { - player.togglePlay(); + _this.proxy(event, player.togglePlay, 'play'); } }); } // Disable right click @@ -4454,21 +4610,21 @@ typeof navigator === "object" && (function (global, factory) { }, { key: "bind", value: function bind(element, type, defaultHandler, customHandlerKey) { - var _this = this; + var _this2 = this; var passive = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; var player = this.player; var customHandler = player.config.listeners[customHandlerKey]; var hasCustomHandler = is.function(customHandler); on.call(player, element, type, function (event) { - return _this.proxy(event, defaultHandler, customHandlerKey); + return _this2.proxy(event, defaultHandler, customHandlerKey); }, passive && !hasCustomHandler); } // Listen for control events }, { key: "controls", value: function controls$$1() { - var _this2 = this; + var _this3 = this; var player = this.player; var elements = player.elements; // IE doesn't support input event, so we fallback to change @@ -4477,7 +4633,7 @@ typeof navigator === "object" && (function (global, factory) { if (elements.buttons.play) { Array.from(elements.buttons.play).forEach(function (button) { - _this2.bind(button, 'click', player.togglePlay, 'play'); + _this3.bind(button, 'click', player.togglePlay, 'play'); }); } // Pause @@ -4584,7 +4740,7 @@ typeof navigator === "object" && (function (global, factory) { if (browser.isIos) { var inputs = getElements.call(player, 'input[type="range"]'); Array.from(inputs).forEach(function (input) { - return _this2.bind(input, inputEvent, function (event) { + return _this3.bind(input, inputEvent, function (event) { return repaint(event.target); }); }); @@ -4610,7 +4766,7 @@ typeof navigator === "object" && (function (global, factory) { if (browser.isWebkit) { Array.from(getElements.call(player, 'input[type="range"]')).forEach(function (element) { - _this2.bind(element, 'input', function (event) { + _this3.bind(element, 'input', function (event) { return controls.updateRangeFill.call(player, event.target); }); }); @@ -4657,7 +4813,7 @@ typeof navigator === "object" && (function (global, factory) { toggleClass(elements.controls, config.classNames.noTransition, false); }, 0); // Delay a little more for mouse users - var delay = _this2.touch ? 3000 : 4000; // Clear timer + var delay = _this3.touch ? 3000 : 4000; // Clear timer clearTimeout(timers.controls); // Hide again after delay @@ -4845,8 +5001,8 @@ typeof navigator === "object" && (function (global, factory) { if (!e.sheet.cssText.length) result = 'e'; } catch (x) { // sheets objects created from load errors don't allow access to - // `cssText` - result = 'e'; + // `cssText` (unless error is Code:18 SecurityError) + if (x.code != 18) result = 'e'; } } @@ -5014,16 +5170,6 @@ typeof navigator === "object" && (function (global, factory) { var regex = /^.*(vimeo.com\/|video\/)(\d+).*/; return url.match(regex) ? RegExp.$2 : url; - } // Get aspect ratio for dimensions - - - function getAspectRatio(width, height) { - var getRatio = function getRatio(w, h) { - return h === 0 ? w : getRatio(h, w % h); - }; - - var ratio = getRatio(width, height); - return "".concat(width / ratio, ":").concat(height / ratio); } // Set playback state and trigger change (only on actual change) @@ -5045,7 +5191,7 @@ typeof navigator === "object" && (function (global, factory) { // Add embed class for responsive toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Set intial ratio - vimeo.setAspectRatio.call(this); // Load the API if not already + setAspectRatio.call(this); // Load the API if not already if (!is.object(window.Vimeo)) { loadScript(this.config.urls.vimeo.sdk).then(function () { @@ -5057,24 +5203,6 @@ typeof navigator === "object" && (function (global, factory) { vimeo.ready.call(this); } }, - // Set aspect ratio - // For Vimeo we have an extra 300% height <div> to hide the standard controls and UI - setAspectRatio: function setAspectRatio(input) { - var _split$map = (is.string(input) ? input : this.config.ratio).split(':').map(Number), - _split$map2 = _slicedToArray(_split$map, 2), - x = _split$map2[0], - y = _split$map2[1]; - - var padding = 100 / x * y; - vimeo.padding = padding; - this.elements.wrapper.style.paddingBottom = "".concat(padding, "%"); - - if (this.supported.ui) { - var height = 240; - var offset = (height - padding) / (height / 50); - this.media.style.transform = "translateY(-".concat(offset, "%)"); - } - }, // API Ready ready: function ready$$1() { var _this2 = this; @@ -5084,7 +5212,7 @@ typeof navigator === "object" && (function (global, factory) { var options = { loop: player.config.loop.active, autoplay: player.autoplay, - // muted: player.muted, + muted: player.muted, byline: false, portrait: false, title: false, @@ -5270,8 +5398,12 @@ typeof navigator === "object" && (function (global, factory) { }); // Set aspect ratio based on video size Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(function (dimensions) { - vimeo.ratio = getAspectRatio(dimensions[0], dimensions[1]); - vimeo.setAspectRatio.call(_this2, vimeo.ratio); + var _dimensions = _slicedToArray(dimensions, 2), + width = _dimensions[0], + height = _dimensions[1]; + + player.embed.ratio = "".concat(width, ":").concat(height); + setAspectRatio.call(_this2, player.embed.ratio); }); // Set autopause player.embed.setAutopause(player.config.autopause).then(function (state) { @@ -5362,24 +5494,6 @@ typeof navigator === "object" && (function (global, factory) { player.embed.on('error', function (detail) { player.media.error = detail; triggerEvent.call(player, player.media, 'error'); - }); // Set height/width on fullscreen - - player.on('enterfullscreen exitfullscreen', function (event) { - var target = player.fullscreen.target; // Ignore for iOS native - - if (target !== player.elements.container) { - return; - } - - var toggle = event.type === 'enterfullscreen'; - - var _vimeo$ratio$split$ma = vimeo.ratio.split(':').map(Number), - _vimeo$ratio$split$ma2 = _slicedToArray(_vimeo$ratio$split$ma, 2), - x = _vimeo$ratio$split$ma2[0], - y = _vimeo$ratio$split$ma2[1]; - - var dimension = x > y ? 'width' : 'height'; - target.style[dimension] = toggle ? "".concat(vimeo.padding, "%") : null; }); // Rebuild UI setTimeout(function () { @@ -5418,7 +5532,7 @@ typeof navigator === "object" && (function (global, factory) { // Add embed class for responsive toggleClass(this.elements.wrapper, this.config.classNames.embed, true); // Set aspect ratio - youtube.setAspectRatio.call(this); // Setup API + setAspectRatio.call(this); // Setup API if (is.object(window.YT) && is.function(window.YT.Player)) { youtube.ready.call(this); @@ -5473,11 +5587,6 @@ typeof navigator === "object" && (function (global, factory) { }).catch(function () {}); } }, - // Set aspect ratio - setAspectRatio: function setAspectRatio() { - var ratio = this.config.ratio.split(':'); - this.elements.wrapper.style.paddingBottom = "".concat(100 / ratio[0] * ratio[1], "%"); - }, // API ready ready: function ready$$1() { var player = this; // Ignore already setup (race condition) @@ -5531,6 +5640,7 @@ typeof navigator === "object" && (function (global, factory) { player.embed = new window.YT.Player(id, { videoId: videoId, + host: player.config.noCookie ? 'https://www.youtube-nocookie.com' : undefined, playerVars: { autoplay: player.config.autoplay ? 1 : 0, // Autoplay @@ -6447,6 +6557,720 @@ typeof navigator === "object" && (function (global, factory) { return Ads; }(); + /** + * Preview thumbnails for seek hover and scrubbing + * Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar + * Scrubbing: Click and drag the seek bar (desktop and mobile): shows the preview image over the entire video, as if the video is scrubbing at very high speed + * + * Notes: + * - Thumbs are set via JS settings on Plyr init, not HTML5 'track' property. Using the track property would be a bit gross, because it doesn't support custom 'kinds'. kind=metadata might be used for something else, and we want to allow multiple thumbnails tracks. Tracks must have a unique combination of 'kind' and 'label'. We would have to do something like kind=metadata,label=thumbnails1 / kind=metadata,label=thumbnails2. Square peg, round hole + * - VTT info: the image URL is relative to the VTT, not the current document. But if the url starts with a slash, it will naturally be relative to the current domain. https://support.jwplayer.com/articles/how-to-add-preview-thumbnails + * - This implementation uses multiple separate img elements. Other implementations use background-image on one element. This would be nice and simple, but Firefox and Safari have flickering issues with replacing backgrounds of larger images. It seems that Youtube perhaps only avoids this because they don't have the option for high-res previews (even the fullscreen ones, when mousedown/seeking). Images appear over the top of each other, and previous ones are discarded once the new ones have been rendered + */ + + var PreviewThumbnails = + /*#__PURE__*/ + function () { + /** + * PreviewThumbnails constructor. + * @param {object} player + * @return {PreviewThumbnails} + */ + function PreviewThumbnails(player) { + _classCallCheck(this, PreviewThumbnails); + + this.player = player; + this.thumbnailsDefs = []; + this.lastMousemoveEventTime = Date.now(); + this.mouseDown = false; + this.loadedImages = []; + + if (this.enabled) { + this.load(); + } + } + + _createClass(PreviewThumbnails, [{ + key: "load", + value: function load() { + var _this = this; + + // Turn off the regular seek tooltip + this.player.config.tooltips.seek = false; + this.getThumbnailsDefs().then(function () { + // Initiate DOM listeners so that our preview thumbnails can be used + _this.listeners(); // Build HTML DOM elements + + + _this.elements(); // Check to see if thumb container size was specified manually in CSS + + + _this.determineContainerAutoSizing(); + }); + } // Download VTT files and parse them + + }, { + key: "getThumbnailsDefs", + value: function getThumbnailsDefs() { + var _this2 = this; + + return new Promise(function (resolve, reject) { + if (!_this2.player.config.previewThumbnails.src) { + throw new Error('Missing previewThumbnails.src config attribute'); + } // previewThumbnails.src can be string or list. If string, convert into single-element list + + + var configSrc = _this2.player.config.previewThumbnails.src; + var urls = typeof configSrc === 'string' ? [configSrc] : configSrc; + var promises = []; // Loop through each src url. Download and process the VTT file, storing the resulting data in this.thumbnailsDefs + + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = urls[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var url = _step.value; + promises.push(_this2.getThumbnailDef(url)); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return != null) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + Promise.all(promises).then(function () { + // Sort smallest to biggest (e.g., [120p, 480p, 1080p]) + _this2.thumbnailsDefs.sort(function (x, y) { + return x.height - y.height; + }); + + _this2.player.debug.log('Preview thumbnails: thumbnailsDefs: ' + JSON.stringify(_this2.thumbnailsDefs, null, 4)); + + resolve(); + }); + }); + } // Process individual VTT file + + }, { + key: "getThumbnailDef", + value: function getThumbnailDef(url) { + var _this3 = this; + + return new Promise(function (resolve, reject) { + fetch(url).then(function (response) { + var thumbnailsDef = { + frames: _this3.parseVtt(response), + height: null, + urlPrefix: '' + }; // If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file + // If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank + + if (!thumbnailsDef.frames[0].text.startsWith('/')) { + thumbnailsDef.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1); + } // Download the first frame, so that we can determine/set the height of this thumbnailsDef + + + var tempImage = new Image(); + tempImage.src = thumbnailsDef.urlPrefix + thumbnailsDef.frames[0].text; + + tempImage.onload = function () { + thumbnailsDef.height = tempImage.naturalHeight; + thumbnailsDef.width = tempImage.naturalWidth; + + _this3.thumbnailsDefs.push(thumbnailsDef); + + resolve(); + }; + }); + }); + } + /** + * Setup hooks for Plyr and window events + */ + + }, { + key: "listeners", + value: function listeners() { + var _this4 = this; + + // Mouse hover over seek bar + on.call(this.player, this.player.elements.progress, 'mousemove', function (event) { + // Wait until media has a duration + if (_this4.player.media.duration) { + // Calculate seek hover position as approx video seconds + var clientRect = _this4.player.elements.progress.getBoundingClientRect(); + + var percentage = 100 / clientRect.width * (event.pageX - clientRect.left); + _this4.seekTime = _this4.player.media.duration * (percentage / 100); + if (_this4.seekTime < 0) _this4.seekTime = 0; // The mousemove fires for 10+px out to the left + + if (_this4.seekTime > _this4.player.media.duration - 1) _this4.seekTime = _this4.player.media.duration - 1; // Took 1 second off the duration for safety, because different players can disagree on the real duration of a video + + _this4.mousePosX = event.pageX; // Set time text inside image container + + _this4.player.elements.display.previewThumbnailTimeText.innerText = formatTime(_this4.seekTime); // Download and show image + + _this4.showImageAtCurrentTime(); + } + }); // Touch device seeking - performs same function as above + + on.call(this.player, this.player.elements.progress, 'touchmove', function (event) { + // Wait until media has a duration + if (_this4.player.media.duration) { + // Calculate seek hover position as approx video seconds + _this4.seekTime = _this4.player.media.duration * (_this4.player.elements.inputs.seek.value / 100); // Download and show image + + _this4.showImageAtCurrentTime(); + } + }); // Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering + + on.call(this.player, this.player.elements.progress, 'mouseleave click', function () { + _this4.hideThumbContainer(true); + }); + this.player.on('play', function () { + _this4.hideThumbContainer(true); + }); + this.player.on('seeked', function () { + _this4.hideThumbContainer(false); + }); // Show scrubbing preview + + on.call(this.player, this.player.elements.progress, 'mousedown touchstart', function (event) { + // Only act on left mouse button (0), or touch device (!event.button) + if (!event.button || event.button === 0) { + _this4.mouseDown = true; // Wait until media has a duration + + if (_this4.player.media.duration) { + _this4.showScrubbingContainer(); + + _this4.hideThumbContainer(true); // Download and show image + + + _this4.showImageAtCurrentTime(); + } + } + }); + on.call(this.player, this.player.media, 'timeupdate', function () { + _this4.timeAtLastTimeupdate = _this4.player.media.currentTime; + }); + on.call(this.player, this.player.elements.progress, 'mouseup touchend', function () { + _this4.mouseDown = false; // Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview + + if (Math.ceil(_this4.timeAtLastTimeupdate) === Math.ceil(_this4.player.media.currentTime)) { + // The video was already seeked/loaded at the chosen time - hide immediately + _this4.hideScrubbingContainer(); + } else { + // The video hasn't seeked yet. Wait for that + once.call(_this4.player, _this4.player.media, 'timeupdate', function () { + // Re-check mousedown - we might have already started scrubbing again + if (!_this4.mouseDown) { + _this4.hideScrubbingContainer(); + } + }); + } + }); + } + /** + * Create HTML elements for image containers + */ + + }, { + key: "elements", + value: function elements() { + // Create HTML element: plyr__preview-thumbnail-container + var previewThumbnailContainer = createElement('div', { + class: this.player.config.classNames.previewThumbnails.thumbnailContainer + }); + this.player.elements.progress.appendChild(previewThumbnailContainer); + this.player.elements.display.previewThumbnailContainer = previewThumbnailContainer; // Create HTML element, parent+span: time text (e.g., 01:32:00) + + var timeTextContainer = createElement('div', { + class: this.player.config.classNames.previewThumbnails.timeTextContainer + }); + this.player.elements.display.previewThumbnailContainer.appendChild(timeTextContainer); + var timeText = createElement('span', {}, '00:00'); + timeTextContainer.appendChild(timeText); + this.player.elements.display.previewThumbnailTimeText = timeText; // Create HTML element: plyr__preview-scrubbing-container + + var previewScrubbingContainer = createElement('div', { + class: this.player.config.classNames.previewThumbnails.scrubbingContainer + }); + this.player.elements.wrapper.appendChild(previewScrubbingContainer); + this.player.elements.display.previewScrubbingContainer = previewScrubbingContainer; + } + }, { + key: "showImageAtCurrentTime", + value: function showImageAtCurrentTime() { + var _this5 = this; + + if (this.mouseDown) { + this.setScrubbingContainerSize(); + } else { + this.showThumbContainer(); + this.setThumbContainerSizeAndPos(); + } // Find the desired thumbnail index + + + var thumbNum = this.thumbnailsDefs[0].frames.findIndex(function (frame) { + return _this5.seekTime >= frame.startTime && _this5.seekTime <= frame.endTime; + }); + var qualityIndex = 0; // Check to see if we've already downloaded higher quality versions of this image + + for (var i = 1; i < this.thumbnailsDefs.length; i++) { + if (this.loadedImages.includes(this.thumbnailsDefs[i].frames[thumbNum].text)) { + qualityIndex = i; + } + } // Only proceed if either thumbnum or thumbfilename has changed + + + if (thumbNum !== this.showingThumb) { + this.showingThumb = thumbNum; + this.loadImage(qualityIndex); + } + } // Show the image that's currently specified in this.showingThumb + + }, { + key: "loadImage", + value: function loadImage() { + var _this6 = this; + + var qualityIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; + var thumbNum = this.showingThumb; + var frame = this.thumbnailsDefs[qualityIndex].frames[thumbNum]; + var thumbFilename = this.thumbnailsDefs[qualityIndex].frames[thumbNum].text; + var urlPrefix = this.thumbnailsDefs[qualityIndex].urlPrefix; + var thumbURL = urlPrefix + thumbFilename; + + if (!this.currentImageElement || this.currentImageElement.getAttribute('data-thumbfilename') !== thumbFilename) { + // If we're already loading a previous image, remove its onload handler - we don't want it to load after this one + // Only do this if not using jpeg sprites. Without jpeg sprites we really want to show as many images as possible, as a best-effort + if (this.loadingImage && this.usingJpegSprites) this.loadingImage.onload = null; // We're building and adding a new image. In other implementations of similar functionality (Youtube), background image is instead used. But this causes issues with larger images in Firefox and Safari - switching between background images causes a flicker. Putting a new image over the top does not + + var previewImage = new Image(); + previewImage.src = thumbURL; + previewImage.setAttribute('data-thumbnum', thumbNum); + previewImage.setAttribute('data-thumbfilename', thumbFilename); + this.showingThumbFilename = thumbFilename; // For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function... + + previewImage.onload = function () { + return _this6.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true); + }; + + this.loadingImage = previewImage; + this.removeOldImages(previewImage); + } else { + // Update the existing image + this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false); + this.currentImageElement.setAttribute('data-thumbnum', thumbNum); + this.removeOldImages(this.currentImageElement); + } + } + }, { + key: "showImage", + value: function showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename) { + var newImage = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : true; + this.player.debug.log('Showing thumb: ' + thumbFilename + '. num: ' + thumbNum + '. qual: ' + qualityIndex + '. newimg: ' + newImage); + this.setImageSizeAndOffset(previewImage, frame); + + if (newImage) { + this.currentContainer.appendChild(previewImage); + this.currentImageElement = previewImage; + if (!this.loadedImages.includes(thumbFilename)) this.loadedImages.push(thumbFilename); + } // Preload images before and after the current one + // Show higher quality of the same frame + // Each step here has a short time delay, and only continues if still hovering/seeking the same spot. This is to protect slow connections from overloading + + + this.preloadNearby(thumbNum, true).then(this.preloadNearby(thumbNum, false)).then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename)); + } // Remove all preview images that aren't the designated current image + + }, { + key: "removeOldImages", + value: function removeOldImages(currentImage) { + var _this7 = this; + + // Get a list of all images, convert it from a DOM list to an array + var allImages = Array.from(this.currentContainer.children); + + var _loop = function _loop() { + var image = allImages[_i]; + + if (image.tagName === 'IMG') { + var removeDelay = _this7.usingJpegSprites ? 500 : 1000; + + if (image.getAttribute('data-thumbnum') !== currentImage.getAttribute('data-thumbnum') && !image.getAttribute('data-deleting')) { + // Wait 200ms, as the new image can take some time to show on certain browsers (even though it was downloaded before showing). This will prevent flicker, and show some generosity towards slower clients + // First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function + image.setAttribute('data-deleting', 'true'); + var currentContainer = _this7.currentContainer; // This has to be set before the timeout - to prevent issues switching between hover and scrub + + setTimeout(function () { + currentContainer.removeChild(image); + + _this7.player.debug.log('Removing thumb: ' + image.getAttribute('data-thumbfilename')); + }, removeDelay); + } + } + }; + + for (var _i = 0; _i < allImages.length; _i++) { + _loop(); + } + } // Preload images before and after the current one. Only if the user is still hovering/seeking the same frame + // This will only preload the lowest quality + + }, { + key: "preloadNearby", + value: function preloadNearby(thumbNum) { + var _this8 = this; + + var forward = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; + return new Promise(function (resolve, reject) { + setTimeout(function () { + var oldThumbFilename = _this8.thumbnailsDefs[0].frames[thumbNum].text; + + if (_this8.showingThumbFilename === oldThumbFilename) { + // Find the nearest thumbs with different filenames. Sometimes it'll be the next index, but in the case of jpeg sprites, it might be 100+ away + var thumbnailsDefsCopy; + + if (forward) { + thumbnailsDefsCopy = _this8.thumbnailsDefs[0].frames.slice(thumbNum); + } else { + thumbnailsDefsCopy = _this8.thumbnailsDefs[0].frames.slice(0, thumbNum).reverse(); + } + + var foundOne = false; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + var _loop2 = function _loop2() { + var frame = _step2.value; + var newThumbFilename = frame.text; + + if (newThumbFilename !== oldThumbFilename) { + // Found one with a different filename. Make sure it hasn't already been loaded on this page visit + if (!_this8.loadedImages.includes(newThumbFilename)) { + foundOne = true; + + _this8.player.debug.log('Preloading thumb filename: ' + newThumbFilename); + + var urlPrefix = _this8.thumbnailsDefs[0].urlPrefix; + var thumbURL = urlPrefix + newThumbFilename; + var previewImage = new Image(); + previewImage.src = thumbURL; + + previewImage.onload = function () { + _this8.player.debug.log('Preloaded thumb filename: ' + newThumbFilename); + + if (!_this8.loadedImages.includes(newThumbFilename)) _this8.loadedImages.push(newThumbFilename); // We don't resolve until the thumb is loaded + + resolve(); + }; + } + + return "break"; + } + }; + + for (var _iterator2 = thumbnailsDefsCopy[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _ret = _loop2(); + + if (_ret === "break") break; + } // If there are none to preload then we want to resolve immediately + + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + if (!foundOne) resolve(); + } + }, 300); + }); + } // If user has been hovering current image for half a second, look for a higher quality one + + }, { + key: "getHigherQuality", + value: function getHigherQuality(currentQualityIndex, previewImage, frame, thumbFilename) { + var _this9 = this; + + if (currentQualityIndex < this.thumbnailsDefs.length - 1) { + // Only use the higher quality version if it's going to look any better - if the current thumb is of a lower pixel density than the thumbnail container + var previewImageHeight = previewImage.naturalHeight; + if (this.usingJpegSprites) previewImageHeight = frame.h; + + if (previewImageHeight < this.thumbContainerHeight) { + // Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while + setTimeout(function () { + // Make sure the mouse hasn't already moved on and started hovering at another image + if (_this9.showingThumbFilename === thumbFilename) { + _this9.player.debug.log('Showing higher quality thumb for: ' + thumbFilename); + + _this9.loadImage(currentQualityIndex + 1); + } + }, 300); + } + } + } + }, { + key: "showThumbContainer", + value: function showThumbContainer() { + this.player.elements.display.previewThumbnailContainer.style.opacity = 1; + } + }, { + key: "hideThumbContainer", + value: function hideThumbContainer() { + var clearShowing = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + this.player.elements.display.previewThumbnailContainer.style.opacity = 0; + + if (clearShowing) { + this.showingThumb = null; + this.showingThumbFilename = null; + } + } + }, { + key: "showScrubbingContainer", + value: function showScrubbingContainer() { + this.player.elements.display.previewScrubbingContainer.style.opacity = 1; + } + }, { + key: "hideScrubbingContainer", + value: function hideScrubbingContainer() { + this.player.elements.display.previewScrubbingContainer.style.opacity = 0; + this.showingThumb = null; + this.showingThumbFilename = null; + } + }, { + key: "determineContainerAutoSizing", + value: function determineContainerAutoSizing() { + if (this.player.elements.display.previewThumbnailContainer.clientHeight > 20) { + this.sizeSpecifiedInCSS = true; // This will prevent auto sizing in this.setThumbContainerSizeAndPos() + } + } // Set the size to be about a quarter of the size of video. Unless option dynamicSize === false, in which case it needs to be set in CSS + + }, { + key: "setThumbContainerSizeAndPos", + value: function setThumbContainerSizeAndPos() { + if (!this.sizeSpecifiedInCSS) { + var thumbWidth = this.thumbContainerHeight * this.thumbAspectRatio; + this.player.elements.display.previewThumbnailContainer.style.height = "".concat(this.thumbContainerHeight, "px"); + this.player.elements.display.previewThumbnailContainer.style.width = "".concat(thumbWidth, "px"); + } + + this.setThumbContainerPos(); + } + }, { + key: "setThumbContainerPos", + value: function setThumbContainerPos() { + var seekbarRect = this.player.elements.progress.getBoundingClientRect(); + var plyrRect = this.player.elements.container.getBoundingClientRect(); + var previewContainer = this.player.elements.display.previewThumbnailContainer; // Find the lowest and highest desired left-position, so we don't slide out the side of the video container + + var minVal = plyrRect.left - seekbarRect.left + 10; + var maxVal = plyrRect.right - seekbarRect.left - previewContainer.clientWidth - 10; // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth + + var previewPos = this.mousePosX - seekbarRect.left - previewContainer.clientWidth / 2; + + if (previewPos < minVal) { + previewPos = minVal; + } + + if (previewPos > maxVal) { + previewPos = maxVal; + } + + previewContainer.style.left = previewPos + 'px'; + } // Can't use 100% width, in case the video is a different aspect ratio to the video container + + }, { + key: "setScrubbingContainerSize", + value: function setScrubbingContainerSize() { + this.player.elements.display.previewScrubbingContainer.style.width = "".concat(this.player.media.clientWidth, "px"); + this.player.elements.display.previewScrubbingContainer.style.height = "".concat(this.player.media.clientWidth / this.thumbAspectRatio, "px"); // Can't use media.clientHeight - html5 video goes big and does black bars above and below + } // Jpeg sprites need to be offset to the correct location + + }, { + key: "setImageSizeAndOffset", + value: function setImageSizeAndOffset(previewImage, frame) { + if (this.usingJpegSprites) { + // Find difference between jpeg height and preview container height + var heightMulti = this.thumbContainerHeight / frame.h; + previewImage.style.height = "".concat(previewImage.naturalHeight * heightMulti, "px"); + previewImage.style.width = "".concat(previewImage.naturalWidth * heightMulti, "px"); + previewImage.style.left = "-".concat(Math.ceil(frame.x * heightMulti), "px"); + previewImage.style.top = "-".concat(frame.y * heightMulti, "px"); // todo: might need to round this one up too + } + } // Arg: vttDataString example: "WEBVTT\n\n1\n00:00:05.000 --> 00:00:10.000\n1080p-00001.jpg" + + }, { + key: "parseVtt", + value: function parseVtt(vttDataString) { + var processedList = []; + var frames = vttDataString.split(/\r\n\r\n|\n\n|\r\r/); + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = frames[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var frame = _step3.value; + var result = {}; + var _iteratorNormalCompletion4 = true; + var _didIteratorError4 = false; + var _iteratorError4 = undefined; + + try { + for (var _iterator4 = frame.split(/\r\n|\n|\r/)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { + var line = _step4.value; + + if (result.startTime == null) { + // The line with start and end times on it is the first line of interest + var matchTimes = line.match(/([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{2,3})( ?--> ?)([0-9]{2}):([0-9]{2}):([0-9]{2}).([0-9]{2,3})/); // Note that this currently ignores caption formatting directives that are optionally on the end of this line - fine for non-captions VTT + + if (matchTimes) { + result.startTime = Number(matchTimes[1]) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number("0." + matchTimes[4]); + result.endTime = Number(matchTimes[6]) * 60 * 60 + Number(matchTimes[7]) * 60 + Number(matchTimes[8]) + Number("0." + matchTimes[9]); + } + } else { + // If we already have the startTime, then we're definitely up to the text line(s) + if (line.trim().length > 0) { + if (!result.text) { + var lineSplit = line.trim().split('#xywh='); + result.text = lineSplit[0]; // If there's content in lineSplit[1], then we have jpeg sprites. If not, then it's just one frame per jpeg + + if (lineSplit[1]) { + var xywh = lineSplit[1].split(','); + result.x = xywh[0]; + result.y = xywh[1]; + result.w = xywh[2]; + result.h = xywh[3]; + } + } + } + } + } + } catch (err) { + _didIteratorError4 = true; + _iteratorError4 = err; + } finally { + try { + if (!_iteratorNormalCompletion4 && _iterator4.return != null) { + _iterator4.return(); + } + } finally { + if (_didIteratorError4) { + throw _iteratorError4; + } + } + } + + if (result.text) { + processedList.push(result); + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return != null) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return processedList; + } + }, { + key: "enabled", + get: function get() { + return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled; + } + }, { + key: "currentContainer", + get: function get() { + if (this.mouseDown) { + return this.player.elements.display.previewScrubbingContainer; + } else { + return this.player.elements.display.previewThumbnailContainer; + } + } + }, { + key: "usingJpegSprites", + get: function get() { + if (this.thumbnailsDefs[0].frames[0].w) { + return true; + } else { + return false; + } + } + }, { + key: "thumbAspectRatio", + get: function get() { + if (this.usingJpegSprites) { + return this.thumbnailsDefs[0].frames[0].w / this.thumbnailsDefs[0].frames[0].h; + } else { + return this.thumbnailsDefs[0].width / this.thumbnailsDefs[0].height; + } + } + }, { + key: "thumbContainerHeight", + get: function get() { + if (this.mouseDown) { + // return this.player.elements.container.clientHeight; + // return this.player.media.clientHeight; + return this.player.media.clientWidth / this.thumbAspectRatio; // Can't use media.clientHeight - html5 video goes big and does black bars above and below + } else { + // return this.player.elements.container.clientHeight / 4; + return this.player.media.clientWidth / this.thumbAspectRatio / 4; + } + } + }, { + key: "currentImageElement", + get: function get() { + if (this.mouseDown) { + return this.currentScrubbingImageElement; + } else { + return this.currentThumbnailImageElement; + } + }, + set: function set(element) { + if (this.mouseDown) { + this.currentScrubbingImageElement = element; + } else { + this.currentThumbnailImageElement = element; + } + } + }]); + + return PreviewThumbnails; + }(); + var source = { // Add elements to HTML5 media (source, tracks, etc) insertElements: function insertElements(type, attributes) { @@ -6792,7 +7616,9 @@ typeof navigator === "object" && (function (global, factory) { this.media.plyr = this; // Wrap media if (!is.element(this.elements.container)) { - this.elements.container = createElement('div'); + this.elements.container = createElement('div', { + tabindex: 0 + }); wrap(this.media, this.elements.container); } // Add style hook @@ -6830,7 +7656,11 @@ typeof navigator === "object" && (function (global, factory) { } // Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek - this.lastSeekTime = 0; + this.lastSeekTime = 0; // Setup preview thumbnails if enabled + + if (this.config.previewThumbnails.enabled) { + this.previewThumbnails = new PreviewThumbnails(this); + } } // --------------------------------------- // API // --------------------------------------- |