Merge branch 'develop' into css-variables

# Conflicts:
#	demo/dist/demo.css
#	demo/index.html
#	dist/plyr.css
#	gulpfile.js
#	package.json
#	yarn.lock
This commit is contained in:
Sam Potts
2019-03-16 12:14:20 +11:00
56 changed files with 24998 additions and 14943 deletions

View File

@ -2,8 +2,9 @@ demo
.github
.vscode
*.code-workspace
build.json
credentials.json
bundles.json
deploy.json
yarn.lock
package-lock.json
*.mp4

46
build.json Normal file
View File

@ -0,0 +1,46 @@
{
"js": {
"plyr.js": {
"src": "./src/js/plyr.js",
"dist": "./dist/",
"formats": ["es", "umd"],
"namespace": "Plyr"
},
"plyr.polyfilled.js": {
"src": "./src/js/plyr.polyfilled.js",
"dist": "./dist/",
"formats": ["es", "umd"],
"namespace": "Plyr"
},
"demo.js": {
"src": "./demo/src/js/demo.js",
"dist": "./demo/dist/",
"formats": ["iife"],
"namespace": "Demo"
}
},
"css": {
"plyr.css": {
"src": "./src/sass/plyr.scss",
"dist": "./dist/"
},
"demo.css": {
"src": "./demo/src/sass/bundles/demo.scss",
"dist": "./demo/dist/"
},
"error.css": {
"src": "./demo/src/sass/bundles/error.scss",
"dist": "./demo/dist/"
}
},
"sprite": {
"plyr.svg": {
"src": "./src/sprite/*.svg",
"dist": "./dist"
},
"demo.svg": {
"src": "./src/sprite/*.svg",
"dist": "./demo/dist"
}
}
}

View File

@ -1,20 +0,0 @@
{
"plyr": {
"sass": {
"plyr.css": "src/sass/plyr.scss"
},
"js": {
"plyr.js": "src/js/plyr.js",
"plyr.polyfilled.js": "src/js/plyr.polyfilled.js"
}
},
"demo": {
"sass": {
"demo.css": "demo/src/sass/bundles/demo.scss",
"error.css": "demo/src/sass/bundles/error.scss"
},
"js": {
"demo.js": "demo/src/js/demo.js"
}
}
}

View File

