Merge branch 'develop' of https://github.com/Selz/plyr into develop

# Conflicts:
#	dist/plyr.js
#	dist/plyr.js.map
#	src/js/controls.js
This commit is contained in:
Sam Potts 2017-11-18 19:33:01 +11:00
commit 5a244b7fed
33 changed files with 626 additions and 631 deletions

2
demo/dist/demo.css vendored

File diff suppressed because one or more lines are too long

2
demo/dist/demo.js vendored
View File

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

File diff suppressed because one or more lines are too long

2
demo/dist/error.css vendored

File diff suppressed because one or more lines are too long

View File

@ -82,17 +82,16 @@
</header>
<main>
<video controls crossorigin playsinline loop poster="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg"
id="player">
<video controls crossorigin playsinline loop poster="media/View_From_A_Blue_Moon_Trailer-HD.jpg" id="player">
<!-- Video files -->
<source src="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4" type="video/mp4">
<source src="media/View_From_A_Blue_Moon_Trailer-HD.mp4" type="video/mp4">
<!-- Text track file -->
<track kind="captions" label="English" srclang="en" src="webvtt/View_From_A_Blue_Moon_Trailer-HD.en.vtt" default>
<track kind="captions" label="Français" srclang="fr" src="webvtt/View_From_A_Blue_Moon_Trailer-HD.fr.vtt">
<track kind="captions" label="English" srclang="en" src="media/View_From_A_Blue_Moon_Trailer-HD.en.vtt" default>
<track kind="captions" label="Français" srclang="fr" src="media/View_From_A_Blue_Moon_Trailer-HD.fr.vtt">
<!-- Fallback for browsers that don't support the <video> element -->
<a href="https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4" download>Download</a>
<a href="media/View_From_A_Blue_Moon_Trailer-HD.mp4" download>Download</a>
</video>
<ul>
@ -155,7 +154,7 @@
</aside>
<!-- Polyfills -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=es6,Array.prototype.includes,CustomEvent"></script>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=es6,Array.prototype.includes,CustomEvent,fetch"></script>
<!-- Plyr core script -->
<script src="../dist/plyr.js"></script>

Binary file not shown.

After

Width:  |  Height:  |  Size: 154 KiB

View File

@ -65,6 +65,9 @@ document.addEventListener('DOMContentLoaded', () => {
'pip',
'airplay',
],
keys: {
google: 'AIzaSyDrNwtN3nLH_8rjCmu5Wq3ZCm4MNAVdc0c',
},
});
// Expose for testing
@ -102,24 +105,24 @@ document.addEventListener('DOMContentLoaded', () => {
title: 'View From A Blue Moon',
sources: [
{
src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4',
src: 'media/View_From_A_Blue_Moon_Trailer-HD.mp4',
type: 'video/mp4',
},
],
poster: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg',
poster: 'hmedia/View_From_A_Blue_Moon_Trailer-HD.jpg',
tracks: [
{
kind: 'captions',
label: 'English',
srclang: 'en',
src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',
src: 'media/View_From_A_Blue_Moon_Trailer-HD.en.vtt',
default: true,
},
{
kind: 'captions',
label: 'French',
srclang: 'fr',
src: 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt',
src: 'media/View_From_A_Blue_Moon_Trailer-HD.fr.vtt',
},
],
};
@ -150,7 +153,7 @@ document.addEventListener('DOMContentLoaded', () => {
title: 'View From A Blue Moon',
sources: [
{
src: 'https://www.youtube.com/watch?v=bTqVqk7FSmY',
src: 'https://youtube.com/watch?v=bTqVqk7FSmY',
type: 'youtube',
},
],
@ -161,7 +164,6 @@ document.addEventListener('DOMContentLoaded', () => {
case types.vimeo:
player.source = {
type: 'video',
title: 'View From A Blue Moon',
sources: [
{
src: 'https://vimeo.com/76979871',

View File

@ -10,7 +10,7 @@ video {
// Example players
.plyr {
margin: 0 auto;
margin: @spacing-base auto;
border-radius: @border-radius-base;
box-shadow: 0 2px 5px fade(#000, 20%);
}

View File

@ -27,15 +27,18 @@ body {
flex-direction: column;
}
.grid {
flex: 1;
overflow: auto;
}
main {
margin: auto;
text-align: center;
}
.grid {
flex: 1;
}
aside {
position: relative;
display: flex;
flex-shrink: 0;
align-items: center;

View File

@ -4,7 +4,7 @@
@font-face {
font-family: 'Avenir';
src: url('https://cdn.plyr.io/static/fonts/avenir-medium.woff2') format('woff2'),
src: local('Avenir-Medium'), url('https://cdn.plyr.io/static/fonts/avenir-medium.woff2') format('woff2'),
url('https://cdn.plyr.io/static/fonts/avenir-medium.woff') format('woff');
font-style: normal;
font-weight: @font-weight-base;
@ -13,7 +13,7 @@
@font-face {
font-family: 'Avenir';
src: url('https://cdn.plyr.io/static/fonts/avenir-bold.woff2') format('woff2'),
src: local('Avenir-Heavy'), url('https://cdn.plyr.io/static/fonts/avenir-bold.woff2') format('woff2'),
url('https://cdn.plyr.io/static/fonts/avenir-bold.woff') format('woff');
font-style: normal;
font-weight: @font-weight-bold;
@ -22,7 +22,7 @@
@font-face {
font-family: 'Avenir';
src: url('https://cdn.plyr.io/static/fonts/avenir-black.woff2?v=3') format('woff2'),
src: local('Avenir-Black'), url('https://cdn.plyr.io/static/fonts/avenir-black.woff2?v=3') format('woff2'),
url('https://cdn.plyr.io/static/fonts/avenir-black.woff?v=3') format('woff');
font-style: normal;
font-weight: @font-weight-heavy;

View File

@ -33,6 +33,7 @@
// ---------------------------------------
.font-size(@font-size: 16) {
@rem: round((@font-size / 16), 3);
font-size: (@font-size * 1px);
font-size: ~'@{rem}rem';
}

2
dist/plyr.css vendored

File diff suppressed because one or more lines are too long

447
readme.md
View File

@ -3,18 +3,15 @@ Beware: This branch is currently in beta and not production-ready
---
# Plyr
A simple, accessible and customizable HTML5, YouTube and Vimeo media player.
[Donate to support Plyr](#donate)
A simple, lightweight, accessible and customizable HTML5, YouTube and Vimeo media player that supports [*modern*](#browser-support) browsers.
[Checkout the demo](https://plyr.io)
[Checkout the demo](https://plyr.io) - [Donate to support Plyr](#donate)
[![Image of Plyr](https://cdn.plyr.io/static/demo/screenshot.png)](https://plyr.io)
## Why?
We wanted a lightweight, accessible and customizable media player that supports [*modern*](#browser-support) browsers. Sure, there are many other players out there but we wanted to keep things simple, using the right elements for the job.
## Features
- **Accessible** - full support for VTT captions and screen readers
- **Lightweight** - just 18KB minified and gzipped
- **[Customisable](#html)** - make the player look how you want with the markup you want
@ -52,38 +49,45 @@ Created and maintained by Dominik Pschenitschni ([@dpschen](https://github.com/d
You can grab the source using one of the following package managers.
### npm
```
npm install plyr
```
[https://www.npmjs.com/package/plyr](https://www.npmjs.com/package/plyr)
## Quick setup
Here's a quick run through on getting up and running. There's also a [demo on Codepen](http://codepen.io/sampotts/pen/jARJYp).
### HTML
Plyr extends upon the standard HTML5 markup so that's all you need for those types. More info on advanced HTML markup can be found under [initialising](#initialising).
#### HTML5 Video
```html
<video poster="/path/to/poster.jpg" id="player" controls>
<source src="/path/to/video.mp4" type="video/mp4">
<source src="/path/to/video.webm" type="video/webm">
<!-- Captions are optional -->
<track kind="captions" label="English captions" src="/path/to/captions.vtt" srclang="en" default>
<source src="/path/to/video.mp4" type="video/mp4">
<source src="/path/to/video.webm" type="video/webm">
<!-- Captions are optional -->
<track kind="captions" label="English captions" src="/path/to/captions.vtt" srclang="en" default>
</video>
```
#### HTML5 Audio
```html
<audio id="player" controls>
<source src="/path/to/audio.mp3" type="audio/mp3">
<source src="/path/to/audio.ogg" type="audio/ogg">
<source src="/path/to/audio.mp3" type="audio/mp3">
<source src="/path/to/audio.ogg" type="audio/ogg">
</audio>
```
For YouTube and Vimeo, Plyr uses the standard YouTube API markup (an empty `<div>`):
#### YouTube embed
```html
<div id="player" data-type="youtube" data-video-id="bTqVqk7FSmY"></div>
```
@ -91,17 +95,19 @@ For YouTube and Vimeo, Plyr uses the standard YouTube API markup (an empty `<div
Note: `data-video-id` value can now be the ID or URL for the video. This attribute name will change in a future release to reflect this change.
#### Vimeo embed
```html
<div id="player" data-type="vimeo" data-video-id="143418951"></div>
```
Note: `data-video-id` value can now be the ID or URL for the video. This attribute name will change in a future release to reflect this change.
### JavaScript
Include the `plyr.js` script before the closing `</body>` tag and then call `plyr.setup()`. More info on `setup()` can be found under [initialising](#initialising).
```html
<script src="path/to/plyr.js"></script>
<script>var player = new Plyr('#player')</script>
<script>const player = new Plyr('#player');</script>
```
If you want to use our CDN (provided by [Fastly](https://www.fastly.com/)) for the JavaScript, you can use the following:
@ -111,6 +117,7 @@ If you want to use our CDN (provided by [Fastly](https://www.fastly.com/)) for t
```
### CSS
Include the `plyr.css` stylsheet into your `<head>`
```html
@ -131,7 +138,7 @@ The SVG sprite is loaded automatically from our CDN (provided by [Fastly](https:
### LESS & SASS/SCSS
You can use `plyr.less` or `plyr.scss` file included in `/src` as part of your build and change variables to suit your design. The LESS and SASS require you to use the [autoprefixer](https://www.npmjs.com/package/gulp-autoprefixer) plugin (you should already) as all declerations use the W3C definitions - e.g. `appearance: none;` will be prefixed to `-webkit-appearance: none;` by autoprefixer.
You can use `plyr.less` or `plyr.scss` file included in `/src` as part of your build and change variables to suit your design. The LESS and SASS require you to use the [autoprefixer](https://www.npmjs.com/package/gulp-autoprefixer) plugin (you be should already!) as all declarations use the W3C definitions.
The HTML markup uses the BEM methodology with `plyr` as the block, e.g. `.plyr__controls`. You can change the class hooks in the options to match any custom CSS you write. Check out the JavaScript source for more on this.
@ -202,6 +209,7 @@ const player = new Plyr('#player', { /* options */ });
The constructor will return a Plyr object that can be used with the [API](#api) methods. See the [API](#api) section for more info.
#### Options
Options can be passed as an object to the constructor as above or as JSON in `data-plyr` attribute on each of your target elements:
```html
@ -225,7 +233,7 @@ Option | Type | Default | Description
`seekTime` | Number | `10` | The time, in seconds, to seek when a user hits fast forward or rewind.
`volume` | Number | `1` | A number, between 0 and 1, representing the initial volume of the player.
`muted` | Boolean | `false` | Whether to start playback muted. If the `muted` attribute is present on a `<video>` or `<audio>` element, this will be automatically set to true.
`clickToPlay` | Boolean | `true` | Click (or tap) of the video container will toggle pause/play.
`clickToPlay` | Boolean | `true` | Click (or tap) of the video container will toggle play/pause.
`disableContextMenu` | Boolean | `true` | Disable right click menu on video to <em>help</em> as very primitive obfuscation to prevent downloads of content.
`hideControls` | Boolean | `true` | Hide video controls automatically after 2s of no mouse or focus movement, on control element blur (tab out), on playback start or entering fullscreen. As soon as the mouse is moved, a control element is focused or playback is paused, the controls reappear instantly.
`showPosterOnEnd` | Boolean | false | This will restore and *reload* HTML5 video once playback is complete. Note: depending on the browser caching, this may result in the video downloading again (or parts of it). Use with caution.
@ -233,9 +241,12 @@ Option | Type | Default | Description
`tooltips` | Object | `{ controls: false, seek: true }` | `controls`: Display control labels as tooltips on `:hover` & `:focus` (by default, the labels are screen reader only). `seek`: Display a seek tooltip to indicate on click where the media would seek to.
`duration` | Number | `null` | Specify a custom duration for media.
`displayDuration` | Boolean | `true` | Displays the duration of the media on the "metadataloaded" event (on startup) in the current time display. This will only work if the `preload` attribute is not set to `none` (or is not set at all) and you choose not to display the duration (see `controls` option).
`invertTime` | Boolean | `true` | Display the current time as a countdown rather than an incremental counter.
`toggleInvert` | Boolean | `true` | Allow users to click to toggle the above.
`listeners` | Object | `null` | Allows binding of event listeners to the controls before the default handlers. See the `defaults.js` for available listeners. IF your handler prevents default on the event, the default handler will not fire.
`captions` | Object | `{ active: false, language: window.navigator.language.split('-')[0] }` | `active`: Toggles if captions should be active by default. `language`: Sets the default language to load (if available).
`fullscreen` | Object | `{ enabled: true, fallback: true }` | `enabled`: Toggles whether fullscreen should be enabled. `fallback`: Allow fallback to a full-window solution.
`ratio` | String | `16:9` | The aspect ratio you want to use for embedded players.
`storage` | Object | `{ enabled: true, key: 'plyr' }` | `enabled`: Allow use of local storage to store user settings. `key`: The key name to use.
`speed` | Object | `{ selected: 1, options: [0.5, 0.75, 1, 1.25, 1.5, 1.75, 2] }` | `selected`: The default speed for playback. `options`: Options to display in the menu. Most browsers will refuse to play slower than 0.5.
`quality` | Object | `{ default: 'default', options: ['hd2160', 'hd1440', 'hd1080', 'hd720', 'large', 'medium', 'small', 'tiny', 'default'] }` | Currently only supported by YouTube. `default` is the default quality level, determined by YouTube. `options` are the options to display.
@ -320,18 +331,18 @@ Property | Getter | Setter | Description
`volume` | ✔ | ✔ | Gets or sets the volume for the player. The setter accepts a float between 0 and 1.
`muted` | ✔ | ✔ | Gets or sets the muted state of the player. The setter accepts a boolean.
`speed` | ✔ | ✔ | Gets or sets the speed for the player. The setter accepts a value in the options specified in your config. Generally the minimum should be 0.5.
`quality`¹ | ✔ | ✔ | Gets or sets the quality for the player. The setter accepts a value from the options specified in your config.
`quality`&sup1; | ✔ | ✔ | Gets or sets the quality for the player. The setter accepts a value from the options specified in your config.
`loop` | ✔ | ✔ | Gets or sets the current loop state of the player. The setter accepts a boolean.
`source` | ✔ | ✔ | Gets or sets the current source for the player. The setter accepts an object. See [source setter](#source-setter) below for examples.
`poster`² | ✔ | ✔ | Gets or sets the current poster image for the player. The setter accepts a string; the URL for the updated poster image.
`poster`&sup2; | ✔ | ✔ | Gets or sets the current poster image for the player. The setter accepts a string; the URL for the updated poster image.
`autoplay` | ✔ | ✔ | Gets or sets the autoplay state of the player. The setter accepts a boolean.
`language` | ✔ | ✔ | Gets or sets the preferred captions language for the player. The setter accepts an ISO two-letter language code. Support for the languages is dependent on the captions you include.
`pip` | ✔ | ✔ | Gets or sets the picture-in-picture state of the player. The setter accepts a boolean. This currently only supported on Safari 10+ on MacOS Sierra+ and iOS 10+.
1. YouTube only. HTML5 will follow.
2. HTML5 only
2. HTML5 only*
#### .source setter
#### The `.source` setter
This allows changing the player source and type on the fly.
@ -394,7 +405,6 @@ YouTube example:
```javascript
player.source = {
type: 'video',
title: 'Example title',
sources: [
{
src: 'bTqVqk7FSmY',
@ -411,7 +421,6 @@ Vimeo example
```javascript
player.source = {
type: 'video',
title: 'Example title',
sources: [
{
src: '143418951',
@ -421,287 +430,107 @@ player.source = {
};
```
Note: `src` can be the video ID or URL
*Note:* `src` property for YouTube and Vimeo can either be the video ID or the whole URL.
More details on the object parameters
Property | Type | Description
-------- | ---- | -----------
`type` | String | Either `video` or `audio`. *Note:* YouTube and Vimeo are currently not supported as audio sources.
`title` | String | *Optional.* Title of the new media. Used for the `aria-label` attribute on the play button, and outer container. YouTube and Vimeo are populated automatically.
`sources` | Array | This is an array of sources. For HTML5 media, the properties of this object are mapped directly to HTML attributes so more can be added to the object if required.
`poster`&sup1; | String | The URL for the poster image (HTML5 video only).
`tracks`&sup1; | String | An array of track objects. Each element in the array is mapped directly to a track element and any keys mapped directly to HTML attributes so as in the example above, it will render as `<track kind="captions" label="English" srclang="en" src="https://cdn.selz.com/plyr/1.0/example_captions_en.vtt" default>` and similar for the French version. Booleans are converted to HTML5 value-less attributes.
<table class="table" width="100%">
<thead>
<tr>
<th width="20%">Key</th>
<th width="15%">Type</th>
<th width="65%">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>type</code></td>
<td>String</td>
<td>Options are <code>video</code>, <code>audio</code>, <code>youtube</code> and <code>vimeo</code></td>
</tr>
<tr>
<td><code>title</code></td>
<td>String</td>
<td>Title of the new media. Used for the `aria-label` attribute on the play button, and outer container.</td>
</tr>
<tr>
<td><code>sources</code></td>
<td>Array</td>
<td>This is an array of sources. <code>type</code> is optional for YouTube and Vimeo when specifying an array. For YouTube and Vimeo media, the video ID or URL must be passed as the source as shown above. The keys of this object are mapped directly to HTML attributes so more can be added to the object if required.</td>
</tr>
<tr>
<td><code>poster</code></td>
<td>String</td>
<td>URL for the poster image (video only).</td>
</tr>
<tr>
<td><code>tracks</code></td>
<td>Array</td>
<td>An array of track objects. Each element in the array is mapped directly to a track element and any keys mapped directly to HTML attributes so as in the example above, it will render as `<track kind="captions" label="English" srclang="en" src="https://cdn.selz.com/plyr/1.0/example_captions_en.vtt" default>`. Booleans are converted to HTML5 value-less attributes.</td>
</tr>
</tbody>
</table>
1. HTML5 only
## Events
You can listen for events on the target element you setup Plyr on (see example under the table). Some events only apply to HTML5 audio and video. Using your reference to the instance, you can use the `on()` API method or `addEventListener()`. Access to the API can be obtained this way through the `event.detail.plyr` property. Here's an example:
```javascript
instance.on('ready', function(event) {
var instance = event.detail.plyr;
player.on('ready', event => {
const instance = event.detail.plyr;
});
```
These events also bubble up the DOM. The event target will be the container element.
### Standard Media Events
<table class="table" width="100%">
<thead>
<tr>
<th width="20%">Event name</th>
<th width="20%">HTML5 only</th>
<th width="60%">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>ready</code></td>
<td></td>
<td>Triggered when the instance is ready for API calls.</td>
</tr>
<tr>
<td><code>canplay</code></td>
<td></td>
<td>Sent when enough data is available that the media can be played, at least for a couple of frames. This corresponds to the <code>HAVE_ENOUGH_DATA</code> <code>readyState</code>.</td>
</tr>
<tr>
<td><code>canplaythrough</code></td>
<td></td>
<td>Sent when the ready state changes to <code>CAN_PLAY_THROUGH</code>, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level. <strong>Note</strong>: Manually setting the <code>currentTime</code> will eventually fire a <code>canplaythrough</code> event in firefox. Other browsers might not fire this event.</td>
</tr>
<tr>
<td><code>emptied</code></td>
<td></td>
<td>The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the <code>load()</code> method is called to reload it.</td>
</tr>
<tr>
<td><code>ended</code></td>
<td></td>
<td>Sent when playback completes. Note: with Vimeo this does not occur if `loop` is enabled.</td>
</tr>
<tr>
<td><code>error</code></td>
<td></td>
<td>Sent when an error occurs.&nbsp; The element's <code>error</code> attribute contains more information.</td>
</tr>
<tr>
<td><code>loadeddata</code></td>
<td></td>
<td>The first frame of the media has finished loading.</td>
</tr>
<tr>
<td><code>loadedmetadata</code></td>
<td></td>
<td>The media's metadata has finished loading; all attributes now contain as much useful information as they're going to.</td>
</tr>
<tr>
<td><code>loadstart</code></td>
<td></td>
<td>Sent when loading of the media begins.</td>
</tr>
<tr>
<td><code>pause</code></td>
<td></td>
<td>Sent when playback is paused.</td>
</tr>
<tr>
<td><code>play</code></td>
<td></td>
<td>Sent when playback of the media starts after having been paused; that is, when playback is resumed after a prior <code>pause</code> event.</td>
</tr>
<tr>
<td><code>playing</code></td>
<td></td>
<td>Sent when the media begins to play (either for the first time, after having been paused, or after ending and then restarting).</td>
</tr>
<tr>
<td><code>progress</code></td>
<td></td>
<td>Sent periodically to inform interested parties of progress downloading the media. Information about the current amount of the media that has been downloaded is available in the media element's <code>buffered</code> attribute.</td>
</tr>
<tr>
<td><code>seeked</code></td>
<td></td>
<td>Sent when a seek operation completes.</td>
</tr>
<tr>
<td><code>seeking</code></td>
<td></td>
<td>Sent when a seek operation begins.</td>
</tr>
<tr>
<td><code>stalled</code></td>
<td></td>
<td>Sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming.</td>
</tr>
<tr>
<td><code>timeupdate</code></td>
<td></td>
<td>The time indicated by the element's <code>currentTime</code> attribute has changed.</td>
</tr>
<tr>
<td><code>volumechange</code></td>
<td></td>
<td>Sent when the audio volume changes (both when the volume is set and when the <code>muted</code> attribute is changed).</td>
</tr>
<tr>
<td><code>waiting</code></td>
<td></td>
<td>Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek).</td>
</tr>
<tr>
<td><code>enterfullscreen</code></td>
<td></td>
<td>User enters fullscreen (either the proper fullscreen or full-window fallback for older browsers)</td>
</tr>
<tr>
<td><code>exitfullscreen</code></td>
<td></td>
<td>User exits fullscreen</td>
</tr>
<tr>
<td><code>captionsenabled</code></td>
<td></td>
<td>Captions toggled on</td>
</tr>
<tr>
<td><code>captionsdisabled</code></td>
<td></td>
<td>Captions toggled off</td>
</tr>
<tr>
<td><code>destroyed</code></td>
<td></td>
<td>When an instance is destroyed. The original element that replaced the container will be returned to your handler as the event target.</td>
</tr>
</tbody>
</table>
Event Type | Description
---------- | -----------
`progress` | Sent periodically to inform interested parties of progress downloading the media. Information about the current amount of the media that has been downloaded is available in the media element's `buffered` attribute.
`playing` | Sent when the media begins to play (either for the first time, after having been paused, or after ending and then restarting).
`play` | Sent when playback of the media starts after having been paused; that is, when playback is resumed after a prior `pause` event.
`pause` | Sent when playback is paused.
`timeupdate` | The time indicated by the element's `currentTime` attribute has changed.
`volumechange` | Sent when the audio volume changes (both when the volume is set and when the `muted` state is changed).
`seeking` | Sent when a seek operation begins.
`seeked` | Sent when a seek operation completes.
`ratechange` | Sent when the playback speed changes.
`ended` | Sent when playback completes.
`enterfullscreen` | Sent when the player enters fullscreen mode (either the proper fullscreen or full-window fallback for older browsers).
`exitfullscreen` | Sent when the player exits fullscreen mode.
`captionsenabled` | Sent when captions are enabled.
`captionsdisabled` | Sent when captions are disabled.
`languagechange` | Sent when the caption language is changed.
`controlshidden` | Sent when the controls are hidden.
`controlsshown` | Sent when the controls are shown.
`ready` | Triggered when the instance is ready for API calls.
Details borrowed from: [https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events)
#### HTML5 only
Event Type | Description
---------- | -----------
`loadstart` | Sent when loading of the media begins.
`loadeddata` | The first frame of the media has finished loading.
`loadedmetadata` | The media's metadata has finished loading; all attributes now contain as much useful information as they're going to.
`canplay` | Sent when enough data is available that the media can be played, at least for a couple of frames. This corresponds to the `HAVE_ENOUGH_DATA` `readyState`.
`canplaythrough` | Sent when the ready state changes to `CAN_PLAY_THROUGH`, indicating that the entire media can be played without interruption, assuming the download rate remains at least at the current level. *Note:* Manually setting the `currentTime` will eventually fire a `canplaythrough` event in firefox. Other browsers might not fire this event.
`stalled` | Sent when the user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
`waiting` | Sent when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek).
`emptied` | he media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the `load()` method is called to reload it.
`cuechange` | Sent when a `TextTrack` has changed the currently displaying cues.
`error` | Sent when an error occurs. The element's `error` attribute contains more information.
#### YouTube only
Event Type | Description
---------- | -----------
`statechange` | The state of the player has changed. The code can be accessed via `event.detail.code`. Possible values are `-1`: Unstarted, `0`: Ended, `1`: Playing, `2`: Paused, `3`: Buffering, `5`: Video cued. See the [YouTube Docs](https://developers.google.com/youtube/iframe_api_reference#onStateChange) for more information.
`qualitychange` | The quality of playback has changed.
`qualityrequested` | A change to playback quality has been requested. *Note:* A change to quality can only be *requested* via the API. There is no guarantee the quality will change to the level requested. You should listen to the `qualitychange` event for true changes.
*Note:* These events also bubble up the DOM. The event target will be the container element.
Some event details borrowed from [MDN](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events).
## Embeds
YouTube and Vimeo are currently supported and function much like a HTML5 video. Check the relevant documentation sections for any differences.
Plyr references a custom version of the Vimeo Froogaloop API as Vimeo have neglected to maintain the library and there were bugs with their version. You don't need to worry about including your own versions of the Vimeo or YouTube JavaScript APIs.
YouTube and Vimeo are currently supported and function much like a HTML5 video. Similar events and API methods are available for all types. However if you wish to access the API's directly. You can do so via the `embed` property of your player object - e.g. `player.embed`. You can then use the relevant methods from the third party APIs. More info on the respective API's here:
The embed third party API's can be accessed through the `getEmbed()` API method.
- [YouTube iframe API Reference](https://developers.google.com/youtube/iframe_api_reference)
- [Vimeo player.js Reference](https://github.com/vimeo/player.js)
More info on the respective API's here:
- [YouTube API Reference](https://developers.google.com/youtube/js_api_reference)
- [Vimeo API Reference](https://developer.vimeo.com/player/js-api#reference)
*Please note*: not all API methods may work 100%. Your mileage may vary. It's better to use the universal plyr API where possible.
*Note*: Not all API methods may work 100%. Your mileage may vary. It's better to use the Plyr API where possible.
## Shortcuts
By default, a player will bind the following keyboard shortcuts when it has focus. If you have the `global` option to `true` and there's only one player in the document then the shortcuts will work when any element has focus, apart from an element that requires input.
<table class="table" width="100%">
<thead>
<tr>
<th width="25%">Key</th>
<th width="25%">Global</th>
<th width="50%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>0</code> to <code>9</code></td>
<td></td>
<td>Seek from 0 to 90% respectively</td>
</tr>
<tr>
<td><code>space</code></td>
<td></td>
<td>Toggle playback</td>
</tr>
<tr>
<td><code>K</code></td>
<td></td>
<td>Toggle playback</td>
</tr>
<tr>
<td><code>&larr;</code></td>
<td></td>
<td>Seek backward by the <code>seekTime</code> option</td>
</tr>
<tr>
<td><code>&rarr;</code></td>
<td></td>
<td>Seek forward by the <code>seekTime</code> option</td>
</tr>
<tr>
<td><code>&uarr;</code></td>
<td></td>
<td>Increase volume</td>
</tr>
<tr>
<td><code>&darr;</code></td>
<td></td>
<td>Decrease volume</td>
</tr>
<tr>
<td><code>M</code></td>
<td></td>
<td>Toggle mute</td>
</tr>
<tr>
<td><code>F</code></td>
<td></td>
<td>Toggle fullscreen</td>
</tr>
<tr>
<td><code>C</code></td>
<td></td>
<td>Toggle captions</td>
</tr>
<tr>
<td><code>l</code></td>
<td></td>
<td>Toggle Loop All/No Loop</td>
</tr>
<tr>
<td><code>i</code></td>
<td></td>
<td>Set the start marker of the loop</td>
</tr>
<tr>
<td><code>o</code></td>
<td></td>
<td>Set the end marker of the loop</td>
</tr>
</tbody>
</table>
Key | Action
--- | ------
`0` to `9` | Seek from 0 to 90% respectively
`space` | Toggle playback
`K` | Toggle playback
&larr; | Seek backward by the `seekTime` option
&rarr; | Seek forward by the `seekTime` option
&uarr; | Increase volume
&darr; | Decrease volume
`M` | Toggle mute
`F` | Toggle fullscreen
`C` | Toggle captions
`L` | Toggle loop
## Streaming
Because Plyr is an extension of the standard HTML5 video and audio elements, third party streaming plugins can be used with Plyr. Massive thanks to Matias Russitto ([@russitto](https://github.com/russitto)) for working on this. Here's a few examples:
- Using [hls.js](https://github.com/dailymotion/hls.js) - [Demo](http://codepen.io/sampotts/pen/JKEMqB)
@ -709,62 +538,54 @@ Because Plyr is an extension of the standard HTML5 video and audio elements, thi
- Using [dash.js](https://github.com/Dash-Industry-Forum/dash.js) - [Demo](http://codepen.io/sampotts/pen/BzpJXN)
## Fullscreen
Fullscreen in Plyr is supported by all browsers that [currently support it](http://caniuse.com/#feat=fullscreen).
## Browser support
<table width="100%" style="text-align: center">
<thead>
<tr>
<td>Safari</td>
<td>Firefox</td>
<td>Chrome</td>
<td>Opera</td>
<td>IE9</td>
<td>IE10+</td>
</tr>
</thead>
<tbody>
<tr>
<td>&sup1;</td>
<td></td>
<td></td>
<td></td>
<td>API&sup2;</td>
<td>&sup3;</td>
</tr>
</tbody>
</table>
Plyr supports the last 2 versions of most *modern* browsers. IE11 is also supported.
&sup1; Mobile Safari on the iPhone forces the native player for `<video>` so no useful customization is possible. `<audio>` elements have volume controls disabled.
Browser | Supported
------- | ---------
Safari | ✔
Mobile Safari | ✔&sup1;
Firefox | ✔
Chrome | ✔
Opera | ✔
Edge | ✔
IE10+ | ✔&sup2;
IE9 | API only&sup3;
&sup2; Native player used (no support for `<progress>` or `<input type="range">`) but the API is supported (v1.0.28+)
&sup3; IE10 has no native fullscreen support, fallback can be used (see [options](#options))
1. Mobile Safari on the iPhone forces the native player for `<video>` unless the `playsinline` attribute is present. Volume controls are also disabled.
2. Native player used (no support for `<progress>` or `<input type="range">`) but the API is supported (v1.0.28+)
3. IE10 has no native fullscreen support, fallback can be used (see [options](#options))
The `enabled` option can be used to disable certain User Agents. For example, if you don't want to use Plyr for smartphones, you could use:
```javascript
enabled: /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)
{ enabled: /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) }
```
If a User Agent is disabled but supports `<video>` and `<audio>` natively, it will use the native player.
Any unsupported browsers will display links to download the media if the correct html is used.
## RangeTouch
Some touch browsers (particularly Mobile Safari on iOS) seem to have issues with `<input type="range">` elements whereby touching the track to set the value doesn't work and sliding the thumb can be tricky. To combat this, I've created [RangeTouch](https://rangetouch.com) which I'd recommend including in your solution. It's a tiny script with a nice benefit for users on touch devices.
## Issues
If you find anything weird with Plyr, please let us know using the GitHub issues tracker.
## Author
Plyr is developed by [@sam_potts](https://twitter.com/sam_potts) / [sampotts.me](http://sampotts.me) with help from the awesome [contributors](https://github.com/sampotts/plyr/graphs/contributors)
## Donate
Plyr costs money to run, not my time - I donate that for free but domains, hosting and more. Any help is appreciated...
Plyr costs money to run, not only my time - I donate that for free but domains, hosting and more. Any help is appreciated...
[Donate to support Plyr](https://www.paypal.me/pottsy/20usd)
## Mentions
- [ProductHunt](https://www.producthunt.com/tech/plyr)
- [The Changelog](http://thechangelog.com/plyr-simple-html5-media-player-custom-controls-webvtt-captions/)
- [HTML5 Weekly #177](http://html5weekly.com/issues/177)
@ -777,6 +598,7 @@ Plyr costs money to run, not my time - I donate that for free but domains, hosti
- [noupe.com](http://www.noupe.com/design/html5-plyr-is-a-responsive-and-accessible-video-player-94389.html)
## Used by
- [Selz.com](https://selz.com)
- [Peugeot.fr](http://www.peugeot.fr/marque-et-technologie/technologies/peugeot-i-cockpit.html)
- [Peugeot.de](http://www.peugeot.de/modelle/modellberater/208-3-turer/fotos-videos.html)
@ -790,14 +612,17 @@ Plyr costs money to run, not my time - I donate that for free but domains, hosti
Let me know on [Twitter](https://twitter.com/sam_potts) I can add you to the above list. It'd be awesome to see how you're using Plyr :-)
## Useful links and credits
Credit to the PayPal HTML5 Video player from which Plyr's caption functionality was originally ported from:
- [PayPal's Accessible HTML5 Video Player](https://github.com/paypal/accessible-html5-video-player)
- [An awesome guide for Plyr in Japanese!](http://syncer.jp/how-to-use-plyr-io) by [@arayutw](https://twitter.com/arayutw)
## Thanks
[![Fastly](https://www.fastly.com/sites/all/themes/custom/fastly2016/logo.png)](https://www.fastly.com/)
Thanks to [Fastly](https://www.fastly.com/) for providing the CDN services.
Massive thanks to [Fastly](https://www.fastly.com/) for providing the CDN services.
## Copyright and License
[The MIT license](license.md).
[The MIT license](license.md)

View File

@ -79,8 +79,9 @@ const captions = {
// Filter doesn't seem to work for a TextTrackList :-(
Array.from(this.captions.tracks).forEach(track => {
if (track.language === this.captions.language.toLowerCase()) {
if (track.language.toLowerCase() === this.language.toLowerCase()) {
this.captions.currentTrack = track;
console.warn(`Set current track to ${this.language}`);
}
});
};

169
src/js/controls.js vendored
View File

@ -75,7 +75,7 @@ const controls = {
const use = document.createElementNS(namespace, 'use');
const path = `${iconPath}-${type}`;
// If the new `href` attribute is supported, use that
// Set `href` attributes
// https://github.com/sampotts/plyr/issues/460
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/xlink:href
if ('href' in use) {
@ -118,6 +118,10 @@ const controls = {
// Create a badge
createBadge(text) {
if (utils.is.empty(text)) {
return null;
}
const badge = utils.createElement('span', {
class: this.config.classNames.menu.value,
});
@ -322,6 +326,39 @@ const controls = {
return container;
},
// Create a settings menu item
createMenuItem(value, list, type, title, badge = null, checked = false) {
const item = utils.createElement('li');
const label = utils.createElement('label', {
class: this.config.classNames.control,
});
const radio = utils.createElement(
'input',
utils.extend(utils.getAttributesFromSelector(this.config.selectors.inputs[type]), {
type: 'radio',
name: `plyr-${type}`,
value,
checked,
class: 'plyr__sr-only',
})
);
const faux = utils.createElement('span', { 'aria-hidden': true });
label.appendChild(radio);
label.appendChild(faux);
label.insertAdjacentHTML('beforeend', title);
if (utils.is.htmlElement(badge)) {
label.appendChild(badge);
}
item.appendChild(label);
list.appendChild(item);
},
// Update hover tooltip for seeking
updateSeekTooltip(event) {
// Bail if setting not true
@ -356,7 +393,7 @@ const controls = {
}
// Display the time a click would seek to
ui.updateTimeDisplay.call(this, this.duration / 100 * percent, this.elements.display.seekTooltip);
ui.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent);
// Set position
this.elements.display.seekTooltip.style.left = `${percent}%`;
@ -393,6 +430,7 @@ const controls = {
// Set the YouTube quality menu
// TODO: Support for HTML5
setQualityMenu(options) {
const type = 'quality';
const list = this.elements.settings.panes.quality.querySelector('ul');
// Set options if passed and filter based on config
@ -404,7 +442,7 @@ const controls = {
// Toggle the pane and tab
const toggle = !utils.is.empty(this.options.quality) && this.type === 'youtube';
controls.toggleTab.call(this, 'quality', toggle);
controls.toggleTab.call(this, type, toggle);
// If we're hiding, nothing more to do
if (!toggle) {
@ -446,35 +484,18 @@ const controls = {
return controls.createBadge.call(this, label);
};
this.options.quality.forEach(quality => {
const item = utils.createElement('li');
const label = utils.createElement('label', {
class: this.config.classNames.control,
});
const radio = utils.createElement(
'input',
utils.extend(utils.getAttributesFromSelector(this.config.selectors.inputs.quality), {
type: 'radio',
name: 'plyr-quality',
value: quality,
})
this.options.quality.forEach(quality =>
controls.createMenuItem.call(
this,
quality,
list,
type,
controls.getLabel.call(this, 'quality', quality),
getBadge(quality)
)
);
label.appendChild(radio);
label.appendChild(document.createTextNode(controls.getLabel.call(this, 'quality', quality)));
const badge = getBadge(quality);
if (utils.is.htmlElement(badge)) {
label.appendChild(badge);
}
item.appendChild(label);
list.appendChild(item);
});
controls.updateSetting.call(this, 'quality', list);
controls.updateSetting.call(this, type, list);
},
// Translate a value into a nice label
@ -576,7 +597,7 @@ const controls = {
},
// Set the looping options
setLoopMenu() {
/* setLoopMenu() {
const options = ['start', 'end', 'all', 'reset'];
const list = this.elements.settings.panes.loop.querySelector('ul');
@ -612,7 +633,7 @@ const controls = {
item.appendChild(button);
list.appendChild(item);
});
},
}, */
// Get current selected caption language
// TODO: rework this to user the getter in the API?
@ -634,11 +655,13 @@ const controls = {
// Set a list of available captions languages
setCaptionsMenu() {
// TODO: Captions or language? Currently it's mixed
const type = 'captions';
const list = this.elements.settings.panes.captions.querySelector('ul');
// Toggle the pane and tab
const toggle = !utils.is.empty(this.captions.tracks);
controls.toggleTab.call(this, 'captions', toggle);
controls.toggleTab.call(this, type, toggle);
// Empty the menu
utils.emptyElement(list);
@ -651,7 +674,6 @@ const controls = {
// Re-map the tracks into just the data we need
const tracks = Array.from(this.captions.tracks).map(track => ({
language: track.language,
badge: true,
label: !utils.is.empty(track.label) ? track.label : track.language.toUpperCase(),
}));
@ -663,41 +685,24 @@ const controls = {
// Generate options
tracks.forEach(track => {
const item = utils.createElement('li');
const label = utils.createElement('label', {
class: this.config.classNames.control,
});
const radio = utils.createElement(
'input',
utils.extend(utils.getAttributesFromSelector(this.config.selectors.inputs.language), {
type: 'radio',
name: 'plyr-language',
value: track.language,
})
controls.createMenuItem.call(
this,
track.language,
list,
'language',
track.label || track.language,
controls.createBadge.call(this, track.language.toUpperCase()),
track.language.toLowerCase() === this.captions.language.toLowerCase()
);
if (track.language.toLowerCase() === this.captions.language.toLowerCase()) {
radio.checked = true;
}
label.appendChild(radio);
label.appendChild(document.createTextNode(track.label || track.language));
if (track.badge) {
label.appendChild(controls.createBadge.call(this, track.language.toUpperCase()));
}
item.appendChild(label);
list.appendChild(item);
});
controls.updateSetting.call(this, 'captions', list);
controls.updateSetting.call(this, type, list);
},
// Set a list of available captions languages
setSpeedMenu(options) {
const type = 'speed';
// Set options if passed and filter based on config
if (utils.is.array(options)) {
this.options.speed = options.filter(speed => this.config.speed.options.includes(speed));
@ -707,7 +712,7 @@ const controls = {
// Toggle the pane and tab
const toggle = !utils.is.empty(this.options.speed);
controls.toggleTab.call(this, 'speed', toggle);
controls.toggleTab.call(this, type, toggle);
// If we're hiding, nothing more to do
if (!toggle) {
@ -725,39 +730,23 @@ const controls = {
utils.emptyElement(list);
// Create items
this.options.speed.forEach(speed => {
const item = utils.createElement('li');
const label = utils.createElement('label', {
class: this.config.classNames.control,
});
const radio = utils.createElement(
'input',
utils.extend(utils.getAttributesFromSelector(this.config.selectors.inputs.speed), {
type: 'radio',
name: 'plyr-speed',
value: speed,
})
this.options.speed.forEach(speed =>
controls.createMenuItem.call(this, speed, list, type, controls.getLabel.call(this, 'speed', speed))
);
label.appendChild(radio);
label.insertAdjacentHTML('beforeend', controls.getLabel.call(this, 'speed', speed));
item.appendChild(label);
list.appendChild(item);
});
controls.updateSetting.call(this, 'speed', list);
controls.updateSetting.call(this, type, list);
},
// Show/hide menu
toggleMenu(event) {
const { form } = this.elements.settings;
const button = this.elements.buttons.settings;
const show = utils.is.boolean(event) ? event : form && form.getAttribute('aria-hidden') === 'true';
const show = utils.is.boolean(event)
? event
: utils.is.htmlElement(form) && form.getAttribute('aria-hidden') === 'true';
if (utils.is.event(event)) {
const isMenuItem = form && form.contains(event.target);
const isMenuItem = utils.is.htmlElement(form) && form.contains(event.target);
const isButton = event.target === this.elements.buttons.settings;
// If the click was inside the form or if the click
@ -774,10 +763,11 @@ const controls = {
}
// Set form and button attributes
if (button) {
if (utils.is.htmlElement(button)) {
button.setAttribute('aria-expanded', show);
}
if (form) {
if (utils.is.htmlElement(form)) {
form.setAttribute('aria-hidden', !show);
if (show) {
@ -885,6 +875,9 @@ const controls = {
pane.setAttribute('aria-hidden', !show);
tab.setAttribute('aria-expanded', show);
pane.removeAttribute('tabindex');
// Focus the first item
pane.querySelectorAll('button:not(:disabled), input:not(:disabled), [tabindex]')[0].focus();
},
// Build the default HTML

View File

@ -22,13 +22,20 @@ const defaults = {
// Pass a custom duration
duration: null,
// Display the media duration
// Display the media duration on load in the current time position
// If you have opted to display both duration and currentTime, this is ignored
displayDuration: true,
// Invert the current time to be a countdown
invertTime: true,
// Clicking the currentTime inverts it's value to show time left rather than elapsed
toggleInvert: true,
// Aspect ratio (for embeds)
ratio: '16:9',
// Click video to play
// Click video container to play/pause
clickToPlay: true,
// Auto hide the controls
@ -203,7 +210,7 @@ const defaults = {
'exitfullscreen',
'captionsenabled',
'captionsdisabled',
'captionchange',
'languagechange',
'controlshidden',
'controlsshown',
'ready',
@ -276,6 +283,7 @@ const defaults = {
isIos: 'plyr--is-ios',
isTouch: 'plyr--is-touch',
uiSupported: 'plyr--full-ui',
noTransition: 'plyr--no-transition',
menu: {
value: 'plyr__menu__value',
badge: 'plyr__badge',
@ -298,6 +306,11 @@ const defaults = {
},
tabFocus: 'plyr__tab-focus',
},
// API keys
keys: {
google: null,
},
};
export default defaults;

View File

@ -101,7 +101,6 @@ const listeners = {
case 75:
// Space and K key
if (!held) {
this.console.warn('togglePlay', event.type);
this.togglePlay();
}
break;
@ -119,7 +118,7 @@ const listeners = {
case 77:
// M key
if (!held) {
this.muted = 'toggle';
this.muted = !this.muted;
}
break;
@ -145,6 +144,11 @@ const listeners = {
}
break;
case 76:
// L key
this.loop = !this.loop;
break;
/* case 73:
this.setLoop('start');
break;
@ -205,7 +209,7 @@ const listeners = {
// Toggle controls on mouse events and entering fullscreen
utils.on(
this.elements.container,
'mouseenter mouseleave mousemove touchstart touchend touchcancel touchmove enterfullscreen',
'click mouseenter mouseleave mousemove touchmove enterfullscreen exitfullscreen',
event => {
this.toggleControls(event);
}
@ -213,11 +217,11 @@ const listeners = {
}
// Handle user exiting fullscreen by escaping etc
if (fullscreen.enabled) {
/* if (fullscreen.enabled) {
utils.on(document, fullscreen.eventType, event => {
this.toggleFullscreen(event);
});
}
} */
},
// Listen for media events
@ -226,7 +230,7 @@ const listeners = {
utils.on(this.media, 'timeupdate seeking', event => ui.timeUpdate.call(this, event));
// Display duration
utils.on(this.media, 'durationchange loadedmetadata', event => ui.displayDuration.call(this, event));
utils.on(this.media, 'durationchange loadedmetadata', event => ui.durationUpdate.call(this, event));
// Handle the media finishing
utils.on(this.media, 'ended', () => {
@ -314,7 +318,7 @@ const listeners = {
});
// Caption language change
utils.on(this.media, 'captionchange', () => {
utils.on(this.media, 'languagechange', () => {
// Save to storage
storage.set.call(this, { language: this.language });
});
@ -337,7 +341,14 @@ const listeners = {
// Proxy events to container
// Bubble up key events for Edge
utils.on(this.media, this.config.events.concat(['keyup', 'keydown']).join(' '), event => {
utils.dispatchEvent.call(this, this.elements.container, event.type, true);
let detail = {};
// Get error details from media
if (event.type === 'error') {
detail = this.media.error;
}
utils.dispatchEvent.call(this, this.elements.container, event.type, true, detail);
});
},
@ -452,11 +463,16 @@ const listeners = {
controls.showTab.call(this, event);
// Settings menu items - use event delegation as items are added/removed
// Settings - Language
if (utils.matches(event.target, this.config.selectors.inputs.language)) {
// Settings - Language
proxy(event, 'language', () => {
this.toggleCaptions(true);
this.language = event.target.value.toLowerCase();
const language = event.target.value;
this.toggleCaptions(!utils.is.empty(language));
if (!utils.is.empty(language)) {
this.language = event.target.value.toLowerCase();
}
});
} else if (utils.matches(event.target, this.config.selectors.inputs.quality)) {
// Settings - Quality
@ -468,7 +484,7 @@ const listeners = {
proxy(event, 'speed', () => {
this.speed = parseFloat(event.target.value);
});
} else if (utils.matches(event.target, this.config.selectors.buttons.loop)) {
} /* else if (utils.matches(event.target, this.config.selectors.buttons.loop)) {
// Settings - Looping
// TODO: use toggle buttons
proxy(event, 'loop', () => {
@ -477,7 +493,7 @@ const listeners = {
this.console.warn('Set loop');
});
}
} */
});
// Seek
@ -487,6 +503,20 @@ const listeners = {
})
);
// Current time invert
// Only if one time element is used for both currentTime and duration
if (this.config.toggleInvert && !utils.is.htmlElement(this.elements.display.duration)) {
utils.on(this.elements.display.currentTime, 'click', () => {
// Do nothing if we're at the start
if (this.currentTime === 0) {
return;
}
this.config.invertTime = !this.config.invertTime;
ui.timeUpdate.call(this);
});
}
// Volume
utils.on(this.elements.inputs.volume, inputEvent, event =>
proxy(event, 'volume', () => {
@ -522,7 +552,7 @@ const listeners = {
// TODO: Check we need capture here
utils.on(
this.elements.controls,
'focus blur',
'focusin focusout',
event => {
this.toggleControls(event);
},

View File

@ -65,7 +65,6 @@ const media = {
utils.wrap(this.media, this.elements.wrapper);
}
// Embeds
if (this.isEmbed) {
switch (this.type) {
case 'youtube':
@ -79,9 +78,9 @@ const media = {
default:
break;
}
} else {
ui.setTitle.call(this);
}
ui.setTitle.call(this);
},
// Cancel current network requests

View File

@ -37,7 +37,8 @@ const vimeo = {
setAspectRatio(input) {
const ratio = utils.is.string(input) ? input.split(':') : this.config.ratio.split(':');
const padding = 100 / ratio[0] * ratio[1];
const offset = (300 - padding) / 6;
const height = 200;
const offset = (height - padding) / (height / 50);
this.elements.wrapper.style.paddingBottom = `${padding}%`;
this.media.style.transform = `translateY(-${offset}%)`;
},
@ -55,6 +56,7 @@ const vimeo = {
title: false,
speed: true,
transparent: 0,
gesture: 'media',
};
const params = utils.buildUrlParameters(options);
const id = utils.parseVimeoId(player.embedId);
@ -70,23 +72,27 @@ const vimeo = {
// https://github.com/vimeo/player.js
player.embed = new window.Vimeo.Player(iframe);
// Create a faux HTML5 API using the Vimeo API
player.media.play = () => {
player.embed.play();
player.media.paused = false;
};
player.media.pause = () => {
player.embed.pause();
player.media.paused = true;
};
player.media.stop = () => {
player.embed.stop();
player.media.paused = true;
};
player.media.paused = true;
player.media.currentTime = 0;
// Create a faux HTML5 API using the Vimeo API
player.media.play = () => {
player.embed.play().then(() => {
player.media.paused = false;
});
};
player.media.pause = () => {
player.embed.pause().then(() => {
player.media.paused = true;
});
};
player.media.stop = () => {
player.embed.stop().then(() => {
player.media.paused = true;
player.currentTime = 0;
});
};
// Seeking
let { currentTime } = player.media;
Object.defineProperty(player.media, 'currentTime', {
@ -121,9 +127,10 @@ const vimeo = {
return speed;
},
set(input) {
speed = input;
player.embed.setPlaybackRate(input);
utils.dispatchEvent.call(player, player.media, 'ratechange');
player.embed.setPlaybackRate(input).then(() => {
speed = input;
utils.dispatchEvent.call(player, player.media, 'ratechange');
});
},
});
@ -134,9 +141,10 @@ const vimeo = {
return volume;
},
set(input) {
volume = input;
player.embed.setVolume(input);
utils.dispatchEvent.call(player, player.media, 'volumechange');
player.embed.setVolume(input).then(() => {
volume = input;
utils.dispatchEvent.call(player, player.media, 'volumechange');
});
},
});
@ -148,9 +156,11 @@ const vimeo = {
},
set(input) {
const toggle = utils.is.boolean(input) ? input : false;
muted = toggle;
player.embed.setVolume(toggle ? 0 : player.config.volume);
utils.dispatchEvent.call(player, player.media, 'volumechange');
player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {
muted = toggle;
utils.dispatchEvent.call(player, player.media, 'volumechange');
});
},
});
@ -161,8 +171,11 @@ const vimeo = {
return loop;
},
set(input) {
loop = utils.is.boolean(input) ? input : player.config.loop.active;
player.embed.setLoop(loop);
const toggle = utils.is.boolean(input) ? input : player.config.loop.active;
player.embed.setLoop(toggle).then(() => {
loop = toggle;
});
},
});
@ -191,6 +204,7 @@ const vimeo = {
// Get title
player.embed.getVideoTitle().then(title => {
player.config.title = title;
ui.setTitle.call(this);
});
// Get current time
@ -269,6 +283,11 @@ const vimeo = {
utils.dispatchEvent.call(player, player.media, 'ended');
});
player.embed.on('error', detail => {
player.media.error = detail;
utils.dispatchEvent.call(player, player.media, 'error');
});
// Rebuild UI
window.setTimeout(() => ui.build.call(player), 0);
},

View File

@ -23,6 +23,22 @@ const youtube = {
// Set ID
this.media.setAttribute('id', utils.generateId(this.type));
// Get the media title via Google API
const key = this.config.keys.google;
if (utils.is.string(key) && !utils.is.empty(key)) {
const url = `https://www.googleapis.com/youtube/v3/videos?id=${videoId}&key=${key}&fields=items(snippet(title))&part=snippet`;
fetch(url)
.then(response => (response.ok ? response.json() : null))
.then(result => {
if (result !== null && utils.is.object(result)) {
this.config.title = result.items[0].snippet.title;
ui.setTitle.call(this);
}
})
.catch(() => {});
}
// Setup API
if (utils.is.object(window.YT)) {
youtube.ready.call(this, videoId);
@ -81,10 +97,47 @@ const youtube = {
},
events: {
onError(event) {
utils.dispatchEvent.call(player, player.media, 'error', true, {
// If we've already fired an error, don't do it again
// YouTube fires onError twice
if (utils.is.object(player.media.error)) {
return;
}
const detail = {
code: event.data,
embed: event.target,
});
};
// Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError
switch (event.data) {
case 2:
detail.message =
'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.';
break;
case 5:
detail.message =
'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.';
break;
case 100:
detail.message =
'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.';
break;
case 101:
case 150:
detail.message =
'The owner of the requested video does not allow it to be played in embedded players.';
break;
default:
detail.message = 'An unknown error occured';
break;
}
player.media.error = detail;
utils.dispatchEvent.call(player, player.media, 'error');
},
onPlaybackQualityChange(event) {
// Get the instance
@ -207,7 +260,9 @@ const youtube = {
}
// Set title
player.config.title = instance.getVideoData().title;
if (utils.is.function(instance.getVideoData)) {
player.config.title = instance.getVideoData().title;
}
// Set the tabindex to avoid focus entering iframe
if (player.supported.ui) {

View File

@ -669,7 +669,7 @@ class Plyr {
const language = input.toLowerCase();
// If nothing to change, bail
if (this.captions.language === language) {
if (this.language === language) {
return;
}
@ -680,7 +680,7 @@ class Plyr {
this.captions.language = language;
// Trigger an event
utils.dispatchEvent.call(this, this.media, 'captionchange');
utils.dispatchEvent.call(this, this.media, 'languagechange');
// Clear caption
captions.set.call(this);
@ -797,31 +797,28 @@ class Plyr {
// Show the player controls in fullscreen mode
toggleControls(toggle) {
const player = this;
// We need controls of course...
if (!utils.is.htmlElement(this.elements.controls)) {
return player;
return this;
}
// Don't hide if config says not to, it's audio, or not ready or loading
if (!this.supported.ui || !this.config.hideControls || this.type === 'audio') {
return player;
return this;
}
let delay = 0;
let show = toggle;
let isEnterFullscreen = false;
const loading = utils.hasClass(this.elements.container, this.config.classNames.loading);
// Default to false if no boolean
// Get toggle state if not set
if (!utils.is.boolean(toggle)) {
if (utils.is.event(toggle)) {
// Is the enter fullscreen event
isEnterFullscreen = toggle.type === 'enterfullscreen';
// Whether to show controls
show = ['mousemove', 'touchstart', 'mouseenter', 'focus'].includes(toggle.type);
show = ['click', 'mousemove', 'touchmove', 'mouseenter', 'focusin'].includes(toggle.type);
// Delay hiding on move events
if (['mousemove', 'touchmove'].includes(toggle.type)) {
@ -829,8 +826,9 @@ class Plyr {
}
// Delay a little more for keyboard users
if (toggle.type === 'focus') {
if (toggle.type === 'focusin') {
delay = 3000;
utils.toggleClass(this.elements.controls, this.config.classNames.noTransition, true);
}
} else {
show = utils.hasClass(this.elements.container, this.config.classNames.hideControls);
@ -841,7 +839,7 @@ class Plyr {
window.clearTimeout(this.timers.hover);
// If the mouse is not over the controls, set a timeout to hide them
if (show || this.media.paused || loading) {
if (show || this.media.paused || this.loading) {
// Check if controls toggled
const toggled = utils.toggleClass(this.elements.container, this.config.classNames.hideControls, false);
@ -851,8 +849,8 @@ class Plyr {
}
// Always show controls when paused or if touch
if (this.media.paused || loading) {
return player;
if (this.media.paused || this.loading) {
return this;
}
// Delay for hiding on touch
@ -870,6 +868,11 @@ class Plyr {
return;
}
// Restore transition behaviour
if (!utils.hasClass(this.elements.container, this.config.classNames.hideControls)) {
utils.toggleClass(this.elements.controls, this.config.classNames.noTransition, false);
}
// Check if controls toggled
const toggled = utils.toggleClass(this.elements.container, this.config.classNames.hideControls, true);

View File

@ -15,7 +15,7 @@ const ui = {
},
// Toggle native HTML5 media controls
toggleNativeControls(toggle) {
toggleNativeControls(toggle = false) {
if (toggle && this.isHTML5) {
this.media.setAttribute('controls', '');
} else {
@ -96,31 +96,8 @@ const ui = {
// Ready event at end of execution stack
utils.dispatchEvent.call(this, this.media, 'ready');
// Autoplay
// TODO: check we still need this?
/* if (this.isEmbed && this.config.autoplay) {
this.play();
} */
},
// Show the duration on metadataloaded
displayDuration() {
if (!this.supported.ui) {
return;
}
// If there's only one time display, display duration there
if (!this.elements.display.duration && this.config.displayDuration && this.paused) {
ui.updateTimeDisplay.call(this, this.duration, this.elements.display.currentTime);
}
// If there's a duration element, update content
if (this.elements.display.duration) {
ui.updateTimeDisplay.call(this, this.duration, this.elements.display.duration);
}
// Update the tooltip (if visible)
controls.updateSeekTooltip.call(this);
// Set the title
ui.setTitle.call(this);
},
// Setup aria attribute for play and iframe title
@ -137,13 +114,10 @@ const ui = {
}
// If there's a play button, set label
if (this.supported.ui) {
if (utils.is.htmlElement(this.elements.buttons.play)) {
this.elements.buttons.play.setAttribute('aria-label', label);
}
if (utils.is.htmlElement(this.elements.buttons.playLarge)) {
this.elements.buttons.playLarge.setAttribute('aria-label', label);
}
if (utils.is.nodeList(this.elements.buttons.play)) {
Array.from(this.elements.buttons.play).forEach(button => {
button.setAttribute('aria-label', label);
});
}
// Set iframe title
@ -171,23 +145,6 @@ const ui = {
this.toggleControls(this.paused);
},
// Update volume UI and storage
updateVolume() {
if (!this.supported.ui) {
return;
}
// Update range
if (utils.is.htmlElement(this.elements.inputs.volume)) {
ui.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);
}
// Update checkbox for mute state
if (utils.is.htmlElement(this.elements.buttons.mute)) {
utils.toggleState(this.elements.buttons.mute, this.muted || this.volume === 0);
}
},
// Check if media is loading
checkLoading(event) {
this.loading = event.type === 'waiting';
@ -205,8 +162,25 @@ const ui = {
}, this.loading ? 250 : 0);
},
// Update volume UI and storage
updateVolume() {
if (!this.supported.ui) {
return;
}
// Update range
if (utils.is.htmlElement(this.elements.inputs.volume)) {
ui.setRange.call(this, this.elements.inputs.volume, this.muted ? 0 : this.volume);
}
// Update checkbox for mute state
if (utils.is.htmlElement(this.elements.buttons.mute)) {
utils.toggleState(this.elements.buttons.mute, this.muted || this.volume === 0);
}
},
// Update seek value and lower fill
setRange(target, value) {
setRange(target, value = 0) {
if (!utils.is.htmlElement(target)) {
return;
}
@ -220,9 +194,8 @@ const ui = {
// Set <progress> value
setProgress(target, input) {
// Default to 0
const value = !utils.is.undefined(input) ? input : 0;
const progress = !utils.is.undefined(target) ? target : this.elements.display.buffer;
const value = utils.is.number(input) ? input : 0;
const progress = utils.is.htmlElement(target) ? target : this.elements.display.buffer;
// Update value and label
if (utils.is.htmlElement(progress)) {
@ -238,7 +211,7 @@ const ui = {
// Update <progress> elements
updateProgress(event) {
if (!this.supported.ui) {
if (!this.supported.ui || !utils.is.event(event)) {
return;
}
@ -286,41 +259,49 @@ const ui = {
},
// Update the displayed time
updateTimeDisplay(value, element) {
// Bail if there's no duration display
if (!utils.is.htmlElement(element)) {
return null;
updateTimeDisplay(target = null, time = 0, inverted = false) {
// Bail if there's no element to display or the value isn't a number
if (!utils.is.htmlElement(target) || !utils.is.number(time)) {
return;
}
// Fallback to 0
const time = !Number.isNaN(value) ? value : 0;
// Format time component to add leading zero
const format = value => `0${value}`.slice(-2);
let secs = parseInt(time % 60, 10);
let mins = parseInt((time / 60) % 60, 10);
const hours = parseInt((time / 60 / 60) % 60, 10);
// Helpers
const getHours = value => parseInt((value / 60 / 60) % 60, 10);
const getMinutes = value => parseInt((value / 60) % 60, 10);
const getSeconds = value => parseInt(value % 60, 10);
// Breakdown to hours, mins, secs
let hours = getHours(time);
const mins = getMinutes(time);
const secs = getSeconds(time);
// Do we need to display hours?
const displayHours = parseInt((this.duration / 60 / 60) % 60, 10) > 0;
// Ensure it's two digits. For example, 03 rather than 3.
secs = `0${secs}`.slice(-2);
mins = `0${mins}`.slice(-2);
// Generate display
const display = `${(displayHours ? `${hours}:` : '') + mins}:${secs}`;
if (getHours(this.duration) > 0) {
hours = `${hours}:`;
} else {
hours = '';
}
// Render
// eslint-disable-next-line
element.textContent = display;
// Return for looping
return display;
// eslint-disable-next-line no-param-reassign
target.textContent = `${inverted ? '-' : ''}${hours}${format(mins)}:${format(secs)}`;
},
// Handle time change event
timeUpdate(event) {
// Only invert if only one time element is displayed and used for both duration and currentTime
const invert = !utils.is.htmlElement(this.elements.display.duration) && this.config.invertTime;
// Duration
ui.updateTimeDisplay.call(this, this.currentTime, this.elements.display.currentTime);
ui.updateTimeDisplay.call(
this,
this.elements.display.currentTime,
invert ? this.duration - this.currentTime : this.currentTime,
invert
);
// Ignore updates while seeking
if (event && event.type === 'timeupdate' && this.media.seeking) {
@ -330,6 +311,26 @@ const ui = {
// Playing progress
ui.updateProgress.call(this, event);
},
// Show the duration on metadataloaded
durationUpdate() {
if (!this.supported.ui) {
return;
}
// If there's only one time display, display duration there
if (!utils.is.htmlElement(this.elements.display.duration) && this.config.displayDuration && this.paused) {
ui.updateTimeDisplay.call(this, this.elements.display.currentTime, this.duration);
}
// If there's a duration element, update content
if (utils.is.htmlElement(this.elements.display.duration)) {
ui.updateTimeDisplay.call(this, this.elements.display.duration, this.duration);
}
// Update the tooltip (if visible)
controls.updateSeekTooltip.call(this);
},
};
export default ui;

View File

@ -31,6 +31,9 @@ const utils = {
htmlElement(input) {
return !this.undefined(input) && input instanceof HTMLElement;
},
textNode(input) {
return this.getConstructor(input) === Text;
},
event(input) {
return !this.undefined(input) && input instanceof Event;
},
@ -49,8 +52,8 @@ const utils = {
return (
input === null ||
typeof input === 'undefined' ||
((this.string(input) || this.array(input) || this.nodeList(input)) && input.length === 0) ||
(this.object(input) && Object.keys(input).length === 0)
((this.string(input) || this.array(input) || this.nodeList(input)) && !input.length) ||
(this.object(input) && !Object.keys(input).length)
);
},
getConstructor(input) {
@ -100,12 +103,12 @@ const utils = {
// Load an external SVG sprite
loadSprite(url, id) {
if (typeof url !== 'string') {
if (!utils.is.string(url)) {
return;
}
const prefix = 'cache-';
const hasId = typeof id === 'string';
const hasId = utils.is.string(id);
let isCached = false;
function updateSprite(data) {
@ -134,34 +137,30 @@ const utils = {
if (isCached) {
const data = JSON.parse(cached);
updateSprite.call(container, data.content);
return;
}
}
// ReSharper disable once InconsistentNaming
const xhr = new XMLHttpRequest();
// Get the sprite
fetch(url)
.then(response => (response.ok ? response.text() : null))
.then(text => {
if (text === null) {
return;
}
// XHR for Chrome/Firefox/Opera/Safari
if ('withCredentials' in xhr) {
xhr.open('GET', url, true);
} else {
return;
}
if (support.storage) {
window.localStorage.setItem(
prefix + id,
JSON.stringify({
content: text,
})
);
}
// Once loaded, inject to container and body
xhr.onload = () => {
if (support.storage) {
window.localStorage.setItem(
prefix + id,
JSON.stringify({
content: xhr.responseText,
})
);
}
updateSprite.call(container, xhr.responseText);
};
xhr.send();
updateSprite.call(container, text);
})
.catch(() => {});
}
},
@ -210,22 +209,6 @@ const utils = {
});
},
// Remove an element
removeElement(element) {
if (!utils.is.htmlElement(element) || !utils.is.htmlElement(element.parentNode)) {
return null;
}
element.parentNode.removeChild(element);
return element;
},
// Inaert an element after another
insertAfter(element, target) {
target.parentNode.insertBefore(element, target.nextSibling);
},
// Create a DocumentFragment
createElement(type, attributes, text) {
// Create a new <element>
@ -245,12 +228,28 @@ const utils = {
return element;
},
// Inaert an element after another
insertAfter(element, target) {
target.parentNode.insertBefore(element, target.nextSibling);
},
// Insert a DocumentFragment
insertElement(type, parent, attributes, text) {
// Inject the new <element>
parent.appendChild(utils.createElement(type, attributes, text));
},
// Remove an element
removeElement(element) {
if (!utils.is.htmlElement(element) || !utils.is.htmlElement(element.parentNode)) {
return null;
}
element.parentNode.removeChild(element);
return element;
},
// Remove all child elements
emptyElement(element) {
let { length } = element.childNodes;
@ -442,9 +441,9 @@ const utils = {
// Trap focus inside container
trapFocus() {
const tabbables = utils.getElements.call(this, 'button:not(:disabled), input:not(:disabled), [tabindex]');
const first = tabbables[0];
const last = tabbables[tabbables.length - 1];
const focusable = utils.getElements.call(this, 'button:not(:disabled), input:not(:disabled), [tabindex]');
const first = focusable[0];
const last = focusable[focusable.length - 1];
utils.on(
this.elements.container,
@ -525,7 +524,7 @@ const utils = {
},
// Trigger event
dispatchEvent(element, type, bubbles, properties) {
dispatchEvent(element, type, bubbles, detail) {
// Bail if no element
if (!element || !type) {
return;
@ -534,7 +533,7 @@ const utils = {
// Create and dispatch the event
const event = new CustomEvent(type, {
bubbles: utils.is.boolean(bubbles) ? bubbles : false,
detail: Object.assign({}, properties, {
detail: Object.assign({}, detail, {
plyr: this instanceof Plyr ? this : null,
}),
});

View File

@ -12,6 +12,7 @@
line-height: @plyr-line-height;
direction: ltr;
text-shadow: none;
transition: box-shadow 0.3s ease;
.plyr-font-smoothing(off);
// Media elements
@ -22,6 +23,11 @@
vertical-align: middle;
border-radius: inherit;
}
&:focus {
outline: 0;
box-shadow: 0 0 0 3px fade(#000, 10%);
}
}
// Full UI only

View File

@ -26,4 +26,5 @@
@import 'states/fullscreen';
@import 'utils/animation';
@import 'utils/hidden';

View File

@ -3,11 +3,11 @@
// --------------------------------------------------------------
.plyr__badge {
padding: 0 4px;
padding: 3px 4px;
border-radius: 2px;
background: @plyr-menu-color;
color: @plyr-menu-bg;
font-size: @plyr-font-size-tiny;
line-height: 1.5;
line-height: 1;
.plyr-font-smoothing(on);
}

View File

@ -53,13 +53,13 @@
.plyr__play-large {
display: none;
position: absolute;
z-index: 1;
z-index: 3;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: ceil(@plyr-control-spacing * 1.25);
padding: ceil(@plyr-control-spacing * 1.5);
background: fade(@plyr-video-control-bg-hover, 80%);
border: 3px solid currentColor;
border: 0;
border-radius: 100%;
box-shadow: 0 1px 1px fade(#000, 15%);
color: @plyr-video-control-color;
@ -81,7 +81,12 @@
}
&:focus {
outline: 1px dotted fade(@plyr-video-control-color, 50%);
outline: 0;
}
&.plyr__tab-focus {
outline: 0;
box-shadow: 0 0 0 3px fade(@plyr-video-control-color, 50%);
}
}

View File

@ -6,7 +6,8 @@
.plyr__video-embed {
// Default to 16:9 ratio but this is set by JavaScript based on config
@padding: ((100 / 16) * 9);
@offset: unit((300 - @padding) / 6, ~'%');
@height: 200;
@offset: unit((@height - @padding) / (@height / 50), ~'%');
padding-bottom: unit(@padding, ~'%');
height: 0;
@ -24,7 +25,7 @@
// Vimeo hack
> div {
position: relative;
padding-bottom: 300%;
padding-bottom: unit(@height, ~'%');
transform: translateY(-@offset);
}
}

View File

@ -129,11 +129,45 @@
}
label.plyr__control {
padding-left: ceil(@plyr-control-padding * 2.5);
padding-left: @plyr-control-padding;
input[type='radio'] {
/*input[type='radio'] {
position: relative;
left: -@plyr-control-padding;
}*/
input[type='radio'] + span {
position: relative;
display: block;
height: 14px;
width: 14px;
border-radius: 100%;
background: fade(#000, 10%);
margin-right: @plyr-control-spacing;
box-shadow: inset 0 1px 1px fade(#000, 15%);
&::after {
content: '';
position: absolute;
height: 6px;
width: 6px;
top: 4px;
left: 4px;
transform: scale(0);
opacity: 0;
background: #fff;
border-radius: 100%;
transition: transform 0.3s ease, opacity 0.3s ease;
}
}
input[type='radio']:checked + span {
background: @plyr-color-main;
&::after {
transform: scale(1);
opacity: 1;
}
}
}

View File

@ -12,6 +12,8 @@
cursor: pointer;
border: none;
background: transparent;
transition: box-shadow 0.3s ease;
border-radius: (@plyr-range-thumb-height * 2);
// Used in JS to populate lower fill for WebKit
color: @plyr-range-selected-bg;
@ -79,10 +81,6 @@
border: 0;
}
&.plyr__tab-focus {
outline-offset: 3px;
}
// Pressed styles
&:active {
&::-webkit-slider-thumb {
@ -114,7 +112,7 @@
}
&.plyr__tab-focus {
outline: 1px dotted fade(@plyr-video-control-color, 50%);
box-shadow: 0 0 0 3px fade(@plyr-video-control-color, 50%);
}
}
@ -133,6 +131,6 @@
}
&.plyr__tab-focus {
outline: 1px dotted fade(@plyr-audio-control-color, 50%);
box-shadow: 0 0 0 3px fade(@plyr-audio-control-color, 50%);
}
}

View File

@ -0,0 +1,7 @@
// --------------------------------------------------------------
// Animation utils
// --------------------------------------------------------------
.plyr--no-transition {
transition: none !important;
}