@ -1,3 +1,28 @@
## v3.5.2
- Fixed issue where the preview thumbnail was present while scrubbing
## v3.5.1
- Fixed build issues with babel and browserslist
## v3.5.0
- Preview seek/scrubbing thumbnails (thanks @jamesoflol)
- Fixes for proxy listeners (thanks @gurupras)
- Fix for buffer progress transition on WebKit (thanks @samuelgozi)
- Fix for error when mime type not specified (fixes #1274)
- Support YouTube noCookie (thanks Omar Khatib)
- Add Angular plugin reference (thanks @smnbbrv)
- Use `Math.trunc` instead of `parseInt` (thanks @taion)
- Many fixes for fullscreen in embedded players with non 16:9 screens or videos
- Added 'force' fallback option for fullscreen
- [RangeTouch](https://rangetouch.com) is now bundled with Plyr as a dependency to fix the scrubber on touch devices
### v3.4.8
- Calling customized controls function with proper arguments (thanks @a60814billy)
### v3.4.7
- Fix for Vimeo fullscreen with non native aspect ratios (fixes #854)
@ -48,7 +73,7 @@
- Add support for YouTube's hl param (thanks @renaudleo)
- Fix for captions positioning when no controls (thanks @friday and @mjfwebb)
- Fix #1108: Make sure youtube.onReady doesn't run twice (thanks @friday)
- Fix for WebKit redraw loop on the `<input type="range">` elements
- Fix for WebKit repaint loop on the `<input type="range">` elements
### v3.3.22

2
demo/dist/demo.css vendored

File diff suppressed because one or more lines are too long

10522
demo/dist/demo.js vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
demo/dist/demo.svg vendored Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 5.4 KiB

View File

@ -33,7 +33,7 @@
<meta name="twitter:card" content="summary_large_image" />
<!-- Docs styles -->
<link rel="stylesheet" href="dist/demo.css?v=2" />
<link rel="stylesheet" href="dist/demo.css" />
<!-- Preload -->
<link
@ -108,7 +108,7 @@
<div class="call-to-action">
<span class="button--with-count">
<a
href="https://github.com/sampotts/plyr"
<a href="https://github.com/sampotts/plyr" target="_blank" class="button js-shr-button">
target="_blank"
class="button"
data-shr-network="github"
@ -261,7 +261,7 @@
<a
href="https://twitter.com/intent/tweet?text=A+simple+HTML5+media+player+with+custom+controls+and+WebVTT+captions.&amp;url=http%3A%2F%2Fplyr.io&amp;via=Sam_Potts"
target="_blank"
data-shr-network="twitter"
class="js-shr-button"
>tweet it</a
>
👍
@ -270,18 +270,12 @@
<!-- Polyfills -->
<script
src="https://cdn.polyfill.io/v2/polyfill.min.js?features=es6,Array.prototype.includes,CustomEvent,Object.entries,Object.values,URL"
src="https://cdn.polyfill.io/v2/polyfill.min.js?features=es6,Array.prototype.includes,CustomEvent,Object.entries,Object.values,URL,Math.trunc"
crossorigin="anonymous"
></script>
<!-- Plyr core script -->
<script src="../dist/plyr.js" crossorigin="anonymous"></script>
<!-- Sharing libary (https://shr.one) -->
<script src="https://cdn.shr.one/1.0.1/shr.js" crossorigin="anonymous"></script>
<!-- Rangetouch to fix <input type="range"> on touch devices (see https://rangetouch.com) -->
<script src="https://cdn.rangetouch.com/1.0.1/rangetouch.js" async crossorigin="anonymous"></script>
<script src="https://cdn.shr.one/2.0.0-beta.2/shr.js" crossorigin="anonymous"></script>
<!-- Docs script -->
<script src="dist/demo.js" crossorigin="anonymous"></script>

View File

@ -5,6 +5,7 @@
// ==========================================================================
import Raven from 'raven-js';
import Plyr from '../../../src/js/plyr';
(() => {
const { host } = window.location;
@ -18,8 +19,8 @@ import Raven from 'raven-js';
const selector = '#player';
const container = document.getElementById('container');
if (window.shr) {
window.shr.setup({
if (window.Shr) {
window.Shr.setup('.js-shr-button', {
count: {
classname: 'button__count',
},
@ -61,7 +62,7 @@ import Raven from 'raven-js';
const player = new Plyr(selector, {
debug: true,
title: 'View From A Blue Moon',
iconUrl: '../dist/plyr.svg',
iconUrl: 'dist/demo.svg',
keyboard: {
global: true,
},
@ -78,6 +79,13 @@ import Raven from 'raven-js';
enabled: env.prod || env.dev,
publisherId: '918848828995742',
},
previewThumbnails: {
enabled: true,
src: [
'https://cdn.plyr.io/static/demo/thumbs/100p.vtt',
'https://cdn.plyr.io/static/demo/thumbs/240p.vtt',
],
},
});
// Expose for tinkering in the console
@ -276,27 +284,4 @@ import Raven from 'raven-js';
if (env.prod) {
Raven.config('https://d4ad9866ad834437a4754e23937071e4@sentry.io/305555').install();
}
// Google analytics
// For demo site (https://plyr.io) only
/* eslint-disable */
if (env.prod) {
((i, s, o, g, r, a, m) => {
i.GoogleAnalyticsObject = r;
i[r] =
i[r] ||
function() {
(i[r].q = i[r].q || []).push(arguments);
};
i[r].l = 1 * new Date();
a = s.createElement(o);
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m);
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
window.ga('create', 'UA-40881672-11', 'auto');
window.ga('send', 'pageview');
}
/* eslint-enable */
})();

12
deploy.json Normal file
View File

@ -0,0 +1,12 @@
{
"cdn": {
"bucket": "plyr",
"domain": "cdn.plyr.io",
"region": "us-east-1"
},
"demo": {
"bucket": "plyr.io",
"domain": "plyr.io",
"region": "us-west-1"
}
}

2
dist/plyr.css vendored

File diff suppressed because one or more lines are too long

2468
dist/plyr.js vendored

File diff suppressed because it is too large Load Diff

1
dist/plyr.js.map vendored

File diff suppressed because one or more lines are too long

2
dist/plyr.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

0
dist/plyr.min.mjs vendored Normal file
View File

1
dist/plyr.min.mjs.map vendored Normal file

File diff suppressed because one or more lines are too long

8918
dist/plyr.mjs vendored Normal file

File diff suppressed because it is too large Load Diff

10448
dist/plyr.polyfilled.js vendored

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

2
dist/plyr.svg vendored

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 5.4 KiB

View File

@ -4,110 +4,117 @@
/* global require, __dirname */
/* eslint no-console: "off" */
const del = require('del');
const path = require('path');
const gulp = require('gulp');
const gutil = require('gulp-util');
const concat = require('gulp-concat');
const filter = require('gulp-filter');
const sass = require('gulp-sass');
const cleancss = require('gulp-clean-css');
const postcss = require('gulp-postcss');
const customprops = require('postcss-custom-properties');
const header = require('gulp-header');
const prefix = require('gulp-autoprefixer');
const gitbranch = require('git-branch');
const svgstore = require('gulp-svgstore');
const svgmin = require('gulp-svgmin');
const rename = require('gulp-rename');
const s3 = require('gulp-s3');
const replace = require('gulp-replace');
const open = require('gulp-open');
const size = require('gulp-size');
// JavaScript
const terser = require('gulp-terser');
const rollup = require('gulp-better-rollup');
const babel = require('rollup-plugin-babel');
const sourcemaps = require('gulp-sourcemaps');
const uglify = require('gulp-uglify-es').default;
const commonjs = require('rollup-plugin-commonjs');
const resolve = require('rollup-plugin-node-resolve');
const FastlyPurge = require('fastly-purge');
// CSS
const sass = require('gulp-sass');
const clean = require('gulp-clean-css');
const prefix = require('gulp-autoprefixer');
const postcss = require('gulp-postcss');
const customprops = require('postcss-custom-properties');
// Images
const svgstore = require('gulp-svgstore');
const imagemin = require('gulp-imagemin');
// Utils
const del = require('del');
const filter = require('gulp-filter');
const header = require('gulp-header');
const gitbranch = require('git-branch');
const rename = require('gulp-rename');
const replace = require('gulp-replace');
const ansi = require('ansi-colors');
const log = require('fancy-log');
const open = require('gulp-open');
const plumber = require('gulp-plumber');
const size = require('gulp-size');
const sourcemaps = require('gulp-sourcemaps');
const through = require('through2');
const bundles = require('./bundles.json');
// Deployment
const aws = require('aws-sdk');
const publish = require('gulp-awspublish');
const FastlyPurge = require('fastly-purge');
const pkg = require('./package.json');
const build = require('./build.json');
const deploy = require('./deploy.json');
const { browserslist: browsers, version } = pkg;
const minSuffix = '.min';
// Get AWS config
Object.values(deploy).forEach(target => {
Object.assign(target, {
publisher: publish.create({
region: target.region,
params: {
Bucket: target.bucket,
},
credentials: new aws.SharedIniFileCredentials({ profile: 'plyr' }),
}),
});
});
// Paths
const root = __dirname;
const paths = {
plyr: {
// Source paths
src: {
sass: path.join(root, 'src/sass/**/*.scss'),
js: path.join(root, 'src/js/**/*.js'),
sprite: path.join(root, 'src/sprite/*.svg'),
sass: path.join(__dirname, 'src/sass/**/*.scss'),
js: path.join(__dirname, 'src/js/**/*.js'),
sprite: path.join(__dirname, 'src/sprite/*.svg'),
},
// Output paths
output: path.join(root, 'dist/'),
output: path.join(__dirname, 'dist/'),
},
demo: {
// Source paths
src: {
sass: path.join(root, 'demo/src/sass/**/*.scss'),
js: path.join(root, 'demo/src/js/**/*.js'),
sass: path.join(__dirname, 'demo/src/sass/**/*.scss'),
js: path.join(__dirname, 'demo/src/js/**/*.js'),
},
// Output paths
output: path.join(root, 'demo/dist/'),
output: path.join(__dirname, 'demo/dist/'),
// Demo
root: path.join(root, 'demo/'),
root: path.join(__dirname, 'demo/'),
},
upload: [
path.join(root, `dist/*${minSuffix}.*`),
path.join(root, 'dist/*.css'),
path.join(root, 'dist/*.svg'),
path.join(root, `demo/dist/*${minSuffix}.*`),
path.join(root, 'demo/dist/*.css'),
path.join(__dirname, `dist/*${minSuffix}.*`),
path.join(__dirname, 'dist/*.css'),
path.join(__dirname, 'dist/*.svg'),
path.join(__dirname, `demo/dist/*${minSuffix}.*`),
path.join(__dirname, 'demo/dist/*.css'),
path.join(__dirname, 'demo/dist/*.svg'),
],
};
// Task arrays
const tasks = {
sass: [],
css: [],
js: [],
sprite: [],
clean: ['clean'],
clean: 'clean',
};
// Size plugin
const sizeOptions = { showFiles: true, gzip: true };
// Browserlist
const browsers = ['> 1%'];
// Babel config
const babelrc = (polyfill = false) => ({
presets: [
[
'@babel/preset-env',
{
targets: {
browsers,
},
useBuiltIns: polyfill ? 'usage' : false,
modules: false,
},
],
],
babelrc: false,
exclude: 'node_modules/**',
});
// Clean out /dist
gulp.task('clean', done => {
gulp.task(tasks.clean, done => {
const dirs = [paths.plyr.output, paths.demo.output].map(dir => path.join(dir, '**/*'));
// Don't delete the mp4
@ -118,109 +125,119 @@ gulp.task('clean', done => {
done();
});
const build = {
js(files, bundle, options) {
Object.keys(files).forEach(key => {
const name = `js:${key}`;
// JavaScript
Object.entries(build.js).forEach(([filename, entry]) => {
entry.formats.forEach(format => {
const name = `js:${filename}:${format}`;
tasks.js.push(name);
const { output } = paths[bundle];
const polyfill = name.includes('polyfilled');
const polyfill = filename.includes('polyfilled');
const extension = format === 'es' ? 'mjs' : 'js';
return gulp.task(name, () =>
gulp.task(name, () =>
gulp
.src(bundles[bundle].js[key])
.src(entry.src)
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(concat(key))
.pipe(
rollup(
{
plugins: [resolve(), commonjs(), babel(babelrc(polyfill))],
plugins: [
resolve(),
commonjs(),
babel({
presets: [
[
'@babel/env',
{
// debug: true,
useBuiltIns: polyfill ? 'usage' : false,
},
],
],
babelrc: false,
exclude: [/\/core-js\//],
}),
],
},
{
name: entry.namespace,
format,
},
options,
),
)
.pipe(header('typeof navigator === "object" && ')) // "Support" SSR (#935)
.pipe(sourcemaps.write(''))
.pipe(gulp.dest(output))
.pipe(filter('**/*.js'))
.pipe(uglify())
.pipe(size(sizeOptions))
.pipe(rename({ suffix: minSuffix }))
.pipe(sourcemaps.write(''))
.pipe(gulp.dest(output)),
);
});
},
sass(files, bundle) {
Object.keys(files).forEach(key => {
const name = `sass:${key}`;
tasks.sass.push(name);
return gulp.task(name, () =>
gulp
.src(bundles[bundle].sass[key])
.pipe(sass())
.on('error', gutil.log)
.pipe(concat(key))
.pipe(prefix(browsers, { cascade: false }))
.pipe(postcss([customprops()]))
.pipe(cleancss())
.pipe(size(sizeOptions))
.pipe(gulp.dest(paths[bundle].output)),
);
});
},
sprite(bundle) {
const name = `svg:sprite:${bundle}`;
tasks.sprite.push(name);
// Process Icons
return gulp.task(name, () =>
gulp
.src(paths[bundle].src.sprite)
.pipe(
svgmin({
plugins: [
{
removeDesc: true,
},
],
rename({
extname: `.${extension}`,
}),
)
.pipe(svgstore())
.pipe(rename({ basename: bundle }))
.pipe(gulp.dest(entry.dist))
.pipe(filter(`**/*.${extension}`))
.pipe(terser())
.pipe(rename({ suffix: minSuffix }))
.pipe(size(sizeOptions))
.pipe(gulp.dest(paths[bundle].output)),
.pipe(sourcemaps.write(''))
.pipe(gulp.dest(entry.dist)),
);
},
};
});
});
// Plyr core files
build.js(bundles.plyr.js, 'plyr', { name: 'Plyr', format: 'umd' });
build.sass(bundles.plyr.sass, 'plyr');
build.sprite('plyr');
// CSS
Object.entries(build.css).forEach(([filename, entry]) => {
const name = `css:${filename}`;
tasks.css.push(name);
// Demo files
build.sass(bundles.demo.sass, 'demo');
build.js(bundles.demo.js, 'demo', { format: 'iife' });
gulp.task(name, () =>
gulp
.src(entry.src)
.pipe(plumber())
.pipe(sass())
.pipe(
prefix(browsers, {
cascade: false,
}),
)
.pipe(postcss([customprops()]))
.pipe(clean())
.pipe(size(sizeOptions))
.pipe(gulp.dest(entry.dist)),
);
});
// SVG Sprites
Object.entries(build.sprite).forEach(([filename, entry]) => {
const name = `sprite:${filename}`;
tasks.sprite.push(name);
gulp.task(name, () =>
gulp
.src(entry.src)
.pipe(plumber())
.pipe(imagemin())
.pipe(svgstore())
.pipe(rename({ basename: path.parse(filename).name }))
.pipe(size(sizeOptions))
.pipe(gulp.dest(entry.dist)),
);
});
// Build all JS
gulp.task('js', () => gulp.parallel(tasks.js));
gulp.task('js', () => gulp.parallel(...tasks.js));
// Watch for file changes
gulp.task('watch', () => {
// Plyr core
gulp.watch(paths.plyr.src.js, gulp.parallel(tasks.js));
gulp.watch(paths.plyr.src.sass, gulp.parallel(tasks.sass));
gulp.watch(paths.plyr.src.sprite, gulp.parallel(tasks.sprite));
gulp.watch(paths.plyr.src.js, gulp.parallel(...tasks.js));
gulp.watch(paths.plyr.src.sass, gulp.parallel(...tasks.css));
gulp.watch(paths.plyr.src.sprite, gulp.parallel(...tasks.sprite));
// Demo
gulp.watch(paths.demo.src.js, gulp.parallel(tasks.js));
gulp.watch(paths.demo.src.sass, gulp.parallel(tasks.sass));
gulp.watch(paths.demo.src.js, gulp.parallel(...tasks.js));
gulp.watch(paths.demo.src.sass, gulp.parallel(...tasks.css));
});
// Build distribution
gulp.task('build', gulp.series(tasks.clean, gulp.parallel(tasks.js, tasks.sass, tasks.sprite)));
gulp.task('build', gulp.series(tasks.clean, gulp.parallel(...tasks.js, ...tasks.css, ...tasks.sprite)));
// Default gulp task
gulp.task('default', gulp.series('build', 'watch'));
@ -235,16 +252,11 @@ try {
// Do nothing
}
// If deployment is setup
if (Object.keys(credentials).includes('aws') && Object.keys(credentials).includes('fastly')) {
const { version } = pkg;
const { aws, fastly } = credentials;
// Get branch info
const branch = {
current: gitbranch.sync(),
master: 'master',
develop: 'develop',
beta: 'beta',
};
const maxAge = 31536000; // 1 year
@ -252,14 +264,12 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
cdn: {
headers: {
'Cache-Control': `max-age=${maxAge}`,
Vary: 'Accept-Encoding',
},
},
demo: {
uploadPath: branch.current === branch.develop ? 'beta/' : null,
uploadPath: branch.current === branch.beta ? 'beta' : null,
headers: {
'Cache-Control': 'no-cache, no-store, must-revalidate, max-age=0',
Vary: 'Accept-Encoding',
},
},
symlinks(ver, filename) {
@ -277,8 +287,8 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
'(?:0|[1-9][0-9]*)\\.(?:0|[1-9][0-9]*).(?:0|[1-9][0-9]*)(?:-[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?(?:\\+[\\da-z\\-]+(?:.[\\da-z\\-]+)*)?';
const semver = new RegExp(`v${regex}`, 'gi');
const localPath = new RegExp('(../)?dist', 'gi');
const versionPath = `https://${aws.cdn.domain}/${version}`;
const cdnpath = new RegExp(`${aws.cdn.domain}/${regex}/`, 'gi');
const versionPath = `https://${deploy.cdn.domain}/${version}`;
const cdnpath = new RegExp(`${deploy.cdn.domain}/${regex}/`, 'gi');
const renameFile = rename(p => {
p.basename = p.basename.replace(minSuffix, ''); // eslint-disable-line
@ -287,7 +297,7 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
// Check we're on the correct branch to deploy
const canDeploy = () => {
const allowed = [branch.master, branch.develop];
const allowed = [branch.master, branch.beta];
if (!allowed.includes(branch.current)) {
console.error(`Must be on ${allowed.join(', ')} to publish! (current: ${branch.current})`);
@ -298,30 +308,40 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
return true;
};
gulp.task('version', () => {
gulp.task('version', done => {
if (!canDeploy()) {
done();
return null;
}
console.log(`Updating versions to '${version}'...`);
const { domain } = deploy.cdn;
log(`Uploading ${ansi.green.bold(version)} to ${ansi.cyan(domain)}...`);
// Replace versioned URLs in source
const files = ['plyr.js', 'plyr.polyfilled.js', 'config/defaults.js'];
return gulp
.src(files.map(file => path.join(root, `src/js/${file}`)), { base: '.' })
.src(files.map(file => path.join(__dirname, `src/js/${file}`)), { base: '.' })
.pipe(replace(semver, `v${version}`))
.pipe(replace(cdnpath, `${aws.cdn.domain}/${version}/`))
.pipe(replace(cdnpath, `${domain}/${version}/`))
.pipe(gulp.dest('./'));
});
// Publish version to CDN bucket
gulp.task('cdn', () => {
gulp.task('cdn', done => {
if (!canDeploy()) {
done();
return null;
}
console.log(`Uploading '${version}' to ${aws.cdn.domain}...`);
const { domain, publisher } = deploy.cdn;
if (!publisher) {
throw new Error('No publisher instance. Check AWS configuration.');
}
log(`Uploading ${ansi.green.bold(pkg.version)} to ${ansi.cyan(domain)}...`);
// Upload to CDN
return (
@ -332,22 +352,23 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
.pipe(
replace(
/sourceMappingURL=([\w-?.]+)/,
(match, p1) => `sourceMappingURL=${p1.replace(minSuffix, '')}`,
(match, filename) => `sourceMappingURL=${filename.replace(minSuffix, '')}`,
),
)
.pipe(
size({
showFiles: true,
gzip: true,
}),
)
.pipe(size(sizeOptions))
.pipe(replace(localPath, versionPath))
.pipe(s3(aws.cdn, options.cdn))
.pipe(publisher.publish(options.cdn.headers))
.pipe(publish.reporter())
);
});
// Purge the fastly cache incase any 403/404 are cached
gulp.task('purge', () => {
if (!Object.keys(credentials).includes('fastly')) {
throw new Error('Fastly credentials required to purge cache.');
}
const { fastly } = credentials;
const list = [];
return gulp
@ -355,7 +376,7 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
.pipe(
through.obj((file, enc, cb) => {
const filename = file.path.split('/').pop();
list.push(`${versionPath}/${filename}`);
list.push(`${versionPath}/${filename.replace(minSuffix, '')}`);
cb(null);
}),
)
@ -363,13 +384,13 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
const purge = new FastlyPurge(fastly.token);
list.forEach(url => {
console.log(`Purging ${url}...`);
log(`Purging ${ansi.cyan(url)}...`);
purge.url(url, (error, result) => {
if (error) {
console.log(error);
log.error(error);
} else if (result) {
console.log(result);
log(result);
}
});
});
@ -377,17 +398,25 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
});
// Publish to demo bucket
gulp.task('demo', () => {
gulp.task('demo', done => {
if (!canDeploy()) {
done();
return null;
}
console.log(`Uploading '${version}' demo to ${aws.demo.domain}...`);
const { publisher } = deploy.demo;
const { domain } = deploy.cdn;
if (!publisher) {
throw new Error('No publisher instance. Check AWS configuration.');
}
log(`Uploading ${ansi.green.bold(pkg.version)} to ${ansi.cyan(domain)}...`);
// Replace versioned files in readme.md
gulp.src([`${root}/readme.md`])
.pipe(replace(cdnpath, `${aws.cdn.domain}/${version}/`))
.pipe(gulp.dest(root));
gulp.src([`${__dirname}/readme.md`])
.pipe(replace(cdnpath, `${domain}/${version}/`))
.pipe(gulp.dest(__dirname));
// Replace local file paths with remote paths in demo HTML
// e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
@ -399,54 +428,45 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
pages.push(error);
}
gulp.src(pages)
return gulp
.src(pages)
.pipe(replace(localPath, versionPath))
.pipe(s3(aws.demo, options.demo));
.pipe(publisher.publish(options.demo.headers))
.pipe(publish.reporter());
});
gulp.task('error', done => {
// Only update CDN for master (prod)
if (branch.current !== branch.master) {
if (!canDeploy() || branch.current !== branch.master) {
done();
return null;
}
// Upload error.html to cdn (as well as demo site)
return gulp
.src([error])
.pipe(replace(localPath, versionPath))
.pipe(s3(aws.cdn, options.demo));
});
const { publisher } = deploy.cdn;
// Update symlinks for latest
/* gulp.task("symlinks", function () {
console.log("Updating symlinks...");
return gulp.src(paths.upload)
.pipe(through.obj(function (chunk, enc, callback) {
if (chunk.stat.isFile()) {
// Get the filename
var filename = chunk.path.split("/").reverse()[0];
// Create the 0 byte redirect files to upload
createFile(filename, "")
.pipe(rename(function (path) {
path.dirname = path.dirname.replace(".", "latest");
}))
// Upload to S3 with correct headers
.pipe(s3(aws.cdn, options.symlinks(version, filename)));
if (!publisher) {
throw new Error('No publisher instance. Check AWS configuration.');
}
callback(null, chunk);
}));
}); */
// Replace local file paths with remote paths in demo HTML
// e.g. "../dist/plyr.js" to "https://cdn.plyr.io/x.x.x/plyr.js"
// Upload error.html to cdn
return gulp
.src(`${paths.demo.root}error.html`)
.pipe(replace(localPath, versionPath))
.pipe(publisher.publish(options.demo.headers))
.pipe(publish.reporter());
});
// Open the demo site to check it's ok
gulp.task('open', callback => {
gulp.src(__filename).pipe(
gulp.task('open', () => {
const { domain } = deploy.demo;
return gulp.src(__filename).pipe(
open({
uri: `https://${aws.demo.domain}`,
uri: `https://${domain}/${branch.current === branch.beta ? 'beta' : ''}`,
}),
);
callback();
});
// Do everything
@ -455,11 +475,10 @@ if (Object.keys(credentials).includes('aws') && Object.keys(credentials).include
gulp.series(
'version',
tasks.clean,
gulp.parallel(tasks.js, tasks.sass, tasks.sprite),
gulp.parallel(...tasks.js, ...tasks.css, ...tasks.sprite),
'cdn',
'demo',
'purge',
'open',
),
);
}

View File

@ -1,9 +1,15 @@
{
"name": "plyr",
"version": "3.4.7",
"version": "3.5.2",
"description": "A simple, accessible and customizable HTML5, YouTube and Vimeo media player",
"homepage": "https://plyr.io",
"author": "Sam Potts <sam@potts.es>",
"main": "dist/plyr.js",
"module": "dist/plyr.min.mjs",
"jsnext:main": "dist/plyr.min.mjs",
"browser": "dist/plyr.min.js",
"sass": "src/sass/plyr.scss",
"style": "dist/plyr.css",
"keywords": [
"HTML5 Video",
"HTML5 Audio",
@ -13,10 +19,6 @@
"WordPress",
"HLS"
],
"main": "./dist/plyr.js",
"browser": "./dist/plyr.min.js",
"sass": "./src/sass/plyr.scss",
"style": "./dist/plyr.css",
"license": "MIT",
"repository": {
"type": "git",
@ -25,67 +27,69 @@
"bugs": {
"url": "https://github.com/sampotts/plyr/issues"
},
"directories": {
"doc": "readme.md"
},
"browserslist": "> 1%",
"scripts": {
"build": "gulp build",
"lint": "eslint src/js && npm run-script remark",
"remark": "remark -f --use 'validate-links=repository:\"sampotts/plyr\"' '{,!(node_modules),.?**/}*.md'",
"test": "echo \"Error: no test specified\" && exit 1"
"deploy": "yarn lint && gulp deploy"
},
"devDependencies": {
"@babel/core": "^7.1.6",
"ansi-colors": "^3.2.4",
"aws-sdk": "^2.422.0",
"@babel/core": "^7.3.4",
"@babel/preset-env": "^7.3.4",
"babel-eslint": "^10.0.1",
"@babel/preset-env": "^7.1.6",
"del": "^3.0.0",
"eslint": "^5.9.0",
"del": "^4.0.0",
"eslint": "^5.15.2",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-config-prettier": "^3.3.0",
"eslint-plugin-import": "^2.14.0",
"eslint-config-prettier": "^4.1.0",
"eslint-plugin-import": "^2.16.0",
"fancy-log": "^1.3.3",
"fastly-purge": "^1.0.1",
"git-branch": "^2.0.1",
"gulp": "^4.0.0",
"gulp-autoprefixer": "^6.0.0",
"gulp-better-rollup": "^3.4.0",
"gulp-awspublish": "^4.0.0",
"gulp-better-rollup": "^4.0.1",
"gulp-clean-css": "^4.0.0",
"gulp-concat": "^2.6.1",
"gulp-filter": "^5.1.0",
"gulp-header": "^2.0.5",
"gulp-header": "^2.0.7",
"gulp-imagemin": "^5.0.3",
"gulp-open": "^3.0.1",
"gulp-plumber": "^1.2.1",
"gulp-postcss": "^8.0.0",
"gulp-rename": "^1.4.0",
"gulp-replace": "^1.0.0",
"gulp-s3": "^0.11.0",
"gulp-sass": "^4.0.2",
"gulp-size": "^3.0.0",
"gulp-sourcemaps": "^2.6.4",
"gulp-svgmin": "^2.1.0",
"gulp-svgstore": "^7.0.0",
"gulp-uglify-es": "^1.0.4",
"gulp-util": "^3.0.8",
"gulp-sourcemaps": "^2.6.5",
"gulp-svgstore": "^7.0.1",
"gulp-terser": "^1.1.7",
"postcss-custom-properties": "^8.0.9",
"prettier-eslint": "^8.8.2",
"prettier-stylelint": "^0.4.2",
"remark-cli": "^6.0.1",
"remark-validate-links": "^7.1.2",
"rollup-plugin-babel": "^4.0.3",
"rollup-plugin-commonjs": "^9.2.0",
"rollup-plugin-node-resolve": "^3.4.0",
"stylelint": "^9.9.0",
"stylelint-config-prettier": "^4.0.0",
"remark-validate-links": "^8.0.1",
"rollup": "^1.6.0",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-commonjs": "^9.2.1",
"rollup-plugin-node-resolve": "^4.0.1",
"stylelint": "^9.10.1",
"stylelint-config-prettier": "^5.0.0",
"stylelint-config-recommended": "^2.1.0",
"stylelint-config-sass-guidelines": "^5.2.0",
"stylelint-order": "^2.0.0",
"stylelint-scss": "^3.4.0",
"stylelint-config-sass-guidelines": "^5.3.0",
"stylelint-order": "^2.1.0",
"stylelint-scss": "^3.5.4",
"stylelint-selector-bem-pattern": "^2.0.0",
"through2": "^3.0.0"
"through2": "^3.0.1"
},
"dependencies": {
"core-js": "^2.5.7",
"core-js": "^2.6.5",
"custom-event-polyfill": "^1.0.6",
"loadjs": "^3.5.4",
"loadjs": "^3.6.0",
"rangetouch": "^2.0.0",
"raven-js": "^3.27.0",
"url-polyfill": "^1.1.3"
"url-polyfill": "^1.1.5"
}
}

View File

@ -5,27 +5,28 @@
}
],
"settings": {
// Exclude from the editor
"files.exclude": {
"**/node_modules": true
},
// Exclude from search
"search.exclude": {
"dist/": true,
"demo/dist/": true
"**/node_modules": true,
"**/dist": true
},
// Linting
"stylelint.enable": true,
"css.validate": false,
"scss.validate": false,
"javascript.validate.enable": false,
// Prettier
"prettier.eslintIntegration": true,
"prettier.stylelintIntegration": true,
// Formatting
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
},
// Trim on save
"files.trimTrailingWhitespace": true
}

250
readme.md
View File

@ -1,94 +1,78 @@
# Plyr
Plyr is a simple, lightweight, accessible and customizable HTML5, YouTube and Vimeo media player that supports [_modern_](#browser-support) browsers.
A simple, lightweight, accessible and customizable HTML5, YouTube and Vimeo media player that supports [_modern_](#browser-support) browsers.
[Checkout the demo](https://plyr.io) - [Donate to support Plyr](#donate) - [Chat on Slack](https://bit.ly/plyr-chat)
[Checkout the demo](https://plyr.io) - [Donate](#donate) - [Slack](https://bit.ly/plyr-chat) - [![npm version](https://badge.fury.io/js/plyr.svg)](https://badge.fury.io/js/plyr)
[![Image of Plyr](https://cdn.plyr.io/static/demo/screenshot.png?v=3)](https://plyr.io)
## Features
# Features
- **Accessible** - full support for VTT captions and screen readers
- **[Customisable](#html)** - make the player look how you want with the markup you want
- **Good HTML** - uses the _right_ elements. `<input type="range">` for volume and `<progress>` for progress and well, `<button>`s for buttons. There's no
- 💪 **Accessible** - full support for VTT captions and screen readers
- 🔧 **[Customisable](#html)** - make the player look how you want with the markup you want
- 😎 **Good HTML** - uses the _right_ elements. `<input type="range">` for volume and `<progress>` for progress and well, `<button>`s for buttons. There's no
`<span>` or `<a href="#">` button hacks
- **Responsive** - works with any screen size
- **HTML Video & Audio** - support for both formats
- **[Embedded Video](#embeds)** - support for YouTube and Vimeo video playback
- **[Monetization](#ads)** - make money from your videos
- **[Streaming](#try-plyr-online)** - support for hls.js, Shaka and dash.js streaming playback
- **[API](#api)** - toggle playback, volume, seeking, and more through a standardized API
- **[Events](#events)** - no messing around with Vimeo and YouTube APIs, all events are standardized across formats
- **[Fullscreen](#fullscreen)** - supports native fullscreen with fallback to "full window" modes
- **[Shortcuts](#shortcuts)** - supports keyboard shortcuts
- **Picture-in-Picture** - supports Safari's picture-in-picture mode
- **Playsinline** - supports the `playsinline` attribute
- **Speed controls** - adjust speed on the fly
- **Multiple captions** - support for multiple caption tracks
- **i18n support** - support for internationalization of controls
- **No dependencies** - written in "vanilla" ES6 JavaScript, no jQuery required
- **SASS** - to include in your build processes
- 📱 **Responsive** - works with any screen size
- 📼 **HTML Video & Audio** - support for both formats
- 📺 **[Embedded Video](#embeds)** - support for YouTube and Vimeo video playback
- 💵 **[Monetization](#ads)** - make money from your videos
- 📹 **[Streaming](#demos)** - support for hls.js, Shaka and dash.js streaming playback
- 🎛 **[API](#api)** - toggle playback, volume, seeking, and more through a standardized API
- 🎤 **[Events](#events)** - no messing around with Vimeo and YouTube APIs, all events are standardized across formats
- 🔎 **[Fullscreen](#fullscreen)** - supports native fullscreen with fallback to "full window" modes
- ⌨️ **[Shortcuts](#shortcuts)** - supports keyboard shortcuts
- 🖥 **Picture-in-Picture** - supports picture-in-picture mode
- 📱 **Playsinline** - supports the `playsinline` attribute
- 🏎 **Speed controls** - adjust speed on the fly
- 📖 **Multiple captions** - support for multiple caption tracks
- 🌎 **i18n support** - support for internationalization of controls
- 👌 **[Preview thumbnails](#preview-thumbnails)** - support for displaying preview thumbnails
- 🤟 **No dependencies** - written in "vanilla" ES6 JavaScript, no jQuery required
- 💁‍♀️ **SASS** - to include in your build processes
Oh and yes, it works with Bootstrap.
## Changelog
Check out the [changelog](changelog.md) to see what's new with Plyr.
## Plugins & Components
Some awesome folks have made plugins for CMSs and Components for JavaScript frameworks:
| Type | Maintainer | Link |
| --------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| WordPress | Brandon Lavigne ([@drrobotnik](https://github.com/drrobotnik)) | [https://wordpress.org/plugins/plyr/](https://wordpress.org/plugins/plyr/) |
| React | Jose Miguel Bejarano ([@xDae](https://github.com/xDae)) | [https://github.com/xDae/react-plyr](https://github.com/xDae/react-plyr) |
| Vue | Gabe Dunn ([@redxtech](https://github.com/redxtech)) | [https://github.com/redxtech/vue-plyr](https://github.com/redxtech/vue-plyr) |
| Neos | Jon Uhlmann ([@jonnitto](https://github.com/jonnitto)) | [https://packagist.org/packages/jonnitto/plyr](https://packagist.org/packages/jonnitto/plyr) |
| Kirby | Dominik Pschenitschni ([@dpschen](https://github.com/dpschen)) | [https://github.com/dpschen/kirby-plyrtag](https://github.com/dpschen/kirby-plyrtag) |
## 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). You can grab all of the source with [NPM](https://www.npmjs.com/package/plyr) using `npm install plyr`.
### Try Plyr online
### Demos
You can try Plyr in Codepen using our minimal templates: [HTML5 video](https://codepen.io/pen?template=bKeqpr), [HTML5 audio](https://codepen.io/pen?template=rKLywR), [YouTube](https://codepen.io/pen?template=GGqbbJ), [Vimeo](https://codepen.io/pen?template=bKeXNq). For Streaming we also have example integrations with: [Dash.js](https://codepen.io/pen?template=zaBgBy), [Hls.js](https://codepen.io/pen?template=oyLKQb) and [Shaka Player](https://codepen.io/pen?template=ZRpzZO)
### HTML
# Quick setup
## HTML
Plyr extends upon the standard [HTML5 media element](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement) markup so that's all you need for those types.
#### HTML5 Video
### HTML5 Video
```html
<video poster="/path/to/poster.jpg" id="player" playsinline controls>
<source src="/path/to/video.mp4" type="video/mp4">
<source src="/path/to/video.webm" type="video/webm">
<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>
<track kind="captions" label="English captions" src="/path/to/captions.vtt" srclang="en" default />
</video>
```
#### HTML5 Audio
### 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 players, Plyr uses progressive enhancement to enhance the default `<iframe>` embeds. Below are some examples. The `plyr__video-embed` classname will make the embed responsive. You can add the `autoplay`, `loop`, `hl` (YouTube only) and `playsinline` (YouTube only) query parameters to the URL and they will be set as config options automatically. For YouTube, the `origin` should be updated to reflect the domain you're hosting the embed on, or you can opt to omit it.
#### YouTube embed
### YouTube
We recommend [progressive enhancement](https://www.smashingmagazine.com/2009/04/progressive-enhancement-what-it-is-and-how-to-use-it/) with the embedded players. You can elect to use an `<iframe>` as the source element (which Plyr will progressively enhance) or a bog standard `<div>` with two essential data attributes - `data-plyr-provider` and `data-plyr-embed-id`.
```html
<div class="plyr__video-embed" id="player">
<iframe src="https://www.youtube.com/embed/bTqVqk7FSmY?origin=https://plyr.io&amp;iv_load_policy=3&amp;modestbranding=1&amp;playsinline=1&amp;showinfo=0&amp;rel=0&amp;enablejsapi=1" allowfullscreen allowtransparency allow="autoplay"></iframe>
<iframe
src="https://www.youtube.com/embed/bTqVqk7FSmY?origin=https://plyr.io&amp;iv_load_policy=3&amp;modestbranding=1&amp;playsinline=1&amp;showinfo=0&amp;rel=0&amp;enablejsapi=1"
allowfullscreen
allowtransparency
allow="autoplay"
></iframe>
</div>
```
@ -102,13 +86,18 @@ Or the `<div>` non progressively enhanced method:
_Note_: The `data-plyr-embed-id` can either be the video ID or URL for the media.
#### Vimeo embed
### Vimeo
Much the same as YouTube above.
```html
<div class="plyr__video-embed" id="player">
<iframe src="https://player.vimeo.com/video/76979871?loop=false&amp;byline=false&amp;portrait=false&amp;title=false&amp;speed=true&amp;transparent=0&amp;gesture=media" allowfullscreen allowtransparency allow="autoplay"></iframe>
<iframe
src="https://player.vimeo.com/video/76979871?loop=false&amp;byline=false&amp;portrait=false&amp;title=false&amp;speed=true&amp;transparent=0&amp;gesture=media"
allowfullscreen
allowtransparency
allow="autoplay"
></iframe>
</div>
```
@ -118,13 +107,15 @@ Or the `<div>` non progressively enhanced method:
<div id="player" data-plyr-provider="vimeo" data-plyr-embed-id="76979871"></div>
```
### JavaScript
## JavaScript
Include the `plyr.js` script before the closing `</body>` tag and then in your JS create a new instance of Plyr as below.
```html
<script src="path/to/plyr.js"></script>
<script>const player = new Plyr('#player');</script>
<script>
const player = new Plyr('#player');
</script>
```
See [initialising](#initialising) for more information on advanced setups.
@ -132,35 +123,35 @@ See [initialising](#initialising) for more information on advanced setups.
You can use our CDN (provided by [Fastly](https://www.fastly.com/)) for the JavaScript. There's 2 versions; one with and one without [polyfills](#polyfills). My recommendation would be to manage polyfills seperately as part of your application but to make life easier you can use the polyfilled build.
```html
<script src="https://cdn.plyr.io/3.4.7/plyr.js"></script>
<script src="https://cdn.plyr.io/3.5.2/plyr.js"></script>
```
...or...
```html
<script src="https://cdn.plyr.io/3.4.7/plyr.polyfilled.js"></script>
<script src="https://cdn.plyr.io/3.5.2/plyr.polyfilled.js"></script>
```
### CSS
## CSS
Include the `plyr.css` stylsheet into your `<head>`
```html
<link rel="stylesheet" href="path/to/plyr.css">
<link rel="stylesheet" href="path/to/plyr.css" />
```
If you want to use our CDN (provided by [Fastly](https://www.fastly.com/)) for the default CSS, you can use the following:
```html
<link rel="stylesheet" href="https://cdn.plyr.io/3.4.7/plyr.css">
<link rel="stylesheet" href="https://cdn.plyr.io/3.5.2/plyr.css" />
```
### SVG Sprite
## SVG Sprite
The SVG sprite is loaded automatically from our CDN (provided by [Fastly](https://www.fastly.com/)). To change this, see the [options](#options) below. For
reference, the CDN hosted SVG sprite can be found at `https://cdn.plyr.io/3.4.7/plyr.svg`.
reference, the CDN hosted SVG sprite can be found at `https://cdn.plyr.io/3.5.2/plyr.svg`.
## Ads
# Ads
Plyr has partnered up with [vi.ai](https://vi.ai/publisher-video-monetization/?aid=plyrio) to offer monetization options for your videos. Getting setup is easy:
@ -170,9 +161,9 @@ Plyr has partnered up with [vi.ai](https://vi.ai/publisher-video-monetization/?a
Any questions regarding the ads can be sent straight to vi.ai and any issues with rendering raised through GitHub issues.
## Advanced
# Advanced
### SASS
## SASS
You can use `bundle.scss` file included in `/src` as part of your build and change variables to suit your design. The SASS require you to
use the [autoprefixer](https://www.npmjs.com/package/gulp-autoprefixer) plugin (you should be already!) as all declarations use the W3C definitions.
@ -180,12 +171,12 @@ use the [autoprefixer](https://www.npmjs.com/package/gulp-autoprefixer) plugin (
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.
### SVG
## SVG
The icons used in the Plyr controls are loaded in an SVG sprite. The sprite is automatically loaded from our CDN by default. If you already have an icon build
system in place, you can include the source plyr icons (see `/src/sprite` for source icons).
#### Using the `iconUrl` option
### Using the `iconUrl` option
You can however specify your own `iconUrl` option and Plyr will determine if the url is absolute and requires loading by AJAX/CORS due to current browser
limitations or if it's a relative path, just use the path directly.
@ -195,32 +186,31 @@ If you're using the `<base>` tag on your site, you may need to use something lik
More info on SVG sprites here: [http://css-tricks.com/svg-sprites-use-better-icon-fonts/](http://css-tricks.com/svg-sprites-use-better-icon-fonts/) and the AJAX
technique here: [http://css-tricks.com/ajaxing-svg-sprite/](http://css-tricks.com/ajaxing-svg-sprite/)
### Cross Origin (CORS)
## Cross Origin (CORS)
You'll notice the `crossorigin` attribute on the example `<video>` elements. This is because the TextTrack captions are loaded from another domain. If your
TextTrack captions are also hosted on another domain, you will need to add this attribute and make sure your host has the correct headers setup. For more info
on CORS checkout the MDN docs:
[https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
### Captions
## Captions
WebVTT captions are supported. To add a caption track, check the HTML example above and look for the `<track>` element. Be sure to
[validate your caption files](https://quuz.org/webvtt/).
### JavaScript
## JavaScript
#### Initialising
### Initialising
You can specify a range of arguments for the constructor to use:
- A CSS string selector that's compatible with [`querySelector`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)
- A [`HTMLElement`](https://developer.mozilla.org/en/docs/Web/API/HTMLElement)
- A [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList)
- A [jQuery](https://jquery.com) object
_Note_: If a `NodeList`, `Array`, or jQuery object are passed, the first element will be used for setup. To setup multiple players, see [setting up multiple players](#setting-up-multiple-players) below.
_Note_: If a `NodeList`, `Array`, or jQuery object are passed, the first element will be used for setup. To setup multiple players, see [multiple players](#multiple-players) below.
Here's some examples
#### Single player
Passing a [string selector](https://developer.mozilla.org/en-US/docs/Web/API/NodeList):
@ -234,15 +224,13 @@ Passing a [HTMLElement](https://developer.mozilla.org/en/docs/Web/API/HTMLElemen
const player = new Plyr(document.getElementById('player'));
```
Passing a [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) (see note below):
```javascript
const player = new Plyr(document.querySelectorAll('.js-player'));
const player = new Plyr(document.querySelector('.js-player'));
```
The NodeList, HTMLElement or string selector can be the target `<video>`, `<audio>`, or `<div>` wrapper for embeds.
The HTMLElement or string selector can be the target `<video>`, `<audio>`, or `<div>` wrapper for embeds.
##### Setting up multiple players
#### Multiple players
You have two choices here. You can either use a simple array loop to map the constructor:
@ -250,7 +238,7 @@ You have two choices here. You can either use a simple array loop to map the con
const players = Array.from(document.querySelectorAll('.js-player')).map(p => new Plyr(p));
```
...or use a static method where you can pass a [string selector](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), a [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) or an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of elements:
...or use a static method where you can pass a [string selector](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), a [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) of elements, or a [JQuery](https://jquery.com) object:
```javascript
const players = Plyr.setup('.js-player');
@ -258,30 +246,26 @@ const players = Plyr.setup('.js-player');
Both options will also return an array of instances in the order of they were in the DOM for the string selector or the source NodeList or Array.
##### Passing options
#### Options
The second argument for the constructor is the [options](#options) object:
```javascript
const player = new Plyr('#player', {
/* options */
title: 'Example Title',
});
```
In all cases, 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-config` attribute on each of your target elements:
```html
<video src="/path/to/video.mp4" id="player" controls data-plyr-config='{ "title": "This is an example video", "volume": 1, "debug": true }'></video>
<video src="/path/to/video.mp4" id="player" controls data-plyr-config='{ "title": "Example Title" }'></video>
```
Note the single quotes encapsulating the JSON and double quotes on the object keys. Only string values need double quotes.
| Option | Type | Default | Description |
| -------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| -------------------- | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enabled` | Boolean | `true` | Completely disable Plyr. This would allow you to do a User Agent check or similar to programmatically enable or disable Plyr for a certain UA. Example below. |
| `debug` | Boolean | `false` | Display debugging information in the console |
| `controls` | Array, Function or Element | `['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen']` | If a function is passed, it is assumed your method will return either an element or HTML string for the controls. Three arguments will be passed to your function; `id` (the unique id for the player), `seektime` (the seektime step in seconds), and `title` (the media title). See [controls.md](controls.md) for more info on how the html needs to be structured. |
@ -308,22 +292,25 @@ Note the single quotes encapsulating the JSON and double quotes on the object ke
| `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 (`event.preventDefault()`), the default handler will not fire. |
| `captions` | Object | `{ active: false, language: 'auto', update: false }` | `active`: Toggles if captions should be active by default. `language`: Sets the default language to load (if available). 'auto' uses the browser language. `update`: Listen to changes to tracks and update menu. This is needed for some streaming libraries, but can result in unselectable language options). |
| `fullscreen` | Object | `{ enabled: true, fallback: true, iosNative: false }` | `enabled`: Toggles whether fullscreen should be enabled. `fallback`: Allow fallback to a full-window solution. `iosNative`: whether to use native iOS fullscreen when entering fullscreen (no custom controls) |
| `fullscreen` | Object | `{ enabled: true, fallback: true, iosNative: false }` | `enabled`: Toggles whether fullscreen should be enabled. `fallback`: Allow fallback to a full-window solution (`true`/`false`/`'force'`). `iosNative`: whether to use native iOS fullscreen when entering fullscreen (no custom controls) |
| `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. |
| `quality` | Object | `{ default: 576, options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240] }` | `default` is the default quality level (if it exists in your sources). `options` are the options to display. This is used to filter the available sources. |
| `loop` | Object | `{ active: false }` | `active`: Whether to loop the current video. If the `loop` attribute is present on a `<video>` or `<audio>` element, this will be automatically set to true This is an object to support future functionality. |
| `ads` | Object | `{ enabled: false, publisherId: '' }` | `enabled`: Whether to enable vi.ai ads. `publisherId`: Your unique vi.ai publisher ID. |
| `ads` | Object | `{ enabled: false, publisherId: '' }` | `enabled`: Whether to enable advertisements. `publisherId`: Your unique [vi.ai](https://vi.ai/publisher-video-monetization/?aid=plyrio) publisher ID. |
| `urls` | Object | See source. | If you wish to override any API URLs then you can do so here. You can also set a custom download URL for the download button. |
| `vimeo` | Object | `{ byline: false, portrait: false, title: false, speed: true, transparent: false }` | See [Vimeo embed options](https://github.com/vimeo/player.js/#embed-options). Some are set automatically based on other config options, namely: `loop`, `autoplay`, `muted`, `gesture`, `playsinline` |
| `youtube` | Object | `{ noCookie: false, rel: 0, showinfo: 0, iv_load_policy: 3, modestbranding: 1 }` | See [YouTube embed options](https://developers.google.com/youtube/player_parameters#Parameters). The only custom option is `noCookie` to use an alternative to YouTube that doesn't use cookies (useful for GDPR, etc). Some are set automatically based on other config options, namely: `autoplay`, `hl`, `controls`, `disablekb`, `playsinline`, `cc_load_policy`, `cc_lang_pref`, `widget_referrer` |
| `previewThumbnails` | Object | `{ enabled: false, src: '' }` | `enabled`: Whether to enable the preview thumbnails (they must be generated by you). `src` must be either a string or an array of strings representing URLs for the VTT files containing the image URL(s). Learn more about [preview thumbnails](#preview-thumbnails) below. |
1. Vimeo only
## API
# API
There are methods, setters and getters on a Plyr object.
### Object
## Object
The easiest way to access the Plyr object is to set the return value from your call to the constructor to a variable. For example:
@ -341,7 +328,7 @@ element.addEventListener('ready', event => {
});
```
### Methods
## Methods
Example method use:
@ -375,7 +362,7 @@ player.fullscreen.enter(); // Enter fullscreen
1. For HTML5 players, `play()` will return a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) in _some_ browsers - WebKit and Mozilla [according to MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) at time of writing.
### Getters and Setters
## Getters and Setters
Example setters:
@ -422,7 +409,7 @@ player.fullscreen.active; // false;
1. YouTube only. HTML5 will follow.
2. HTML5 only
#### The `.source` setter
### The `.source` setter
This allows changing the player source and type on the fly.
@ -524,7 +511,7 @@ _Note:_ `src` property for YouTube and Vimeo can either be the video ID or the w
1. HTML5 only
## Events
# 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`
@ -536,7 +523,7 @@ player.on('ready', event => {
});
```
### Standard Media Events
## Standard Media Events
| Event Type | Description |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@ -559,7 +546,7 @@ player.on('ready', event => {
| `controlsshown` | Sent when the controls are shown. |
| `ready` | Triggered when the instance is ready for API calls. |
#### HTML5 only
### HTML5 only
| Event Type | Description |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@ -575,7 +562,7 @@ player.on('ready', event => {
| `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
### YouTube only
| Event Type | Description |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
@ -585,7 +572,7 @@ _Note:_ These events also bubble up the DOM. The event target will be the contai
Some event details borrowed from [MDN](https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events).
## Embeds
# Embeds
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
@ -596,7 +583,7 @@ third party APIs. More info on the respective API's here:
_Note_: Not all API methods may work 100%. Your mileage may vary. It's better to use the Plyr API where possible.
## Shortcuts
# 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.
@ -615,11 +602,17 @@ document then the shortcuts will work when any element has focus, apart from an
| `C` | Toggle captions |
| `L` | Toggle loop |
## Fullscreen
# Preview thumbnails
It's possible to display preview thumbnails as per the demo when you hover over the scrubber or while you are scrubbing in the main video area. This can be used for all video types but is easiest with HTML5 of course. You will need to generate the sprite or images yourself. This is possible using something like AWS transcoder to generate the frames and then combine them into a sprite image. Sprites are recommended for performance reasons - they will be much faster to download and easier to compress into a small file size making them load faster.
You can see the example VTT files [here](https://cdn.plyr.io/static/demo/thumbs/100p.vtt) and [here](https://cdn.plyr.io/static/demo/thumbs/240p.vtt) for how the sprites are done. The coordinates are set as the `xywh` hash on the URL in the order X Offset, Y Offset, Width, Height (e.g. `240p-00001.jpg#xywh=1708,480,427,240` is offset `1708px` from the left, `480px` from the top and is `427x240px`. If you want to include images per frame, this is also possible but will be slower, resulting in a degraded experience.
# Fullscreen
Fullscreen in Plyr is supported by all browsers that [currently support it](http://caniuse.com/#feat=fullscreen).
## Browser support
# Browser support
Plyr supports the last 2 versions of most _modern_ browsers.
@ -638,11 +631,11 @@ Plyr supports the last 2 versions of most _modern_ browsers.
2. Native player used (no support for `<progress>` or `<input type="range">`) but the API is supported. No native fullscreen support, fallback can be used (see [options](#options)).
3. Polyfills required. See below.
### Polyfills
## Polyfills
Plyr uses ES6 which isn't supported in all browsers quite yet. This means some features will need to be polyfilled to be available otherwise you'll run into issues. We've elected to not burden the ~90% of users that do support these features with extra JS and instead leave polyfilling to you to work out based on your needs. The easiest method I've found is to use [polyfill.io](https://polyfill.io) which provides polyfills based on user agent. This is the method the demo uses.
### Checking for support
## Checking for support
You can use the static method to check for support. For example
@ -656,7 +649,7 @@ The arguments are:
- Provider (`html5`, `youtube` or `vimeo`)
- Whether the player has the `playsinline` attribute (only applicable to iOS 10+)
### Disable support programatically
## Disable support programatically
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:
@ -668,29 +661,36 @@ The `enabled` option can be used to disable certain User Agents. For example, if
If a User Agent is disabled but supports `<video>` and `<audio>` natively, it will use the native player.
## RangeTouch
# Plugins & Components
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.
Some awesome folks have made plugins for CMSs and Components for JavaScript frameworks:
## Issues
| Type | Maintainer | Link |
| --------- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| WordPress | Brandon Lavigne ([@drrobotnik](https://github.com/drrobotnik)) | [https://wordpress.org/plugins/plyr/](https://wordpress.org/plugins/plyr/) |
| Angular | Simon Bobrov ([@smnbbrv](https://github.com/smnbbrv)) | [https://github.com/smnbbrv/ngx-plyr](https://github.com/smnbbrv/ngx-plyr) |
| React | Jose Miguel Bejarano ([@xDae](https://github.com/xDae)) | [https://github.com/xDae/react-plyr](https://github.com/xDae/react-plyr) |
| Vue | Gabe Dunn ([@redxtech](https://github.com/redxtech)) | [https://github.com/redxtech/vue-plyr](https://github.com/redxtech/vue-plyr) |
| Neos | Jon Uhlmann ([@jonnitto](https://github.com/jonnitto)) | [https://packagist.org/packages/jonnitto/plyr](https://packagist.org/packages/jonnitto/plyr) |
| Kirby | Dominik Pschenitschni ([@dpschen](https://github.com/dpschen)) | [https://github.com/dpschen/kirby-plyrtag](https://github.com/dpschen/kirby-plyrtag) |
# Issues
If you find anything weird with Plyr, please let us know using the GitHub issues tracker.
## Author
# 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
# Donate
Plyr costs money to run, not only my time. I donate my time for free as I enjoy building Plyr but unfortunately have to pay for domains, hosting, and more. Any help with costs is appreciated...
- [Donate via Patreon](https://www.patreon.com/plyr)
- [Donate via PayPal](https://www.paypal.me/pottsy/20usd)
## Mentions
# Mentions
- [ProductHunt](https://www.producthunt.com/tech/plyr)
- [The Changelog](http://thechangelog.com/plyr-simple-html5-media-player-custom-controls-webvtt-captions/)
@ -703,7 +703,7 @@ Plyr costs money to run, not only my time. I donate my time for free as I enjoy
- [The Treehouse Show #131](https://teamtreehouse.com/library/episode-131-origami-react-responsive-hero-images)
- [noupe.com](http://www.noupe.com/design/html5-plyr-is-a-responsive-and-accessible-video-player-94389.html)
## Used by
# Used by
- [Selz.com](https://selz.com)
- [Peugeot.fr](http://www.peugeot.fr/marque-et-technologie/technologies/peugeot-i-cockpit.html)
@ -718,14 +718,14 @@ Plyr costs money to run, not only my time. I donate my time for free as I enjoy
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
# 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
# Thanks
[![Fastly](https://cdn.plyr.io/static/fastly-logo.png)](https://www.fastly.com/)
@ -735,6 +735,6 @@ Massive thanks to [Fastly](https://www.fastly.com/) for providing the CDN servic
Massive thanks to [Sentry](https://sentry.io/) for providing the logging services for the demo site.
## Copyright and License
# Copyright and License
[The MIT license](license.md)

View File

@ -60,7 +60,7 @@ const defaults = {
// Sprite (for icons)
loadSprite: true,
iconPrefix: 'plyr',
iconUrl: 'https://cdn.plyr.io/3.4.7/plyr.svg',
iconUrl: 'https://cdn.plyr.io/3.5.2/plyr.svg',
// Blank video (used to prevent errors on source change)
blankVideo: 'https://cdn.plyr.io/static/blank.mp4',
@ -108,7 +108,7 @@ const defaults = {
// Fullscreen settings
fullscreen: {
enabled: true, // Allow fullscreen?
fallback: true, // Fallback for vintage browsers
fallback: true, // Fallback using full viewport/window
iosNative: false, // Use the native fullscreen in iOS (disables custom controls)
},
@ -374,6 +374,16 @@ const defaults = {
active: 'plyr--airplay-active',
},
tabFocus: 'plyr__tab-focus',
previewThumbnails: {
// Tooltip thumbs
thumbContainer: 'plyr__preview-thumb',
thumbContainerShown: 'plyr__preview-thumb--is-shown',
imageContainer: 'plyr__preview-thumb__image-container',
timeContainer: 'plyr__preview-thumb__time-container',
// Scrubbing
scrubbingContainer: 'plyr__preview-scrubbing',
scrubbingContainerShown: 'plyr__preview-scrubbing--is-shown',
},
},
// Embed attributes
@ -394,6 +404,31 @@ const defaults = {
ads: {
enabled: false,
publisherId: '',
tagUrl: '',
},
// Preview Thumbnails plugin
previewThumbnails: {
enabled: false,
src: '',
},
// Vimeo plugin
vimeo: {
byline: false,
portrait: false,
title: false,
speed: true,
transparent: false,
},
// YouTube plugin
youtube: {
noCookie: false, // Whether to use an alternative version of YouTube without cookies
rel: 0, // No related vids
showinfo: 0, // Hide info
iv_load_policy: 3, // Hide annotations
modestbranding: 1, // Hide logos as much as possible (they still show one in the corner when paused)
},
};

View File

@ -19,7 +19,7 @@ export const types = {
*/
export 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;
}

37
src/js/controls.js vendored
View File

@ -3,13 +3,27 @@
// TODO: This needs to be split into smaller files and cleaned up
// ==========================================================================
import RangeTouch from 'rangetouch';
import captions from './captions';
import html5 from './html5';
import support from './support';
import { repaint, transitionEndEvent } from './utils/animation';
import { dedupe } from './utils/arrays';
import browser from './utils/browser';
import { createElement, emptyElement, getAttributesFromSelector, getElement, getElements, hasClass, matches, removeElement, setAttributes, setFocus, toggleClass, toggleHidden } from './utils/elements';
import {
createElement,
emptyElement,
getAttributesFromSelector,
getElement,
getElements,
hasClass,
matches,
removeElement,
setAttributes,
setFocus,
toggleClass,
toggleHidden,
} from './utils/elements';
import { off, on } from './utils/events';
import i18n from './utils/i18n';
import is from './utils/is';
@ -321,6 +335,9 @@ const controls = {
// Set the fill for webkit now
controls.updateRangeFill.call(this, input);
// Improve support on touch devices
RangeTouch.setup(input);
return input;
},
@ -334,7 +351,7 @@ const controls = {
min: 0,
max: 100,
value: 0,
role: 'presentation',
role: 'progressbar',
'aria-hidden': true,
},
attributes,
@ -667,7 +684,7 @@ const controls = {
}
// Set CSS custom property
range.style.setProperty('--value', `${range.value / range.max * 100}%`);
range.style.setProperty('--value', `${(range.value / range.max) * 100}%`);
},
// Update hover tooltip for seeking
@ -699,7 +716,7 @@ const controls = {
// Determine percentage, if already visible
if (is.event(event)) {
percent = 100 / clientRect.width * (event.pageX - clientRect.left);
percent = (100 / clientRect.width) * (event.pageX - clientRect.left);
} else if (hasClass(this.elements.display.seekTooltip, visible)) {
percent = parseFloat(this.elements.display.seekTooltip.style.left, 10);
} else {
@ -714,7 +731,7 @@ const controls = {
}
// Display the time a click would seek to
controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, this.duration / 100 * percent);
controls.updateTimeDisplay.call(this, this.elements.display.seekTooltip, (this.duration / 100) * percent);
// Set position
this.elements.display.seekTooltip.style.left = `${percent}%`;
@ -1587,7 +1604,7 @@ const controls = {
// 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)
@ -1674,15 +1691,17 @@ const controls = {
.filter(Boolean)
.forEach(button => {
if (is.array(button) || is.nodeList(button)) {
Array.from(button).filter(Boolean).forEach(addProperty);
Array.from(button)
.filter(Boolean)
.forEach(addProperty);
} else {
addProperty(button);
}
});
}
// Edge sometimes doesn't finish the paint so force a redraw
if (window.navigator.userAgent.includes('Edge')) {
// Edge sometimes doesn't finish the paint so force a repaint
if (browser.isEdge) {
repaint(target);
}

View File

@ -94,6 +94,9 @@ class Fullscreen {
// Scroll position
this.scrollPosition = { x: 0, y: 0 };
// 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(
@ -130,6 +133,11 @@ class Fullscreen {
);
}
// If we're actually using native
get usingNative() {
return Fullscreen.native && !this.forceFallback;
}
// Get the prefix for handlers
static get prefix() {
// No prefix
@ -174,7 +182,7 @@ class Fullscreen {
}
// Fallback using classname
if (!Fullscreen.native) {
if (!Fullscreen.native || this.forceFallback) {
return hasClass(this.target, this.player.config.classNames.fullscreen.fallback);
}
@ -193,7 +201,17 @@ class Fullscreen {
// Update UI
update() {
if (this.enabled) {
this.player.debug.log(`${Fullscreen.native ? 'Native' : 'Fallback'} fullscreen enabled`);
let mode;
if (this.forceFallback) {
mode = 'Fallback (forced)';
} else if (Fullscreen.native) {
mode = 'Native';
} else {
mode = 'Fallback';
}
this.player.debug.log(`${mode} fullscreen enabled`);
} else {
this.player.debug.log('Fullscreen not supported and fallback disabled');
}
@ -211,7 +229,7 @@ class Fullscreen {
// iOS native fullscreen doesn't need the request step
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();
@ -230,7 +248,7 @@ class Fullscreen {
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);

View File

@ -5,6 +5,7 @@
import support from './support';
import { removeElement } from './utils/elements';
import { triggerEvent } from './utils/events';
import is from './utils/is';
const html5 = {
getSources() {
@ -14,8 +15,16 @@ const html5 = {
const sources = Array.from(this.media.querySelectorAll('source'));
// Filter out unsupported sources
return sources.filter(source => support.mime.call(this, source.getAttribute('type')));
// Filter out unsupported sources (if type is specified)
return sources.filter(source => {
const type = source.getAttribute('type');
if (is.empty(type)) {
return true;
}
return support.mime.call(this, type);
});
},
// Get quality levels

View File

@ -7,8 +7,9 @@ import ui from './ui';
import { repaint } from './utils/animation';
import browser from './utils/browser';
import { getElement, getElements, matches, toggleClass, toggleHidden } from './utils/elements';
import { on, once, toggleListener, triggerEvent } from './utils/events';
import { off, on, once, toggleListener, triggerEvent } from './utils/events';
import is from './utils/is';
import { setAspectRatio } from './utils/style';
class Listeners {
constructor(player) {
@ -164,7 +165,7 @@ class Listeners {
// Escape is handle natively when in full screen
// 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();
}
@ -261,10 +262,10 @@ class Listeners {
// Container listeners
container() {
const { player } = this;
const { elements } = player;
const { config, elements, timers } = player;
// 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);
}
@ -294,12 +295,78 @@ class Listeners {
}
// Clear timer
clearTimeout(player.timers.controls);
clearTimeout(timers.controls);
// Set new timer to prevent flicker when seeking
player.timers.controls = setTimeout(() => ui.toggleControls.call(player, false), delay);
timers.controls = setTimeout(() => 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
const setGutter = (ratio, padding, toggle) => {
if (!player.isVimeo) {
return;
}
const target = player.elements.wrapper.firstChild;
const [, height] = ratio.split(':').map(Number);
const [videoWidth, videoHeight] = player.embed.ratio.split(':').map(Number);
target.style.maxWidth = toggle ? `${(height / videoHeight) * videoWidth}px` : null;
target.style.margin = toggle ? '0 auto' : null;
};
// Resize on fullscreen change
const setPlayerSize = measure => {
// If we don't need to measure the viewport
if (!measure) {
return setAspectRatio.call(player);
}
const rect = elements.container.getBoundingClientRect();
const { width, height } = rect;
return setAspectRatio.call(player, `${width}:${height}`);
};
const resized = () => {
window.clearTimeout(timers.resized);
timers.resized = window.setTimeout(setPlayerSize, 50);
};
on.call(player, elements.container, 'enterfullscreen exitfullscreen', event => {
const { target, usingNative } = player.fullscreen;
// Ignore for iOS native
if (!player.isEmbed || target !== elements.container) {
return;
}
const isEnter = event.type === 'enterfullscreen';
// Set the player size when entering fullscreen to viewport size
const { padding, ratio } = setPlayerSize(isEnter);
// 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
@ -347,20 +414,6 @@ class Listeners {
// Loading state
on.call(player, player.media, 'waiting canplay seeked playing', event => ui.checkLoading.call(player, event));
// If autoplay, then load advertisement if required
// TODO: Show some sort of loading state while the ad manager loads else there's a delay before ad shows
on.call(player, player.media, 'playing', () => {
if (!player.ads) {
return;
}
// If ads are enabled, wait for them first
if (player.ads.enabled && !player.ads.initialized) {
// Wait for manager response
player.ads.managerPromise.then(() => player.ads.play()).catch(() => player.play());
}
});
// Click video
if (player.supported.ui && player.config.clickToPlay && !player.isAudio) {
// Re-fetch the wrapper
@ -386,10 +439,10 @@ class Listeners {
}
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');
}
});
}
@ -673,6 +726,42 @@ class Listeners {
controls.updateSeekTooltip.call(player, event),
);
// Preview thumbnails plugin
// TODO: Really need to work on some sort of plug-in wide event bus or pub-sub for this
this.bind(elements.progress, 'mousemove touchmove', event => {
const { previewThumbnails } = player;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.startMove(event);
}
});
// Hide thumbnail preview - on mouse click, mouse leave, and video play/seek. All four are required, e.g., for buffering
this.bind(elements.progress, 'mouseleave click', () => {
const { previewThumbnails } = player;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.endMove(false, true);
}
});
// Show scrubbing preview
this.bind(elements.progress, 'mousedown touchstart', event => {
const { previewThumbnails } = player;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.startScrubbing(event);
}
});
this.bind(elements.progress, 'mouseup touchend', event => {
const { previewThumbnails } = player;
if (previewThumbnails && previewThumbnails.loaded) {
previewThumbnails.endScrubbing(event);
}
});
// Polyfill for lower fill in <input type="range"> for webkit
if (browser.isWebkit) {
Array.from(getElements.call(player, 'input[type="range"]')).forEach(element => {

View File

@ -17,12 +17,12 @@ import { buildUrlParams } from '../utils/urls';
class Ads {
/**
* Ads constructor.
* @param {object} player
* @param {Object} player
* @return {Ads}
*/
constructor(player) {
this.player = player;
this.publisherId = player.config.ads.publisherId;
this.config = player.config.ads;
this.playing = false;
this.initialized = false;
this.elements = {
@ -49,8 +49,13 @@ class Ads {
}
get enabled() {
const { config } = this;
return (
this.player.isHTML5 && this.player.isVideo && this.player.config.ads.enabled && !is.empty(this.publisherId)
this.player.isHTML5 &&
this.player.isVideo &&
config.enabled &&
(!is.empty(config.publisherId) || is.url(config.tagUrl))
);
}
@ -95,8 +100,14 @@ class Ads {
this.setupIMA();
}
// Build the default tag URL
// Build the tag URL
get tagUrl() {
const { config } = this;
if (is.url(config.tagUrl)) {
return config.tagUrl;
}
const params = {
AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',
AV_CHANNELID: '5a0458dc28a06145e4519d21',
@ -125,6 +136,7 @@ class Ads {
this.elements.container = createElement('div', {
class: this.player.config.classNames.ads,
});
this.player.elements.container.appendChild(this.elements.container);
// So we can run VPAID2
@ -133,9 +145,11 @@ class Ads {
// Set language
google.ima.settings.setLocale(this.player.config.ads.language);
// We assume the adContainer is the video container of the plyr element
// that will house the ads
this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container);
// Set playback for iOS10+
google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);
// We assume the adContainer is the video container of the plyr element that will house the ads
this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media);
// Request video ads to be pre-loaded
this.requestAds();
@ -184,7 +198,7 @@ class Ads {
/**
* Update the ad countdown
* @param {boolean} start
* @param {Boolean} start
*/
pollCountdown(start = false) {
if (!start) {
@ -226,25 +240,6 @@ class Ads {
// Get the cue points for any mid-rolls by filtering out the pre- and post-roll
this.cuePoints = this.manager.getCuePoints();
// Add advertisement cue's within the time line if available
if (!is.empty(this.cuePoints)) {
this.cuePoints.forEach(cuePoint => {
if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {
const seekElement = this.player.elements.progress;
if (is.element(seekElement)) {
const cuePercentage = 100 / this.player.duration * cuePoint;
const cue = createElement('span', {
class: this.player.config.classNames.cues,
});
cue.style.left = `${cuePercentage.toString()}%`;
seekElement.appendChild(cue);
}
}
});
}
// Set volume to match player
this.manager.setVolume(this.player.volume);
@ -261,6 +256,27 @@ class Ads {
this.trigger('loaded');
}
addCuePoints() {
// Add advertisement cue's within the time line if available
if (!is.empty(this.cuePoints)) {
this.cuePoints.forEach(cuePoint => {
if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {
const seekElement = this.player.elements.progress;
if (is.element(seekElement)) {
const cuePercentage = (100 / this.player.duration) * cuePoint;
const cue = createElement('span', {
class: this.player.config.classNames.cues,
});
cue.style.left = `${cuePercentage.toString()}%`;
seekElement.appendChild(cue);
}
}
});
}
}
/**
* This is where all the event handling takes place. Retrieve the ad from the event. Some
* events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated
@ -273,6 +289,7 @@ class Ads {
// Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated
const ad = event.getAd();
const adData = event.getAdData();
// Proxy event
const dispatchEvent = type => {
@ -368,6 +385,12 @@ class Ads {
dispatchEvent(event.type);
break;
case google.ima.AdEvent.Type.LOG:
if (adData.adError) {
this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);
}
break;
default:
break;
}
@ -391,14 +414,16 @@ class Ads {
const { container } = this.player.elements;
let time;
// Add listeners to the required events
this.player.on('canplay', () => {
this.addCuePoints();
});
this.player.on('ended', () => {
this.loader.contentComplete();
});
this.player.on('seeking', () => {
this.player.on('timeupdate', () => {
time = this.player.currentTime;
return time;
});
this.player.on('seeked', () => {
@ -471,10 +496,8 @@ class Ads {
// Ad is stopped
this.playing = false;
// Play our video
if (this.player.currentTime < this.player.duration) {
this.player.play();
}
// Play video
this.player.media.play();
}
/**
@ -484,11 +507,11 @@ class Ads {
// Show the advertisement container
this.elements.container.style.zIndex = 3;
// Ad is playing.
// Ad is playing
this.playing = true;
// Pause our video.
this.player.pause();
this.player.media.pause();
}
/**
@ -536,7 +559,7 @@ class Ads {
/**
* Handles callbacks after an ad event was invoked
* @param {string} event - Event type
* @param {String} event - Event type
*/
trigger(event, ...args) {
const handlers = this.events[event];
@ -552,8 +575,8 @@ class Ads {
/**
* Add event listeners
* @param {string} event - Event type
* @param {function} callback - Callback for when event occurs
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
* @return {Ads}
*/
on(event, callback) {
@ -571,8 +594,8 @@ class Ads {
* The advertisement has 12 seconds to get its things together. We stop this timer when the
* advertisement is playing, or when a user action is required to start, then we clear the
* timer on ad ready
* @param {number} time
* @param {string} from
* @param {Number} time
* @param {String} from
*/
startSafetyTimer(time, from) {
this.player.debug.log(`Safety timer invoked from: ${from}`);
@ -585,7 +608,7 @@ class Ads {
/**
* Clear our safety timer(s)
* @param {string} from
* @param {String} from
*/
clearSafetyTimer(from) {
if (!is.nullOrUndefined(this.safetyTimer)) {

View File

@ -0,0 +1,639 @@
import { createElement } from '../utils/elements';
import { once } from '../utils/events';
import fetch from '../utils/fetch';
import is from '../utils/is';
import { formatTime } from '../utils/time';
// Arg: vttDataString example: "WEBVTT\n\n1\n00:00:05.000 --> 00:00:10.000\n1080p-00001.jpg"
const parseVtt = vttDataString => {
const processedList = [];
const frames = vttDataString.split(/\r\n\r\n|\n\n|\r\r/);
frames.forEach(frame => {
const result = {};
const lines = frame.split(/\r\n|\n|\r/);
lines.forEach(line => {
if (!is.number(result.startTime)) {
// The line with start and end times on it is the first line of interest
const 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 (!is.empty(line.trim()) && is.empty(result.text)) {
// If we already have the startTime, then we're definitely up to the text line(s)
const lineSplit = line.trim().split('#xywh=');
[result.text] = lineSplit;
// If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image
if (lineSplit[1]) {
[result.x, result.y, result.w, result.h] = lineSplit[1].split(',');
}
}
});
if (result.text) {
processedList.push(result);
}
});
return processedList;
};
/**
* 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
*/
class PreviewThumbnails {
/**
* PreviewThumbnails constructor.
* @param {Plyr} player
* @return {PreviewThumbnails}
*/
constructor(player) {
this.player = player;
this.thumbnails = [];
this.loaded = false;
this.lastMouseMoveTime = Date.now();
this.mouseDown = false;
this.loadedImages = [];
this.elements = {
thumb: {},
scrubbing: {},
};
this.load();
}
get enabled() {
return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;
}
load() {
// Togglethe regular seek tooltip
if (this.player.elements.display.seekTooltip) {
this.player.elements.display.seekTooltip.hidden = this.enabled;
}
if (!this.enabled) {
return;
}
this.getThumbnails().then(() => {
// Render DOM elements
this.render();
// Check to see if thumb container size was specified manually in CSS
this.determineContainerAutoSizing();
this.loaded = true;
});
}
// Download VTT files and parse them
getThumbnails() {
return new Promise(resolve => {
const { src } = this.player.config.previewThumbnails;
if (is.empty(src)) {
throw new Error('Missing previewThumbnails.src config attribute');
}
// If string, convert into single-element list
const urls = is.string(src) ? [src] : src;
// Loop through each src URL. Download and process the VTT file, storing the resulting data in this.thumbnails
const promises = urls.map(u => this.getThumbnail(u));
Promise.all(promises).then(() => {
// Sort smallest to biggest (e.g., [120p, 480p, 1080p])
this.thumbnails.sort((x, y) => x.height - y.height);
this.player.debug.log('Preview thumbnails', this.thumbnails);
resolve();
});
});
}
// Process individual VTT file
getThumbnail(url) {
return new Promise(resolve => {
fetch(url).then(response => {
const thumbnail = {
frames: 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 (!thumbnail.frames[0].text.startsWith('/')) {
thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);
}
// Download the first frame, so that we can determine/set the height of this thumbnailsDef
const tempImage = new Image();
tempImage.onload = () => {
thumbnail.height = tempImage.naturalHeight;
thumbnail.width = tempImage.naturalWidth;
this.thumbnails.push(thumbnail);
resolve();
};
tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;
});
});
}
startMove(event) {
if (!this.loaded) {
return;
}
if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {
return;
}
// Wait until media has a duration
if (!this.player.media.duration) {
return;
}
if (event.type === 'touchmove') {
// Calculate seek hover position as approx video seconds
this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);
} else {
// Calculate seek hover position as approx video seconds
const clientRect = this.player.elements.progress.getBoundingClientRect();
const percentage = (100 / clientRect.width) * (event.pageX - clientRect.left);
this.seekTime = this.player.media.duration * (percentage / 100);
if (this.seekTime < 0) {
// The mousemove fires for 10+px out to the left
this.seekTime = 0;
}
if (this.seekTime > this.player.media.duration - 1) {
// Took 1 second off the duration for safety, because different players can disagree on the real duration of a video
this.seekTime = this.player.media.duration - 1;
}
this.mousePosX = event.pageX;
// Set time text inside image container
this.elements.thumb.time.innerText = formatTime(this.seekTime);
}
// Download and show image
this.showImageAtCurrentTime();
}
endMove() {
this.toggleThumbContainer(false, true);
}
startScrubbing(event) {
// Only act on left mouse button (0), or touch device (event.button is false)
if (event.button === false || event.button === 0) {
this.mouseDown = true;
// Wait until media has a duration
if (this.player.media.duration) {
this.toggleScrubbingContainer(true);
this.toggleThumbContainer(false, true);
// Download and show image
this.showImageAtCurrentTime();
}
}
}
endScrubbing() {
this.mouseDown = false;
// Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview
if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {
// The video was already seeked/loaded at the chosen time - hide immediately
this.toggleScrubbingContainer(false);
} else {
// The video hasn't seeked yet. Wait for that
once.call(this.player, this.player.media, 'timeupdate', () => {
// Re-check mousedown - we might have already started scrubbing again
if (!this.mouseDown) {
this.toggleScrubbingContainer(false);
}
});
}
}
/**
* Setup hooks for Plyr and window events
*/
listeners() {
// Hide thumbnail preview - on mouse click, mouse leave (in listeners.js for now), and video play/seek. All four are required, e.g., for buffering
this.player.on('play', () => {
this.toggleThumbContainer(false, true);
});
this.player.on('seeked', () => {
this.toggleThumbContainer(false);
});
this.player.on('timeupdate', () => {
this.lastTime = this.player.media.currentTime;
});
}
/**
* Create HTML elements for image containers
*/
render() {
// Create HTML element: plyr__preview-thumbnail-container
this.elements.thumb.container = createElement('div', {
class: this.player.config.classNames.previewThumbnails.thumbContainer,
});
// Wrapper for the image for styling
this.elements.thumb.imageContainer = createElement('div', {
class: this.player.config.classNames.previewThumbnails.imageContainer,
});
this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);
// Create HTML element, parent+span: time text (e.g., 01:32:00)
const timeContainer = createElement('div', {
class: this.player.config.classNames.previewThumbnails.timeContainer,
});
this.elements.thumb.time = createElement('span', {}, '00:00');
timeContainer.appendChild(this.elements.thumb.time);
this.elements.thumb.container.appendChild(timeContainer);
// Inject the whole thumb
this.player.elements.progress.appendChild(this.elements.thumb.container);
// Create HTML element: plyr__preview-scrubbing-container
this.elements.scrubbing.container = createElement('div', {
class: this.player.config.classNames.previewThumbnails.scrubbingContainer,
});
this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);
}
showImageAtCurrentTime() {
if (this.mouseDown) {
this.setScrubbingContainerSize();
} else {
this.setThumbContainerSizeAndPos();
}
// Find the desired thumbnail index
// TODO: Handle a video longer than the thumbs where thumbNum is null
const thumbNum = this.thumbnails[0].frames.findIndex(
frame => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime,
);
const hasThumb = thumbNum >= 0;
let qualityIndex = 0;
// Show the thumb container if we're not scrubbing
if (!this.mouseDown) {
this.toggleThumbContainer(hasThumb);
}
// No matching thumb found
if (!hasThumb) {
return;
}
// Check to see if we've already downloaded higher quality versions of this image
this.thumbnails.forEach((thumbnail, index) => {
if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {
qualityIndex = index;
}
});
// 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
loadImage(qualityIndex = 0) {
const thumbNum = this.showingThumb;
const thumbnail = this.thumbnails[qualityIndex];
const { urlPrefix } = thumbnail;
const frame = thumbnail.frames[thumbNum];
const thumbFilename = thumbnail.frames[thumbNum].text;
const thumbUrl = urlPrefix + thumbFilename;
if (!this.currentImageElement || this.currentImageElement.dataset.filename !== 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 sprites. Without sprites we really want to show as many images as possible, as a best-effort
if (this.loadingImage && this.usingSprites) {
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
const previewImage = new Image();
previewImage.src = thumbUrl;
previewImage.dataset.index = thumbNum;
previewImage.dataset.filename = thumbFilename;
this.showingThumbFilename = thumbFilename;
this.player.debug.log(`Loading image: ${thumbUrl}`);
// For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function...
previewImage.onload = () =>
this.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.dataset.index = thumbNum;
this.removeOldImages(this.currentImageElement);
}
}
showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) {
this.player.debug.log(
`Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`,
);
this.setImageSizeAndOffset(previewImage, frame);
if (newImage) {
this.currentImageContainer.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
removeOldImages(currentImage) {
// Get a list of all images, convert it from a DOM list to an array
Array.from(this.currentImageContainer.children).forEach(image => {
if (image.tagName.toLowerCase() !== 'img') {
return;
}
const removeDelay = this.usingSprites ? 500 : 1000;
if (image.dataset.index !== currentImage.dataset.index && !image.dataset.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.dataset.deleting = true;
// This has to be set before the timeout - to prevent issues switching between hover and scrub
const { currentImageContainer } = this;
setTimeout(() => {
currentImageContainer.removeChild(image);
this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);
}, removeDelay);
}
});
}
// 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
preloadNearby(thumbNum, forward = true) {
return new Promise(resolve => {
setTimeout(() => {
const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;
if (this.showingThumbFilename === oldThumbFilename) {
// Find the nearest thumbs with different filenames. Sometimes it'll be the next index, but in the case of sprites, it might be 100+ away
let thumbnailsClone;
if (forward) {
thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);
} else {
thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();
}
let foundOne = false;
thumbnailsClone.forEach(frame => {
const 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 (!this.loadedImages.includes(newThumbFilename)) {
foundOne = true;
this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);
const { urlPrefix } = this.thumbnails[0];
const thumbURL = urlPrefix + newThumbFilename;
const previewImage = new Image();
previewImage.src = thumbURL;
previewImage.onload = () => {
this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);
if (!this.loadedImages.includes(newThumbFilename))
this.loadedImages.push(newThumbFilename);
// We don't resolve until the thumb is loaded
resolve();
};
}
}
});
// If there are none to preload then we want to resolve immediately
if (!foundOne) {
resolve();
}
}
}, 300);
});
}
// If user has been hovering current image for half a second, look for a higher quality one
getHigherQuality(currentQualityIndex, previewImage, frame, thumbFilename) {
if (currentQualityIndex < this.thumbnails.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
let previewImageHeight = previewImage.naturalHeight;
if (this.usingSprites) {
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(() => {
// Make sure the mouse hasn't already moved on and started hovering at another image
if (this.showingThumbFilename === thumbFilename) {
this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);
this.loadImage(currentQualityIndex + 1);
}
}, 300);
}
}
}
get currentImageContainer() {
if (this.mouseDown) {
return this.elements.scrubbing.container;
}
return this.elements.thumb.imageContainer;
}
get usingSprites() {
return Object.keys(this.thumbnails[0].frames[0]).includes('w');
}
get thumbAspectRatio() {
if (this.usingSprites) {
return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;
}
return this.thumbnails[0].width / this.thumbnails[0].height;
}
get thumbContainerHeight() {
if (this.mouseDown) {
// Can't use media.clientHeight - HTML5 video goes big and does black bars above and below
return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio);
}
return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);
}
get currentImageElement() {
if (this.mouseDown) {
return this.currentScrubbingImageElement;
}
return this.currentThumbnailImageElement;
}
set currentImageElement(element) {
if (this.mouseDown) {
this.currentScrubbingImageElement = element;
} else {
this.currentThumbnailImageElement = element;
}
}
toggleThumbContainer(toggle = false, clearShowing = false) {
const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;
this.elements.thumb.container.classList.toggle(className, toggle);
if (!toggle && clearShowing) {
this.showingThumb = null;
this.showingThumbFilename = null;
}
}
toggleScrubbingContainer(toggle = false) {
const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;
this.elements.scrubbing.container.classList.toggle(className, toggle);
if (!toggle) {
this.showingThumb = null;
this.showingThumbFilename = null;
}
}
determineContainerAutoSizing() {
if (this.elements.thumb.imageContainer.clientHeight > 20) {
// This will prevent auto sizing in this.setThumbContainerSizeAndPos()
this.sizeSpecifiedInCSS = true;
}
}
// 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
setThumbContainerSizeAndPos() {
if (!this.sizeSpecifiedInCSS) {
const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);
this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;
this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;
}
this.setThumbContainerPos();
}
setThumbContainerPos() {
const seekbarRect = this.player.elements.progress.getBoundingClientRect();
const plyrRect = this.player.elements.container.getBoundingClientRect();
const { container } = this.elements.thumb;
// Find the lowest and highest desired left-position, so we don't slide out the side of the video container
const minVal = plyrRect.left - seekbarRect.left + 10;
const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10;
// Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth
let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;
if (previewPos < minVal) {
previewPos = minVal;
}
if (previewPos > maxVal) {
previewPos = maxVal;
}
container.style.left = `${previewPos}px`;
}
// Can't use 100% width, in case the video is a different aspect ratio to the video container
setScrubbingContainerSize() {
this.elements.scrubbing.container.style.width = `${this.player.media.clientWidth}px`;
// Can't use media.clientHeight - html5 video goes big and does black bars above and below
this.elements.scrubbing.container.style.height = `${this.player.media.clientWidth / this.thumbAspectRatio}px`;
}
// Sprites need to be offset to the correct location
setImageSizeAndOffset(previewImage, frame) {
if (!this.usingSprites) {
return;
}
// Find difference between height and preview container height
const multiplier = this.thumbContainerHeight / frame.h;
previewImage.style.height = `${Math.floor(previewImage.naturalHeight * multiplier)}px`;
previewImage.style.width = `${Math.floor(previewImage.naturalWidth * multiplier)}px`;
previewImage.style.left = `-${frame.x * multiplier}px`;
previewImage.style.top = `-${frame.y * multiplier}px`;
}
}
export default PreviewThumbnails;

View File

@ -10,7 +10,9 @@ import { triggerEvent } from '../utils/events';
import fetch from '../utils/fetch';
import is from '../utils/is';
import loadScript from '../utils/loadScript';
import { extend } from '../utils/objects';
import { format, stripHTML } from '../utils/strings';
import { setAspectRatio } from '../utils/style';
import { buildUrlParams } from '../utils/urls';
// Parse Vimeo ID from URL
@ -27,13 +29,6 @@ function parseId(url) {
return url.match(regex) ? RegExp.$2 : url;
}
// Get aspect ratio for dimensions
function getAspectRatio(width, height) {
const getRatio = (w, h) => (h === 0 ? w : getRatio(h, w % h));
const ratio = getRatio(width, height);
return `${width / ratio}:${height / ratio}`;
}
// Set playback state and trigger change (only on actual change)
function assurePlaybackState(play) {
if (play && !this.embed.hasPlayed) {
@ -51,7 +46,7 @@ const vimeo = {
toggleClass(this.elements.wrapper, this.config.classNames.embed, true);
// Set intial ratio
vimeo.setAspectRatio.call(this);
setAspectRatio.call(this);
// Load the API if not already
if (!is.object(window.Vimeo)) {
@ -67,40 +62,25 @@ const vimeo = {
}
},
// Set aspect ratio
// For Vimeo we have an extra 300% height <div> to hide the standard controls and UI
setAspectRatio(input) {
const [x, y] = (is.string(input) ? input : this.config.ratio).split(':').map(Number);
const padding = (100 / x) * y;
vimeo.padding = padding;
this.elements.wrapper.style.paddingBottom = `${padding}%`;
if (this.supported.ui) {
const height = 240;
const offset = (height - padding) / (height / 50);
this.media.style.transform = `translateY(-${offset}%)`;
}
},
// API Ready
ready() {
const player = this;
const config = player.config.vimeo;
// Get Vimeo params for the iframe
const options = {
const params = buildUrlParams(
extend(
{},
{
loop: player.config.loop.active,
autoplay: player.autoplay,
// muted: player.muted,
byline: false,
portrait: false,
title: false,
speed: true,
transparent: 0,
muted: player.muted,
gesture: 'media',
playsinline: !this.config.fullscreen.iosNative,
};
const params = buildUrlParams(options);
},
config,
),
);
// Get the source URL or ID
let source = player.media.getAttribute('src');
@ -300,8 +280,9 @@ const vimeo = {
// Set aspect ratio based on video size
Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => {
vimeo.ratio = getAspectRatio(dimensions[0], dimensions[1]);
vimeo.setAspectRatio.call(this, vimeo.ratio);
const [width, height] = dimensions;
player.embed.ratio = `${width}:${height}`;
setAspectRatio.call(this, player.embed.ratio);
});
// Set autopause
@ -405,22 +386,6 @@ const vimeo = {
triggerEvent.call(player, player.media, 'error');
});
// Set height/width on fullscreen
player.on('enterfullscreen exitfullscreen', event => {
const { target } = player.fullscreen;
// Ignore for iOS native
if (target !== player.elements.container) {
return;
}
const toggle = event.type === 'enterfullscreen';
const [x, y] = vimeo.ratio.split(':').map(Number);
const dimension = x > y ? 'width' : 'height';
target.style[dimension] = toggle ? `${vimeo.padding}%` : null;
});
// Rebuild UI
setTimeout(() => ui.build.call(player), 0);
},

View File

@ -9,7 +9,9 @@ import fetch from '../utils/fetch';
import is from '../utils/is';
import loadImage from '../utils/loadImage';
import loadScript from '../utils/loadScript';
import { extend } from '../utils/objects';
import { format, generateId } from '../utils/strings';
import { setAspectRatio } from '../utils/style';
// Parse YouTube ID from URL
function parseId(url) {
@ -38,7 +40,7 @@ const youtube = {
toggleClass(this.elements.wrapper, this.config.classNames.embed, true);
// Set aspect ratio
youtube.setAspectRatio.call(this);
setAspectRatio.call(this);
// Setup API
if (is.object(window.YT) && is.function(window.YT.Player)) {
@ -98,12 +100,6 @@ const youtube = {
}
},
// Set aspect ratio
setAspectRatio() {
const ratio = this.config.ratio.split(':');
this.elements.wrapper.style.paddingBottom = `${100 / ratio[0] * ratio[1]}%`;
},
// API ready
ready() {
const player = this;
@ -134,7 +130,7 @@ const youtube = {
player.media = replaceElement(container, player.media);
// Id to poster wrapper
const posterSrc = format => `https://img.youtube.com/vi/${videoId}/${format}default.jpg`;
const posterSrc = format => `https://i.ytimg.com/vi/${videoId}/${format}default.jpg`;
// Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)
loadImage(posterSrc('maxres'), 121) // Higest quality and unpadded
@ -149,29 +145,29 @@ const youtube = {
})
.catch(() => {});
const config = player.config.youtube;
// Setup instance
// https://developers.google.com/youtube/iframe_api_reference
player.embed = new window.YT.Player(id, {
videoId,
playerVars: {
host: config.noCookie ? 'https://www.youtube-nocookie.com' : undefined,
playerVars: extend(
{},
{
autoplay: player.config.autoplay ? 1 : 0, // Autoplay
hl: player.config.hl, // iframe interface language
controls: player.supported.ui ? 0 : 1, // Only show controls if not fully supported
rel: 0, // No related vids
showinfo: 0, // Hide info
iv_load_policy: 3, // Hide annotations
modestbranding: 1, // Hide logos as much as possible (they still show one in the corner when paused)
disablekb: 1, // Disable keyboard as we handle it
playsinline: 1, // Allow iOS inline playback
// Tracking for stats
// origin: window ? `${window.location.protocol}//${window.location.host}` : null,
widget_referrer: window ? window.location.href : null,
playsinline: !player.config.fullscreen.iosNative ? 1 : 0, // Allow iOS inline playback
// Captions are flaky on YouTube
cc_load_policy: player.captions.active ? 1 : 0,
cc_lang_pref: player.config.captions.language,
// Tracking for stats
widget_referrer: window ? window.location.href : null,
},
config,
),
events: {
onError(event) {
// YouTube may fire onError twice, so only handle it once

View File

@ -1,6 +1,6 @@
// ==========================================================================
// Plyr
// plyr.js v3.4.7
// plyr.js v3.5.2
// https://github.com/sampotts/plyr
// License: The MIT License (MIT)
// ==========================================================================
@ -15,6 +15,7 @@ import Fullscreen from './fullscreen';
import Listeners from './listeners';
import media from './media';
import Ads from './plugins/ads';
import PreviewThumbnails from './plugins/previewThumbnails';
import source from './source';
import Storage from './storage';
import support from './support';
@ -187,7 +188,7 @@ class Plyr {
// YouTube requires the playsinline in the URL
if (this.isYouTube) {
this.config.playsinline = truthy.includes(url.searchParams.get('playsinline'));
this.config.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?
this.config.youtube.hl = url.searchParams.get('hl'); // TODO: Should this be setting language?
} else {
this.config.playsinline = true;
}
@ -262,7 +263,7 @@ class Plyr {
// 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);
}
@ -306,6 +307,11 @@ class Plyr {
// Seek time will be recorded (in listeners.js) so we can prevent hiding controls for a few seconds after seek
this.lastSeekTime = 0;
// Setup preview thumbnails if enabled
if (this.config.previewThumbnails.enabled) {
this.previewThumbnails = new PreviewThumbnails(this);
}
}
// ---------------------------------------
@ -347,6 +353,11 @@ class Plyr {
return null;
}
// Intecept play with ads
if (this.ads && this.ads.enabled) {
this.ads.managerPromise.then(() => this.ads.play()).catch(() => this.media.play());
}
// Return the promise (for HTML5)
return this.media.play();
}
@ -392,7 +403,7 @@ class Plyr {
/**
* Toggle playback based on current status
* @param {boolean} input
* @param {Boolean} input
*/
togglePlay(input) {
// Toggle based on current state if nothing passed
@ -426,7 +437,7 @@ class Plyr {
/**
* Rewind
* @param {number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime
* @param {Number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime
*/
rewind(seekTime) {
this.currentTime = this.currentTime - (is.number(seekTime) ? seekTime : this.config.seekTime);
@ -434,7 +445,7 @@ class Plyr {
/**
* Fast forward
* @param {number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime
* @param {Number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime
*/
forward(seekTime) {
this.currentTime = this.currentTime + (is.number(seekTime) ? seekTime : this.config.seekTime);
@ -442,7 +453,7 @@ class Plyr {
/**
* Seek to a time
* @param {number} input - where to seek to in seconds. Defaults to 0 (the start)
* @param {Number} input - where to seek to in seconds. Defaults to 0 (the start)
*/
set currentTime(input) {
// Bail if media duration isn't available yet
@ -512,7 +523,7 @@ class Plyr {
/**
* Set the player volume
* @param {number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage
* @param {Number} value - must be between 0 and 1. Defaults to the value from local storage and config.volume if not set in storage
*/
set volume(value) {
let volume = value;
@ -563,7 +574,7 @@ class Plyr {
/**
* Increase volume
* @param {boolean} step - How much to decrease by (between 0 and 1)
* @param {Boolean} step - How much to decrease by (between 0 and 1)
*/
increaseVolume(step) {
const volume = this.media.muted ? 0 : this.volume;
@ -572,7 +583,7 @@ class Plyr {
/**
* Decrease volume
* @param {boolean} step - How much to decrease by (between 0 and 1)
* @param {Boolean} step - How much to decrease by (between 0 and 1)
*/
decreaseVolume(step) {
this.increaseVolume(-step);
@ -580,7 +591,7 @@ class Plyr {
/**
* Set muted state
* @param {boolean} mute
* @param {Boolean} mute
*/
set muted(mute) {
let toggle = mute;
@ -632,7 +643,7 @@ class Plyr {
/**
* Set playback speed
* @param {number} speed - the speed of playback (0.5-2.0)
* @param {Number} speed - the speed of playback (0.5-2.0)
*/
set speed(input) {
let speed = null;
@ -679,7 +690,7 @@ class Plyr {
/**
* Set playback quality
* Currently HTML5 & YouTube only
* @param {number} input - Quality level
* @param {Number} input - Quality level
*/
set quality(input) {
const config = this.config.quality;
@ -729,7 +740,7 @@ class Plyr {
/**
* Toggle loop
* TODO: Finish fancy new logic. Set the indicator on load as user may pass loop as config
* @param {boolean} input - Whether to loop or not
* @param {Boolean} input - Whether to loop or not
*/
set loop(input) {
const toggle = is.boolean(input) ? input : this.config.loop.active;
@ -789,7 +800,7 @@ class Plyr {
/**
* Set new media source
* @param {object} input - The new source object (see docs)
* @param {Object} input - The new source object (see docs)
*/
set source(input) {
source.change.call(this, input);
@ -813,7 +824,7 @@ class Plyr {
/**
* Set the poster image for a video
* @param {input} - the URL for the new poster image
* @param {String} input - the URL for the new poster image
*/
set poster(input) {
if (!this.isVideo) {
@ -837,7 +848,7 @@ class Plyr {
/**
* Set the autoplay state
* @param {boolean} input - Whether to autoplay or not
* @param {Boolean} input - Whether to autoplay or not
*/
set autoplay(input) {
const toggle = is.boolean(input) ? input : this.config.autoplay;
@ -853,7 +864,7 @@ class Plyr {
/**
* Toggle captions
* @param {boolean} input - Whether to enable captions
* @param {Boolean} input - Whether to enable captions
*/
toggleCaptions(input) {
captions.toggle.call(this, input, false);
@ -861,7 +872,7 @@ class Plyr {
/**
* Set the caption track by index
* @param {number} - Caption index
* @param {Number} - Caption index
*/
set currentTrack(input) {
captions.set.call(this, input, false);
@ -878,7 +889,7 @@ class Plyr {
/**
* Set the wanted language for captions
* Since tracks can be added later it won't update the actual caption track until there is a matching track
* @param {string} - Two character ISO language code (e.g. EN, FR, PT, etc)
* @param {String} - Two character ISO language code (e.g. EN, FR, PT, etc)
*/
set language(input) {
captions.setLanguage.call(this, input, false);
@ -951,7 +962,7 @@ class Plyr {
/**
* Toggle the player controls
* @param {boolean} [toggle] - Whether to show the controls
* @param {Boolean} [toggle] - Whether to show the controls
*/
toggleControls(toggle) {
// Don't toggle if missing UI support or if it's audio
@ -984,8 +995,8 @@ class Plyr {
/**
* Add event listeners
* @param {string} event - Event type
* @param {function} callback - Callback for when event occurs
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
*/
on(event, callback) {
on.call(this, this.elements.container, event, callback);
@ -993,8 +1004,8 @@ class Plyr {
/**
* Add event listeners once
* @param {string} event - Event type
* @param {function} callback - Callback for when event occurs
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
*/
once(event, callback) {
once.call(this, this.elements.container, event, callback);
@ -1002,8 +1013,8 @@ class Plyr {
/**
* Remove event listeners
* @param {string} event - Event type
* @param {function} callback - Callback for when event occurs
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
*/
off(event, callback) {
off(this.elements.container, event, callback);
@ -1013,8 +1024,8 @@ class Plyr {
* Destroy an instance
* Event listeners are removed when elements are removed
* http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory
* @param {function} callback - Callback for when destroy is complete
* @param {boolean} soft - Whether it's a soft destroy (for source changes etc)
* @param {Function} callback - Callback for when destroy is complete
* @param {Boolean} soft - Whether it's a soft destroy (for source changes etc)
*/
destroy(callback, soft = false) {
if (!this.ready) {
@ -1113,7 +1124,7 @@ class Plyr {
/**
* Check for support for a mime type (HTML5 only)
* @param {string} type - Mime type
* @param {String} type - Mime type
*/
supports(type) {
return support.mime.call(this, type);
@ -1121,9 +1132,9 @@ class Plyr {
/**
* Check for support
* @param {string} type - Player type (audio/video)
* @param {string} provider - Provider (html5/youtube/vimeo)
* @param {bool} inline - Where player has `playsinline` sttribute
* @param {String} type - Player type (audio/video)
* @param {String} provider - Provider (html5/youtube/vimeo)
* @param {Boolean} inline - Where player has `playsinline` sttribute
*/
static supported(type, provider, inline) {
return support.check(type, provider, inline);
@ -1131,8 +1142,8 @@ class Plyr {
/**
* Load an SVG sprite into the page
* @param {string} url - URL for the SVG sprite
* @param {string} [id] - Unique ID
* @param {String} url - URL for the SVG sprite
* @param {String} [id] - Unique ID
*/
static loadSprite(url, id) {
return loadSprite(url, id);
@ -1141,7 +1152,7 @@ class Plyr {
/**
* Setup multiple instances
* @param {*} selector
* @param {object} options
* @param {Object} options
*/
static setup(selector, options = {}) {
let targets = null;

View File

@ -1,6 +1,6 @@
// ==========================================================================
// Plyr Polyfilled Build
// plyr.js v3.4.7
// plyr.js v3.5.2
// https://github.com/sampotts/plyr
// License: The MIT License (MIT)
// ==========================================================================

View File

@ -125,11 +125,16 @@ const source = {
ui.build.call(this);
}
if (this.isHTML5) {
// Load HTML5 sources
if (this.isHTML5) {
this.media.load();
}
// Reload thumbnails
if (this.previewThumbnails) {
this.previewThumbnails.load();
}
// Update the fullscreen support
this.fullscreen.update();
},

View File

@ -68,9 +68,13 @@ const support = {
// Check for mime type support against a player instance
// Credits: http://diveintohtml5.info/everything.html
// Related: http://www.leanbackplayer.com/test/h5mt.html
mime(inputType) {
const [mediaType] = inputType.split('/');
let type = inputType;
mime(input) {
if (is.empty(input)) {
return false;
}
const [mediaType] = input.split('/');
let type = input;
// Verify we're using HTML5 and there's no media type mismatch
if (!this.isHTML5 || mediaType !== this.type) {
@ -79,7 +83,7 @@ const support = {
// Add codec if required
if (Object.keys(defaultCodecs).includes(type)) {
type += `; codecs="${defaultCodecs[inputType]}"`;
type += `; codecs="${defaultCodecs[input]}"`;
}
try {

View File

@ -5,6 +5,7 @@
const browser = {
isIE: /* @cc_on!@ */ false || !!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),

View File

@ -73,10 +73,10 @@ export function off(element, events = '', callback, passive = true, capture = fa
// Bind once-only event handler
export function once(element, events = '', callback, passive = true, capture = false) {
function onceCallback(...args) {
const onceCallback = (...args) => {
off(element, events, onceCallback, passive, capture);
callback.apply(this, args);
}
};
toggleListener.call(this, element, events, onceCallback, true, passive, capture);
}
@ -114,7 +114,7 @@ export function unbindListeners() {
// Run method when / if player is ready
export function ready() {
return new Promise(
resolve => (this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve)),
return new Promise(resolve =>
this.ready ? setTimeout(resolve, 0) : on.call(this, this.elements.container, 'ready', resolve),
).then(() => {});
}

View File

@ -19,6 +19,7 @@ const isEvent = input => instanceOf(input, Event);
const isKeyboardEvent = input => instanceOf(input, KeyboardEvent);
const isCue = input => instanceOf(input, window.TextTrackCue) || instanceOf(input, window.VTTCue);
const isTrack = input => instanceOf(input, TextTrack) || (!isNullOrUndefined(input) && isString(input.kind));
const isPromise = input => instanceOf(input, Promise);
const isEmpty = input =>
isNullOrUndefined(input) ||
@ -65,6 +66,7 @@ export default {
keyboardEvent: isKeyboardEvent,
cue: isCue,
track: isTrack,
promise: isPromise,
url: isUrl,
empty: isEmpty,
};

40
src/js/utils/style.js Normal file
View File

@ -0,0 +1,40 @@
// ==========================================================================
// Style utils
// ==========================================================================
import is from './is';
/* 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
export function setAspectRatio(input) {
let ratio = input;
if (!is.string(ratio) && !is.nullOrUndefined(this.embed)) {
({ ratio } = this.embed);
}
if (!is.string(ratio)) {
({ ratio } = this.config);
}
const [x, y] = ratio.split(':').map(Number);
const padding = (100 / x) * y;
this.elements.wrapper.style.paddingBottom = `${padding}%`;
// For Vimeo we have an extra <div> to hide the standard controls and UI
if (this.isVimeo && this.supported.ui) {
const height = 240;
const offset = (height - padding) / (height / 50);
this.media.style.transform = `translateY(-${offset}%)`;
}
return { padding, ratio };
}
export default { setAspectRatio };

View File

@ -5,9 +5,9 @@
import is from './is';
// Time helpers
export const getHours = value => parseInt((value / 60 / 60) % 60, 10);
export const getMinutes = value => parseInt((value / 60) % 60, 10);
export const getSeconds = value => parseInt(value % 60, 10);
export const getHours = value => Math.trunc((value / 60 / 60) % 60, 10);
export const getMinutes = value => Math.trunc((value / 60) % 60, 10);
export const getSeconds = value => Math.trunc(value % 60, 10);
// Format time to UI friendly string
export function formatTime(time = 0, displayHours = false, inverted = false) {

View File

@ -6,8 +6,8 @@ import is from './is';
/**
* Parse a string to a URL object
* @param {string} input - the URL to be parsed
* @param {boolean} safe - failsafe parsing
* @param {String} input - the URL to be parsed
* @param {Boolean} safe - failsafe parsing
*/
export function parseUrl(input, safe = true) {
let url = input;

View File

@ -42,13 +42,13 @@
&::-webkit-progress-bar {
background: transparent;
transition: width 0.2s ease;
}
&::-webkit-progress-value {
background: currentColor;
border-radius: 100px;
min-width: $plyr-range-track-height;
transition: width 0.2s ease;
}
// Mozilla

View File

@ -69,11 +69,6 @@
width: 100%;
}
.plyr__video-embed {
// Revert overflow change
overflow: visible;
}
// Vimeo requires some different styling
&.plyr--vimeo .plyr__video-wrapper {
height: 0;

View File

@ -0,0 +1,118 @@
// --------------------------------------------------------------
// Preview Thumbnails
// --------------------------------------------------------------
$plyr-preview-padding: $plyr-tooltip-padding !default;
$plyr-preview-bg: $plyr-tooltip-bg !default;
$plyr-preview-radius: $plyr-tooltip-radius !default;
$plyr-preview-shadow: $plyr-tooltip-shadow !default;
$plyr-preview-arrow-size: $plyr-tooltip-arrow-size !default;
$plyr-preview-image-bg: $plyr-color-heather !default;
$plyr-preview-time-font-size: $plyr-font-size-time !default;
$plyr-preview-time-padding: 3px 6px !default;
$plyr-preview-time-bg: rgba(0, 0, 0, 0.55);
$plyr-preview-time-color: #fff;
$plyr-preview-time-bottom-offset: 6px;
.plyr__preview-thumb {
background-color: $plyr-preview-bg;
border-radius: 3px;
bottom: 100%;
box-shadow: $plyr-preview-shadow;
margin-bottom: $plyr-preview-padding * 2;
opacity: 0;
padding: $plyr-preview-radius;
pointer-events: none;
position: absolute;
transform: translate(0, 10px) scale(0.8);
transform-origin: 50% 100%;
transition: transform 0.2s 0.1s ease, opacity 0.2s 0.1s ease;
z-index: 2;
&--is-shown {
opacity: 1;
transform: translate(0, 0) scale(1);
}
// The background triangle
&::before {
border-left: $plyr-preview-arrow-size solid transparent;
border-right: $plyr-preview-arrow-size solid transparent;
border-top: $plyr-preview-arrow-size solid $plyr-preview-bg;
bottom: -$plyr-preview-arrow-size;
content: '';
height: 0;
left: 50%;
position: absolute;
transform: translateX(-50%);
width: 0;
z-index: 2;
}
&__image-container {
background: $plyr-preview-image-bg;
border-radius: ($plyr-preview-radius - 1px);
overflow: hidden;
position: relative;
z-index: 0;
img {
height: 100%; // Non sprite images are 100%. Sprites will have their size applied by JavaScript
left: 0;
max-height: none;
max-width: none;
position: absolute;
top: 0;
width: 100%;
}
}
// Seek time text
&__time-container {
bottom: $plyr-preview-time-bottom-offset;
left: 0;
position: absolute;
right: 0;
white-space: nowrap;
z-index: 3;
span {
background-color: $plyr-preview-time-bg;
border-radius: ($plyr-preview-radius - 1px);
color: $plyr-preview-time-color;
font-size: $plyr-preview-time-font-size;
padding: $plyr-preview-time-padding;
}
}
}
.plyr__preview-scrubbing {
bottom: 0;
filter: blur(1px);
height: 100%;
left: 0;
margin: auto; // Required when video is different dimensions to container (e.g. fullscreen)
opacity: 0;
overflow: hidden;
position: absolute;
right: 0;
top: 0;
transition: opacity 0.3s ease;
width: 100%;
z-index: 1;
&--is-shown {
opacity: 1;
}
img {
height: 100%;
left: 0;
max-height: none;
max-width: none;
object-fit: contain;
position: absolute;
top: 0;
width: 100%;
}
}

View File

@ -45,6 +45,7 @@ $css-vars-use-native: true;
@import 'states/fullscreen';
@import 'plugins/ads';
@import 'plugins/previewThumbnails';
@import 'utils/animation';
@import 'utils/hidden';

View File

@ -6,13 +6,13 @@
$plyr-range-thumb-active-shadow-width: 3px !default;
// Thumb
$plyr-range-thumb-height: 14px !default;
$plyr-range-thumb-height: 13px !default;
$plyr-range-thumb-bg: #fff !default;
$plyr-range-thumb-border: 2px solid transparent !default;
$plyr-range-thumb-shadow: 0 1px 1px rgba(#000, 0.15), 0 0 0 1px rgba($plyr-color-gunmetal, 0.2) !default;
// Track
$plyr-range-track-height: 4px !default;
$plyr-range-track-height: 5px !default;
$plyr-range-max-height: ($plyr-range-thumb-active-shadow-width * 2) + $plyr-range-thumb-height !default;
// Fill

3861
yarn.lock

File diff suppressed because it is too large Load Diff